Ejemplo n.º 1
0
def create_note(title, content, tagNames=None, notebookGuid=None):

    # put the note into the :INBOX notebook by default
    inbox_nb_guid = notebook(name=':INBOX').guid

    note_template = u"""<?xml version="1.0" encoding="UTF-8" standalone="no"?>
    <!DOCTYPE en-note SYSTEM "http://xml.evernote.com/pub/enml2.dtd">
    <en-note style="word-wrap: break-word; -webkit-nbsp-mode: space; -webkit-line-break: after-white-space;">
    {0}
    </en-note>"""

    note = Note()

    note.title = title.encode('utf-8')
    note.content = note_template.format(content).encode('utf-8')
    if tagNames is None:
        note.tagNames = []
    else:
        note.tagNames = tagNames

    if notebookGuid is None:
        note.notebookGuid = inbox_nb_guid
    else:
        note.notebookGuid = notebookGuid

    note = noteStore.createNote(note)
    return note
Ejemplo n.º 2
0
def create_note(auth_token,
                note_store,
                note_title,
                note_body,
                note_tags,
                parentNotebook=None):
    body = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
    body += "<!DOCTYPE en-note SYSTEM \"http://xml.evernote.com/pub/enml2.dtd\">"
    body += "<en-note>%s</en-note>" % note_body

    # strip spaces, see http://dev.evernote.com/doc/reference/Types.html#Struct_Note
    note_title = note_title.strip()

    # https://dev.evernote.com/doc/reference/javadoc/constant-values.html#com.evernote.edam.limits.Constants.EDAM_APPLICATIONDATA_VALUE_LEN_MIN
    if len(note_title) > 255:
        note_title = note_title[:255]
    elif not note_title:
        note_title = "无标题文档"

    logger.info(f"title: {note_title}")
    logger.info(f"body: {body}")

    # Create note object
    note = Note()
    note.title = note_title
    note.content = body
    note.tagNames = note_tags

    # parentNotebook is optional; if omitted, default notebook is used
    if parentNotebook and hasattr(parentNotebook, 'guid'):
        note.notebookGuid = parentNotebook.guid

    # Attempt to create note in Evernote account
    note = note_store.createNote(auth_token, note)
    return note
def make_note(auth_token,
              note_store,
              title,
              body,
              date,
              tag,
              parent_notebook=None):

    # Create note object
    note = Note()
    note.title = title
    note.tagGuids = [tag]
    note.created = date
    note.updated = date
    note.content = ''.join([
        '<?xml version="1.0" encoding="UTF-8"?>',
        '<!DOCTYPE en-note SYSTEM "http://xml.evernote.com/pub/enml2.dtd">',
        '<en-note>{}</en-note>'.format(body),
    ])

    # parent_notebook is optional; if omitted, default notebook is used
    if parent_notebook:
        note.notebookGuid = parent_notebook

    # Attempt to create note in Evernote account
    try:
        return note_store.createNote(note)
    except Exception as e:
        # Something was wrong with the note data
        # See EDAMErrorCode enumeration for error code explanation
        # http://dev.evernote.com/documentation/reference/Errors.html#Enum_EDAMErrorCode
        print('whoa', e)
        return None
Ejemplo n.º 4
0
    def get(self, file_id):
        client = self.get_authorized_client()
        if not client:
            return self.redirect('/auth-evernote?next={0}'.format(self.request.path))

        try:
            file = self.get_file(file_id)
        except webapp2.HTTPException as http_ex:
            if http_ex.code == 401:
                return self.redirect('/auth?next={0}'.format(self.request.path))

        base_url = self.request.host_url + '/edit/{0}'.format(file['id'])
        extension_loaded = bool(int(self.request.get('extensionLoaded', 1)))

        # Look for the VideoNot.es Notebook
        notestore = client.get_note_store()
        notesbooks = notestore.listNotebooks()
        notebook = None

        for a_notesbook in notesbooks:
            if a_notesbook.name == 'VideoNot.es':
                notebook = a_notesbook
                break

        if not notebook:
            notebook = Notebook()
            notebook.name = 'VideoNot.es'
            notebook = notestore.createNotebook(notebook)

        # Formatting the note in ENML
        content_enml = FileUtils.to_ENML(file, base_url)
        content_enml.append('<br></br><br></br>')

        content_enml.append('<a href="{0}">View in VideoNot.es</a>'.format(base_url))
        if not extension_loaded:
            content_enml.append('<br/>')
            content_enml.append('(Tip: you can add snapshots of the video to your export by installing our <a href="https://chrome.google.com/webstore/detail/kmbcnighpdagelfjmlbakfnciogcelgi">Chrome Extension</a>)')

        # Saving the note in Evernote
        note = Note()
        note.title = file['title']
        note_content = ''.join(content_enml).encode('utf-8')
        note.content = '<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE en-note SYSTEM "http://xml.evernote.com/pub/enml2.dtd"><en-note>{0}</en-note>'.format(note_content)
        note.content = note.content.replace('&', '&amp;')
        if notebook:
            note.notebookGuid = notebook.guid
        note = notestore.createNote(note)

        logging.debug('VideoNot.es %s exported to Evernote: %s', file_id, note_content)
        logging.info('VideoNot.es %s exported to Evernote with id: %s', file_id, note.guid)

        # Returning to the new note in Evernote
        user_store = client.get_user_store()
        notestore_url = '/'.join(user_store.getNoteStoreUrl().split('/')[0:5])
        return self.redirect(notestore_url + '/view/notebook/{0}'.format(note.guid))
Ejemplo n.º 5
0
 def store_note(self, note_title, note_content):
     notebook_guid = self.get_notebook_guid()
     if notebook_guid is None:
         notebook_guid = self.create_default_notebook()
     note = Note()
     note.title = note_title
     note.content = HackzurichEvernoteClient.NOTE_BOILERPLATE.format(
         note_content)
     note.notebookGuid = notebook_guid
     self._note_store.createNote(note)
     return note.guid
 def store_note(self, note_title, note_content):
     notebook_guid = self.get_notebook_guid()
     if notebook_guid is None:
         notebook_guid = self.create_default_notebook()
     note = Note()
     note.title = note_title
     note.content = HackzurichEvernoteClient.NOTE_BOILERPLATE.format(
         note_content)
     note.notebookGuid = notebook_guid
     self._note_store.createNote(note)
     return note.guid
Ejemplo n.º 7
0
def create_note(accessToken,title,content,notebookGuid,files,tags,password):

    # Generating note body
    content = safeglobals.ENCRYPTED_PREFIX+stringMD5(content)+"__"+encryptNote(content,password)+safeglobals.ENCRYPTED_SUFFIX
    nBody = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
    nBody += "<!DOCTYPE en-note SYSTEM \"http://xml.evernote.com/pub/enml2.dtd\">"
    nBody += "<en-note>%s</en-note>" % content
    tagNames = []

    # Creating note object
    note = Note()
    note.title = title.strip()
    note.content = nBody
    note.notebookGuid = notebookGuid
    for tag in tags:
        tagNames.append(str(tag).strip())
    note.tagNames = tagNames

    # Processing resources
    resources = []
    for file in files:
        if (file.get('name') and file.get('mime')):
            with open("static/tmp/"+file.get('name'),"rb") as f:
                
                # Calculating hash
                binaryData = encryptData(f.read(),password)
                md5 = hashlib.md5()
                md5.update(binaryData)
                hash = md5.digest()

                # Creating Evernote data object
                
                data = Data()
                data.size = len(binaryData)
                data.bodyHash = hash
                data.body = binaryData

                # Creating resource
                resource = Resource()
                resource.mime = file.get('mime')
                resource.data = data

                # Creating attributes
                attributes = ResourceAttributes()
                attributes.fileName = file.get('name')

                # Adding the resource to resource collection
                resource.attributes = attributes
                resources.append(resource)

    note.resources = resources
    return note
Ejemplo n.º 8
0
def createNote(firstID, title="I am a test title", contents="Testing Contents"):
    userStore = client.get_user_store()
    noteStore = client.get_note_store()
    note = Note()
    note.title = title
    note.content = (
        '<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE en-note SYSTEM "http://xml.evernote.com/pub/enml2.dtd">'
    )
    note.content += "<en-note>" + contents + "</en-note>"
    note.notebookGuid = firstID
    note = noteStore.createNote(note)

    print ("successfully created a note!!")
Ejemplo n.º 9
0
    def create_note(self, ino):
        note_name = self.find_child_by_parent_and_ino(self.parent[ino], ino)
        logging.info('create note: ' + note_name)

        notebook_guid = self.get_notebook_by_ino(self.parent[ino]).guid

        note = Note()
        note.title = note_name
        note.notebookGuid = notebook_guid
        note.content = self.get_note_content_by_ino(ino)
        created_note = self.note_store.createNote(note)
        self.notes_ino[ino] = created_note
        self.notebook_notes[notebook_guid][created_note.guid] = created_note
Ejemplo n.º 10
0
def makenote(tokenmn,
             notestore,
             notetitle,
             notebody='真元商贸——休闲食品经营专家',
             parentnotebook=None):
    """
    创建一个note
    :param tokenmn:
    :param notestore:
    :param notetitle:
    :param notebody:
    :param parentnotebook:
    :return:
    """
    # global log
    nbody = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
    nbody += "<!DOCTYPE en-note SYSTEM \"http://xml.evernote.com/pub/enml2.dtd\">"
    nbody += "<en-note>%s</en-note>" % notebody

    # Create note object
    ournote = Note()
    ournote.title = notetitle
    ournote.content = nbody

    # parentNotebook is optional; if omitted, default notebook is used
    if parentnotebook and hasattr(parentnotebook, 'guid'):
        ournote.notebookGuid = parentnotebook.guid

    # Attempt to create note in Evernote account
    try:
        note = notestore.createNote(tokenmn, ournote)
        evernoteapijiayi()
        log.info('笔记《' + notetitle + '》在笔记本《' + parentnotebook.name +
                 '》中创建成功。')
        return note
    except EDAMUserException as usere:
        # Something was wrong with the note data
        # See EDAMErrorCode enumeration for error code explanation
        # http://dev.evernote.com/documentation/reference/Errors.html#Enum_EDAMErrorCode
        log.critical("用户错误!%s" % str(usere))
    except EDAMNotFoundException as notfounde:
        # Parent Notebook GUID doesn't correspond to an actual notebook
        print("无效的笔记本guid(识别符)!%s" % str(notfounde))
    except EDAMSystemException as systeme:
        if systeme.errorCode == EDAMErrorCode.RATE_LIMIT_REACHED:
            log.critical("API达到调用极限,需要 %d 秒后重来" % systeme.rateLimitDuration)
            exit(1)
        else:
            log.critical('创建笔记时出现严重错误:' + str(systeme))
            exit(2)
Ejemplo n.º 11
0
 def create_or_update_note(self, new_note):
     """ Create new note or update existing one if there's any with provided tile
     Arguments:
     new_note  -- new note dictionary with the following items:
       'title'    -- note title, should be unique, this field is used to search for existing note
       'content'  -- note data in ENML markup. See https://dev.evernote.com/doc/articles/enml.php
       'notebook' -- name of the notebook to create note in (ignored on 'update')
       'created'  -- note creation time in milliseconds from epoch
       'updated'  -- note last updated time in milliseconds from epoch
     """
     note_title = new_note.get('title')
     note_contents = new_note.get('content')
     notebook_name = new_note.get('notebook')
     note_created = new_note.get('created')
     note_updated = new_note.get('updated')
     note = self.find_note(note_title)
     if note:
         note.content = note_contents
         note.created = note_created
         note.updated = note_updated
         Evernote.call_method(self.note_store.updateNote, note)
     else:
         note = Note()
         note.title, note.content = note_title, note_contents
         note.created, note.updated = note_created, note_updated
         for notebook in Evernote.call_method(self.note_store.listNotebooks):
             if notebook.name == notebook_name:
                 note.notebookGuid = notebook.guid
                 break
         else:
             if notebook_name:
                 # Notebook not found, create new one
                 notebook = Notebook()
                 notebook.name = notebook_name
                 notebook = Evernote.call_method(self.note_store.createNotebook, notebook)
                 note.notebookGuid = notebook.guid
         Evernote.call_method(self.note_store.createNote, note)
Ejemplo n.º 12
0
    def createNote(self, title, resource=None):
        user_store = self.client.get_user_store()
        note_store = self.client.get_note_store()
        try:
            note = Note()
            note.tagNames = self.tag
            note.notebookGuid = self.bookguid
            if resource is not None:
                note.resources = [resource]
                self.content += "<span><en-media type=\"%s\" hash=\"%s\"/></span>" % (
                    resource.mime, resource.data.bodyHash)
            note.title = title
            note.content = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
            note.content += "<!DOCTYPE en-note SYSTEM \"http://xml.evernote.com/pub/enml2.dtd\">"
            note.content += "<en-note>%s</en-note>" % self.content
            created_note = note_store.createNote(note)
        except:
            return False

        note_share_url = None
        note_share_resource_url = None
        if self.share:
            note_share_url = ToEver.getNoteShareUrl(
                sys_config.evernote_url,
                user_store.getUser().shardId, created_note.guid,
                note_store.shareNote(self.token, created_note.guid))
            if resource is not None:
                for x in created_note.resources:
                    note_share_resource_url = note_share_url + "/res/%s/%s" % (
                        x.guid, x.attributes.fileName)

        message = None
        if not self.hide:
            message = "Created note title is '" + title + "'"
            message += " [" + ToEver.getUserUploadState(
                note_store.getSyncState().uploaded,
                user_store.getUser().accounting.uploadLimitNextMonth) + "]"
            if note_share_url is not None:
                message += "\n" + "share link --> " + note_share_url
                if note_share_resource_url is not None:
                    message += "\n" + "share attachment link --> " + note_share_resource_url
        elif note_share_url is not None:
            message = note_share_url
            if note_share_resource_url is not None:
                message += "\n" + note_share_resource_url
        if message is not None:
            print(textui.colored.blue(message))
        return True
Ejemplo n.º 13
0
def make_note(client, noteTitle, noteBody, resources=[], guid=''):
    ## Build body of note
    body = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
    body += "<!DOCTYPE en-note SYSTEM \"http://xml.evernote.com/pub/enml2.dtd\">"
    body += "<en-note>%s" % noteBody

    ourNote = Note()
    ourNote.title = noteTitle

    if len(resources) > 0:
        ourNote.resources = []
        body += "<br />" * 2
        for res in resources:
            src = res['src']
            file = StringIO.StringIO(urllib.urlopen(src).read())
            img = Image.open(file)
            # img = Image.open(file).resize((120,120))
            output = io.BytesIO()
            img.save(output, format='png')
            im = output.getvalue()
            md5 = hashlib.md5()
            md5.update(im)
            hash = md5.digest()
            data = Types.Data()
            data.size = res['size']
            data.bodyHash = hash
            data.body = im
            resource = Types.Resource()
            resource.mime = res['type']
            resource.data = data
            ourNote.resources.append(resource)
            hash_hex = binascii.hexlify(hash)
            insert = "<br /><en-media type=\"%s\" hash=\"%s\" /><br />" % (resource.mime, hash_hex)
            body = body.replace('<p id="'+res['name']+'"></p>', insert)

    body += "</en-note>"

    ourNote.content = body
    token = client.token
    ourNote.notebookGuid = guid

    try:
        client = get_evernote_client(token=token)
        note_store = client.get_note_store()
        note = note_store.createNote(token, ourNote)
    except Errors.EDAMUserException, edue:
        print "EDAMUserException:", edue
        return None
Ejemplo n.º 14
0
def create_note(store, path, notebook):
    """Create a note from the content in a local file
    """
    ext = utils.get_file_ext(path)
    processor_cls = note_processors.get(ext)
    processor = processor_cls(path)
    note = Note()
    note.title = processor.get_title()
    note.content = processor.get_content()
    attributes = NoteAttributes()
    attributes.sourceURL = utils.path_to_source_url(notebook, path)
    note.attributes = attributes
    note.notebookGuid = notebook.guid
    try:
        return store.createNote(dev_token, note)
    except EDAMUserException as e:
        evernote_api_error(e, note)
Ejemplo n.º 15
0
def create_note(store, path, notebook):
    """Create a note from the content in a local file
    """
    ext = utils.get_file_ext(path)
    processor_cls = note_processors.get(ext)
    processor = processor_cls(path)
    note = Note()
    note.title = processor.get_title()
    note.content = processor.get_content()
    attributes = NoteAttributes()
    attributes.sourceURL = utils.path_to_source_url(notebook, path)
    note.attributes = attributes
    note.notebookGuid = notebook.guid
    try:
        return store.createNote(dev_token, note)
    except EDAMUserException as e:
        evernote_api_error(e, note)
Ejemplo n.º 16
0
    def createNote(self, title, resource=None):
        user_store = self.client.get_user_store()
        note_store = self.client.get_note_store()
        try:
            note = Note()
            note.tagNames = self.tag
            note.notebookGuid = self.bookguid
            if resource is not None:
                note.resources = [resource]
                self.content += "<span><en-media type=\"%s\" hash=\"%s\"/></span>" % (resource.mime, resource.data.bodyHash)
            note.title = title
            note.content = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
            note.content += "<!DOCTYPE en-note SYSTEM \"http://xml.evernote.com/pub/enml2.dtd\">"
            note.content += "<en-note>%s</en-note>" % self.content
            created_note = note_store.createNote(note)
        except:
            return False

        note_share_url = None
        note_share_resource_url = None
        if self.share:
            note_share_url = ToEver.getNoteShareUrl(
                sys_config.evernote_url,
                user_store.getUser().shardId,
                created_note.guid,
                note_store.shareNote(self.token, created_note.guid)
            )
            if resource is not None:
                for x in created_note.resources:
                    note_share_resource_url = note_share_url + "/res/%s/%s" % (x.guid, x.attributes.fileName)

        message = None
        if not self.hide:
            message = "Created note title is '" + title + "'"
            message += " [" + ToEver.getUserUploadState(note_store.getSyncState().uploaded, user_store.getUser().accounting.uploadLimitNextMonth) + "]"
            if note_share_url is not None:
                message += "\n" + "share link --> " + note_share_url
                if note_share_resource_url is not None:
                    message += "\n" + "share attachment link --> " + note_share_resource_url
        elif note_share_url is not None:
            message = note_share_url
            if note_share_resource_url is not None:
                message += "\n" + note_share_resource_url
        if message is not None:
            print(textui.colored.blue(message))
        return True
Ejemplo n.º 17
0
def add_new_note(request):
    if request.method == "POST":
        try:
            nBody = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
            nBody += "<!DOCTYPE en-note SYSTEM \"http://xml.evernote.com/pub/enml2.dtd\">"
            nBody += "<en-note>%s</en-note>" % request.POST.get("desc", "")
            ourNote = Note()
            ourNote.title = request.POST.get("title", "")
            ourNote.content = nBody
            ourNote.notebookGuid = request.POST.get("notebook_guid", "")
            user_obj = User.objects.get(username=request.user.get_username())
            evernote_token = user_obj.evernotecredential.evernote_token
            client = get_evernote_client(evernote_token)
            note_store = client.get_note_store()
            note = note_store.createNote(ourNote)
        except Exception as ex:
            print ex

        return redirect('/')
Ejemplo n.º 18
0
def add_new_note(request):
    if request.method == "POST":
        try:
            nBody = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
            nBody += "<!DOCTYPE en-note SYSTEM \"http://xml.evernote.com/pub/enml2.dtd\">"
            nBody += "<en-note>%s</en-note>" % request.POST.get("desc", "")
            ourNote = Note()
            ourNote.title = request.POST.get("title", "")
            ourNote.content = nBody
            ourNote.notebookGuid = request.POST.get("notebook_guid", "")
            user_obj = User.objects.get(username=request.user.get_username())
            evernote_token = user_obj.evernotecredential.evernote_token
            client = get_evernote_client(evernote_token)
            note_store = client.get_note_store()
            note = note_store.createNote(ourNote)
        except Exception as ex:
            print ex

        return redirect('/')
Ejemplo n.º 19
0
    def create_summary_log(self,notebook_name,title,content):

        new_note = Note()
        new_note.title = title
        new_note.content = content

        notebook_guid = None
        for notebook in self.get_note_store().listNotebooks():
            if notebook.name == notebook_name:
                notebook_guid = notebook.guid
                break

        if notebook_guid is None:
            raise EvernoteConnectorException("Cannot find notebook called " + notebook_name)

        new_note.notebookGuid = notebook_guid

        try:
            note = self.get_note_store().createNote(self.auth_token, new_note)

        except (EDAMUserException, EDAMNotFoundException) as e:
            raise EvernoteConnectorException(e)
Ejemplo n.º 20
0
    def create_summary_log(self, notebook_name, title, content):

        new_note = Note()
        new_note.title = title
        new_note.content = content

        notebook_guid = None
        for notebook in self.get_note_store().listNotebooks():
            if notebook.name == notebook_name:
                notebook_guid = notebook.guid
                break

        if notebook_guid is None:
            raise EvernoteConnectorException("Cannot find notebook called " +
                                             notebook_name)

        new_note.notebookGuid = notebook_guid

        try:
            note = self.get_note_store().createNote(self.auth_token, new_note)

        except (EDAMUserException, EDAMNotFoundException) as e:
            raise EvernoteConnectorException(e)
Ejemplo n.º 21
0
    def make_note_with_image(self, image_string):

        note = Note()
        note.title = 'Note created with ...'

        data = Data()
        data.body = image_string
        hash_md5 = hashlib.md5()
        hash_md5.update(data.body)
        data.bodyHash = hash_md5.digest()
        data.size = len(image_string)
        resource = Resource()
        resource.data = data
        resource.mime = 'image/jpeg'
        resource.width = 4160
        resource.height = 3120
        resource_attr = ResourceAttributes()
        resource_attr.attachment = False
        resource.attributes = resource_attr
        note.resources = [resource]

        hexhash = binascii.hexlify(resource.data.bodyHash)
        note.content = HackzurichEvernoteClient.NOTE_WITH_IMAGE.format(
            '', hexhash, 'image/jpeg', hexhash)

        note.notebookGuid = self.get_notebook_guid()

        try:
            created_note = self._note_store.createNote(note)
        except EDAMUserException as edue:
            print "EDAMUserException:", edue
            return None
        except EDAMNotFoundException:
            print "EDAMNotFoundException: Invalid parent notebook GUID"
            return None
        return created_note
Ejemplo n.º 22
0
    def make_note_with_image(self, image_string):

        note = Note()
        note.title = 'Note created with ...'

        data = Data()
        data.body = image_string
        hash_md5 = hashlib.md5()
        hash_md5.update(data.body)
        data.bodyHash = hash_md5.digest()
        data.size = len(image_string)
        resource = Resource()
        resource.data = data
        resource.mime = 'image/jpeg'
        resource.width = 4160
        resource.height = 3120
        resource_attr = ResourceAttributes()
        resource_attr.attachment = False
        resource.attributes = resource_attr
        note.resources = [resource]

        hexhash = binascii.hexlify(resource.data.bodyHash)
        note.content = HackzurichEvernoteClient.NOTE_WITH_IMAGE.format(
            '', hexhash, 'image/jpeg', hexhash)

        note.notebookGuid = self.get_notebook_guid()

        try:
            created_note = self._note_store.createNote(note)
        except EDAMUserException as edue:
            print "EDAMUserException:", edue
            return None
        except EDAMNotFoundException:
            print "EDAMNotFoundException: Invalid parent notebook GUID"
            return None
        return created_note
Ejemplo n.º 23
0
def main():
    client = EvernoteClient(token=dev_token, sandbox=False)
    noteStore = client.get_note_store()
    noteStore = client.get_note_store()
    Filter=NodeTypes.NoteFilter()
    Filter.words = 'tag:@smarttodo'
    notes = noteStore.findNotes(dev_token, Filter, 0, 10)
    for note in notes.notes:
        nt = noteStore.getNote(dev_token, note.guid, True, False, False, False)
        root = ElementTree.fromstring(nt.content)
        ElementTree.dump(root)
        sections = split_into_sections(root)
        today = datetime.date.today() - datetime.timedelta(1)
        tomorrow = today + datetime.timedelta(1)
        conversions = {
            'today': today,
            'tomorrow': tomorrow,
            'yesterday': today - datetime.timedelta(1),
        }
        print sections
        unfinished = parse_out_due_dates(sections['today'][1:], today, conversions,
                                         sections['settings']['Date format'])
        unfinished.extend(
            parse_out_due_dates(sections['later'][1:], tomorrow, conversions,
                                sections['settings']['Date format']))
        new_today_list = [x for x in unfinished if x[0] <= tomorrow]
        new_tomorrow_list = [x for x in unfinished if x[0] > tomorrow]
        new_tomorrow_list.sort(key=lambda x: x[0])
        sections['today'][1:] = update_tasks(new_today_list, sections['settings']['Date format'], sections['settings']['Date separator'])
        sections['later'][1:] = update_tasks(new_tomorrow_list, sections['settings']['Date format'], sections['settings']['Date separator'])
        text, tail, attrib, tag = root.text, root.tail, root.attrib, root.tag
        root.clear()
        root.text, root.tail, root.attrib, root.tag = text, tail, attrib, tag
        for sec in ['start', 'today', 'later', 'end']:
            for section in sections[sec]:
                if sec in ['today', 'later']:
                    root.extend(section)
                else:
                    root.append(section)
        while len(root) > 0 and root[-1].tag == 'br':
            root.remove(root[-1])
        new_node_content = ElementTree.tostring(root, 'utf-8')
        nt.content = content_prefix + new_node_content
        print 'Updated:'
        ElementTree.dump(root)
        noteStore.updateNote(dev_token, nt)

        if len(sections['completed']) <= 0:
            continue
        history_notebook = sections['settings']['History notebook'].strip()
        history_interval = sections['settings']['History interval'].strip()
        history_prefix = sections['settings']['History note'].strip()
        history_title = get_history_note_title(history_prefix, today,
                                               history_interval,
                                               sections['settings']['Date format'],
                                               sections['settings']['Date separator'])
        notebooks = noteStore.listNotebooks(dev_token)
        notebook_guid = None
        for notebook in notebooks:
            if notebook.name == history_notebook:
                notebook_guid = notebook.guid
        if notebook_guid == None:
            notebook = Notebook()
            notebook.name = history_notebook
            notebook = noteStore.createNotebook(dev_token, notebook)
            notebook_guid = notebook.guid
        Filter = NodeTypes.NoteFilter()
        Filter.notebookGuid = notebook_guid
        Filter.words = 'intitle:' + history_title
        history_notes = noteStore.findNotes(dev_token, Filter, 0, 1)
        if len(history_notes.notes) < 1:
            hist_root = ElementTree.Element('en-note')
            hist_note = Note()
            hist_note.title = history_title
            hist_note.notebookGuid = notebook_guid
        else:
            hist_note = noteStore.getNote(dev_token, history_notes.notes[0].guid,
                                          True, False, False, False)
            hist_root = ElementTree.fromstring(hist_note.content)
        day_element = ElementTree.fromstring('<div><strong>{}</strong></div>'.format(
            date_to_string(today,
                           sections['settings']['Date format'],
                           sections['settings']['Date separator'])))
        hist_root.append(day_element)
        for x in sections['completed']:
            hist_root.extend(x)
        hist_note.content = content_prefix + ElementTree.tostring(hist_root, 'utf-8')
        if len(history_notes.notes) < 1:
            noteStore.createNote(dev_token, hist_note)
        else:
            noteStore.updateNote(dev_token, hist_note)
Ejemplo n.º 24
0
# 第一件事,get_note_store
noteStore = client.get_note_store()
notebook = Notebook()
notebook.name = "My Notebook"
notebook = noteStore.createNotebook(notebook)
print(notebook.guid)

# --- 加笔记
noteStore = client.get_note_store()
note = Note()
note.title = "I'm a test note!"
note.content = '<?xml version="1.0" encoding="UTF-8"?>' \
               '<!DOCTYPE en-note SYSTEM "http://xml.evernote.com/pub/enml2.dtd">'
note.content += '<en-note>Hello, world!</en-note>'
# 如果不附notebookGUID的话会创建到默认笔记本里
note.notebookGuid = notebook.guid
note = noteStore.createNote(note)

# --- 搜索笔记
noteStore = client.get_note_store()
# notebooks = noteStore.listNotebooks()
guid_notebook = '2d083d6b-b84e-4dea-b6de-e4fa42d8fd72'
notebook = noteStore.getNotebook(guid_notebook)  # OneNote迁移 笔记本
guid_notebook_bak = '9a93a8dc-d863-4621-8ab5-c91f4fdf8576'
notebook_bak = noteStore.getNotebook(guid_notebook_bak)  # 迁移备份 笔记本

filter = NoteStore.NoteFilter()
filter.notebookGuid = guid_notebook
spec = NoteStore.NotesMetadataResultSpec()
spec.includeTitle = True
notes = noteStore.findNotesMetadata(filter, 0, 200, spec).notes