tools.py 12 KB

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