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