tools.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382
  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. """
  20. Define the CLI interface for pwman3 and the helper functions
  21. """
  22. from __future__ import print_function
  23. from pwman.util.callback import Callback
  24. import pwman.util.config as config
  25. import subprocess as sp
  26. import getpass
  27. import sys
  28. import struct
  29. import os
  30. import colorama
  31. from pwman.data.tags import TagNew as Tag
  32. import pwman.util.generator as generator
  33. if sys.platform != 'win32':
  34. import termios
  35. import fcntl
  36. import tty
  37. import readline
  38. _readline_available = True
  39. else: # pragma: no cover
  40. try:
  41. import pyreadline as readline
  42. _readline_available = True
  43. except ImportError, e:
  44. _readline_available = False
  45. _defaultwidth = 10
  46. class ANSI(object):
  47. """
  48. ANSI Colors
  49. """
  50. Reset = 0
  51. Bold = 1
  52. Underscore = 2
  53. Black = 30
  54. Red = 31
  55. Green = 32
  56. Yellow = 33
  57. Blue = 34
  58. Magenta = 35
  59. Cyan = 36
  60. White = 37
  61. def typeset(text, color, bold=False, underline=False): # pragma: no cover
  62. """
  63. print colored strings using colorama
  64. """
  65. if not config.get_value("Global", "colors") == 'yes':
  66. return text
  67. if bold:
  68. text = colorama.Style.BRIGHT + text
  69. if underline and not 'win32' in sys.platform:
  70. text = ANSI.Underscore + text
  71. return color + text + colorama.Style.RESET_ALL
  72. def select(question, possible): # pragma: no cover
  73. """
  74. select input from user
  75. """
  76. for i in range(0, len(possible)):
  77. print ("%d - %-" + str(_defaultwidth) + "s") % (i + 1, possible[i])
  78. while 1:
  79. uinput = getonechar(question)
  80. if uinput.isdigit() and int(uinput) in range(1, len(possible) + 1):
  81. return possible[int(uinput) - 1]
  82. def text_to_clipboards(text): # pragma: no cover
  83. """
  84. copy text to clipboard
  85. credit:
  86. https://pythonadventures.wordpress.com/tag/xclip/
  87. """
  88. # "primary":
  89. try:
  90. xsel_proc = sp.Popen(['xsel', '-pi'], stdin=sp.PIPE)
  91. xsel_proc.communicate(text)
  92. # "clipboard":
  93. xsel_proc = sp.Popen(['xsel', '-bi'], stdin=sp.PIPE)
  94. xsel_proc.communicate(text)
  95. except OSError, e:
  96. print (e, "\nExecuting xsel failed, is it installed ?\n \
  97. please check your configuration file ... ")
  98. def text_to_mcclipboard(text): # pragma: no cover
  99. """
  100. copy text to mac os x clip board
  101. credit:
  102. https://pythonadventures.wordpress.com/tag/xclip/
  103. """
  104. # "primary":
  105. try:
  106. pbcopy_proc = sp.Popen(['pbcopy'], stdin=sp.PIPE)
  107. pbcopy_proc.communicate(text)
  108. except OSError, e:
  109. print (e, "\nExecuting pbcoy failed...")
  110. def open_url(link, macosx=False): # pragma: no cover
  111. """
  112. launch xdg-open or open in MacOSX with url
  113. """
  114. uopen = "xdg-open"
  115. if macosx:
  116. uopen = "open"
  117. try:
  118. sp.Popen([uopen, link], stdin=sp.PIPE)
  119. except OSError, e:
  120. print ("Executing open_url failed with:\n", e)
  121. def getpassword(question, argsgiven=None,
  122. width=_defaultwidth, echo=False,
  123. reader=getpass.getpass, numerics=False, leetify=False,
  124. symbols=False, special_signs=False, length=None): # pragma: no cover
  125. # TODO: getpassword should recieve a config insatce
  126. # and generate the policy according to it,
  127. # so that getpassword in cli would be simplified
  128. if argsgiven == 1 or length:
  129. while not length:
  130. try:
  131. length = getinput("Password length (default 7): ", default='7')
  132. length = int(length)
  133. except ValueError:
  134. print("please enter a proper integer")
  135. password, dumpme = generator.generate_password(length, length,
  136. True, leetify,
  137. numerics,
  138. special_signs)
  139. print ("New password: %s" % (password))
  140. return password
  141. # no args given
  142. while True:
  143. a1 = reader(question.ljust(width))
  144. if not a1:
  145. return getpassword('', argsgiven=1)
  146. a2 = reader("[Repeat] %s" % (question.ljust(width)))
  147. if a1 == a2:
  148. if leetify:
  149. return generator.leetify(a1)
  150. else:
  151. return a1
  152. else:
  153. print ("Passwords don't match. Try again.")
  154. def gettermsize(): # pragma: no cover
  155. s = struct.pack("HHHH", 0, 0, 0, 0)
  156. f = sys.stdout.fileno()
  157. x = fcntl.ioctl(f, termios.TIOCGWINSZ, s)
  158. rows, cols, width, height = struct.unpack("HHHH", x)
  159. return rows, cols
  160. def getinput(question, default="", reader=raw_input,
  161. completer =None, width=_defaultwidth): # pragma: no cover
  162. """
  163. http://stackoverflow.com/questions/2617057/\
  164. supply-inputs-to-python-unittests
  165. """
  166. if reader == raw_input:
  167. if not _readline_available:
  168. val = raw_input(question.ljust(width))
  169. if val:
  170. return val
  171. else:
  172. return default
  173. else:
  174. def defaulter():
  175. """define default behavior startup"""
  176. if _readline_available:
  177. readline.insert_text(default)
  178. readline.set_startup_hook(defaulter)
  179. readline.get_completer()
  180. readline.set_completer(completer)
  181. x = raw_input(question.ljust(width))
  182. readline.set_completer(completer)
  183. readline.set_startup_hook()
  184. return x
  185. else:
  186. return reader()
  187. class CliMenu(object): # pragma: no cover
  188. def __init__(self):
  189. self.items = []
  190. def add(self, item):
  191. if (isinstance(item, CliMenuItem)):
  192. self.items.append(item)
  193. else:
  194. print (item.__class__)
  195. def run(self):
  196. while True:
  197. i = 0
  198. for x in self.items:
  199. i = i + 1
  200. # don't break compatability with old db
  201. try:
  202. current = x.getter()
  203. except TypeError:
  204. current = x.getter
  205. currentstr = ''
  206. if type(current) == list:
  207. for c in current:
  208. currentstr += ("%s " % (c))
  209. else:
  210. currentstr = current
  211. print ("%d - %-" + str(_defaultwidth)
  212. + "s %s") % (i, x.name + ":",
  213. currentstr)
  214. print ("%c - Finish editing" % ('X'))
  215. option = getonechar("Enter your choice:")
  216. try:
  217. print ("selection, ", option)
  218. # substract 1 because array subscripts start at 0
  219. selection = int(option) - 1
  220. # new value is created by calling the editor with the
  221. # previous value as a parameter
  222. # TODO: enable overriding password policy as if new node
  223. # is created.
  224. if selection == 1: # for password
  225. value = self.items[selection].editor(0)
  226. else:
  227. try:
  228. edit = self.items[selection].getter()
  229. value = self.items[selection].editor(edit)
  230. self.items[selection].setter(value)
  231. except TypeError:
  232. edit = self.items[selection].getter
  233. value = self.items[selection].editor(edit)
  234. self.items[selection].setter = value
  235. except (ValueError, IndexError):
  236. if (option.upper() == 'X'):
  237. break
  238. print ("Invalid selection")
  239. class CMDLoop(CliMenu): # pragma: no cover
  240. """
  241. Override CliMenu. This class is only used
  242. when editing NewNode,
  243. """
  244. def run(self, new_node=None):
  245. while True:
  246. i = 0
  247. for x in self.items:
  248. i = i + 1
  249. try:
  250. current = x.getter
  251. except AttributeError:
  252. current = x
  253. # when printing tags, we have list ...
  254. currentstr = ''
  255. if type(current) == list:
  256. for c in current:
  257. try:
  258. currentstr += ' ' + c
  259. except TypeError:
  260. currentstr += ' ' + c.name
  261. # for the case we are not dealing with
  262. # a list of tags
  263. else:
  264. currentstr = current
  265. print ("%s - %s: %s" % (i, x.name, currentstr))
  266. print("X - Finish editing")
  267. option = getonechar("Enter your choice:")
  268. try:
  269. print ("Selection, ", option)
  270. # substract 1 because array subscripts start at 0
  271. selection = int(option) - 1
  272. # new value is created by calling the editor with the
  273. # previous value as a parameter
  274. # TODO: enable overriding password policy as if new node
  275. # is created.
  276. if selection == 0:
  277. new_node.username = getinput("Username:")
  278. self.items[0].getter = new_node.username
  279. self.items[0].setter = new_node.username
  280. elif selection == 1: # for password
  281. new_node.password = getpassword('New Password:')
  282. self.items[1].getter = new_node.password
  283. self.items[1].setter = new_node.password
  284. elif selection == 2:
  285. new_node.url = getinput("Url:")
  286. self.items[2].getter = new_node.url
  287. self.items[2].setter = new_node.url
  288. elif selection == 3: # for notes
  289. # new_node.notes = getinput("Notes:")
  290. new_node.notes = getinput("Notes:")
  291. self.items[3].getter = new_node.notes
  292. self.items[3].setter = new_node.notes
  293. elif selection == 4:
  294. taglist = getinput("Tags:")
  295. tagstrings = taglist.split()
  296. tags = [Tag(tn) for tn in tagstrings]
  297. new_node.tags = tags
  298. self.items[4].setter = new_node.tags
  299. self.items[4].getter = new_node.tags
  300. except (ValueError, IndexError):
  301. if (option.upper() == 'X'):
  302. break
  303. print("Invalid selection")
  304. def getonechar(question, width=_defaultwidth): # pragma: no cover
  305. question = "%s " % (question)
  306. print (question.ljust(width),)
  307. try:
  308. sys.stdout.flush()
  309. fd = sys.stdin.fileno()
  310. # tty module exists only if we are on Posix
  311. try:
  312. tty_mode = tty.tcgetattr(fd)
  313. tty.setcbreak(fd)
  314. except NameError:
  315. pass
  316. try:
  317. ch = os.read(fd, 1)
  318. finally:
  319. try:
  320. tty.tcsetattr(fd, tty.TCSAFLUSH, tty_mode)
  321. except NameError:
  322. pass
  323. except AttributeError:
  324. ch = sys.stdin.readline()[0]
  325. print(ch)
  326. return ch
  327. class CliMenuItem(object):
  328. def __init__(self, name, editor, getter, setter):
  329. self.name = name
  330. self.editor = editor
  331. self.getter = getter
  332. self.setter = setter
  333. class CLICallback(Callback): # pragma: no cover
  334. def getinput(self, question):
  335. return raw_input(question)
  336. def getsecret(self, question):
  337. return getpass.getpass(question + ":")
  338. def getnewsecret(self, question):
  339. return getpass.getpass(question + ":")