todo_wunderlist.py 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. import logging
  2. import base
  3. import tts
  4. import clips
  5. import ears
  6. import requests
  7. _LISTEN_TIMEOUT = 600
  8. _GROCERIES = ['milk', 'bread']
  9. _WUNDERLIST_CLIENT_ID = '34e0e31945afeb63e1b8'
  10. _WUNDERLIST_ACCESS_TOKEN = 'a7258e8b6596fdaffc904fc6b65d40c23afe6d2a28bfe7be1a9026d44b59'
  11. class _WunderlistClient(object):
  12. lists = None
  13. def __init__(self, client_id, access_token):
  14. self.client_id = client_id
  15. self.access_token = access_token
  16. def call(self, method, url, body=None):
  17. headers = {
  18. 'x-client-id': self.client_id,
  19. 'x-access-token': self.access_token,
  20. 'content-type': 'application/json',
  21. 'accept': 'application/json'
  22. }
  23. resp = requests.request(method, url, headers=headers, json=body)
  24. if resp.status_code < 300:
  25. return resp.json()
  26. else:
  27. raise Exception(resp.content)
  28. def create_task(self, list_name, title):
  29. list_id = self.lists[list_name]
  30. self.call('POST', 'https://a.wunderlist.com/api/v1/tasks', {'list_id': list_id, 'title': title})
  31. def init(self):
  32. lists_res = self.call('GET', 'https://a.wunderlist.com/api/v1/lists')
  33. self.lists = {x['title'].lower(): x['id'] for x in lists_res}
  34. class Wunderlist(base.BaseFunction):
  35. client = None
  36. def __init__(self, multiple_tasks, list_name=None):
  37. self.client = _WunderlistClient(_WUNDERLIST_CLIENT_ID, _WUNDERLIST_ACCESS_TOKEN)
  38. self.multiple_tasks = multiple_tasks
  39. self.list_name = list_name
  40. self.initialized = False
  41. def init(self):
  42. self.client.init()
  43. if self.list_name and self.list_name not in self.client.lists:
  44. logging.error('Could not find list %s', self.list_name)
  45. return
  46. self.initialized = True
  47. def _get_list(self):
  48. if self.list_name:
  49. return self.list_name
  50. else:
  51. list_name = ears.listen(pause_threshold=1, preferred_phrases=self.client.lists.keys()).lower()
  52. if list_name in self.client.lists:
  53. return list_name
  54. else:
  55. return None
  56. def call(self, **_):
  57. list_name = self._get_list()
  58. if list_name is None:
  59. clips.play(clips.Clips.FAILURE)
  60. return
  61. lines, terminator = ears.listen_until_terminated(timeout=_LISTEN_TIMEOUT, preferred_phrases=_GROCERIES)
  62. if terminator == 'cancel':
  63. tts.tts('cancelled')
  64. return
  65. else:
  66. items = []
  67. for line in lines:
  68. items.extend([t.strip() for t in line.split(' and ') if t.strip()])
  69. for item in items:
  70. self.client.create_task(self.list_name, item)
  71. tts.tts('ok')