cli.py 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957
  1. #============================================================================
  2. # This file is part of Pwman3.
  3. #
  4. # Pwman3 is free software; you can redistribute it and/or modify
  5. # it under the terms of the GNU General Public License, version 2
  6. # as published by the Free Software Foundation;
  7. #
  8. # Pwman3 is distributed in the hope that it will be useful,
  9. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. # GNU General Public License for more details.
  12. #
  13. # You should have received a copy of the GNU General Public License
  14. # along with Pwman3; if not, write to the Free Software
  15. # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
  16. #============================================================================
  17. # Copyright (C) 2012 Oz Nahum <nahumoz@gmail.com>
  18. #============================================================================
  19. # Copyright (C) 2006 Ivan Kelly <ivan@ivankelly.net>
  20. #============================================================================
  21. """
  22. Define the CLI interface for pwman3 and the helper functions
  23. """
  24. import pwman
  25. import pwman.exchange.importer as importer
  26. import pwman.exchange.exporter as exporter
  27. import pwman.util.generator as generator
  28. from pwman.data.nodes import Node
  29. from pwman.data.tags import Tag
  30. from pwman.util.crypto import CryptoEngine
  31. #, CryptoBadKeyException, \
  32. # CryptoPasswordMismatchException
  33. from pwman.util.callback import Callback
  34. import pwman.util.config as config
  35. import re
  36. import sys
  37. import os
  38. import struct
  39. import getpass
  40. import cmd
  41. #import traceback
  42. import time
  43. import select as uselect
  44. import subprocess as sp
  45. import ast
  46. if sys.platform != 'win32':
  47. import tty
  48. import termios
  49. import fcntl
  50. try:
  51. import readline
  52. _readline_available = True
  53. except ImportError, e:
  54. _readline_available = False
  55. class CLICallback(Callback):
  56. def getinput(self, question):
  57. return raw_input(question)
  58. def getsecret(self, question):
  59. return getpass.getpass(question + ":")
  60. class ANSI(object):
  61. Reset = 0
  62. Bold = 1
  63. Underscore = 2
  64. Black = 30
  65. Red = 31
  66. Green = 32
  67. Yellow = 33
  68. Blue = 34
  69. Magenta = 35
  70. Cyan = 36
  71. White = 37
  72. class PwmanCli(cmd.Cmd):
  73. def error(self, exception):
  74. if (isinstance(exception, KeyboardInterrupt)):
  75. print
  76. else:
  77. # traceback.print_exc()
  78. print "Error: %s " % (exception)
  79. def do_EOF(self, args):
  80. return self.do_exit(args)
  81. def do_exit(self, args):
  82. print
  83. #try:
  84. # print "goodbye"
  85. self._db.close()
  86. #except DatabaseException, e:
  87. # self.error(e)
  88. return True
  89. def get_ids(self, args):
  90. ids = []
  91. rex = re.compile(r"^(\d+)-(\d+)$")
  92. idstrs = args.split()
  93. for i in idstrs:
  94. m = rex.match(i)
  95. if m == None:
  96. try:
  97. ids.append(int(i))
  98. except ValueError:
  99. self._db.clearfilter()
  100. self._db.filter([Tag(i)])
  101. ids += self._db.listnodes()
  102. else:
  103. ids += range(int(m.group(1)),
  104. int(m.group(2))+1)
  105. return ids
  106. def get_filesystem_path(self, default=""):
  107. return getinput("Enter filename: ", default)
  108. def get_username(self, default=""):
  109. return getinput("Username: ", default)
  110. def get_password(self, numerics=False,leetify=False):
  111. # TODO: add key word symbols = False
  112. password = getpassword("Password (Blank to generate): ", _defaultwidth, \
  113. False)
  114. if len(password) == 0:
  115. length = getinput("Password length (default 7): ", "7")
  116. length = int(length)
  117. numerics = config.get_value("Generator", "numerics") == 'true'
  118. leetify = config.get_value("Generator", "leetify") == 'true'
  119. (password, dumpme) = generator.generate_password(length, length, \
  120. True, leetify, numerics)
  121. print "New password: %s" % (password)
  122. return password
  123. else:
  124. return password
  125. def get_url(self, default=""):
  126. return getinput("Url: ", default)
  127. def get_notes(self, default=""):
  128. return getinput("Notes: ", default)
  129. def get_tags(self, default="tag"):
  130. defaultstr = ''
  131. if len(default) > 0:
  132. for t in default:
  133. defaultstr += "%s " % (t.get_name())
  134. else:
  135. tags = self._db.currenttags()
  136. for t in tags:
  137. defaultstr += "%s " % (t.get_name())
  138. strings = []
  139. tags = self._db.listtags(True)
  140. for t in tags:
  141. strings.append(t.get_name())
  142. def complete(text, state):
  143. count = 0
  144. for s in strings:
  145. if s.startswith(text):
  146. if count == state:
  147. return s
  148. else:
  149. count += 1
  150. taglist = getinput("Tags: ", defaultstr, complete)
  151. tagstrings = taglist.split()
  152. tags = []
  153. for tn in tagstrings:
  154. tags.append(Tag(tn))
  155. return tags
  156. def print_node(self, node):
  157. width = str(_defaultwidth)
  158. print "Node %d." % (node.get_id())
  159. print ("%"+width+"s %s") % (typeset("Username:", ANSI.Red),
  160. node.get_username())
  161. print ("%"+width+"s %s") % (typeset("Password:", ANSI.Red),
  162. node.get_password())
  163. print ("%"+width+"s %s") % (typeset("Url:", ANSI.Red),
  164. node.get_url())
  165. print ("%"+width+"s %s") % (typeset("Notes:", ANSI.Red),
  166. node.get_notes())
  167. print typeset("Tags: ", ANSI.Red),
  168. for t in node.get_tags():
  169. print " %s " % t.get_name(),
  170. print
  171. def heardEnter():
  172. i, o, e = uselect.select([sys.stdin], [], [], 0.0001)
  173. for s in i:
  174. if s == sys.stdin:
  175. sys.stdin.readline()
  176. return True
  177. return False
  178. def heardEnterWin():
  179. import msvcrt
  180. c = msvcrt.kbhit()
  181. if c == 1:
  182. ret = msvcrt.getch()
  183. if ret is not None:
  184. return True
  185. return False
  186. def waituntil_enter(somepredicate, timeout, period=0.25):
  187. mustend = time.time() + timeout
  188. while time.time() < mustend:
  189. cond = somepredicate()
  190. if cond:
  191. break
  192. time.sleep(period)
  193. self.do_cls('')
  194. flushtimeout = int(config.get_value("Global", "cls_timeout"))
  195. if flushtimeout > 0:
  196. if sys.platform != 'win32':
  197. print "Type Enter to flush screen (autoflash in 5 sec.)"
  198. waituntil_enter(heardEnter, flushtimeout)
  199. else:
  200. print "Press any key to flush screen (autoflash in 5 sec.)"
  201. waituntil_enter(heardEnterWin, flushtimeout)
  202. def do_tags(self, arg):
  203. tags = self._db.listtags()
  204. if len(tags) > 0:
  205. tags[0].get_name() # hack to get password request before output
  206. print "Tags: ",
  207. if len(tags) == 0:
  208. print "None",
  209. for t in tags:
  210. print "%s " % (t.get_name()),
  211. print
  212. def complete_filter(self, text, line, begidx, endidx):
  213. strings = []
  214. enc = CryptoEngine.get()
  215. if not enc.alive():
  216. return strings
  217. tags = self._db.listtags()
  218. for t in tags:
  219. name = t.get_name()
  220. if name.startswith(text):
  221. strings.append(t.get_name())
  222. return strings
  223. def do_filter(self, args):
  224. tagstrings = args.split()
  225. try:
  226. tags = []
  227. for ts in tagstrings:
  228. tags.append(Tag(ts))
  229. self._db.filter(tags)
  230. tags = self._db.currenttags()
  231. print "Current tags: ",
  232. if len(tags) == 0:
  233. print "None",
  234. for t in tags:
  235. print "%s " % (t.get_name()),
  236. print
  237. except Exception, e:
  238. self.error(e)
  239. def do_clear(self, args):
  240. try:
  241. self._db.clearfilter()
  242. except Exception, e:
  243. self.error(e)
  244. def do_e(self, arg):
  245. self.do_edit(arg)
  246. def do_edit(self, arg):
  247. ids = self.get_ids(arg)
  248. for i in ids:
  249. try:
  250. i = int(i)
  251. node = self._db.getnodes([i])[0]
  252. menu = CliMenu()
  253. print "Editing node %d." % (i)
  254. menu.add(CliMenuItem("Username", self.get_username,
  255. node.get_username,
  256. node.set_username))
  257. menu.add(CliMenuItem("Password", self.get_password,
  258. node.get_password,
  259. node.set_password))
  260. menu.add(CliMenuItem("Url", self.get_url,
  261. node.get_url,
  262. node.set_url))
  263. menu.add(CliMenuItem("Notes", self.get_notes,
  264. node.get_notes,
  265. node.set_notes))
  266. menu.add(CliMenuItem("Tags", self.get_tags,
  267. node.get_tags,
  268. node.set_tags))
  269. menu.run()
  270. self._db.editnode(i, node)
  271. except Exception, e:
  272. self.error(e)
  273. def do_import(self, arg):
  274. try:
  275. args = arg.split()
  276. if len(args) == 0:
  277. types = importer.Importer.types()
  278. intype = select("Select filetype:", types)
  279. imp = importer.Importer.get(intype)
  280. infile = getinput("Select file:")
  281. imp.import_data(self._db, infile)
  282. else:
  283. for i in args:
  284. types = importer.Importer.types()
  285. intype = select("Select filetype:", types)
  286. imp = importer.Importer.get(intype)
  287. imp.import_data(self._db, i)
  288. except Exception, e:
  289. self.error(e)
  290. def do_export(self, arg):
  291. try:
  292. nodes = self.get_ids(arg)
  293. types = exporter.Exporter.types()
  294. ftype = select("Select filetype:", types)
  295. exp = exporter.Exporter.get(ftype)
  296. out_file = getinput("Select output file:")
  297. if len(nodes) > 0:
  298. b = getyesno("Export nodes %s?" % (nodes), True)
  299. if not b:
  300. return
  301. exp.export_data(self._db, out_file, nodes)
  302. else:
  303. nodes = self._db.listnodes()
  304. tags = self._db.currenttags()
  305. tagstr = ""
  306. if len(tags) > 0:
  307. tagstr = " for "
  308. for t in tags:
  309. tagstr += "'%s' " % (t.get_name())
  310. b = getyesno("Export all nodes%s?" % (tagstr), True)
  311. if not b:
  312. return
  313. exp.export_data(self._db, out_file, nodes)
  314. print "Data exported."
  315. except Exception, e:
  316. self.error(e)
  317. def do_h(self, arg):
  318. self.do_help(arg)
  319. def do_n(self, arg):
  320. self.do_new(arg)
  321. def do_new(self, args):
  322. """
  323. can override default config settings the following way:
  324. Pwman3 0.2.1 (c) visit: http://github.com/pwman3/pwman3
  325. pwman> n {'leetify':False, 'numerics':True}
  326. Password (Blank to generate):
  327. """
  328. try:
  329. username = self.get_username()
  330. if args:
  331. args = ast.literal_eval(args)
  332. password = self.get_password(**args)
  333. else:
  334. password = self.get_password()
  335. url = self.get_url()
  336. notes = self.get_notes()
  337. node = Node(username, password, url, notes)
  338. tags = self.get_tags()
  339. node.set_tags(tags)
  340. self._db.addnodes([node])
  341. print "Password ID: %d" % (node.get_id())
  342. except Exception, e:
  343. self.error(e)
  344. def do_p(self, arg):
  345. self.do_print(arg)
  346. def do_print(self, arg):
  347. for i in self.get_ids(arg):
  348. try:
  349. node = self._db.getnodes([i])
  350. self.print_node(node[0])
  351. except Exception, e:
  352. self.error(e)
  353. def do_rm(self, arg):
  354. self.do_delete(arg)
  355. def do_delete(self, arg):
  356. ids = self.get_ids(arg)
  357. try:
  358. nodes = self._db.getnodes(ids)
  359. for n in nodes:
  360. b = getyesno("Are you sure you want to delete '%s@%s'?"
  361. % (n.get_username(), n.get_url()), False)
  362. if b == True:
  363. self._db.removenodes([n])
  364. print "%s@%s deleted" % (n.get_username(), n.get_url())
  365. except Exception, e:
  366. self.error(e)
  367. def do_l(self, args):
  368. self.do_list(args)
  369. def do_ls(self, args):
  370. self.do_list(args)
  371. def do_list(self, args):
  372. if len(args.split()) > 0:
  373. self.do_clear('')
  374. self.do_filter(args)
  375. try:
  376. if sys.platform != 'win32':
  377. rows, cols = gettermsize()
  378. else:
  379. rows, cols = 18, 80 # fix this !
  380. nodeids = self._db.listnodes()
  381. nodes = self._db.getnodes(nodeids)
  382. cols -= 8
  383. i = 0
  384. for n in nodes:
  385. tags = n.get_tags()
  386. tagstring = ''
  387. first = True
  388. for t in tags:
  389. if not first:
  390. tagstring += ", "
  391. else:
  392. first = False
  393. tagstring += t.get_name()
  394. name = "%s@%s" % (n.get_username(), n.get_url())
  395. name_len = cols * 2 / 3
  396. tagstring_len = cols / 3
  397. if len(name) > name_len:
  398. name = name[:name_len-3] + "..."
  399. if len(tagstring) > tagstring_len:
  400. tagstring = tagstring[:tagstring_len-3] + "..."
  401. fmt = "%%5d. %%-%ds %%-%ds" % (name_len, tagstring_len)
  402. print typeset(fmt % (n.get_id(), name, tagstring),
  403. ANSI.Yellow, False)
  404. i += 1
  405. if i > rows-2:
  406. i = 0
  407. c = getonechar("Press <Space> for more, or 'Q' to cancel")
  408. if c == 'q':
  409. break
  410. except Exception, e:
  411. self.error(e)
  412. def do_forget(self, args):
  413. try:
  414. enc = CryptoEngine.get()
  415. enc.forget()
  416. except Exception, e:
  417. self.error(e)
  418. def do_passwd(self, args):
  419. try:
  420. self._db.changepassword()
  421. except Exception, e:
  422. self.error(e)
  423. def do_set(self, args):
  424. argstrs = args.split()
  425. try:
  426. if len(argstrs) == 0:
  427. conf = config.get_conf()
  428. for s in conf.keys():
  429. for n in conf[s].keys():
  430. print "%s.%s = %s" % (s, n, conf[s][n])
  431. elif len(argstrs) == 1:
  432. r = re.compile("(.+)\.(.+)")
  433. m = r.match(argstrs[0])
  434. if m is None or len(m.groups()) != 2:
  435. print "Invalid option format"
  436. self.help_set()
  437. return
  438. print "%s.%s = %s" % (m.group(1), m.group(2),
  439. config.get_value(m.group(1), m.group(2)))
  440. elif len(argstrs) == 2:
  441. r = re.compile("(.+)\.(.+)")
  442. m = r.match(argstrs[0])
  443. if m is None or len(m.groups()) != 2:
  444. print "Invalid option format"
  445. self.help_set()
  446. return
  447. config.set_value(m.group(1), m.group(2), argstrs[1])
  448. else:
  449. self.help_set()
  450. except Exception, e:
  451. self.error(e)
  452. def do_save(self, args):
  453. argstrs = args.split()
  454. try:
  455. if len(argstrs) > 0:
  456. config.save(argstrs[0])
  457. else:
  458. config.save()
  459. print "Config saved."
  460. except Exception, e:
  461. self.error(e)
  462. def do_cls(self, args):
  463. os.system('clear')
  464. def do_copy(self, args):
  465. if self.hasxsel:
  466. ids = self.get_ids(args)
  467. if len(ids) > 1:
  468. print "Can copy only 1 password at a time..."
  469. return None
  470. try:
  471. node = self._db.getnodes(ids)
  472. text_to_clipboards(node[0].get_password())
  473. print "copied password for %s@%s clipboard... erasing in 10 sec..." % \
  474. (node[0].get_username(), node[0].get_url())
  475. time.sleep(10)
  476. text_to_clipboards("")
  477. except Exception, e:
  478. self.error(e)
  479. else:
  480. print "Can't copy to clipboard, no xsel found in the system!"
  481. def do_cp(self, args):
  482. self.do_copy(args)
  483. def do_open(self, args):
  484. ids = self.get_ids(args)
  485. if len(ids) > 1:
  486. print "Can open only 1 link at a time ..."
  487. return None
  488. try:
  489. node = self._db.getnodes(ids)
  490. url = node[0].get_url()
  491. open_url(url)
  492. except Exception, e:
  493. self.error(e)
  494. def do_o(self, args):
  495. self.do_open(args)
  496. ##
  497. ## Help functions
  498. ##
  499. def usage(self, string):
  500. print "Usage: %s" % (string)
  501. def help_open(self):
  502. self.usage("open <ID>")
  503. print "Launch default browser with 'xdg-open url',\n\
  504. the url must contain http:// or https://."
  505. def help_o(self):
  506. self.help_open()
  507. def help_copy(self):
  508. self.usage("copy <ID>")
  509. print "Copy password to X clipboard (xsel required)"
  510. def help_cp(self):
  511. self.help_copy()
  512. def help_cls(self):
  513. self.usage("cls")
  514. print "Clear the Screen from information."
  515. def help_list(self):
  516. self.usage("list <tag> ...")
  517. print "List nodes that match current or specified filter. ls is an alias."
  518. def help_EOF(self):
  519. self.help_exit()
  520. def help_delete(self):
  521. self.usage("delete <ID|tag> ...")
  522. print "Deletes nodes. rm is an alias."
  523. self._mult_id_help()
  524. def help_h(self):
  525. self.help_help()
  526. def help_help(self):
  527. self.usage("help [topic]")
  528. print "Prints a help message for a command."
  529. def help_e(self):
  530. self.help_edit()
  531. def help_n(self):
  532. self.help_new()
  533. def help_p(self):
  534. self.help_print()
  535. def help_l(self):
  536. self.help_list()
  537. def help_edit(self):
  538. self.usage("edit <ID|tag> ... ")
  539. print "Edits a nodes."
  540. self._mult_id_help()
  541. def help_import(self):
  542. self.usage("import [filename] ...")
  543. print "Imports a nodes from a file."
  544. def help_export(self):
  545. self.usage("export <ID|tag> ... ")
  546. print "Exports a list of ids to an external format. If no IDs or tags are specified, then all nodes under the current filter are exported."
  547. self._mult_id_help()
  548. def help_new(self):
  549. self.usage("new")
  550. print """Creates a new node.,
  551. You can override default config settings the following way:
  552. pwman> n {'leetify':False, 'numerics':True}"""
  553. def help_rm(self):
  554. self.help_delete()
  555. def help_print(self):
  556. self.usage("print <ID|tag> ...")
  557. print "Displays a node. ",
  558. self._mult_id_help()
  559. def _mult_id_help(self):
  560. print "Multiple ids and nodes can be specified, separated by a space. A range of ids can be specified in the format n-N. e.g. '10-20' would specify all nodes having ids from 10 to 20 inclusive. Tags are considered one-by-one. e.g. 'foo 2 bar' would yield to all nodes with tag 'foo', node 2 and all nodes with tag 'bar'."
  561. def help_exit(self):
  562. self.usage("exit")
  563. print "Exits the application."
  564. def help_save(self):
  565. self.usage("save [filename]")
  566. print "Saves the current configuration to [filename]. If no filename is given, the configuration is saved to the file from which the initial configuration was loaded."
  567. def help_set(self):
  568. self.usage("set [configoption] [value]")
  569. print "Sets a configuration option. If no value is specified, the current value for [configoption] is output. If neither [configoption] nor [value] are specified, the whole current configuration is output. [configoption] must be of the format <section>.<option>"
  570. def help_passwd(self):
  571. self.usage("passwd")
  572. print "Changes the password on the database. "
  573. def help_forget(self):
  574. self.usage("forget")
  575. print "Forgets the database password. Your password will need to be reentered before accessing the database again."
  576. def help_clear(self):
  577. self.usage("clear")
  578. print "Clears the filter criteria. "
  579. def help_filter(self):
  580. self.usage("filter <tag> ...")
  581. print "Filters nodes on tag. Arguments can be zero or more tags. Displays current tags if called without arguments."
  582. def help_tags(self):
  583. self.usage("tags")
  584. print "Displays all tags in used in the database."
  585. def postloop(self):
  586. try:
  587. readline.write_history_file(self._historyfile)
  588. except Exception:
  589. pass
  590. def __init__(self, db, hasxsel):
  591. """
  592. initialize CLI interface, set up the DB
  593. connecion, see if we have xsel ...
  594. """
  595. cmd.Cmd.__init__(self)
  596. self.intro = "%s %s (c) visit: %s" % (pwman.appname, pwman.version,
  597. pwman.website)
  598. self._historyfile = config.get_value("Readline", "history")
  599. self.hasxsel = hasxsel
  600. try:
  601. enc = CryptoEngine.get()
  602. enc.set_callback(CLICallback())
  603. self._db = db
  604. self._db.open()
  605. except Exception, e:
  606. self.error(e)
  607. sys.exit(1)
  608. try:
  609. readline.read_history_file(self._historyfile)
  610. except IOError, e:
  611. pass
  612. self.prompt = "pwman> "
  613. class PwmanCliMac(PwmanCli):
  614. """
  615. inherit from PwmanCli, override the right functions...
  616. """
  617. def do_copy(self, args):
  618. ids = self.get_ids(args)
  619. if len(ids) > 1:
  620. print "Can only 1 password at a time..."
  621. try:
  622. node = self._db.getnodes(ids)
  623. node[0].get_password()
  624. text_to_mcclipboard(node[0].get_password())
  625. print "copied password for %s@%s clipboard... erasing in 10 sec..." % \
  626. (node[0].get_username(), node[0].get_url())
  627. time.sleep(10)
  628. text_to_clipboards("")
  629. except Exception, e:
  630. self.error(e)
  631. def do_cp(self, args):
  632. self.do_copy(args)
  633. def do_open(self, args):
  634. ids = self.get_ids(args)
  635. if len(ids) > 1:
  636. print "Can open only 1 link at a time ..."
  637. return None
  638. try:
  639. node = self._db.getnodes(ids)
  640. url = node[0].get_url()
  641. open_url(url, macosx=True)
  642. except Exception, e:
  643. self.error(e)
  644. def do_o(self, args):
  645. self.do_open(args)
  646. ##
  647. ## Help functions
  648. ##
  649. def help_open(self):
  650. self.usage("open <ID>")
  651. print "Launch default browser with 'open url',\n\
  652. the url must contain http:// or https://."
  653. def help_o(self):
  654. self.help_open()
  655. def help_copy(self):
  656. self.usage("copy <ID>")
  657. print "Copy password to Cocoa clipboard using pbcopy)"
  658. def help_cp(self):
  659. self.help_copy()
  660. _defaultwidth = 10
  661. def getonechar(question, width=_defaultwidth):
  662. question = "%s " % (question)
  663. print question.ljust(width),
  664. sys.stdout.flush()
  665. fd = sys.stdin.fileno()
  666. tty_mode = tty.tcgetattr(fd)
  667. tty.setcbreak(fd)
  668. try:
  669. ch = os.read(fd, 1)
  670. finally:
  671. tty.tcsetattr(fd, tty.TCSAFLUSH, tty_mode)
  672. print ch
  673. return ch
  674. def getyesno(question, defaultyes=False, width=_defaultwidth):
  675. if (defaultyes):
  676. default = "[Y/n]"
  677. else:
  678. default = "[y/N]"
  679. ch = getonechar("%s %s" % (question, default), width)
  680. if (ch == '\n'):
  681. if (defaultyes):
  682. return True
  683. else:
  684. return False
  685. elif (ch == 'y' or ch == 'Y'):
  686. return True
  687. elif (ch == 'n' or ch == 'N'):
  688. return False
  689. else:
  690. return getyesno(question, defaultyes, width)
  691. def gettermsize():
  692. s = struct.pack("HHHH", 0, 0, 0, 0)
  693. f = sys.stdout.fileno()
  694. x = fcntl.ioctl(f, termios.TIOCGWINSZ, s)
  695. rows, cols, width, height = struct.unpack("HHHH", x)
  696. return rows, cols
  697. def getinput(question, default="", completer=None, width=_defaultwidth):
  698. if (not _readline_available):
  699. return raw_input(question.ljust(width))
  700. else:
  701. def defaulter():
  702. """define default behavior startup"""
  703. readline.insert_text(default)
  704. readline.set_startup_hook(defaulter)
  705. oldcompleter = readline.get_completer()
  706. readline.set_completer(completer)
  707. x = raw_input(question.ljust(width))
  708. readline.set_completer(oldcompleter)
  709. readline.set_startup_hook()
  710. return x
  711. def getpassword(question, width=_defaultwidth, echo=False):
  712. if echo:
  713. print question.ljust(width),
  714. return sys.stdin.readline().rstrip()
  715. else:
  716. while 1:
  717. a1 = getpass.getpass(question.ljust(width))
  718. if len(a1) == 0:
  719. return a1
  720. a2 = getpass.getpass("[Repeat] %s" % (question.ljust(width)))
  721. if a1 == a2:
  722. return a1
  723. else:
  724. print "Passwords don't match. Try again."
  725. def typeset(text, color, bold=False, underline=False):
  726. if not config.get_value("Global", "colors") == 'yes':
  727. return text
  728. if (bold):
  729. bold = "%d ;" % (ANSI.Bold)
  730. else:
  731. bold = ""
  732. if (underline):
  733. underline = "%d;" % (ANSI.Underscore)
  734. else:
  735. underline = ""
  736. return "\033[%s%s%sm%s\033[%sm" % (bold, underline, color,
  737. text, ANSI.Reset)
  738. def select(question, possible):
  739. for i in range(0, len(possible)):
  740. print ("%d - %-"+str(_defaultwidth)+"s") % (i+1, possible[i])
  741. while 1:
  742. uinput = getonechar(question)
  743. if uinput.isdigit() and int(uinput) in range(1, len(possible)+1):
  744. return possible[int(uinput)-1]
  745. def text_to_clipboards(text):
  746. """
  747. copy text to clipboard
  748. credit:
  749. https://pythonadventures.wordpress.com/tag/xclip/
  750. """
  751. # "primary":
  752. try:
  753. xsel_proc = sp.Popen(['xsel', '-pi'], stdin=sp.PIPE)
  754. xsel_proc.communicate(text)
  755. # "clipboard":
  756. xsel_proc = sp.Popen(['xsel', '-bi'], stdin=sp.PIPE)
  757. xsel_proc.communicate(text)
  758. except OSError, e:
  759. print e, "\nExecuting xsel failed, is it installed ?\n \
  760. please check your configuration file ... "
  761. def text_to_mcclipboard(text):
  762. """
  763. copy text to mac os x clip board
  764. credit:
  765. https://pythonadventures.wordpress.com/tag/xclip/
  766. """
  767. # "primary":
  768. try:
  769. pbcopy_proc = sp.Popen(['pbcopy'], stdin=sp.PIPE)
  770. pbcopy_proc.communicate(text)
  771. except OSError, e:
  772. print e, "\nExecuting pbcoy failed..."
  773. def open_url(link, macosx=False):
  774. """
  775. launch xdg-open or open in MacOSX with url
  776. """
  777. uopen = "xdg-open"
  778. if macosx:
  779. uopen = "open"
  780. try:
  781. sp.Popen([uopen, link], stdin=sp.PIPE)
  782. except OSError, e:
  783. print "Executing open_url failed with:\n", e
  784. class CliMenu(object):
  785. def __init__(self):
  786. self.items = []
  787. def add(self, item):
  788. if (isinstance(item, CliMenuItem)):
  789. self.items.append(item)
  790. else:
  791. print item.__class__
  792. def run(self):
  793. while True:
  794. i = 0
  795. for x in self.items:
  796. i = i + 1
  797. current = x.getter()
  798. currentstr = ''
  799. if type(current) == list:
  800. for c in current:
  801. currentstr += ("%s " % (c))
  802. else:
  803. currentstr = current
  804. print ("%d - %-"+str(_defaultwidth)+"s %s") % (i, x.name+":",
  805. currentstr)
  806. print "%c - Finish editing" % ('X')
  807. option = getonechar("Enter your choice:")
  808. try:
  809. # substract 1 because array subscripts start at 1
  810. selection = int(option) - 1
  811. value = self.items[selection].editor(self.items[selection].getter())
  812. self.items[selection].setter(value)
  813. except (ValueError, IndexError):
  814. if (option.upper() == 'X'):
  815. break
  816. print "Invalid selection"
  817. class CliMenuItem(object):
  818. def __init__(self, name, editor, getter, setter):
  819. self.name = name
  820. self.editor = editor
  821. self.getter = getter
  822. self.setter = setter