Learning by doing: Reading books and trying to understand the (code) examples
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

163 lines
4.8 KiB

  1. # python modules
  2. import sys
  3. import pickle
  4. import base64
  5. import getpass
  6. import gzip
  7. # own modules
  8. from notebook import Notebook
  9. # cryptography module
  10. from cryptography.fernet import Fernet, InvalidToken
  11. from cryptography.hazmat.primitives import hashes
  12. from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC
  13. from cryptography.hazmat.backends import default_backend
  14. class Menu:
  15. """Display a menu and respond to choices when run."""
  16. def __init__(self):
  17. self.salt = "a683c64de226677703f56e6b6ead94bbc3690ec5293c3de3ffdc"
  18. self.savefile = 'notebook.safe'
  19. self.notebook = Notebook()
  20. self.choices = {
  21. "1": self.show_notes,
  22. "2": self.search_notes,
  23. "3": self.add_note,
  24. "4": self.modify_note,
  25. "5": self.remove_note,
  26. "6": self.load_notes,
  27. "7": self.save_notes,
  28. "8": self.__init__,
  29. "9": self.quit
  30. }
  31. def display_menu(self):
  32. print("""
  33. Notebook Menu
  34. 1. Show all Notes
  35. 2. Search Notes
  36. 3. Add Note
  37. 4. Modify Note
  38. 5. Remove Note
  39. 6. Load Notes
  40. 7. Save Notes
  41. 8. Reset Notes
  42. 9. Quit """)
  43. def run(self):
  44. """Display the menu and respond to choices."""
  45. while True:
  46. self.display_menu()
  47. choice = input("Enter an option: ")
  48. action = self.choices.get(choice)
  49. try:
  50. action()
  51. except TypeError:
  52. print("{0} is not a valid choice".format(choice))
  53. def show_notes(self, notes=None):
  54. """Display all notes stored in notebook object"""
  55. if not notes:
  56. notes = self.notebook.notes
  57. for note in notes:
  58. print("{0}: {1}\n{2}".format(note.id, note.tags, note.memo))
  59. def search_notes(self):
  60. """Search for a note containing given string"""
  61. filter = input("Search for: ")
  62. notes = self.notebook.search(filter)
  63. self.show_notes(notes)
  64. def add_note(self):
  65. """Add a given not to notebook object"""
  66. memo = input("Enter a memo: ")
  67. self.notebook.new_note(memo)
  68. print("Your note has been added.")
  69. def modify_note(self):
  70. """Modify tag and memo of note with given id"""
  71. id = input("Enter a note id: ")
  72. memo = input("Enter a memo: ")
  73. tags = input("Enter tags: ")
  74. if memo:
  75. if not self.notebook.modify_memo(id, memo):
  76. print("Note with id {0} doesn't exist.".format(id))
  77. return
  78. if tags:
  79. if not self.notebook.modify_tags(id, tags):
  80. print("Note with id {0} doesn't exist.".format(id))
  81. def remove_note(self):
  82. """Remove note with given id from note list"""
  83. id = input("Enter a note id: ")
  84. if self.notebook.remove_note(id):
  85. print("Note with id {0} removed.".format(id))
  86. else:
  87. print("Note with id {0} doesn't exist.".format(id))
  88. def load_notes(self):
  89. """Decrypt notebook safe file and load it into notebook object"""
  90. try:
  91. f = open(self.savefile, 'rb')
  92. except IOError:
  93. print("Could not open file")
  94. else:
  95. cipher = f.read()
  96. f.close()
  97. notebook = self._decode_notefile(cipher)
  98. if notebook:
  99. self.notebook = notebook
  100. self.notebook._set_id()
  101. def save_notes(self):
  102. """Encrypt notebook object and store it into notebook safe file"""
  103. cipher = self._encode_notefile()
  104. try:
  105. f = open(self.savefile, 'wb')
  106. except IOError:
  107. print("Could not open file")
  108. else:
  109. f.write(cipher)
  110. f.close()
  111. def _decode_notefile(self, cipher):
  112. crypt = Fernet(self._get_password())
  113. try:
  114. plain = crypt.decrypt(cipher)
  115. except InvalidToken:
  116. print("Wrong password")
  117. else:
  118. try:
  119. plain = gzip.decompress(plain)
  120. except OSError:
  121. print("File not valid")
  122. else:
  123. return pickle.loads(plain)
  124. def _encode_notefile(self):
  125. plain = pickle.dumps(self.notebook, pickle.HIGHEST_PROTOCOL)
  126. crypt = Fernet(self._get_password())
  127. plain = gzip.compress(plain)
  128. return crypt.encrypt(plain)
  129. def _get_password(self):
  130. """Request passphrase and derive key from it"""
  131. passphrase = getpass.getpass()
  132. kdf = PBKDF2HMAC(
  133. algorithm=hashes.SHA256(),
  134. length=32,
  135. salt=self.salt.encode('utf-8'),
  136. iterations=10000,
  137. backend=default_backend()
  138. )
  139. return base64.urlsafe_b64encode(kdf.derive(passphrase.encode('utf-8')))
  140. def quit(self):
  141. """Quit application"""
  142. print("Thank you for using your notebook today.")
  143. sys.exit(0)
  144. if __name__ == "__main__":
  145. Menu().run()