tools.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339
  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. import subprocess as sp
  24. import getpass
  25. import sys
  26. import struct
  27. import colorama
  28. #from pwman.util.config import get_pass_conf
  29. from pwman.util.callback import Callback
  30. if sys.version_info.major > 2: # pragma: no cover
  31. raw_input = input
  32. if sys.platform != 'win32':
  33. import termios
  34. import fcntl
  35. import tty
  36. import readline
  37. _readline_available = True
  38. else: # pragma: no cover
  39. try:
  40. import readline
  41. _readline_available = True
  42. except ImportError as e:
  43. _readline_available = False
  44. _defaultwidth = 10
  45. class ANSI(object):
  46. """
  47. ANSI Colors
  48. """
  49. Reset = 0
  50. Bold = 1
  51. Underscore = 2
  52. Black = 30
  53. Red = 31
  54. Green = 32
  55. Yellow = 33
  56. Blue = 34
  57. Magenta = 35
  58. Cyan = 36
  59. White = 37
  60. def typeset(text, color, bold=False, underline=False,
  61. has_colorama=True): # pragma: no cover
  62. """
  63. print colored strings using colorama
  64. """
  65. if not has_colorama:
  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 as 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 as 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 as e:
  120. print("Executing open_url failed with:\n", e)
  121. def get_password(question, config):
  122. # TODO: enable old functionallity, with password generator.
  123. if sys.stdin.isatty(): # pragma: no cover
  124. p = getpass.getpass()
  125. else:
  126. p = sys.stdin.readline().rstrip()
  127. return p
  128. def getpassword(question, argsgiven=None,
  129. width=_defaultwidth, echo=False,
  130. reader=getpass.getpass, numerics=False, leetify=False,
  131. symbols=False, special_signs=False,
  132. length=None, config=None): # pragma: no cover
  133. if argsgiven == 1 or length:
  134. while not length:
  135. try:
  136. default_length = config.get_value(
  137. 'Generator', 'default_pw_length') or '8'
  138. length = getinput(
  139. "Password length (default %s): " % default_length,
  140. default=default_length)
  141. length = int(length)
  142. except ValueError:
  143. print("please enter a proper integer")
  144. #password, dumpme = generator.generate_password(
  145. # length, length, True, symbols=leetify, numerics=numerics,
  146. # special_chars=special_signs)
  147. #print ("New password: %s" % (password))
  148. #return password
  149. # no args given
  150. while True:
  151. a1 = reader(question.ljust(width))
  152. if not a1:
  153. return getpassword(
  154. '', argsgiven=1, width=width, echo=echo, reader=reader,
  155. numerics=numerics, leetify=leetify, symbols=symbols,
  156. special_signs=special_signs, length=length, config=config)
  157. a2 = reader("[Repeat] %s" % (question.ljust(width)))
  158. if a1 == a2:
  159. if leetify:
  160. pass # return generator.leetify(a1)
  161. else:
  162. return a1
  163. else:
  164. print ("Passwords don't match. Try again.")
  165. def gettermsize(): # pragma: no cover
  166. if sys.stdout.isatty():
  167. s = struct.pack("HHHH", 0, 0, 0, 0)
  168. f = sys.stdout.fileno()
  169. x = fcntl.ioctl(f, termios.TIOCGWINSZ, s)
  170. rows, cols, width, height = struct.unpack("HHHH", x)
  171. return rows, cols
  172. else:
  173. return 40, 80
  174. def getinput(question, default="", reader=raw_input,
  175. completer=None, width=_defaultwidth): # pragma: no cover
  176. """
  177. http://stackoverflow.com/questions/2617057/\
  178. supply-inputs-to-python-unittests
  179. """
  180. if reader == raw_input:
  181. if not _readline_available:
  182. val = raw_input(question.ljust(width))
  183. if val:
  184. return val
  185. else:
  186. return default
  187. else:
  188. def defaulter():
  189. """define default behavior startup"""
  190. if _readline_available:
  191. readline.insert_text(default)
  192. readline.set_startup_hook(defaulter)
  193. readline.get_completer()
  194. readline.set_completer(completer)
  195. x = raw_input(question.ljust(width))
  196. readline.set_completer(completer)
  197. readline.set_startup_hook()
  198. if not x:
  199. return default
  200. return x
  201. else:
  202. return reader()
  203. class CMDLoop(object): # pragma: no cover
  204. """
  205. The menu that drives editing of a node
  206. """
  207. def __init__(self, config):
  208. self.items = []
  209. self.config = config
  210. def add(self, item):
  211. if (isinstance(item, CliMenuItem)):
  212. self.items.append(item)
  213. else:
  214. print (item.__class__)
  215. def run(self, new_node=None, reader=raw_input):
  216. while True:
  217. for i, x in enumerate(self.items):
  218. current = x.getter
  219. print ("%s - %s: %s" % (i + 1, x.name, current))
  220. print("X - Finish editing")
  221. option = reader("Enter your choice:")[0]
  222. try:
  223. print ("Selection, ", option)
  224. # substract 1 because array subscripts start at 0
  225. selection = int(option) - 1
  226. # new value is created by calling the editor with the
  227. # previous value as a parameter
  228. # TODO: enable overriding password policy as if new node
  229. # is created.
  230. if selection == 0:
  231. new_node.username = getinput("Username:")
  232. self.items[0].getter = new_node.username
  233. self.items[0].setter = new_node.username
  234. elif selection == 1: # for password
  235. new_node.password = get_password("Password:", self.config)
  236. self.items[1].getter = new_node.password
  237. self.items[1].setter = new_node.password
  238. elif selection == 2:
  239. new_node.url = getinput("Url:")
  240. self.items[2].getter = new_node.url
  241. self.items[2].setter = new_node.url
  242. elif selection == 3: # for notes
  243. # new_node.notes = getinput("Notes:")
  244. new_node.notes = reader("Notes:")
  245. self.items[3].getter = new_node.notes
  246. self.items[3].setter = new_node.notes
  247. elif selection == 4:
  248. taglist = getinput("Tags:")
  249. tagstrings = taglist.split()
  250. tags = [tn for tn in tagstrings]
  251. #tags = ''
  252. new_node.tags = tags
  253. self.items[4].setter = new_node.tags
  254. self.items[4].getter = new_node.tags
  255. except (ValueError, IndexError):
  256. if (option.upper() == 'X'):
  257. break
  258. print("Invalid selection")
  259. def getonechar(question, width=_defaultwidth): # pragma: no cover
  260. question = "%s " % (question)
  261. print (question.ljust(width),)
  262. try:
  263. sys.stdout.flush()
  264. fd = sys.stdin.fileno()
  265. # tty module exists only if we are on Posix
  266. try:
  267. tty_mode = tty.tcgetattr(fd)
  268. tty.setcbreak(fd)
  269. except NameError:
  270. pass
  271. try:
  272. ch = os.read(fd, 1)
  273. finally:
  274. try:
  275. tty.tcsetattr(fd, tty.TCSAFLUSH, tty_mode)
  276. except NameError:
  277. pass
  278. except AttributeError:
  279. ch = sys.stdin.readline()[0]
  280. print(ch)
  281. return ch
  282. class CliMenuItem(object): # pragma: no cover
  283. def __init__(self, name, editor, getter, setter):
  284. self.name = name
  285. self.editor = editor
  286. self.getter = getter
  287. self.setter = setter
  288. class CLICallback(Callback): # pragma: no cover
  289. def getinput(self, question):
  290. return raw_input(question)
  291. def getsecret(self, question):
  292. return getpass.getpass(question + ":")
  293. def getnewsecret(self, question):
  294. return getpass.getpass(question + ":")