tools.py 12 KB

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