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.

102 lines
3.3KB

  1. from uuid import uuid1
  2. from api import StandardNotesAPI
  3. class ItemManager:
  4. items = {}
  5. def map_items(self, response_items, metadata_only=False):
  6. DATA_KEYS = ['content', 'enc_item_key', 'auth_hash']
  7. for response_item in response_items:
  8. uuid = response_item['uuid']
  9. if response_item['deleted']:
  10. if uuid in self.items:
  11. del self.items[uuid]
  12. continue
  13. response_item['dirty'] = False
  14. if uuid not in self.items:
  15. self.items[uuid] = {}
  16. for key, value in response_item.items():
  17. if metadata_only and key in DATA_KEYS:
  18. continue
  19. self.items[uuid][key] = value
  20. def sync_items(self):
  21. dirty_items = [item for uuid, item in self.items.items() if item['dirty']]
  22. # remove keys (note: this removes them from self.items as well)
  23. for item in dirty_items:
  24. item.pop('dirty', None)
  25. item.pop('updated_at', None)
  26. response = self.sn_api.sync(dirty_items)
  27. self.map_items(response['response_items'])
  28. self.map_items(response['saved_items'], metadata_only=True)
  29. def get_notes(self):
  30. notes = {}
  31. sorted_items = sorted(
  32. self.items.items(), key=lambda x: x[1]['created_at'])
  33. for uuid, item in sorted_items:
  34. if item['content_type'] == 'Note':
  35. note = item['content']
  36. text = note['text']
  37. # Add a new line so it outputs pretty
  38. if not text.endswith('\n'):
  39. text += '\n';
  40. text = text.encode() # convert to binary data
  41. # remove title duplicates by adding a number to the end
  42. count = 0
  43. while True:
  44. title = note['title'] + ('' if not count else
  45. ' ' + str(count + 1))
  46. if title in notes:
  47. count += 1
  48. else:
  49. break
  50. notes[title] = dict(
  51. text=text, created=item['created_at'],
  52. modified=item.get('updated_at', item['created_at']),
  53. uuid=item['uuid'])
  54. return notes
  55. def touch_note(self, uuid):
  56. item = self.items[uuid]
  57. item['dirty'] = True
  58. def write_note(self, uuid, text):
  59. item = self.items[uuid]
  60. item['content']['text'] = text.decode() # convert back to string
  61. item['dirty'] = True
  62. def create_note(self, name, time):
  63. uuid = str(uuid1())
  64. content = dict(title=name, text='', references=[])
  65. self.items[uuid] = dict(content_type='Note', dirty=True, auth_hash=None,
  66. uuid=uuid, created_at=time, updated_at=time,
  67. enc_item_key='', content=content)
  68. def rename_note(self, uuid, new_note_name):
  69. item = self.items[uuid]
  70. item['content']['title'] = new_note_name
  71. item['dirty'] = True
  72. def delete_note(self, uuid):
  73. item = self.items[uuid]
  74. item['deleted'] = True
  75. item['dirty'] = True
  76. def __init__(self, sn_api):
  77. self.sn_api = sn_api
  78. self.sync_items()