9
9
:license: MIT, see LICENSE for more details.
10
10
"""
11
11
import sys
12
+ import base64
13
+ import time
14
+ import uuid
12
15
if sys .version_info > (3 , 0 ):
13
16
import urllib .request as urllib2
14
17
import urllib .error
15
18
from urllib .error import HTTPError
16
- import urllib .parse as urllib
17
- import html
18
19
from http .client import BadStatusLine
19
20
else :
20
21
import urllib2
21
22
from urllib2 import HTTPError
22
- import urllib
23
- from HTMLParser import HTMLParser
24
23
from httplib import BadStatusLine
25
24
26
- import base64
27
- import time
28
- import datetime
29
- import uuid
30
-
31
25
try :
32
26
import json
33
27
except ImportError :
37
31
# For Google AppEngine
38
32
from django .utils import simplejson as json
39
33
40
- APP_ID = 'chalk-bump-f49'
34
+ APP_ID = 'chalk-bump-f49'
41
35
# There is no way for us to hide this key, only obfuscate it.
42
36
# So please be kind and don't (ab)use it.
43
37
# Simplenote/Simperium didn't have to provide us with this.
44
- API_KEY = base64 .b64decode ('YzhjMmI4NjMzNzE1NGNkYWJjOTg5YjIzZTMwYzZiZjQ=' )
45
- BUCKET = 'note'
38
+ API_KEY = base64 .b64decode ('YzhjMmI4NjMzNzE1NGNkYWJjOTg5YjIzZTMwYzZiZjQ=' )
39
+ BUCKET = 'note'
46
40
AUTH_URL = 'https://auth.simperium.com/1/%s/authorize/' % (APP_ID )
47
41
DATA_URL = 'https://api.simperium.com/1/%s/%s' % (APP_ID , BUCKET )
48
42
NOTE_FETCH_LENGTH = 1000
49
43
50
44
class SimplenoteLoginFailed (Exception ):
45
+ """ Class for reporting login failures """
51
46
pass
52
47
53
48
@@ -71,7 +66,6 @@ def authenticate(self, user, password):
71
66
72
67
Returns:
73
68
Simplenote API token as string
74
-
75
69
"""
76
70
77
71
request = Request (AUTH_URL )
@@ -99,10 +93,10 @@ def get_token(self):
99
93
Simplenote API token as string
100
94
101
95
"""
102
- if self .token == None :
96
+ if self .token is None :
103
97
self .token = self .authenticate (self .username , self .password )
104
98
try :
105
- return str (self .token ,'utf-8' )
99
+ return str (self .token , 'utf-8' )
106
100
except TypeError :
107
101
return self .token
108
102
@@ -130,15 +124,15 @@ def get_note(self, noteid, version=None):
130
124
request .add_header (self .header , self .get_token ())
131
125
try :
132
126
response = urllib2 .urlopen (request )
133
- except HTTPError as e :
134
- if e .code == 401 :
127
+ except HTTPError as error :
128
+ if error .code == 401 :
135
129
raise SimplenoteLoginFailed ('Login to Simplenote API failed! Check Token.' )
136
- else :
137
- return e , - 1
138
- except (IOError , BadStatusLine ) as e :
139
- return e , - 1
130
+ return error , - 1
131
+ except (IOError , BadStatusLine ) as error :
132
+ return error , - 1
140
133
note = json .loads (response .read ().decode ('utf-8' ))
141
- note = self .__add_simplenote_api_fields (note , noteid , int (response .info ().get ("X-Simperium-Version" )))
134
+ note = self .__add_simplenote_api_fields (note , noteid ,
135
+ int (response .info ().get ("X-Simperium-Version" )))
142
136
# Sort tags
143
137
# For early versions of notes, tags not always available
144
138
if "tags" in note :
@@ -188,15 +182,15 @@ def update_note(self, note):
188
182
response = ""
189
183
try :
190
184
response = urllib2 .urlopen (request )
191
- except HTTPError as e :
192
- if e .code == 401 :
185
+ except HTTPError as error :
186
+ if error .code == 401 :
193
187
raise SimplenoteLoginFailed ('Login to Simplenote API failed! Check Token.' )
194
- else :
195
- return e , - 1
196
- except (IOError , BadStatusLine ) as e :
197
- return e , - 1
188
+ return error , - 1
189
+ except (IOError , BadStatusLine ) as error :
190
+ return error , - 1
198
191
note_to_update = json .loads (response .read ().decode ('utf-8' ))
199
- note_to_update = self .__add_simplenote_api_fields (note_to_update , noteid , int (response .info ().get ("X-Simperium-Version" )))
192
+ note_to_update = self .__add_simplenote_api_fields (
193
+ note_to_update , noteid , int (response .info ().get ("X-Simperium-Version" )))
200
194
return note_to_update , 0
201
195
202
196
def add_note (self , note ):
@@ -220,10 +214,9 @@ def add_note(self, note):
220
214
221
215
if type (note ) == str :
222
216
return self .update_note ({"content" : note })
223
- elif (type (note ) == dict ) and "content" in note :
217
+ if (type (note ) == dict ) and "content" in note :
224
218
return self .update_note (note )
225
- else :
226
- return "No string or valid note." , - 1
219
+ return "No string or valid note." , - 1
227
220
228
221
def get_note_list (self , data = True , since = None , tags = []):
229
222
""" Method to get the note list
@@ -253,9 +246,8 @@ def get_note_list(self, data=True, since=None, tags=[]):
253
246
"""
254
247
# initialize data
255
248
status = 0
256
- ret = []
257
249
response_notes = {}
258
- notes = { "index" : [] }
250
+ notes = {"index" : []}
259
251
260
252
# get the note index
261
253
params = '/index?limit=%s' % (str (NOTE_FETCH_LENGTH ))
@@ -274,20 +266,20 @@ def get_note_list(self, data=True, since=None, tags=[]):
274
266
response_notes = json .loads (response .read ().decode ('utf-8' ))
275
267
# re-write for v1 consistency
276
268
note_objects = []
277
- for n in response_notes ["index" ]:
278
- # If data=False then can't do this bit... or not all of it, just have id and version. Add empty data object.
269
+ for nitem in response_notes ["index" ]:
270
+ # If data=False then can't do this bit... or not all of it,
271
+ # just have id and version. Add empty data object.
279
272
if not data :
280
- n ['d' ] = {}
281
- note_object = self .__add_simplenote_api_fields (n ['d' ], n ['id' ], n ['v' ])
273
+ nitem ['d' ] = {}
274
+ note_object = self .__add_simplenote_api_fields (nitem ['d' ], nitem ['id' ], nitem ['v' ])
282
275
note_objects .append (note_object )
283
276
notes ["index" ].extend (note_objects )
284
- except HTTPError as e :
285
- if e .code == 401 :
277
+ except HTTPError as error :
278
+ if error .code == 401 :
286
279
raise SimplenoteLoginFailed ('Login to Simplenote API failed! Check Token.' )
287
- else :
288
- return e , - 1
289
- except (IOError , BadStatusLine ) as e :
290
- return e , - 1
280
+ return error , - 1
281
+ except (IOError , BadStatusLine ) as error :
282
+ return error , - 1
291
283
292
284
# get additional notes if bookmark was set in response
293
285
while "mark" in response_notes :
@@ -301,25 +293,25 @@ def get_note_list(self, data=True, since=None, tags=[]):
301
293
response_notes = json .loads (response .read ().decode ('utf-8' ))
302
294
# re-write for v1 consistency
303
295
note_objects = []
304
- for n in response_notes ["index" ]:
296
+ for nitem in response_notes ["index" ]:
305
297
if not data :
306
- n ['d' ] = {}
307
- note_object = n ['d' ]
308
- note_object = self .__add_simplenote_api_fields (n ['d' ], n ['id' ], n ['v' ])
298
+ nitem ['d' ] = {}
299
+ note_object = nitem ['d' ]
300
+ note_object = self .__add_simplenote_api_fields (
301
+ nitem ['d' ], nitem ['id' ], nitem ['v' ])
309
302
note_objects .append (note_object )
310
303
notes ["index" ].extend (note_objects )
311
- except HTTPError as e :
312
- if e .code == 401 :
304
+ except HTTPError as error :
305
+ if error .code == 401 :
313
306
raise SimplenoteLoginFailed ('Login to Simplenote API failed! Check Token.' )
314
- else :
315
- return e , - 1
316
- except (IOError , BadStatusLine ) as e :
317
- return e , - 1
307
+ return error , - 1
308
+ except (IOError , BadStatusLine ) as error :
309
+ return error , - 1
318
310
note_list = notes ["index" ]
319
311
self .current = response_notes ["current" ]
320
312
# Can only filter for tags at end, once all notes have been retrieved.
321
- if ( len ( tags ) > 0 ) :
322
- note_list = [n for n in note_list if ( len ( set (n ["tags" ]).intersection (tags )) > 0 )]
313
+ if tags :
314
+ note_list = [n for n in note_list if set (n ["tags" ]).intersection (tags )]
323
315
return note_list , status
324
316
325
317
def trash_note (self , note_id ):
@@ -337,7 +329,7 @@ def trash_note(self, note_id):
337
329
"""
338
330
# get note
339
331
note , status = self .get_note (note_id )
340
- if ( status == - 1 ) :
332
+ if status == - 1 :
341
333
return note , status
342
334
# set deleted property, but only if not already trashed
343
335
# TODO: A 412 is ok, that's unmodified. Should handle this in update_note and
@@ -347,8 +339,7 @@ def trash_note(self, note_id):
347
339
note ["modificationDate" ] = time .time ()
348
340
# update note
349
341
return self .update_note (note )
350
- else :
351
- return note , 0
342
+ return note , 0
352
343
353
344
def delete_note (self , note_id ):
354
345
""" Method to permanently delete a note
@@ -365,21 +356,20 @@ def delete_note(self, note_id):
365
356
"""
366
357
# notes have to be trashed before deletion
367
358
note , status = self .trash_note (note_id )
368
- if ( status == - 1 ) :
359
+ if status == - 1 :
369
360
return note , status
370
361
371
362
params = '/i/%s' % (str (note_id ))
372
363
request = Request (url = DATA_URL + params , method = 'DELETE' )
373
364
request .add_header (self .header , self .get_token ())
374
365
try :
375
- response = urllib2 .urlopen (request )
376
- except (IOError , BadStatusLine ) as e :
377
- return e , - 1
378
- except HTTPError as e :
379
- if e .code == 401 :
366
+ urllib2 .urlopen (request )
367
+ except HTTPError as error :
368
+ if error .code == 401 :
380
369
raise SimplenoteLoginFailed ('Login to Simplenote API failed! Check Token.' )
381
- else :
382
- return e , - 1
370
+ return error , - 1
371
+ except (IOError , BadStatusLine ) as error :
372
+ return error , - 1
383
373
return {}, 0
384
374
385
375
def __add_simplenote_api_fields (self , note , noteid , version ):
@@ -409,18 +399,18 @@ def __remove_simplenote_api_fields(self, note):
409
399
# Let's only set these ones if they exist. We don't want None so we can
410
400
# still set defaults afterwards
411
401
mappings = {
412
- "modifydate" : "modificationDate" ,
413
- "createdate" : "creationDate" ,
414
- "systemtags" : "systemTags"
402
+ "modifydate" : "modificationDate" ,
403
+ "createdate" : "creationDate" ,
404
+ "systemtags" : "systemTags"
415
405
}
416
406
if sys .version_info < (3 , 0 ):
417
- for k , v in mappings .iteritems ():
418
- if k in note :
419
- note [v ] = note .pop (k )
407
+ for nkey , nvalue in mappings .iteritems ():
408
+ if nkey in note :
409
+ note [nvalue ] = note .pop (nkey )
420
410
else :
421
- for k , v in mappings .items ():
422
- if k in note :
423
- note [v ] = note .pop (k )
411
+ for nkey , nvalue in mappings .items ():
412
+ if nkey in note :
413
+ note [nvalue ] = note .pop (nkey )
424
414
# Need to add missing dict stuff if missing, might as well do by
425
415
# default, not just for note objects only containing content
426
416
createDate = time .time ()
@@ -434,11 +424,11 @@ def __remove_simplenote_api_fields(self, note):
434
424
"publishURL" : "" ,
435
425
}
436
426
if sys .version_info < (3 , 0 ):
437
- for k , v in note_dict .iteritems ():
438
- note .setdefault (k , v )
427
+ for nkey , nvalue in note_dict .iteritems ():
428
+ note .setdefault (nkey , nvalue )
439
429
else :
440
- for k , v in note_dict .items ():
441
- note .setdefault (k , v )
430
+ for nkey , nvalue in note_dict .items ():
431
+ note .setdefault (nkey , nvalue )
442
432
return note
443
433
444
434
class Request (urllib2 .Request ):
@@ -448,7 +438,7 @@ class Request(urllib2.Request):
448
438
449
439
if sys .version_info < (3 , 0 ):
450
440
def __init__ (self , url , data = None , headers = {}, origin_req_host = None ,
451
- unverifiable = False , method = None ):
441
+ unverifiable = False , method = None ):
452
442
urllib2 .Request .__init__ (self , url , data , headers , origin_req_host , unverifiable )
453
443
self .method = method
454
444
0 commit comments