tools.py 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276
  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): # 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:
  121. return val
  122. else:
  123. return default
  124. else:
  125. def defaulter():
  126. """define default behavior startup"""
  127. readline.insert_text(default)
  128. if _readline_available:
  129. readline.set_startup_hook(defaulter)
  130. readline.get_completer()
  131. readline.set_completer(completer)
  132. x = raw_input(question.ljust(width))
  133. if _readline_available:
  134. readline.set_startup_hook()
  135. return x if x else default
  136. else:
  137. return reader()
  138. def get_or_create_pass(): # pragma: no cover
  139. p = getpass.getpass(prompt='Password (leave empty to create one):')
  140. if p:
  141. return p
  142. while not p:
  143. print("Password length (default: 8):", end="")
  144. sys.stdout.flush()
  145. ans = sys.stdin.readline().strip()
  146. try:
  147. ans = ast.literal_eval(ans)
  148. if isinstance(ans, int):
  149. kwargs = {'pass_len': ans}
  150. break
  151. elif isinstance(ans, dict):
  152. kwargs = ans
  153. break
  154. else:
  155. print("Did not understand your input...")
  156. continue
  157. except ValueError:
  158. print("Something evil happend.")
  159. print("Did not understand your input...")
  160. continue
  161. except SyntaxError:
  162. kwargs = {}
  163. break
  164. p = generate_password(**kwargs)
  165. return p
  166. def _get_secret():
  167. if sys.stdin.isatty(): # pragma: no cover
  168. p = get_or_create_pass()
  169. else:
  170. p = sys.stdin.readline().rstrip()
  171. return p
  172. def set_selection(new_node, items, selection, reader): # pragma: no cover
  173. if selection == 0:
  174. new_node.username = getinput("Username:", new_node.username)
  175. items[0].getter = new_node.username
  176. elif selection == 1: # for password
  177. new_node.password = _get_secret()
  178. items[1].getter = new_node.password
  179. elif selection == 2:
  180. new_node.url = getinput("Url:", new_node.url)
  181. items[2].getter = new_node.url
  182. elif selection == 3: # for notes
  183. new_node.notes = getinput("Notes :", new_node.notes)
  184. items[3].getter = new_node.notes
  185. elif selection == 4:
  186. taglist = getinput(
  187. "Tags:", " ".join(t.encode() for t in new_node.tags))
  188. tags = taglist.split()
  189. new_node.tags = tags
  190. items[4].getter = ','.join(t.encode() for t in new_node.tags)
  191. class CMDLoop(object):
  192. """
  193. The menu that drives editing of a node
  194. """
  195. def __init__(self, config):
  196. self.items = []
  197. self.config = config
  198. def add(self, item):
  199. if isinstance(item, CliMenuItem):
  200. self.items.append(item)
  201. def run(self, new_node=None, reader=raw_input):
  202. while True:
  203. for i, x in enumerate(self.items):
  204. print("%s - %s: %s" % (i + 1, x.name, x.getter))
  205. print("X - Finish editing")
  206. # read just the first character entered
  207. option = reader("Enter your choice:")[0]
  208. try:
  209. print("Selection, ", option)
  210. # substract 1 because array subscripts start at 0
  211. selection = int(option) - 1
  212. set_selection(new_node, self.items, selection, reader)
  213. except (ValueError, IndexError): # pragma: no cover
  214. if (option.upper() == 'X'):
  215. break
  216. print("Invalid selection")
  217. class CliMenuItem(object):
  218. def __init__(self, name, getter):
  219. self.name = name
  220. self.getter = getter
  221. class CLICallback(Callback): # pragma: no cover
  222. def getinput(self, question):
  223. return raw_input(question)
  224. def getsecret(self, question):
  225. return getpass.getpass(question + ":")
  226. def getnewsecret(self, question):
  227. return getpass.getpass(question + ":")