File: simplenote.py

package info (click to toggle)
python-simplenote 2.1.4-1.1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, bullseye, forky, sid, trixie
  • size: 164 kB
  • sloc: python: 495; makefile: 116
file content (461 lines) | stat: -rw-r--r-- 16,405 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
# -*- coding: utf-8 -*-
"""
    simplenote.py
    ~~~~~~~~~~~~~~

    Python library for accessing the Simplenote API

    :copyright: (c) 2011 by Daniel Schauenberg
    :license: MIT, see LICENSE for more details.
"""
import sys
if sys.version_info > (3, 0):
    import urllib.request as urllib2
    import urllib.error
    from urllib.error import HTTPError
    import urllib.parse as urllib
    import html
    from http.client import BadStatusLine
else:
    import urllib2
    from urllib2 import HTTPError
    import urllib
    from HTMLParser import HTMLParser
    from httplib import BadStatusLine

import base64
import time
import datetime
import uuid

try:
    import json
except ImportError:
    try:
        import simplejson as json
    except ImportError:
        # For Google AppEngine
        from django.utils import simplejson as json

APP_ID   = 'chalk-bump-f49'
# There is no way for us to hide this key, only obfuscate it.
# So please be kind and don't (ab)use it.
# Simplenote/Simperium didn't have to provide us with this.
API_KEY  = base64.b64decode('YzhjMmI4NjMzNzE1NGNkYWJjOTg5YjIzZTMwYzZiZjQ=')
BUCKET   = 'note'
AUTH_URL = 'https://auth.simperium.com/1/%s/authorize/' % (APP_ID)
DATA_URL = 'https://api.simperium.com/1/%s/%s' % (APP_ID, BUCKET)
NOTE_FETCH_LENGTH = 1000

class SimplenoteLoginFailed(Exception):
    pass


class Simplenote(object):
    """ Class for interacting with the simplenote web service """

    def __init__(self, username, password):
        """ object constructor """
        self.username = username
        self.password = password
        self.header = 'X-Simperium-Token'
        self.token = None
        self.current = ""

    def authenticate(self, user, password):
        """ Method to get simplenote auth token

        Arguments:
            - User (string):     simplenote email address
            - password (string): simplenote password

        Returns:
            Simplenote API token as string
            
        """

        request = Request(AUTH_URL)
        request.add_header('X-Simperium-API-Key', API_KEY)
        if sys.version_info < (3, 3):
            request.add_data(json.dumps({'username': user, 'password': password}))
        else:
            request.data = json.dumps({'username': user, 'password': password}).encode()
        try:
            res = urllib2.urlopen(request).read()
            token = json.loads(res.decode('utf-8'))["access_token"]
        except (HTTPError, BadStatusLine):
            raise SimplenoteLoginFailed('Login to Simplenote API failed!')
        except IOError: # no connection exception
            token = None
        return token

    def get_token(self):
        """ Method to retrieve an auth token.

        The cached global token is looked up and returned if it exists. If it
        is `None` a new one is requested and returned.

        Returns:
            Simplenote API token as string

        """
        if self.token == None:
            self.token = self.authenticate(self.username, self.password)
        try:
            return str(self.token,'utf-8')
        except TypeError:
            return self.token

    def get_note(self, noteid, version=None):
        """ Method to get a specific note

        Arguments:
            - noteid (string): ID of the note to get
            - version (int): optional version of the note to get

        Returns:
            A tuple `(note, status)`

            - note (dict): note object
            - status (int): 0 on success and -1 otherwise

        """
        # request note
        params_version = ""
        if version is not None:
            params_version = '/v/' + str(version)

        params = '/i/%s%s' % (str(noteid), params_version)
        request = Request(DATA_URL+params)
        request.add_header(self.header, self.get_token())
        try:
            response = urllib2.urlopen(request)
        except HTTPError as e:
            if e.code == 401:
                raise SimplenoteLoginFailed('Login to Simplenote API failed! Check Token.')
            else:
                return e, -1
        except (IOError, BadStatusLine) as e:
            return e, -1
        note = json.loads(response.read().decode('utf-8'))
        note = self.__add_simplenote_api_fields(note, noteid, int(response.info().get("X-Simperium-Version")))
        # Sort tags
        # For early versions of notes, tags not always available
        if "tags" in note:
            note["tags"] = sorted(note["tags"])

        return note, 0

    def update_note(self, note):
        """ Method to update a specific note object, if the note object does not
        have a "key" field, a new note is created

        Arguments
            - note (dict): note object to update

        Returns:
            A tuple `(note, status)`
            - note (dict): note object
            - status (int): 0 on success and -1 otherwise

        """
        # Let's create a copy to work with so we don't alter original
        note_to_update = note.copy()
        # determine whether to create a new note or update an existing one
        # Also need to add/remove key field to keep simplenote.py consistency
        if "key" in note_to_update:
            # Then already have a noteid we need to remove before passing to Simperium API
            noteid = note_to_update.pop("key", None)
        else:
            # Adding a new note
            noteid = uuid.uuid4().hex


        # TODO: Set a ccid?
        # ccid = uuid.uuid4().hex
        if "version" in note_to_update:
            version = note_to_update.pop("version", None)
            url = '%s/i/%s/v/%s?response=1' % (DATA_URL, noteid, version)
        else:
            url = '%s/i/%s?response=1' % (DATA_URL, noteid)

        # TODO: Could do with being consistent here. Everywhere else is Request(DATA_URL+params)
        note_to_update = self.__remove_simplenote_api_fields(note_to_update)
        request = Request(url, data=json.dumps(note_to_update).encode('utf-8'))
        request.add_header(self.header, self.get_token())
        request.add_header('Content-Type', 'application/json')

        response = ""
        try:
            response = urllib2.urlopen(request)
        except HTTPError as e:
            if e.code == 401:
                raise SimplenoteLoginFailed('Login to Simplenote API failed! Check Token.')
            else:
                return e, -1
        except (IOError, BadStatusLine) as e:
            return e, -1
        note_to_update = json.loads(response.read().decode('utf-8'))
        note_to_update = self.__add_simplenote_api_fields(note_to_update, noteid, int(response.info().get("X-Simperium-Version")))
        return note_to_update, 0

    def add_note(self, note):
        """ Wrapper method to add a note

        The method can be passed the note as a dict with the `content`
        property set, which is then directly send to the web service for
        creation. Alternatively, only the body as string can also be passed. In
        this case the parameter is used as `content` for the new note.

        Arguments:
            - note (dict or string): the note to add

        Returns:
            A tuple `(note, status)`

            - note (dict): the newly created note
            - status (int): 0 on success and -1 otherwise

        """

        if type(note) == str:
            return self.update_note({"content": note})
        elif (type(note) == dict) and "content" in note:
            return self.update_note(note)
        else:
            return "No string or valid note.", -1

    def get_note_list(self, data=True, since=None, tags=[]):
        """ Method to get the note list

        The method can be passed optional arguments to limit the list to
        notes containing a certain tag, or only updated since a certain
        Simperium cursor. If omitted a list of all notes is returned.

        By default data objects are returned. If data is set to false only
        keys/ids and versions are returned. An empty data object is inserted
        for compatibility.

        Arguments:
            - tags=[] list of tags as string: return notes that have
              at least one of these tags
            - since=cursor Simperium cursor as string: return only changes
              since this cursor
            - data=True If false only return keys/ids and versions

        Returns:
            A tuple `(notes, status)`

            - notes (list): A list of note objects with all properties set except
            `content`.
            - status (int): 0 on success and -1 otherwise

        """
        # initialize data
        status = 0
        ret = []
        response_notes = {}
        notes = { "index" : [] }

        # get the note index
        params = '/index?limit=%s' % (str(NOTE_FETCH_LENGTH))

        if since is not None:
            params += '&since=%s' % (since)
        # Fetching data is the default
        if data:
            params += '&data=true'

        # perform initial HTTP request
        request = Request(DATA_URL+params)
        request.add_header(self.header, self.get_token())
        try:
            response = urllib2.urlopen(request)
            response_notes = json.loads(response.read().decode('utf-8'))
            # re-write for v1 consistency
            note_objects = []
            for n in response_notes["index"]:
                # If data=False then can't do this bit... or not all of it, just have id and version. Add empty data object.
                if not data:
                    n['d'] = {}
                note_object = self.__add_simplenote_api_fields(n['d'], n['id'], n['v'])
                note_objects.append(note_object)
            notes["index"].extend(note_objects)
        except HTTPError as e:
            if e.code == 401:
                raise SimplenoteLoginFailed('Login to Simplenote API failed! Check Token.')
            else:
                return e, -1
        except (IOError, BadStatusLine) as e:
            return e, -1

        # get additional notes if bookmark was set in response
        while "mark" in response_notes:
            params += '&mark=%s' % response_notes["mark"]

            # perform the actual HTTP request
            request = Request(DATA_URL+params)
            request.add_header(self.header, self.get_token())
            try:
                response = urllib2.urlopen(request)
                response_notes = json.loads(response.read().decode('utf-8'))
                # re-write for v1 consistency
                note_objects = []
                for n in response_notes["index"]:
                    if not data:
                        n['d'] = {}
                    note_object = n['d']
                    note_object = self.__add_simplenote_api_fields(n['d'], n['id'], n['v'])
                    note_objects.append(note_object)
                notes["index"].extend(note_objects)
            except HTTPError as e:
                if e.code == 401:
                    raise SimplenoteLoginFailed('Login to Simplenote API failed! Check Token.')
                else:
                    return e, -1
            except (IOError, BadStatusLine) as e:
                return e, -1
        note_list = notes["index"]
        self.current = response_notes["current"]
        # Can only filter for tags at end, once all notes have been retrieved.
        if (len(tags) > 0):
            note_list = [n for n in note_list if (len(set(n["tags"]).intersection(tags)) > 0)]
        return note_list, status

    def trash_note(self, note_id):
        """ Method to move a note to the trash

        Arguments:
            - note_id (string): key of the note to trash

        Returns:
            A tuple `(note, status)`

            - note (dict): the newly created note or an error message
            - status (int): 0 on success and -1 otherwise

        """
        # get note
        note, status = self.get_note(note_id)
        if (status == -1):
            return note, status
        # set deleted property, but only if not already trashed
        # TODO: A 412 is ok, that's unmodified. Should handle this in update_note and
        # then not worry about checking here
        if not note["deleted"]:
            note["deleted"] = True
            note["modificationDate"] = time.time()
            # update note
            return self.update_note(note)
        else:
            return note, 0

    def delete_note(self, note_id):
        """ Method to permanently delete a note

        Arguments:
            - note_id (string): key of the note to trash

        Returns:
            A tuple `(note, status)`

            - note (dict): an empty dict or an error message
            - status (int): 0 on success and -1 otherwise

        """
        # notes have to be trashed before deletion
        note, status = self.trash_note(note_id)
        if (status == -1):
            return note, status

        params = '/i/%s' % (str(note_id))
        request = Request(url=DATA_URL+params, method='DELETE')
        request.add_header(self.header, self.get_token())
        try:
            response = urllib2.urlopen(request)
        except (IOError, BadStatusLine) as e:
            return e, -1
        except HTTPError as e:
            if e.code == 401:
                raise SimplenoteLoginFailed('Login to Simplenote API failed! Check Token.')
            else:
                return e, -1
        return {}, 0

    def __add_simplenote_api_fields(self, note, noteid, version):
        # Compatibility with original Simplenote API v2.1.5

        # We are not creating a copy of the note to work with as these are only
        # used internally and so doesn't matter if we alter "original"
        note[u'key'] = noteid
        note[u'version'] = version
        try:
            note[u'modifydate'] = note["modificationDate"]
            note[u'createdate'] = note["creationDate"]
            note[u'systemtags'] = note["systemTags"]
        except KeyError:
            # For when data=False
            pass
        return note

    def __remove_simplenote_api_fields(self, note):
        # We are not creating a copy of the note to work with as these are only
        # used internally and so doesn't matter if we alter "original"

        # These two should have already removed by this point since they are
        # needed for updating, etc, but _just_ incase...
        note.pop("key", None)
        note.pop("version", None)
        # Let's only set these ones if they exist. We don't want None so we can
        # still set defaults afterwards
        mappings = {
                "modifydate": "modificationDate",
                "createdate": "creationDate",
                "systemtags": "systemTags"
        }
        if sys.version_info < (3, 0):
            for k,v in mappings.iteritems():
                if k in note:
                    note[v] = note.pop(k)
        else:
            for k,v in mappings.items():
                if k in note:
                    note[v] = note.pop(k)
        # Need to add missing dict stuff if missing, might as well do by
        # default, not just for note objects only containing content
        createDate = time.time()
        note_dict = {
            "tags" : [],
            "systemTags" : [],
            "creationDate" : createDate,
            "modificationDate" : createDate,
            "deleted" : False,
            "shareURL" : "",
            "publishURL" : "",
        }
        if sys.version_info < (3, 0):
            for k,v in note_dict.iteritems():
                note.setdefault(k, v)
        else:
            for k,v in note_dict.items():
                note.setdefault(k, v)
        return note

class Request(urllib2.Request):
    """ monkey patched version of urllib2's Request to support HTTP DELETE
        Taken from http://python-requests.org, thanks @kennethreitz
    """

    if sys.version_info < (3, 0):
        def __init__(self, url, data=None, headers={}, origin_req_host=None,
                    unverifiable=False, method=None):
            urllib2.Request.__init__(self, url, data, headers, origin_req_host, unverifiable)
            self.method = method

        def get_method(self):
            if self.method:
                return self.method

            return urllib2.Request.get_method(self)
    else:
        pass