720c0d2de8692b188f6656bc1a05e13ac5f67180
[doneit] / src / rtm_api.py
1
2 """
3 Python library for Remember The Milk API
4
5 @note For help, see http://www.rememberthemilk.com/services/api/methods/
6 """
7
8 import weakref
9 import warnings
10 import urllib
11 import urllib2
12 import hashlib
13 import time
14
15 _use_simplejson = False
16 try:
17         import simplejson
18         _use_simplejson = True
19 except ImportError:
20         pass
21
22
23 __author__ = 'Sridhar Ratnakumar <http://nearfar.org/>'
24
25 SERVICE_URL = 'http://api.rememberthemilk.com/services/rest/'
26 AUTH_SERVICE_URL = 'http://www.rememberthemilk.com/services/auth/'
27
28
29 class RTMError(StandardError):
30         pass
31
32
33 class RTMAPIError(RTMError):
34         pass
35
36
37 class RTMParseError(RTMError):
38         pass
39
40
41 class AuthStateMachine(object):
42         """If the state is in those setup for the machine, then return
43         the datum sent.  Along the way, it is an automatic call if the
44         datum is a method.
45         """
46
47         class NoData(RTMError):
48                 pass
49
50         def __init__(self, states):
51                 self.states = states
52                 self.data = {}
53
54         def dataReceived(self, state, datum):
55                 if state not in self.states:
56                         raise RTMError, "Invalid state <%s>" % state
57                 self.data[state] = datum
58
59         def get(self, state):
60                 if state in self.data:
61                         return self.data[state]
62                 else:
63                         raise AuthStateMachine.NoData('No data for <%s>' % state)
64
65
66 class RTMapi(object):
67
68         def __init__(self, userID, apiKey, secret, token=None):
69                 self._userID = userID
70                 self._apiKey = apiKey
71                 self._secret = secret
72                 self._authInfo = AuthStateMachine(['frob', 'token'])
73
74                 # this enables one to do 'rtm.tasks.getList()', for example
75                 for prefix, methods in API.items():
76                         setattr(self, prefix,
77                                         RTMAPICategory(self, prefix, methods))
78
79                 if token:
80                         self._authInfo.dataReceived('token', token)
81
82         def _sign(self, params):
83                 "Sign the parameters with MD5 hash"
84                 pairs = ''.join(['%s%s' % (k, v) for (k, v) in sortedItems(params)])
85                 return hashlib.md5(self._secret+pairs).hexdigest()
86
87         @staticmethod
88         def open_url(url, queryArgs=None):
89                 if queryArgs:
90                         url += '?' + urllib.urlencode(queryArgs)
91                 warnings.warn("Performing download of %s" % url, stacklevel=5)
92                 return urllib2.urlopen(url)
93
94         def get(self, **params):
95                 "Get the XML response for the passed `params`."
96                 params['api_key'] = self._apiKey
97                 params['format'] = 'json'
98                 params['api_sig'] = self._sign(params)
99
100                 connection = self.open_url(SERVICE_URL, params)
101
102                 # It appears that urllib uses the non-blocking variant of file objects
103                 # which means reads might not always be complete, so grabbing as much
104                 # of the data as possible with a sleep in between to give it more time
105                 # to grab data.
106                 chunks = []
107                 chunk = connection.read()
108                 while chunk:
109                         chunks.append(chunk)
110                         time.sleep(1)
111                         chunk = connection.read()
112                 json = "".join(chunks)
113                 if "Content-Length" in connection.info():
114                         assert len(json) == int(connection.info()["Content-Length"]), "The packet header promised %s of data but only was able to read %s of data" % (
115                                 len(json),
116                                 connection.info()["Content-Length"],
117                         )
118
119                 data = DottedDict('ROOT', parse_json(json))
120                 rsp = data.rsp
121
122                 if rsp.stat == 'fail':
123                         raise RTMAPIError, 'API call failed - %s (%s)' % (
124                                 rsp.err.msg, rsp.err.code)
125                 else:
126                         return rsp
127
128         def getNewFrob(self):
129                 rsp = self.get(method='rtm.auth.getFrob')
130                 self._authInfo.dataReceived('frob', rsp.frob)
131                 return rsp.frob
132
133         def getAuthURL(self):
134                 try:
135                         frob = self._authInfo.get('frob')
136                 except AuthStateMachine.NoData:
137                         frob = self.getNewFrob()
138
139                 params = {
140                         'api_key': self._apiKey,
141                         'perms': 'delete',
142                         'frob': frob
143                 }
144                 params['api_sig'] = self._sign(params)
145                 return AUTH_SERVICE_URL + '?' + urllib.urlencode(params)
146
147         def getToken(self):
148                 frob = self._authInfo.get('frob')
149                 rsp = self.get(method='rtm.auth.getToken', frob=frob)
150                 self._authInfo.dataReceived('token', rsp.auth.token)
151                 return rsp.auth.token
152
153
154 class RTMAPICategory(object):
155         "See the `API` structure and `RTM.__init__`"
156
157         def __init__(self, rtm, prefix, methods):
158                 self._rtm = weakref.ref(rtm)
159                 self._prefix = prefix
160                 self._methods = methods
161
162         def __getattr__(self, attr):
163                 if attr not in self._methods:
164                         raise AttributeError, 'No such attribute: %s' % attr
165
166                 rargs, oargs = self._methods[attr]
167                 if self._prefix == 'tasksNotes':
168                         aname = 'rtm.tasks.notes.%s' % attr
169                 else:
170                         aname = 'rtm.%s.%s' % (self._prefix, attr)
171                 return lambda **params: self.callMethod(
172                         aname, rargs, oargs, **params
173                 )
174
175         def callMethod(self, aname, rargs, oargs, **params):
176                 # Sanity checks
177                 for requiredArg in rargs:
178                         if requiredArg not in params:
179                                 raise TypeError, 'Required parameter (%s) missing' % requiredArg
180
181                 for param in params:
182                         if param not in rargs + oargs:
183                                 warnings.warn('Invalid parameter (%s)' % param)
184
185                 return self._rtm().get(method=aname,
186                                                         auth_token=self._rtm()._authInfo.get('token'),
187                                                         **params)
188
189
190 def sortedItems(dictionary):
191         "Return a list of (key, value) sorted based on keys"
192         keys = dictionary.keys()
193         keys.sort()
194         for key in keys:
195                 yield key, dictionary[key]
196
197
198 class DottedDict(object):
199         "Make dictionary items accessible via the object-dot notation."
200
201         def __init__(self, name, dictionary):
202                 self._name = name
203
204                 if isinstance(dictionary, dict):
205                         for key, value in dictionary.items():
206                                 if isinstance(value, dict):
207                                         value = DottedDict(key, value)
208                                 elif isinstance(value, (list, tuple)):
209                                         value = [DottedDict('%s_%d' % (key, i), item)
210                                                          for i, item in enumerate(value)]
211                                 setattr(self, key, value)
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         def __str__(self):
220                 children = [(c, getattr(self, c)) for c in dir(self) if not c.startswith('_')]
221                 return '{dotted %s: %s}' % (
222                         self._name,
223                         ', '.join(
224                                 ('%s: "%s"' % (k, str(v)))
225                                 for (k, v) in children)
226                 )
227
228
229 def safer_eval(string):
230         try:
231                 return eval(string, {}, {})
232         except SyntaxError, e:
233                 print "="*60
234                 print string
235                 print "="*60
236                 newE = RTMParseError("Error parseing json")
237                 newE.error = e
238                 raise newE
239
240
241 if _use_simplejson:
242         parse_json = simplejson.loads
243 else:
244         parse_json = safer_eval
245
246
247 API = {
248         'auth': {
249                 'checkToken':
250                         [('auth_token'), ()],
251                 'getFrob':
252                         [(), ()],
253                 'getToken':
254                         [('frob'), ()]
255         },
256         'contacts': {
257                 'add':
258                         [('timeline', 'contact'), ()],
259                 'delete':
260                         [('timeline', 'contact_id'), ()],
261                 'getList':
262                         [(), ()],
263         },
264         'groups': {
265                 'add':
266                         [('timeline', 'group'), ()],
267                 'addContact':
268                         [('timeline', 'group_id', 'contact_id'), ()],
269                 'delete':
270                         [('timeline', 'group_id'), ()],
271                 'getList':
272                         [(), ()],
273                 'removeContact':
274                         [('timeline', 'group_id', 'contact_id'), ()],
275         },
276         'lists': {
277                 'add':
278                         [('timeline', 'name'), ('filter'), ()],
279                 'archive':
280                         [('timeline', 'list_id'), ()],
281                 'delete':
282                         [('timeline', 'list_id'), ()],
283                 'getList':
284                         [(), ()],
285                 'setDefaultList':
286                         [('timeline'), ('list_id'), ()],
287                 'setName':
288                         [('timeline', 'list_id', 'name'), ()],
289                 'unarchive':
290                         [('timeline'), ('list_id'), ()],
291         },
292         'locations': {
293                 'getList':
294                         [(), ()],
295         },
296         'reflection': {
297                 'getMethodInfo':
298                         [('methodName',), ()],
299                 'getMethods':
300                         [(), ()],
301         },
302         'settings': {
303                 'getList':
304                         [(), ()],
305         },
306         'tasks': {
307                 'add':
308                         [('timeline', 'name',), ('list_id', 'parse',)],
309                 'addTags':
310                         [('timeline', 'list_id', 'taskseries_id', 'task_id', 'tags'),
311                          ()],
312                 'complete':
313                         [('timeline', 'list_id', 'taskseries_id', 'task_id',), ()],
314                 'delete':
315                         [('timeline', 'list_id', 'taskseries_id', 'task_id'), ()],
316                 'getList':
317                         [(),
318                          ('list_id', 'filter', 'last_sync')],
319                 'movePriority':
320                         [('timeline', 'list_id', 'taskseries_id', 'task_id', 'direction'),
321                          ()],
322                 'moveTo':
323                         [('timeline', 'from_list_id', 'to_list_id', 'taskseries_id', 'task_id'),
324                          ()],
325                 'postpone':
326                         [('timeline', 'list_id', 'taskseries_id', 'task_id'),
327                          ()],
328                 'removeTags':
329                         [('timeline', 'list_id', 'taskseries_id', 'task_id', 'tags'),
330                          ()],
331                 'setDueDate':
332                         [('timeline', 'list_id', 'taskseries_id', 'task_id'),
333                          ('due', 'has_due_time', 'parse')],
334                 'setEstimate':
335                         [('timeline', 'list_id', 'taskseries_id', 'task_id'),
336                          ('estimate',)],
337                 'setLocation':
338                         [('timeline', 'list_id', 'taskseries_id', 'task_id'),
339                          ('location_id',)],
340                 'setName':
341                         [('timeline', 'list_id', 'taskseries_id', 'task_id', 'name'),
342                          ()],
343                 'setPriority':
344                         [('timeline', 'list_id', 'taskseries_id', 'task_id'),
345                          ('priority',)],
346                 'setRecurrence':
347                         [('timeline', 'list_id', 'taskseries_id', 'task_id'),
348                          ('repeat',)],
349                 'setTags':
350                         [('timeline', 'list_id', 'taskseries_id', 'task_id'),
351                          ('tags',)],
352                 'setURL':
353                         [('timeline', 'list_id', 'taskseries_id', 'task_id'),
354                          ('url',)],
355                 'uncomplete':
356                         [('timeline', 'list_id', 'taskseries_id', 'task_id'),
357                          ()],
358         },
359         'tasksNotes': {
360                 'add':
361                         [('timeline', 'list_id', 'taskseries_id', 'task_id', 'note_title', 'note_text'), ()],
362                 'delete':
363                         [('timeline', 'note_id'), ()],
364                 'edit':
365                         [('timeline', 'note_id', 'note_title', 'note_text'), ()],
366         },
367         'test': {
368                 'echo':
369                         [(), ()],
370                 'login':
371                         [(), ()],
372         },
373         'time': {
374                 'convert':
375                         [('to_timezone',), ('from_timezone', 'to_timezone', 'time')],
376                 'parse':
377                         [('text',), ('timezone', 'dateformat')],
378         },
379         'timelines': {
380                 'create':
381                         [(), ()],
382         },
383         'timezones': {
384                 'getList':
385                         [(), ()],
386         },
387         'transactions': {
388                 'undo':
389                         [('timeline', 'transaction_id'), ()],
390         },
391 }