base.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349
  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) 2013 Oz Nahum <nahumoz@gmail.com>
  18. # ============================================================================
  19. # pylint: disable=I0011
  20. """
  21. Define the base CLI interface for pwman3
  22. """
  23. from __future__ import print_function
  24. from pwman.util.crypto_engine import zerome
  25. import re
  26. import sys
  27. import time
  28. import select as uselect
  29. from pwman.ui import tools
  30. from pwman.ui.tools import CliMenuItem
  31. from colorama import Fore
  32. from pwman.ui.tools import CMDLoop
  33. if sys.version_info.major > 2: # pragma: no cover
  34. raw_input = input
  35. class HelpUIMixin(object): # pragma: no cover
  36. """
  37. this class holds all the UI help functionality.
  38. in PwmanCliNew. The later inherits from this class
  39. and allows it to print help messages to the console.
  40. """
  41. def usage(self, string):
  42. print ("Usage: %s" % (string))
  43. def help_open(self):
  44. self.usage("open <ID>")
  45. print ("Launch default browser with 'xdg-open url',\n",
  46. "the url must contain http:// or https://.")
  47. def help_o(self):
  48. self.help_open()
  49. def help_copy(self):
  50. self.usage("copy <ID>")
  51. print ("Copy password to X clipboard (xsel required)")
  52. def help_cp(self):
  53. self.help_copy()
  54. def help_cls(self):
  55. self.usage("cls")
  56. print ("Clear the Screen from information.")
  57. def help_list(self):
  58. self.usage("list <tag> ...")
  59. print ("List nodes that match current or specified filter.",
  60. " ls is an alias.")
  61. def help_EOF(self):
  62. self.help_exit()
  63. def help_delete(self):
  64. self.usage("delete <ID|tag> ...")
  65. print ("Deletes nodes. rm is an alias.")
  66. self._mult_id_help()
  67. def help_h(self):
  68. self.help_help()
  69. def help_help(self):
  70. self.usage("help [topic]")
  71. print ("Prints a help message for a command.")
  72. def help_e(self):
  73. self.help_edit()
  74. def help_n(self):
  75. self.help_new()
  76. def help_p(self):
  77. self.help_print()
  78. def help_l(self):
  79. self.help_list()
  80. def help_edit(self):
  81. self.usage("edit <ID|tag> ... ")
  82. print ("Edits a nodes.")
  83. def help_import(self):
  84. self.usage("import [filename] ...")
  85. print ("Not implemented...")
  86. def help_export(self):
  87. self.usage("export [{'filename': 'foo.csv', 'delimiter':'|'}] ")
  88. print("All nodes under the current filter are exported.")
  89. def help_new(self):
  90. self.usage("new")
  91. print ("Creates a new node.,",
  92. "You can override default config settings the following way:\n",
  93. "pwman> n {'leetify':False, 'numerics':True}")
  94. def help_rm(self):
  95. self.help_delete()
  96. def help_print(self):
  97. self.usage("print <ID|tag> ...")
  98. print ("Displays a node. ")
  99. self._mult_id_help()
  100. def _mult_id_help(self):
  101. print("Multiple ids and nodes can be specified, separated by a space.",
  102. " A range of ids can be specified in the format n-N. e.g. ",
  103. " '10-20' would specify all nodes having ids from 10 to 20 ",
  104. " inclusive. Tags are considered one-by-one. e.g. 'foo 2 bar'",
  105. " would yield to all nodes with tag 'foo', node 2 and all ",
  106. " nodes with tag 'bar'.")
  107. def help_exit(self):
  108. self.usage("exit")
  109. print("Exits the application.")
  110. def help_passwd(self):
  111. self.usage("passwd")
  112. print("Changes the password on the database. ")
  113. def help_forget(self):
  114. self.usage("forget")
  115. print("Forgets the database password. Your password will need to ",
  116. "be reentered before accessing the database again.")
  117. def help_clear(self):
  118. self.usage("clear")
  119. print("Clears the filter criteria. ")
  120. def help_filter(self):
  121. self.usage("filter <tag> ...")
  122. print("Filters nodes on tag. Arguments can be zero or more tags. ",
  123. "Displays current tags if called without arguments.")
  124. def help_tags(self):
  125. self.usage("tags")
  126. print("Displays all tags in used in the database.")
  127. class BaseCommands(object):
  128. """
  129. Inherit from the old class, override
  130. all the methods related to tags, and
  131. newer Node format, so backward compatability is kept...
  132. Commands defined here, can have aliases definded in Aliases.
  133. You can define the aliases here too, but it makes
  134. the class code really long and unclear.
  135. """
  136. def do_edit(self, arg, menu=None):
  137. ids = self.get_ids(arg)
  138. for i in ids:
  139. try:
  140. i = int(i)
  141. node = self._db.getnodes([i])[0]
  142. if not menu:
  143. menu = CMDLoop()
  144. print ("Editing node %d." % (i))
  145. menu.add(CliMenuItem("Username", self.get_username,
  146. node.username,
  147. node.username))
  148. menu.add(CliMenuItem("Password", self.get_password,
  149. node.password,
  150. node.password))
  151. menu.add(CliMenuItem("Url", self.get_url,
  152. node.url,
  153. node.url))
  154. menunotes = CliMenuItem("Notes", self.get_notes,
  155. node.notes,
  156. node.notes)
  157. menu.add(menunotes)
  158. menu.add(CliMenuItem("Tags", self.get_tags,
  159. node.tags,
  160. node.tags))
  161. menu.run(node)
  162. self._db.editnode(i, node)
  163. # when done with node erase it
  164. zerome(node._password)
  165. except Exception as e:
  166. self.error(e)
  167. def print_node(self, node):
  168. width = str(tools._defaultwidth)
  169. print ("Node %d." % (node._id))
  170. print (("%" + width + "s %s") % (tools.typeset("Username:", Fore.RED),
  171. node.username))
  172. print (("%" + width + "s %s") % (tools.typeset("Password:", Fore.RED),
  173. node.password))
  174. print (("%" + width + "s %s") % (tools.typeset("Url:", Fore.RED),
  175. node.url))
  176. print (("%" + width + "s %s") % (tools.typeset("Notes:", Fore.RED),
  177. node.notes))
  178. print (tools.typeset("Tags: ", Fore.RED)),
  179. for t in node.tags:
  180. print (" %s " % t)
  181. print()
  182. def heardEnter():
  183. i, o, e = uselect.select([sys.stdin], [], [], 0.0001)
  184. for s in i:
  185. if s == sys.stdin:
  186. sys.stdin.readline()
  187. return True
  188. return False
  189. def waituntil_enter(somepredicate, timeout, period=0.25):
  190. mustend = time.time() + timeout
  191. while time.time() < mustend:
  192. cond = somepredicate()
  193. if cond:
  194. break
  195. time.sleep(period)
  196. self.do_cls('')
  197. try:
  198. flushtimeout = int(self.config.get_value("Global", "cls_timeout"))
  199. except ValueError:
  200. flushtimeout = 10
  201. if flushtimeout > 0:
  202. print ("Type Enter to flush screen (autoflash in "
  203. "%d sec.)" % flushtimeout)
  204. waituntil_enter(heardEnter, flushtimeout)
  205. def do_passwd(self, args):
  206. raise Exception("Not Implemented ...")
  207. #try:
  208. # key = self._db.changepassword()
  209. # self._db.savekey(key)
  210. #except Exception as e:
  211. # self.error(e)
  212. def do_print(self, arg):
  213. for i in self.get_ids(arg):
  214. try:
  215. node = self._db.getnodes([i])
  216. self.print_node(node[0])
  217. # when done with node erase it
  218. zerome(node[0]._password)
  219. except Exception as e:
  220. self.error(e)
  221. def do_delete(self, arg):
  222. ids = self.get_ids(arg)
  223. try:
  224. nodes = self._db.getnodes(ids)
  225. for n in nodes:
  226. ans = ''
  227. while True:
  228. ans = tools.getinput(("Are you sure you want to"
  229. " delete '%s@%s' ([y/N])?"
  230. ) % (n.username, n.url)
  231. ).lower().strip('\n')
  232. if ans == '' or ans == 'y' or ans == 'n':
  233. break
  234. if ans == 'y':
  235. self._db.removenodes([n])
  236. print ("%s@%s deleted" % (n.username, n.url))
  237. except Exception as e:
  238. self.error(e)
  239. def get_ids(self, args):
  240. """
  241. Command can get a single ID or
  242. a range of IDs, with begin-end.
  243. e.g. 1-3 , will get 1 to 3.
  244. """
  245. # TODO: add documentation and testing
  246. ids = []
  247. rex = re.compile("^(?P<begin>\d+)(?:-(?P<end>\d+))?$")
  248. rex = rex.match(args)
  249. if hasattr(rex, 'groupdict'):
  250. try:
  251. begin = int(rex.groupdict()['begin'])
  252. end = int(rex.groupdict()['end'])
  253. if not end > begin:
  254. print("Start node should be smaller than end node")
  255. return ids
  256. ids += range(begin, end+1)
  257. return ids
  258. except TypeError:
  259. ids.append(int(begin))
  260. else:
  261. print("Could not understand your input...")
  262. return ids
  263. # def get_password(self, argsgiven, numerics=False, leetify=False,
  264. # symbols=False, special_signs=False,
  265. # reader=getpass.getpass, length=None):
  266. # return tools.getpassword("Password (Blank to generate): ",
  267. # reader=reader, length=length,
  268. # leetify=leetify,
  269. # special_signs=special_signs, symbols=symbols,
  270. # numerics=numerics, config=self.config)
  271. class AliasesMixin(object): # pragma: no cover
  272. """
  273. Define all the alias you want here...
  274. """
  275. def do_cp(self, args):
  276. self.do_copy(args)
  277. def do_e(self, arg):
  278. self.do_edit(arg)
  279. def do_EOF(self, args):
  280. return self.do_exit(args)
  281. def do_l(self, args):
  282. self.do_list(args)
  283. def do_ls(self, args):
  284. self.do_list(args)
  285. def do_p(self, arg):
  286. self.do_print(arg)
  287. def do_rm(self, arg):
  288. self.do_delete(arg)
  289. def do_o(self, args):
  290. self.do_open(args)
  291. def do_h(self, arg):
  292. self.do_help(arg)
  293. def do_n(self, arg):
  294. self.do_new(arg)