tools.py 10 KB

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