tools.py 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279
  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 struct
  26. import shlex
  27. import platform
  28. import colorama
  29. import os
  30. import ast
  31. from pwman.util.callback import Callback
  32. from pwman.util.crypto_engine import generate_password
  33. if sys.version_info.major > 2: # pragma: no cover
  34. raw_input = input
  35. if not sys.platform.startswith('win'):
  36. import termios
  37. import fcntl
  38. import readline
  39. _readline_available = True
  40. else: # pragma: no cover
  41. try:
  42. import readline
  43. _readline_available = True
  44. except ImportError as e:
  45. try:
  46. import pyreadline as readrline
  47. _readline_available = True
  48. except ImportError as e:
  49. _readline_available = False
  50. _defaultwidth = 10
  51. class ANSI(object):
  52. """
  53. ANSI Colors
  54. """
  55. Reset = 0
  56. Bold = 1
  57. Underscore = 2
  58. Black = 30
  59. Red = 31
  60. Green = 32
  61. Yellow = 33
  62. Blue = 34
  63. Magenta = 35
  64. Cyan = 36
  65. White = 37
  66. def typeset(text, color, bold=False, underline=False,
  67. has_colorama=True): # pragma: no cover
  68. """
  69. print colored strings using colorama
  70. """
  71. if not has_colorama:
  72. return text
  73. if bold:
  74. text = colorama.Style.BRIGHT + text
  75. if underline and 'win32' not in sys.platform:
  76. text = ANSI.Underscore + text
  77. return color + text + colorama.Style.RESET_ALL
  78. def text_to_clipboards(text): # pragma: no cover
  79. """
  80. copy text to clipboard
  81. credit:
  82. https://pythonadventures.wordpress.com/tag/xclip/
  83. """
  84. # "primary":
  85. try:
  86. xsel_proc = sp.Popen(['xsel', '-pi'], stdin=sp.PIPE)
  87. xsel_proc.communicate(text)
  88. # "clipboard":
  89. xsel_proc = sp.Popen(['xsel', '-bi'], stdin=sp.PIPE)
  90. xsel_proc.communicate(text)
  91. except OSError as e:
  92. print (e, "\nExecuting xsel failed, is it installed ?\n \
  93. please check your configuration file ... ")
  94. def text_to_mcclipboard(text): # pragma: no cover
  95. """
  96. copy text to mac os x clip board
  97. credit:
  98. https://pythonadventures.wordpress.com/tag/xclip/
  99. """
  100. # "primary":
  101. try:
  102. pbcopy_proc = sp.Popen(['pbcopy'], stdin=sp.PIPE)
  103. pbcopy_proc.communicate(text)
  104. except OSError as e:
  105. print (e, "\nExecuting pbcoy failed...")
  106. def open_url(link, macosx=False,): # pragma: no cover
  107. """
  108. launch xdg-open or open in MacOSX with url
  109. """
  110. import webbrowser
  111. try:
  112. webbrowser.open(link)
  113. except webbrowser.Error as E:
  114. print("Executing open_url failed with:\n", e)
  115. def getinput(question, default="", reader=raw_input,
  116. completer=None, width=_defaultwidth): # pragma: no cover
  117. """
  118. http://stackoverflow.com/questions/2617057/\
  119. supply-inputs-to-python-unittests
  120. """
  121. if reader == raw_input:
  122. if not _readline_available:
  123. val = raw_input(question.ljust(width))
  124. if val:
  125. return val
  126. else:
  127. return default
  128. else:
  129. def defaulter():
  130. """define default behavior startup"""
  131. readline.insert_text(default)
  132. if _readline_available:
  133. readline.set_startup_hook(defaulter)
  134. readline.get_completer()
  135. readline.set_completer(completer)
  136. x = raw_input(question.ljust(width))
  137. if _readline_available:
  138. readline.set_startup_hook()
  139. return x if x else default
  140. else:
  141. return reader()
  142. def get_or_create_pass(): # pragma: no cover
  143. p = getpass.getpass(prompt='Password (leave empty to create one):')
  144. if p:
  145. return p
  146. while not p:
  147. print("Password length (default: 8):", end="")
  148. sys.stdout.flush()
  149. ans = sys.stdin.readline().strip()
  150. try:
  151. ans = ast.literal_eval(ans)
  152. if isinstance(ans, int):
  153. kwargs = {'pass_len': ans}
  154. break
  155. elif isinstance(ans, dict):
  156. kwargs = ans
  157. break
  158. else:
  159. print("Did not understand your input...")
  160. continue
  161. except ValueError:
  162. print("Something evil happend.")
  163. print("Did not understand your input...")
  164. continue
  165. except SyntaxError:
  166. kwargs = {}
  167. break
  168. p = generate_password(**kwargs)
  169. return p
  170. def _get_secret():
  171. if sys.stdin.isatty(): # pragma: no cover
  172. p = get_or_create_pass()
  173. else:
  174. p = sys.stdin.readline().rstrip()
  175. return p
  176. def set_selection(new_node, items, selection, reader): # pragma: no cover
  177. if selection == 0:
  178. new_node.username = getinput("Username:", new_node.username)
  179. items[0].getter = new_node.username
  180. elif selection == 1: # for password
  181. new_node.password = _get_secret()
  182. items[1].getter = new_node.password
  183. elif selection == 2:
  184. new_node.url = getinput("Url:", new_node.url)
  185. items[2].getter = new_node.url
  186. elif selection == 3: # for notes
  187. new_node.notes = getinput("Notes :", new_node.notes)
  188. items[3].getter = new_node.notes
  189. elif selection == 4:
  190. taglist = getinput("Tags:", " ".join(new_node.tags))
  191. tags = taglist.split()
  192. new_node.tags = tags
  193. items[4].getter = ','.join(new_node.tags)
  194. class CMDLoop(object):
  195. """
  196. The menu that drives editing of a node
  197. """
  198. def __init__(self, config):
  199. self.items = []
  200. self.config = config
  201. def add(self, item):
  202. if isinstance(item, CliMenuItem):
  203. self.items.append(item)
  204. def run(self, new_node=None, reader=raw_input):
  205. while True:
  206. for i, x in enumerate(self.items):
  207. print ("%s - %s: %s" % (i + 1, x.name, x.getter))
  208. print("X - Finish editing")
  209. # read just the first character entered
  210. option = reader("Enter your choice:")[0]
  211. try:
  212. print ("Selection, ", option)
  213. # substract 1 because array subscripts start at 0
  214. selection = int(option) - 1
  215. set_selection(new_node, self.items, selection, reader)
  216. except (ValueError, IndexError): # pragma: no cover
  217. if (option.upper() == 'X'):
  218. break
  219. print("Invalid selection")
  220. class CliMenuItem(object):
  221. def __init__(self, name, getter):
  222. self.name = name
  223. self.getter = getter
  224. class CLICallback(Callback): # pragma: no cover
  225. def getinput(self, question):
  226. return raw_input(question)
  227. def getsecret(self, question):
  228. return getpass.getpass(question + ":")
  229. def getnewsecret(self, question):
  230. return getpass.getpass(question + ":")