tools.py 11 KB

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