tools.py 11 KB

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