tools.py 10 KB

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