Debian Codegraph @

GTG/backends/unmaintained/rtm/rtm.py

raw
1 # Python library for Remember The Milk API
2
3 import urllib.request
4 import urllib.parse
5 import urllib.error
6 from hashlib import md5
7
8 from gettext import gettext as _
9 import logging
10
11 log = logging.getLogger(__name__)
12
13 _use_jsonlib = False
14 try:
15 import simplejson as json
16 assert json
17 _use_jsonlib = True
18 except ImportError:
19 try:
20 import json as json
21 assert json
22 _use_jsonlib = True
23 except ImportError:
24 try:
25 from django.utils import simplejson as json
26 _use_jsonlib = True
27 except ImportError:
28 pass
29
30 if not _use_jsonlib:
31 log.warning("simplejson module is not available, "
32 "falling back to the internal JSON parser. "
33 "Please consider installing the simplejson module from "
34 "http://pypi.python.org/pypi/simplejson.")
35
36 __author__ = 'Sridhar Ratnakumar <http://nearfar.org/>'
37 __all__ = (
38 'API',
39 'createRTM',
40 'set_log_level',
41 )
42
43 SERVICE_URL = 'http://api.rememberthemilk.com/services/rest/'
44 AUTH_SERVICE_URL = 'http://www.rememberthemilk.com/services/auth/'
45
46
47 class RTMError(Exception):
48 pass
49
50
51 class RTMAPIError(RTMError):
52 pass
53
54
55 class AuthStateMachine():
56
57 class NoData(RTMError):
58 pass
59
60 def __init__(self, states):
61 self.states = states
62 self.data = {}
63
64 def dataReceived(self, state, datum):
65 if state not in self.states:
66 error_string = _("Invalid state") + " <%s>"
67
68 raise RTMError(error_string % state)
69 self.data[state] = datum
70
71 def get(self, state):
72 if state in self.data:
73 return self.data[state]
74 else:
75 raise AuthStateMachine.NoData(f'No data for <{state}>')
76
77
78 class RTM():
79
80 def __init__(self, apiKey, secret, token=None):
81 self.apiKey = apiKey
82 self.secret = secret
83 self.authInfo = AuthStateMachine(['frob', 'token'])
84
85 # this enables one to do 'rtm.tasks.getList()', for example
86 for prefix, methods in list(API.items()):
87 setattr(self, prefix,
88 RTMAPICategory(self, prefix, methods))
89
90 if token:
91 self.authInfo.dataReceived('token', token)
92
93 def _sign(self, params):
94 "Sign the parameters with MD5 hash"
95 pairs = ''.join(['%s%s' % (k, v) for k, v in sortedItems(params)])
96 return md5((self.secret + pairs).encode('utf-8')).hexdigest()
97
98 def get(self, **params):
99 "Get the XML response for the passed `params`."
100 params['api_key'] = self.apiKey
101 params['format'] = 'json'
102 params['api_sig'] = self._sign(params)
103
104 json_data = openURL(SERVICE_URL, params).read()
105
106 # LOG.debug("JSON response: \n%s" % json)
107 if _use_jsonlib:
108 data = dottedDict('ROOT', json.loads(json_data.decode('utf-8')))
109 else:
110 data = dottedJSON(json_data.decode('utf-8'))
111 rsp = data.rsp
112
113 if rsp.stat == 'fail':
114 raise RTMAPIError(f'API call failed - {rsp.err.msg} ({rsp.err.code})')
115 else:
116 return rsp
117
118 def getNewFrob(self):
119 rsp = self.get(method='rtm.auth.getFrob')
120 self.authInfo.dataReceived('frob', rsp.frob)
121 return rsp.frob
122
123 def getAuthURL(self):
124 try:
125 frob = self.authInfo.get('frob')
126 except AuthStateMachine.NoData:
127 frob = self.getNewFrob()
128
129 params = {
130 'api_key': self.apiKey,
131 'perms': 'delete',
132 'frob': frob
133 }
134 params['api_sig'] = self._sign(params)
135 return AUTH_SERVICE_URL + '?' + urllib.parse.urlencode(params)
136
137 def getToken(self):
138 frob = self.authInfo.get('frob')
139 rsp = self.get(method='rtm.auth.getToken', frob=frob)
140 self.authInfo.dataReceived('token', rsp.auth.token)
141 return rsp.auth.token
142
143
144 class RTMAPICategory():
145 "See the `API` structure and `RTM.__init__`"
146
147 def __init__(self, rtm, prefix, methods):
148 self.rtm = rtm
149 self.prefix = prefix
150 self.methods = methods
151
152 def __getattr__(self, attr):
153 if attr in self.methods:
154 rargs, oargs = self.methods[attr]
155 if self.prefix == 'tasksNotes':
156 aname = f'rtm.tasks.notes.{attr}'
157 else:
158 aname = f'rtm.{self.prefix}.{attr}'
159 return lambda **params: self.callMethod(
160 aname, rargs, oargs, **params)
161 else:
162 raise AttributeError(f'No such attribute: {attr}')
163
164 def callMethod(self, aname, rargs, oargs, **params):
165 # Sanity checks
166 for requiredArg in rargs:
167 if requiredArg not in params:
168 raise TypeError(
169 f'Required parameter ({requiredArg}) missing')
170
171 for param in params:
172 if param not in rargs + oargs:
173 log.error('Invalid parameter (%s)', param)
174
175 return self.rtm.get(method=aname,
176 auth_token=self.rtm.authInfo.get('token'),
177 **params)
178
179
180 # Utility functions
181 def sortedItems(dictionary):
182 "Return a list of (key, value) sorted based on keys"
183 keys = list(dictionary.keys())
184 keys.sort()
185 for key in keys:
186 yield key, dictionary[key]
187
188
189 def openURL(url, queryArgs=None):
190 if queryArgs:
191 url = url + '?' + urllib.parse.urlencode(queryArgs)
192 # LOG.debug("URL> %s", url)
193 return urllib.request.urlopen(url)
194
195
196 class dottedDict():
197 """Make dictionary items accessible via the object-dot notation."""
198
199 def __init__(self, name, dictionary):
200 self._name = name
201
202 if type(dictionary) is dict:
203 for key, value in list(dictionary.items()):
204 if type(value) is dict:
205 value = dottedDict(key, value)
206 elif type(value) in (list, tuple) and key != 'tag':
207 value = [dottedDict(f'{key}_{i:d}', item)
208 for i, item in indexed(value)]
209 setattr(self, key, value)
210 else:
211 raise ValueError(f'not a dict: {dictionary}')
212
213 def __repr__(self):
214 children = [c for c in dir(self) if not c.startswith('_')]
215 return 'dotted <%s> : %s' % (
216 self._name,
217 ', '.join(children))
218
219
220 def safeEval(string):
221 return eval(string, {}, {})
222
223
224 def dottedJSON(json):
225 return dottedDict('ROOT', safeEval(json))
226
227
228 def indexed(seq):
229 index = 0
230 for item in seq:
231 yield index, item
232 index += 1
233
234
235 # API spec
236
237 API = {
238 'auth': {
239 'checkToken':
240 [('auth_token',), ()],
241 'getFrob':
242 [(), ()],
243 'getToken':
244 [('frob',), ()]
245 },
246 'contacts': {
247 'add': [('timeline', 'contact'), ()],
248 'delete': [('timeline', 'contact_id'), ()],
249 'getList': [(), ()]
250 },
251 'groups': {
252 'add': [('timeline', 'group'), ()],
253 'addContact': [('timeline', 'group_id', 'contact_id'), ()],
254 'delete': [('timeline', 'group_id'), ()],
255 'getList': [(), ()],
256 'removeContact': [('timeline', 'group_id', 'contact_id'), ()],
257 },
258 'lists': {
259 'add': [('timeline', 'name',), ('filter',)],
260 'archive': [('timeline', 'list_id'), ()],
261 'delete': [('timeline', 'list_id'), ()],
262 'getList': [(), ()],
263 'setDefaultList': [('timeline'), ('list_id')],
264 'setName': [('timeline', 'list_id', 'name'), ()],
265 'unarchive': [('timeline',), ('list_id',)]
266 },
267 'locations': {
268 'getList': [(), ()]
269 },
270 'reflection': {
271 'getMethodInfo': [('methodName',), ()],
272 'getMethods': [(), ()]
273 },
274 'settings': {
275 'getList': [(), ()]
276 },
277 'tasks': {
278 'add': [('timeline', 'name',), ('list_id', 'parse',)],
279 'addTags': [
280 ('timeline', 'list_id', 'taskseries_id', 'task_id', 'tags'), (),
281 ],
282 'complete': [('timeline', 'list_id', 'taskseries_id', 'task_id',), ()],
283 'delete': [('timeline', 'list_id', 'taskseries_id', 'task_id'), ()],
284 'getList': [(), ('list_id', 'filter', 'last_sync')],
285 'movePriority': [
286 ('timeline', 'list_id', 'taskseries_id', 'task_id', 'direction'),
287 (),
288 ],
289 'moveTo': [
290 ('timeline', 'from_list_id', 'to_list_id',
291 'taskseries_id', 'task_id'),
292 (),
293 ],
294 'postpone':
295 [('timeline', 'list_id', 'taskseries_id', 'task_id'),
296 ()],
297 'removeTags':
298 [('timeline', 'list_id', 'taskseries_id', 'task_id', 'tags'),
299 ()],
300 'setDueDate':
301 [('timeline', 'list_id', 'taskseries_id', 'task_id'),
302 ('due', 'has_due_time', 'parse')],
303 'setEstimate':
304 [('timeline', 'list_id', 'taskseries_id', 'task_id'),
305 ('estimate',)],
306 'setLocation':
307 [('timeline', 'list_id', 'taskseries_id', 'task_id'),
308 ('location_id',)],
309 'setName':
310 [('timeline', 'list_id', 'taskseries_id', 'task_id', 'name'),
311 ()],
312 'setPriority':
313 [('timeline', 'list_id', 'taskseries_id', 'task_id'),
314 ('priority',)],
315 'setRecurrence':
316 [('timeline', 'list_id', 'taskseries_id', 'task_id'),
317 ('repeat',)],
318 'setTags':
319 [('timeline', 'list_id', 'taskseries_id', 'task_id'),
320 ('tags',)],
321 'setURL':
322 [('timeline', 'list_id', 'taskseries_id', 'task_id'),
323 ('url',)],
324 'uncomplete':
325 [('timeline', 'list_id', 'taskseries_id', 'task_id'),
326 ()],
327 },
328 'tasksNotes': {
329 'add': [
330 ('timeline', 'list_id', 'taskseries_id', 'task_id',
331 'note_title', 'note_text'), ()],
332 'delete': [('timeline', 'note_id'), ()],
333 'edit': [('timeline', 'note_id', 'note_title', 'note_text'), ()]
334 },
335 'test': {
336 'echo': [(), ()],
337 'login': [(), ()]
338 },
339 'time': {
340 'convert': [
341 ('to_timezone',), ('from_timezone', 'to_timezone', 'time')],
342 'parse': [('text',), ('timezone', 'dateformat')]
343 },
344 'timelines': {
345 'create': [(), ()]
346 },
347 'timezones': {
348 'getList': [(), ()]
349 },
350 'transactions': {
351 'undo': [('timeline', 'transaction_id'), ()]
352 },
353 }
354
355
356 def createRTM(apiKey, secret, token=None):
357 rtm = RTM(apiKey, secret, token)
358 # if token is None:
359 # print 'No token found'
360 # print 'Give me access here:', rtm.getAuthURL()
361 # raw_input('Press enter once you gave access')
362 # print 'Note down this token for future use:', rtm.getToken()
363
364 return rtm
365
366
367 def test(apiKey, secret, token=None):
368 rtm = createRTM(apiKey, secret, token)
369
370 rspTasks = rtm.tasks.getList(filter='dueWithin:"1 week of today"')
371 print([t.name for t in rspTasks.tasks.list.taskseries])
372 print(rspTasks.tasks.list.id)
373
374 rspLists = rtm.lists.getList()
375 # print rspLists.lists.list
376 print([(x.name, x.id) for x in rspLists.lists.list])
377
378
379 def set_log_level(level):
380 """Sets the log level of the logger used by the module.
381
382 >>> import rtm
383 >>> import logging
384 >>> rtm.set_log_level(logging.INFO)
385 """
386
387 # LOG.setLevel(level)