tools.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361
  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 shlex
  28. import platform
  29. import colorama
  30. import os
  31. from pwman.util.callback import Callback
  32. from pwman.util.crypto_engine import generate_password
  33. if sys.version_info.major > 2: # pragma: no cover
  34. raw_input = input
  35. if sys.platform != 'win32':
  36. import termios
  37. import fcntl
  38. import readline
  39. _readline_available = True
  40. else: # pragma: no cover
  41. try:
  42. import readline
  43. _readline_available = True
  44. except ImportError as e:
  45. _readline_available = False
  46. _defaultwidth = 10
  47. class ANSI(object):
  48. """
  49. ANSI Colors
  50. """
  51. Reset = 0
  52. Bold = 1
  53. Underscore = 2
  54. Black = 30
  55. Red = 31
  56. Green = 32
  57. Yellow = 33
  58. Blue = 34
  59. Magenta = 35
  60. Cyan = 36
  61. White = 37
  62. def typeset(text, color, bold=False, underline=False,
  63. has_colorama=True): # pragma: no cover
  64. """
  65. print colored strings using colorama
  66. """
  67. if not has_colorama:
  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 text_to_clipboards(text): # pragma: no cover
  75. """
  76. copy text to clipboard
  77. credit:
  78. https://pythonadventures.wordpress.com/tag/xclip/
  79. """
  80. # "primary":
  81. try:
  82. xsel_proc = sp.Popen(['xsel', '-pi'], stdin=sp.PIPE)
  83. xsel_proc.communicate(text)
  84. # "clipboard":
  85. xsel_proc = sp.Popen(['xsel', '-bi'], stdin=sp.PIPE)
  86. xsel_proc.communicate(text)
  87. except OSError as e:
  88. print (e, "\nExecuting xsel failed, is it installed ?\n \
  89. please check your configuration file ... ")
  90. def text_to_mcclipboard(text): # pragma: no cover
  91. """
  92. copy text to mac os x clip board
  93. credit:
  94. https://pythonadventures.wordpress.com/tag/xclip/
  95. """
  96. # "primary":
  97. try:
  98. pbcopy_proc = sp.Popen(['pbcopy'], stdin=sp.PIPE)
  99. pbcopy_proc.communicate(text)
  100. except OSError as e:
  101. print (e, "\nExecuting pbcoy failed...")
  102. def open_url(link, macosx=False): # pragma: no cover
  103. """
  104. launch xdg-open or open in MacOSX with url
  105. """
  106. uopen = "xdg-open"
  107. if macosx:
  108. uopen = "open"
  109. try:
  110. sp.Popen([uopen, link], stdin=sp.PIPE)
  111. except OSError as e:
  112. print("Executing open_url failed with:\n", e)
  113. def get_terminal_size():
  114. """ getTerminalSize()
  115. - get width and height of console
  116. - works on linux,os x,windows,cygwin(windows)
  117. originally retrieved from:
  118. http://stackoverflow.com/questions/566746/how-to-get-\
  119. console-window-width-in-python
  120. """
  121. current_os = platform.system()
  122. tuple_xy = None
  123. if current_os == 'Windows':
  124. tuple_xy = _get_terminal_size_windows()
  125. if tuple_xy is None:
  126. tuple_xy = _get_terminal_size_tput()
  127. # needed for window's python in cygwin's xterm!
  128. if current_os in ['Linux', 'Darwin'] or current_os.startswith('CYGWIN'):
  129. tuple_xy = _get_terminal_size_linux()
  130. if tuple_xy is None:
  131. tuple_xy = (80, 25) # default value
  132. return tuple_xy
  133. def _get_terminal_size_windows(): # pragma: no cover
  134. try:
  135. from ctypes import windll, create_string_buffer
  136. # stdin handle is -10
  137. # stdout handle is -11
  138. # stderr handle is -12
  139. h = windll.kernel32.GetStdHandle(-12)
  140. csbi = create_string_buffer(22)
  141. res = windll.kernel32.GetConsoleScreenBufferInfo(h, csbi)
  142. if res:
  143. (bufx, bufy, curx, cury, wattr,
  144. left, top, right, bottom,
  145. maxx, maxy) = struct.unpack("hhhhHhhhhhh", csbi.raw)
  146. sizex = right - left + 1
  147. sizey = bottom - top + 1
  148. return sizex, sizey
  149. except:
  150. pass
  151. def _get_terminal_size_tput(): # pragma: no cover
  152. # get terminal width
  153. # src: http://stackoverflow.com/questions/263890/how-do-i-\
  154. # find-the-width-height-of-a-terminal-window
  155. try:
  156. cols = int(sp.check_call(shlex.split('tput cols')))
  157. rows = int(sp.check_call(shlex.split('tput lines')))
  158. return (cols, rows)
  159. except:
  160. pass
  161. def _get_terminal_size_linux(): # pragma: no cover
  162. def ioctl_GWINSZ(fd):
  163. try:
  164. import fcntl
  165. import termios
  166. cr = struct.unpack('hh',
  167. fcntl.ioctl(fd, termios.TIOCGWINSZ, '1234'))
  168. return cr
  169. except:
  170. pass
  171. cr = ioctl_GWINSZ(0) or ioctl_GWINSZ(1) or ioctl_GWINSZ(2)
  172. if not cr:
  173. try:
  174. fd = os.open(os.ctermid(), os.O_RDONLY)
  175. cr = ioctl_GWINSZ(fd)
  176. os.close(fd)
  177. except:
  178. pass
  179. if not cr:
  180. try:
  181. cr = (os.environ['LINES'], os.environ['COLUMNS'])
  182. except:
  183. return None
  184. return int(cr[1]), int(cr[0])
  185. def gettermsize(): # pragma: no cover
  186. if sys.stdout.isatty():
  187. s = struct.pack("HHHH", 0, 0, 0, 0)
  188. f = sys.stdout.fileno()
  189. x = fcntl.ioctl(f, termios.TIOCGWINSZ, s)
  190. rows, cols, width, height = struct.unpack("HHHH", x)
  191. return rows, cols
  192. else:
  193. return 40, 80
  194. def getinput(question, default="", reader=raw_input,
  195. completer=None, width=_defaultwidth): # pragma: no cover
  196. """
  197. http://stackoverflow.com/questions/2617057/\
  198. supply-inputs-to-python-unittests
  199. """
  200. if reader == raw_input:
  201. if not _readline_available:
  202. val = raw_input(question.ljust(width))
  203. if val:
  204. return val
  205. else:
  206. return default
  207. else:
  208. def defaulter():
  209. """define default behavior startup"""
  210. if _readline_available:
  211. readline.insert_text(default)
  212. readline.set_startup_hook(defaulter)
  213. readline.get_completer()
  214. readline.set_completer(completer)
  215. x = raw_input(question.ljust(width))
  216. readline.set_completer(completer)
  217. readline.set_startup_hook()
  218. if not x:
  219. return default
  220. return x
  221. else:
  222. return reader()
  223. def get_or_create_pass():
  224. p = getpass.getpass(prompt='Password (leave empty to create one):')
  225. if not p:
  226. while True:
  227. try:
  228. print("Password length (default: 8):", end="")
  229. sys.stdout.flush()
  230. l = sys.stdin.readline().strip()
  231. l = int(l) if l else 8
  232. break
  233. except ValueError:
  234. print("You did not enter an integer...")
  235. p = generate_password(l)
  236. return p
  237. def _get_secret():
  238. # TODO: enable old functionallity, with password generator.
  239. if sys.stdin.isatty(): # pragma: no cover
  240. p = get_or_create_pass()
  241. else:
  242. p = sys.stdin.readline().rstrip()
  243. return p
  244. class CMDLoop(object): # pragma: no cover
  245. """
  246. The menu that drives editing of a node
  247. """
  248. def __init__(self, config):
  249. self.items = []
  250. self.config = config
  251. def add(self, item):
  252. if (isinstance(item, CliMenuItem)):
  253. self.items.append(item)
  254. else:
  255. print (item.__class__)
  256. def run(self, new_node=None, reader=raw_input):
  257. while True:
  258. for i, x in enumerate(self.items):
  259. current = x.getter
  260. print ("%s - %s: %s" % (i + 1, x.name, current))
  261. print("X - Finish editing")
  262. option = reader("Enter your choice:")[0]
  263. try:
  264. print ("Selection, ", option)
  265. # substract 1 because array subscripts start at 0
  266. selection = int(option) - 1
  267. # new value is created by calling the editor with the
  268. # previous value as a parameter
  269. # TODO: enable overriding password policy as if new node
  270. # is created.
  271. if selection == 0:
  272. new_node.username = getinput("Username:")
  273. self.items[0].getter = new_node.username
  274. self.items[0].setter = new_node.username
  275. elif selection == 1: # for password
  276. new_node.password = _get_secret()
  277. self.items[1].getter = new_node.password
  278. self.items[1].setter = new_node.password
  279. elif selection == 2:
  280. new_node.url = getinput("Url:")
  281. self.items[2].getter = new_node.url
  282. self.items[2].setter = new_node.url
  283. elif selection == 3: # for notes
  284. # new_node.notes = getinput("Notes:")
  285. new_node.notes = reader("Notes:")
  286. self.items[3].getter = new_node.notes
  287. self.items[3].setter = new_node.notes
  288. elif selection == 4:
  289. taglist = getinput("Tags:")
  290. tagstrings = taglist.split()
  291. tags = [tn for tn in tagstrings]
  292. #tags = ''
  293. new_node.tags = tags
  294. self.items[4].setter = new_node.tags
  295. self.items[4].getter = new_node.tags
  296. except (ValueError, IndexError):
  297. if (option.upper() == 'X'):
  298. break
  299. print("Invalid selection")
  300. class CliMenuItem(object): # pragma: no cover
  301. def __init__(self, name, editor, getter, setter):
  302. self.name = name
  303. self.editor = editor
  304. self.getter = getter
  305. self.setter = setter
  306. class CLICallback(Callback): # pragma: no cover
  307. def getinput(self, question):
  308. return raw_input(question)
  309. def getsecret(self, question):
  310. return getpass.getpass(question + ":")
  311. def getnewsecret(self, question):
  312. return getpass.getpass(question + ":")