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.

71 lines
2.4KB

  1. import requests
  2. from crypt import EncryptionHelper
  3. class SNAPIException(Exception):
  4. pass
  5. class RESTAPI:
  6. def __init__(self, base_url):
  7. self.base_url = base_url
  8. self.headers = {}
  9. def get(self, route, params=None):
  10. url = self.base_url + route
  11. return requests.get(url, params, headers=self.headers).json()
  12. def post(self, route, data=None):
  13. url = self.base_url + route
  14. return requests.post(url, json=data, headers=self.headers).json()
  15. def add_header(self, header):
  16. self.headers.update(header)
  17. class StandardNotesAPI:
  18. encryption_helper = EncryptionHelper()
  19. sync_token = None
  20. def get_auth_params_for_email(self):
  21. return self.api.get('/auth/params', dict(email=self.username))
  22. def gen_keys(self, password):
  23. pw_info = self.get_auth_params_for_email()
  24. if 'error' in pw_info:
  25. raise SNAPIException(pw_info['error']['message'])
  26. return self.encryption_helper.pure_generate_password_and_key(
  27. password, pw_info['pw_salt'], pw_info['pw_cost'])
  28. def sign_in(self, keys):
  29. self.keys = keys
  30. res = self.api.post('/auth/sign_in', dict(email=self.username,
  31. password=self.keys['pw']))
  32. if 'error' in res:
  33. raise SNAPIException(res['error']['message'])
  34. self.api.add_header(dict(Authorization='Bearer ' + res['token']))
  35. def sync(self, dirty_items):
  36. items = self.handle_dirty_items(dirty_items)
  37. response = self.api.post('/items/sync', dict(sync_token=self.sync_token,
  38. items=items))
  39. self.sync_token = response['sync_token']
  40. return self.handle_response_items(response)
  41. def handle_dirty_items(self, dirty_items):
  42. items = self.encryption_helper.encrypt_dirty_items(
  43. dirty_items, self.keys)
  44. return items
  45. def handle_response_items(self, response):
  46. response_items = self.encryption_helper.decrypt_response_items(
  47. response['retrieved_items'], self.keys)
  48. saved_items = self.encryption_helper.decrypt_response_items(
  49. response['saved_items'], self.keys)
  50. return dict(response_items=response_items, saved_items=saved_items)
  51. def __init__(self, base_url, username):
  52. self.api = RESTAPI(base_url)
  53. self.username = username