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