tools.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352
  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="", completer=None, width=_defaultwidth):
  144. if not _readline_available:
  145. return raw_input(question.ljust(width))
  146. else:
  147. def defaulter():
  148. """define default behavior startup"""
  149. if _readline_available:
  150. readline.insert_text(default)
  151. readline.set_startup_hook(defaulter)
  152. oldcompleter = readline.get_completer()
  153. readline.set_completer(completer)
  154. x = raw_input(question.ljust(width))
  155. readline.set_completer(completer)
  156. readline.set_startup_hook()
  157. return x
  158. def getyesno(question, defaultyes=False, width=_defaultwidth):
  159. if (defaultyes):
  160. default = "[Y/n]"
  161. else:
  162. default = "[y/N]"
  163. ch = getonechar("%s %s" % (question, default), width)
  164. if (ch == '\n'):
  165. if (defaultyes):
  166. return True
  167. else:
  168. return False
  169. elif (ch == 'y' or ch == 'Y'):
  170. return True
  171. elif (ch == 'n' or ch == 'N'):
  172. return False
  173. else:
  174. return getyesno(question, defaultyes, width)
  175. class CliMenu(object):
  176. def __init__(self):
  177. self.items = []
  178. def add(self, item):
  179. if (isinstance(item, CliMenuItem)):
  180. self.items.append(item)
  181. else:
  182. print item.__class__
  183. def run(self):
  184. while True:
  185. i = 0
  186. for x in self.items:
  187. i = i + 1
  188. # don't break compatability with old db
  189. try:
  190. current = x.getter()
  191. except TypeError:
  192. current = x.getter
  193. currentstr = ''
  194. if type(current) == list:
  195. for c in current:
  196. currentstr += ("%s " % (c))
  197. else:
  198. currentstr = current
  199. print ("%d - %-"+str(_defaultwidth)
  200. + "s %s") % (i, x.name+":",
  201. currentstr)
  202. print "%c - Finish editing" % ('X')
  203. option = getonechar("Enter your choice:")
  204. try:
  205. print "selection, ", option
  206. # substract 1 because array subscripts start at 0
  207. selection = int(option) - 1
  208. # new value is created by calling the editor with the
  209. # previous value as a parameter
  210. # TODO: enable overriding password policy as if new node
  211. # is created.
  212. if selection == 1: # for password
  213. value = self.items[selection].editor(0)
  214. else:
  215. try:
  216. edit = self.items[selection].getter()
  217. value = self.items[selection].editor(edit)
  218. self.items[selection].setter(value)
  219. except TypeError:
  220. edit = self.items[selection].getter
  221. value = self.items[selection].editor(edit)
  222. self.items[selection].setter = value
  223. except (ValueError, IndexError):
  224. if (option.upper() == 'X'):
  225. break
  226. print "Invalid selection"
  227. def runner(self, new_node):
  228. while True:
  229. i = 0
  230. for x in self.items:
  231. i = i + 1
  232. # don't break compatability with old db
  233. try:
  234. current = x.getter()
  235. except TypeError:
  236. current = x.getter
  237. except AttributeError:
  238. current = x
  239. currentstr = ''
  240. if type(current) == list:
  241. for c in current:
  242. try:
  243. currentstr += ' '+c
  244. except TypeError:
  245. currentstr += ' '+c._name
  246. else:
  247. currentstr = current
  248. print ("%d - %-"+str(_defaultwidth)
  249. + "s %s") % (i, x.name+":",
  250. currentstr)
  251. print "%c - Finish editing" % ('X')
  252. option = getonechar("Enter your choice:")
  253. try:
  254. print "selection, ", option
  255. # substract 1 because array subscripts start at 0
  256. selection = int(option) - 1
  257. # new value is created by calling the editor with the
  258. # previous value as a parameter
  259. # TODO: enable overriding password policy as if new node
  260. # is created.
  261. if selection == 0:
  262. new_node.username = getinput("Username:")
  263. self.items[2].getter = new_node.username
  264. elif selection == 1: # for password
  265. value = self.items[selection].editor(0)
  266. new_node.password = value
  267. self.items[2].getter = new_node.password
  268. elif selection == 2:
  269. new_node.notes = getinput("Url:")
  270. self.items[2].getter = new_node.url
  271. elif selection == 3: # for notes
  272. new_node.notes = getinput("Notes:")
  273. self.items[3].getter = new_node.notes
  274. self.items[3].setter = new_node.notes
  275. elif selection == 4:
  276. taglist = getinput("Tags:")
  277. tagstrings = taglist.split()
  278. tags = [Tag(tn) for tn in tagstrings]
  279. new_node.tags = tags
  280. self.items[4].setter = new_node.tags
  281. self.items[4].getter = new_node.tags
  282. except (ValueError, IndexError):
  283. if (option.upper() == 'X'):
  284. break
  285. print "Invalid selection"
  286. def getonechar(question, width=_defaultwidth):
  287. question = "%s " % (question)
  288. print question.ljust(width),
  289. sys.stdout.flush()
  290. fd = sys.stdin.fileno()
  291. tty_mode = tty.tcgetattr(fd)
  292. tty.setcbreak(fd)
  293. try:
  294. ch = os.read(fd, 1)
  295. finally:
  296. tty.tcsetattr(fd, tty.TCSAFLUSH, tty_mode)
  297. print ch
  298. return ch
  299. class CliMenuItem(object):
  300. def __init__(self, name, editor, getter, setter):
  301. self.name = name
  302. self.editor = editor
  303. self.getter = getter
  304. self.setter = setter
  305. class CLICallback(Callback):
  306. def getinput(self, question):
  307. return raw_input(question)
  308. def getsecret(self, question):
  309. return getpass.getpass(question + ":")