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.

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