todo_wunderlist.py 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  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. print self.lists
  35. class Wunderlist(base.BaseFunction):
  36. client = None
  37. def __init__(self, multiple_tasks, list_name=None):
  38. self.client = _WunderlistClient(_WUNDERLIST_CLIENT_ID, _WUNDERLIST_ACCESS_TOKEN)
  39. self.multiple_tasks = multiple_tasks
  40. self.list_name = list_name
  41. self.initialized = False
  42. def init(self):
  43. self.client.init()
  44. if self.list_name and self.list_name not in self.client.lists:
  45. logging.error('Could not find list %s', self.list_name)
  46. return
  47. self.initialized = True
  48. def _get_list(self):
  49. if self.list_name:
  50. return self.list_name
  51. else:
  52. list_name = ears.listen(pause_threshold=1, preferred_phrases=self.client.lists.keys()).lower()
  53. if list_name in self.client.lists:
  54. return list_name
  55. else:
  56. return None
  57. def call(self, **_):
  58. list_name = self._get_list()
  59. if list_name is None:
  60. clips.play(clips.Clips.FAILURE)
  61. return
  62. lines, terminator = ears.listen_until_terminated(timeout=_LISTEN_TIMEOUT, preferred_phrases=_GROCERIES)
  63. if terminator == 'cancel':
  64. tts.tts('cancelled')
  65. return
  66. else:
  67. items = []
  68. for line in lines:
  69. items.extend([t.strip() for t in line.split(' and ') if t.strip()])
  70. for item in items:
  71. self.client.create_task(self.list_name, item)
  72. tts.tts('ok')