tools.py 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283
  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) 2017 Oz Nahum Tiram <oz.tiram@gmail.com>
  18. # ============================================================================
  19. """
  20. Define the CLI interface for pwman3 and the helper functions
  21. """
  22. import subprocess as sp
  23. import getpass
  24. import sys
  25. import colorama
  26. import ast
  27. from pwman.util.callback import Callback
  28. from pwman.util.crypto_engine import generate_password
  29. if sys.version_info.major > 2: # pragma: no cover
  30. raw_input = input
  31. if not sys.platform.startswith('win'):
  32. import termios # noqa
  33. import fcntl # noqa
  34. import readline
  35. _readline_available = True
  36. else: # pragma: no cover
  37. try:
  38. import readline
  39. _readline_available = True
  40. except ImportError as e:
  41. try:
  42. import pyreadline as readrline # noqa
  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 'win32' not 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. import webbrowser
  107. try:
  108. webbrowser.open(link)
  109. except webbrowser.Error as E:
  110. print("Executing open_url failed with:\n", E)
  111. def getinput(question, default="", reader=input,
  112. completer=None, width=_defaultwidth, drop="drop"): # pragma: no cover
  113. """
  114. http://stackoverflow.com/questions/2617057/\
  115. supply-inputs-to-python-unittests
  116. """
  117. if reader == input:
  118. if not _readline_available:
  119. val = input(question.ljust(width))
  120. if val == "drop":
  121. return ""
  122. elif val:
  123. return val
  124. else:
  125. return default
  126. else:
  127. def defaulter():
  128. """define default behavior startup"""
  129. readline.insert_text(default)
  130. if _readline_available:
  131. readline.set_startup_hook(defaulter)
  132. readline.get_completer()
  133. readline.set_completer(completer)
  134. x = input(question.ljust(width))
  135. if _readline_available:
  136. readline.set_startup_hook()
  137. if x == "drop":
  138. return ""
  139. elif x:
  140. return x
  141. else:
  142. return default
  143. else:
  144. return reader()
  145. def get_or_create_pass(): # pragma: no cover
  146. p = getpass.getpass(prompt='Password (leave empty to create one):')
  147. if p:
  148. return p
  149. while not p:
  150. print("Password length (default: 8):", end="")
  151. sys.stdout.flush()
  152. ans = sys.stdin.readline().strip()
  153. try:
  154. ans = ast.literal_eval(ans)
  155. if isinstance(ans, int):
  156. kwargs = {'pass_len': ans}
  157. break
  158. elif isinstance(ans, dict):
  159. kwargs = ans
  160. break
  161. else:
  162. print("Did not understand your input...")
  163. continue
  164. except ValueError:
  165. print("Something evil happend.")
  166. print("Did not understand your input...")
  167. continue
  168. except SyntaxError:
  169. kwargs = {}
  170. break
  171. p = generate_password(**kwargs)
  172. return p
  173. def _get_secret():
  174. if sys.stdin.isatty(): # pragma: no cover
  175. p = get_or_create_pass()
  176. else:
  177. p = sys.stdin.readline().rstrip()
  178. return p
  179. def set_selection(new_node, items, selection, reader): # pragma: no cover
  180. if selection == 0:
  181. new_node.username = getinput("Username:", new_node.username)
  182. items[0].getter = new_node.username
  183. elif selection == 1: # for password
  184. new_node.password = _get_secret()
  185. items[1].getter = new_node.password
  186. elif selection == 2:
  187. new_node.url = getinput("Url:", new_node.url)
  188. items[2].getter = new_node.url
  189. elif selection == 3: # for notes
  190. new_node.notes = getinput("Notes :", new_node.notes)
  191. items[3].getter = new_node.notes
  192. elif selection == 4:
  193. taglist = getinput(
  194. "Tags:", " ".join(map(bytes.decode, new_node.tags)))
  195. tags = taglist.split()
  196. new_node.tags = tags
  197. items[4].getter = ','.join(t for t in tags)
  198. class CMDLoop(object):
  199. """
  200. The menu that drives editing of a node
  201. """
  202. def __init__(self, config):
  203. self.items = []
  204. self.config = config
  205. def add(self, item):
  206. if isinstance(item, CliMenuItem):
  207. self.items.append(item)
  208. def run(self, new_node=None, reader=raw_input):
  209. while True:
  210. for i, x in enumerate(self.items):
  211. print("%s - %s: %s" % (i + 1, x.name, x.getter))
  212. print("X - Finish editing")
  213. # read just the first character entered
  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. set_selection(new_node, self.items, selection, reader)
  220. except (ValueError, IndexError): # pragma: no cover
  221. if (option.upper() == 'X'):
  222. break
  223. print("Invalid selection")
  224. class CliMenuItem(object):
  225. def __init__(self, name, getter):
  226. self.name = name
  227. self.getter = getter
  228. class CLICallback(Callback): # pragma: no cover
  229. def getinput(self, question):
  230. return raw_input(question)
  231. def getsecret(self, question):
  232. return getpass.getpass(question + ":")
  233. def getnewsecret(self, question):
  234. return getpass.getpass(question + ":")