Ejemplo n.º 1
0
 def get_info(auth_token):
     try:
         sdk = EvernoteSdk(token=auth_token, sandbox=self.sandbox)
         user_store = sdk.get_user_store()
         user = user_store.getUser(auth_token)
         return user
     except Exception as e:
         message = 'get_user() failed. Code: %s, message: %s' % (
             e.errorCode, e.parameter)
         self.logger.error(message)
Ejemplo n.º 2
0
    def create_note(self,
                    auth_token,
                    text,
                    title=None,
                    files=None,
                    notebook_guid=None):
        if files is None:
            files = []
        sdk = EvernoteSdk(token=auth_token, sandbox=self.sandbox)
        # user_store = sdk.get_user_store()
        note_store = sdk.get_note_store()
        note = Types.Note()
        note.title = title or ('%s...' % text[:25] if len(text) > 30 else text)
        if notebook_guid is not None:
            note.notebookGuid = notebook_guid

        attachments = []
        for filename, mime_type in files:
            with open(filename, 'rb') as f:
                data_bytes = f.read()
                md5 = hashlib.md5()
                md5.update(data_bytes)

                data = Types.Data()
                data.size = len(data_bytes)
                data.bodyHash = md5.digest()
                data.body = data_bytes

                resource = Types.Resource()
                resource.mime = mime_type
                resource.data = data
                resource.attributes = Types.ResourceAttributes(
                    fileName=basename(filename))

                # Now, add the new Resource to the note's list of resources
                note.resources = [resource]

            attachments.append(
                '<br /><en-media type="%(mime_type)s" hash="%(md5)s" />' % {
                    'mime_type': mime_type,
                    'md5': md5.hexdigest(),
                })

        note.content = '<?xml version="1.0" encoding="UTF-8"?>' \
            '<!DOCTYPE en-note SYSTEM "http://xml.evernote.com/pub/enml2.dtd">' \
            '<en-note>%(text)s<br />%(attachments)s</en-note>' % {
                'text': text,
                'attachments': ''.join(attachments),
            }
        try:
            created_note = note_store.createNote(note)
        except Exception as e:
            print(e)
            logging.getLogger().error(traceback.format_exc())
        return created_note.guid
Ejemplo n.º 3
0
 def __init__(self,
              consumer_key,
              consumer_secret,
              oauth_callback,
              sandbox=True):
     self.oauth_callback = oauth_callback
     self.consumer_key = consumer_key
     self.consumer_secret = consumer_secret
     self.sandbox = sandbox
     self.sdk = EvernoteSdk(consumer_key=consumer_key,
                            consumer_secret=consumer_secret,
                            sandbox=sandbox)
Ejemplo n.º 4
0
    def update_note(self, auth_token, guid, text, files=None):
        sdk = EvernoteSdk(token=auth_token, sandbox=self.sandbox)
        note_store = sdk.get_note_store()
        note = note_store.getNote(guid, True, True, False, False)

        content = NoteContent(note)
        content.add_text(text)
        if files is not None:
            for filename, mime_type in files:
                content.add_file(filename, mime_type)

        note.resources = content.get_resources()
        note.content = str(content)

        note_store.updateNote(note)
Ejemplo n.º 5
0
 def _get_oauth_data():
     sdk = EvernoteSdk(consumer_key=api_key,
                       consumer_secret=api_secret,
                       sandbox=self.sandbox)
     bytes_key = ('%s%s%s' % (api_key, api_secret, user_id)).encode()
     callback_key = hashlib.sha1(bytes_key).hexdigest()
     callback_url = "%(callback_url)s?key=%(key)s&session_key=%(session_key)s" % {
         'callback_url': oauth_callback,
         'key': callback_key,
         'session_key': session_key,
     }
     request_token = sdk.get_request_token(callback_url)
     oauth_url = sdk.get_authorize_url(request_token)
     return {
         'oauth_url': oauth_url,
         'oauth_token': request_token['oauth_token'],
         'oauth_token_secret': request_token['oauth_token_secret'],
         'callback_key': callback_key
     }
Ejemplo n.º 6
0
    def __call_store_method(self, method_name, auth_token, *args, **kwargs):
        try:
            start_time = time.time()
            self.logger.debug("Start call '{0}'".format(method_name))
            sdk = EvernoteSdk(token=auth_token, sandbox=self.sandbox)
            note_store = sdk.get_note_store()
            method = getattr(note_store, method_name)
            result = method(*args, **kwargs)
            self.logger.debug("Finish call '{0}' in {1} sec".format(
                method_name,
                time.time() - start_time))
            return result
        except ErrorTypes.EDAMNotFoundException:
            exc_info = ExceptionInfo(NoteNotFound, 'Note not found')
        except ErrorTypes.EDAMUserException as e:
            if e.errorCode == 3:
                exc_info = ExceptionInfo(
                    PermissionDenied,
                    'It seems that token is invalid (or has no permissions)')
            elif e.errorCode == 9:
                exc_info = ExceptionInfo(TokenExpired,
                                         'Evernote access token is expired')
            else:
                exc_info = ExceptionInfo(
                    EvernoteApiError,
                    'Error code = {0}, parameter = {1}'.format(
                        e.errorCode, e.parameter))
        except ErrorTypes.EDAMSystemException as e:
            if e.errorCode == 19 and hasattr(e, 'rateLimitDuration'):
                exc_info = ExceptionInfo(
                    RateLimitReached,
                    'rateLimitDuration == {0}'.format(e.rateLimitDuration))
            else:
                exc_info = ExceptionInfo(
                    EvernoteApiError,
                    "{0}: {1}".format(getattr(e, 'errorCode', ''),
                                      getattr(e, 'message', '')))
        except Exception as e:
            self.logger.error(e)
            raise EvernoteApiError('Evernote API error') from None

        raise exc_info.exc_type(exc_info.message)
Ejemplo n.º 7
0
 def _list_notebooks():
     sdk = EvernoteSdk(token=auth_token, sandbox=self.sandbox)
     note_store = sdk.get_note_store()
     return note_store.listNotebooks()
Ejemplo n.º 8
0
 def _get_access_token():
     sdk = EvernoteSdk(consumer_key=api_key,
                       consumer_secret=api_secret,
                       sandbox=self.sandbox)
     return sdk.get_access_token(oauth_token, oauth_token_secret,
                                 oauth_verifier)
Ejemplo n.º 9
0
 async def get_service_host(self, auth_token):
     sdk = EvernoteSdk(token=auth_token, sandbox=self.sandbox)
     return sdk.service_host
Ejemplo n.º 10
0
class EvernoteClient:
    def __init__(self,
                 consumer_key,
                 consumer_secret,
                 oauth_callback,
                 sandbox=True):
        self.oauth_callback = oauth_callback
        self.consumer_key = consumer_key
        self.consumer_secret = consumer_secret
        self.sandbox = sandbox
        self.sdk = EvernoteSdk(consumer_key=consumer_key,
                               consumer_secret=consumer_secret,
                               sandbox=sandbox)

    def get_request_token(self, callback_url):
        return self.sdk.get_request_token(callback_url)

    def get_authorize_url(self, request_token):
        return self.sdk.get_authorize_url(request_token)

    def get_access_token(self, oauth_token, oauth_token_secret,
                         oauth_verifier):
        return self.sdk.get_access_token(oauth_token, oauth_token_secret,
                                         oauth_verifier)

    async def get_access_token_async(self, oauth_token, oauth_token_secret,
                                     oauth_verifier):
        # TODO:
        pass

    def get_oauth_data(self, user_id):
        bytes_key = (
            '%s%s%s' %
            (self.consumer_key, self.consumer_secret, user_id)).encode()
        callback_key = hashlib.sha1(bytes_key).hexdigest()
        callback_url = "%(callback_url)s?key=%(key)s" % {
            'callback_url': self.oauth_callback,
            'key': callback_key,
        }
        request_token = self.get_request_token(callback_url)
        oauth_url = self.get_authorize_url(request_token)
        return {
            'oauth_url': oauth_url,
            'oauth_token': request_token['oauth_token'],
            'oauth_token_secret': request_token['oauth_token_secret'],
            'callback_key': callback_key
        }

    async def get_oauth_url_async(self, user_id):
        # with ThreadPoolExecutor(max_workers=1) as executor:
        #     future = executor.submit(pow, 323, 1235)
        #     print(future.result())
        pass

    def create_note(self,
                    auth_token,
                    text,
                    title=None,
                    files=None,
                    notebook_guid=None):
        if files is None:
            files = []
        sdk = EvernoteSdk(token=auth_token, sandbox=self.sandbox)
        # user_store = sdk.get_user_store()
        note_store = sdk.get_note_store()
        note = Types.Note()
        note.title = title or ('%s...' % text[:25] if len(text) > 30 else text)
        if notebook_guid is not None:
            note.notebookGuid = notebook_guid

        attachments = []
        for filename, mime_type in files:
            with open(filename, 'rb') as f:
                data_bytes = f.read()
                md5 = hashlib.md5()
                md5.update(data_bytes)

                data = Types.Data()
                data.size = len(data_bytes)
                data.bodyHash = md5.digest()
                data.body = data_bytes

                resource = Types.Resource()
                resource.mime = mime_type
                resource.data = data
                resource.attributes = Types.ResourceAttributes(
                    fileName=basename(filename))

                # Now, add the new Resource to the note's list of resources
                note.resources = [resource]

            attachments.append(
                '<br /><en-media type="%(mime_type)s" hash="%(md5)s" />' % {
                    'mime_type': mime_type,
                    'md5': md5.hexdigest(),
                })

        note.content = '<?xml version="1.0" encoding="UTF-8"?>' \
            '<!DOCTYPE en-note SYSTEM "http://xml.evernote.com/pub/enml2.dtd">' \
            '<en-note>%(text)s<br />%(attachments)s</en-note>' % {
                'text': text,
                'attachments': ''.join(attachments),
            }
        try:
            created_note = note_store.createNote(note)
        except Exception as e:
            print(e)
            logging.getLogger().error(traceback.format_exc())
        return created_note.guid

    def getDefaultNotebook(self, auth_token):
        sdk = EvernoteSdk(token=auth_token, sandbox=self.sandbox)
        note_store = sdk.get_note_store()
        return note_store.getDefaultNotebook()

    def getNotebook(self, auth_token, guid=None):
        sdk = EvernoteSdk(token=auth_token, sandbox=self.sandbox)
        note_store = sdk.get_note_store()
        if guid is None:
            return note_store.getDefaultNotebook()
        return note_store.getNotebook(guid)

    def list_notebooks(self, auth_token):  # TODO: async version
        sdk = EvernoteSdk(token=auth_token, sandbox=self.sandbox)
        note_store = sdk.get_note_store()
        # List all of the notebooks in the user's account
        return note_store.listNotebooks()

    def get_note(self, auth_token, note_guid):
        sdk = EvernoteSdk(token=auth_token, sandbox=self.sandbox)
        note_store = sdk.get_note_store()
        return note_store.getNote(note_guid, True, True, False, False)

    def update_note(self, auth_token, guid, text, files=None):
        sdk = EvernoteSdk(token=auth_token, sandbox=self.sandbox)
        note_store = sdk.get_note_store()
        note = note_store.getNote(guid, True, True, False, False)

        content = NoteContent(note)
        content.add_text(text)
        if files is not None:
            for filename, mime_type in files:
                content.add_file(filename, mime_type)

        note.resources = content.get_resources()
        note.content = str(content)

        note_store.updateNote(note)
Ejemplo n.º 11
0
 def get_note(self, auth_token, note_guid):
     sdk = EvernoteSdk(token=auth_token, sandbox=self.sandbox)
     note_store = sdk.get_note_store()
     return note_store.getNote(note_guid, True, True, False, False)
Ejemplo n.º 12
0
 def list_notebooks(self, auth_token):  # TODO: async version
     sdk = EvernoteSdk(token=auth_token, sandbox=self.sandbox)
     note_store = sdk.get_note_store()
     # List all of the notebooks in the user's account
     return note_store.listNotebooks()
Ejemplo n.º 13
0
 def getNotebook(self, auth_token, guid=None):
     sdk = EvernoteSdk(token=auth_token, sandbox=self.sandbox)
     note_store = sdk.get_note_store()
     if guid is None:
         return note_store.getDefaultNotebook()
     return note_store.getNotebook(guid)
Ejemplo n.º 14
0
 def getDefaultNotebook(self, auth_token):
     sdk = EvernoteSdk(token=auth_token, sandbox=self.sandbox)
     note_store = sdk.get_note_store()
     return note_store.getDefaultNotebook()