tools.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370
  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. import webbrowser
  112. try:
  113. webbrowser.open(link)
  114. except webbrowser.Error as E:
  115. print("Executing open_url failed with:\n", e)
  116. def get_terminal_size(): # pragma: no cover
  117. """ getTerminalSize()
  118. - get width and height of console
  119. - works on linux,os x,windows,cygwin(windows)
  120. originally retrieved from:
  121. http://stackoverflow.com/questions/566746/how-to-get-\
  122. console-window-width-in-python
  123. """
  124. current_os = platform.system()
  125. tuple_xy = None
  126. if current_os == 'Windows':
  127. tuple_xy = _get_terminal_size_windows()
  128. if tuple_xy is None:
  129. tuple_xy = _get_terminal_size_tput()
  130. # needed for window's python in cygwin's xterm!
  131. if current_os in ['Linux', 'Darwin'] or current_os.startswith('CYGWIN'):
  132. tuple_xy = _get_terminal_size_linux()
  133. if tuple_xy is None:
  134. tuple_xy = (80, 25) # default value
  135. return tuple_xy
  136. def _get_terminal_size_windows(): # pragma: no cover
  137. try:
  138. from ctypes import windll, create_string_buffer
  139. # stdin handle is -10
  140. # stdout handle is -11
  141. # stderr handle is -12
  142. h = windll.kernel32.GetStdHandle(-12)
  143. csbi = create_string_buffer(22)
  144. res = windll.kernel32.GetConsoleScreenBufferInfo(h, csbi)
  145. if res:
  146. (bufx, bufy, curx, cury, wattr,
  147. left, top, right, bottom,
  148. maxx, maxy) = struct.unpack("hhhhHhhhhhh", csbi.raw)
  149. sizex = right - left + 1
  150. sizey = bottom - top + 1
  151. return sizex, sizey
  152. except:
  153. pass
  154. def _get_terminal_size_tput(): # pragma: no cover
  155. # get terminal width
  156. # src: http://stackoverflow.com/questions/263890/how-do-i-\
  157. # find-the-width-height-of-a-terminal-window
  158. try:
  159. cols = int(sp.check_call(shlex.split('tput cols')))
  160. rows = int(sp.check_call(shlex.split('tput lines')))
  161. return (cols, rows)
  162. except:
  163. pass
  164. def _get_terminal_size_linux(): # pragma: no cover
  165. def ioctl_GWINSZ(fd):
  166. try:
  167. import fcntl
  168. import termios
  169. cr = struct.unpack('hh',
  170. fcntl.ioctl(fd, termios.TIOCGWINSZ, '1234'))
  171. return cr
  172. except:
  173. pass
  174. cr = ioctl_GWINSZ(0) or ioctl_GWINSZ(1) or ioctl_GWINSZ(2)
  175. if not cr:
  176. try:
  177. fd = os.open(os.ctermid(), os.O_RDONLY)
  178. cr = ioctl_GWINSZ(fd)
  179. os.close(fd)
  180. except:
  181. pass
  182. if not cr:
  183. try:
  184. cr = (os.environ['LINES'], os.environ['COLUMNS'])
  185. except:
  186. return None
  187. return int(cr[1]), int(cr[0])
  188. def gettermsize(): # pragma: no cover
  189. if sys.stdout.isatty():
  190. s = struct.pack("HHHH", 0, 0, 0, 0)
  191. f = sys.stdout.fileno()
  192. x = fcntl.ioctl(f, termios.TIOCGWINSZ, s)
  193. rows, cols, width, height = struct.unpack("HHHH", x)
  194. return rows, cols
  195. else:
  196. return 40, 80
  197. def getinput(question, default="", reader=raw_input,
  198. completer=None, width=_defaultwidth): # pragma: no cover
  199. """
  200. http://stackoverflow.com/questions/2617057/\
  201. supply-inputs-to-python-unittests
  202. """
  203. if reader == raw_input:
  204. if not _readline_available:
  205. val = raw_input(question.ljust(width))
  206. if val:
  207. return val
  208. else:
  209. return default
  210. else:
  211. def defaulter():
  212. """define default behavior startup"""
  213. readline.insert_text(default)
  214. if _readline_available:
  215. readline.set_startup_hook(defaulter)
  216. readline.get_completer()
  217. readline.set_completer(completer)
  218. x = raw_input(question.ljust(width))
  219. if _readline_available:
  220. readline.set_startup_hook()
  221. return x if x else default
  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:", new_node.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:", new_node.url)
  267. items[2].getter = new_node.url
  268. elif selection == 3: # for notes
  269. new_node.notes = getinput("Notes :", new_node.notes)
  270. items[3].getter = new_node.notes
  271. elif selection == 4:
  272. taglist = getinput("Tags:", " ".join(new_node.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. # read just the first character entered
  292. option = reader("Enter your choice:")[0]
  293. try:
  294. print ("Selection, ", option)
  295. # substract 1 because array subscripts start at 0
  296. selection = int(option) - 1
  297. set_selection(new_node, self.items, selection, reader)
  298. except (ValueError, IndexError): # pragma: no cover
  299. if (option.upper() == 'X'):
  300. break
  301. print("Invalid selection")
  302. class CliMenuItem(object):
  303. def __init__(self, name, getter):
  304. self.name = name
  305. self.getter = getter
  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 + ":")