def test_note_deleted(fake_storage):
    test_notes = [
        Note(
            guid="id1",
            title="test",
            content="test",
            notebookGuid="notebook1",
            active=True,
        ),
        Note(
            guid="id2",
            title="test",
            content="test",
            notebookGuid="notebook1",
            active=True,
        ),
    ]

    for note in test_notes:
        fake_storage.notes.add_note(note)

    fake_storage.notes.expunge_notes(["id2"])

    result = list(fake_storage.notes.iter_notes("notebook1"))

    assert len(result) == 1
    assert result[0].guid == "id1"
def test_get_notes_for_sync(fake_storage):
    test_notes = [
        Note(
            guid="id1",
            title="name1",
        ),
        Note(
            guid="id2",
            title="name2",
        ),
        Note(
            guid="id3",
            title="name3",
        ),
    ]

    fake_storage.notes.add_notes_for_sync(test_notes)

    expected = tuple(
        NoteForSync(guid=n.guid, title=n.title, linked_notebook_guid=None)
        for n in test_notes
    )
    result = fake_storage.notes.get_notes_for_sync()

    assert expected == result
Exemple #3
0
def evernote_create_note(request):
    if request.method != 'POST':
        return redirect('/api')

    title = request.POST.get('title')
    content = request.POST.get('content')

    note_store = get_note_store()
    response_data = {}

    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>"
    
    newNote = Note()
    newNote.title = title
    newNote.content = nBody % content

    note = None
    try:
        note = note_store.createNote( newNote )
        response_data['result'] = "success"
    except:
        response_data['result'] = "error"

    return HttpResponse(
        json.dumps(response_data),
        content_type="application/json"
    )
def saveToEvernote(history):
    EN_URL = 'https://sandbox.evernote.com'

    dev_token = "S=s1:U=8d5df:E=14a1ce2575a:C=142c5312b5c:P=1cd:A=en-devtoken:V=2:H=c3fba302a245ad5e2aa489bc02b3b873"
    client = EvernoteClient(token=dev_token)
    userStore = client.get_user_store()
    note_store = client.get_note_store()

    note = Note()
    note.title = "chat history"
    note.content = '<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE en-note SYSTEM "http://xml.evernote.com/pub/enml2.dtd">'
    content = ''
    for line in history:
        content += "<br>" + line + "</br>"
    note.content += '<en-note>' + content + '</en-note>'
    note = note_store.createNote(note)
    print note.content

    def getUserShardId(authToken, userStore):
        """
	Get the User from userStore and return the user's shard ID
	"""
        try:
            user = userStore.getUser(authToken)
        except (EDAMUserException, EDAMSystemException), e:
            print "Exception while getting user's shardID:"
            print type(e), e
            return None

        if hasattr(user, 'shardId'):
            return user.shardId
        return None
def test_trash_notes_count(fake_storage):
    test_notes = [
        Note(
            guid="id1",
            title="test",
            content="test",
            notebookGuid="test",
            active=True,
        ),
        Note(
            guid="id2",
            title="test",
            content="test",
            notebookGuid="test",
            active=False,
        ),
        Note(
            guid="id3",
            title="test",
            content="test",
            notebookGuid="test",
            active=False,
        ),
    ]

    for note in test_notes:
        fake_storage.notes.add_note(note)

    result = fake_storage.notes.get_notes_count(is_active=False)

    assert result == 2
Exemple #6
0
 def _add_task(self, description, tag):
     note = Note(title=description, tagNames=[tag], notebookGuid=self.notebook_guid)
     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></en-note>'
     
     self.notes.append(self.client.createNote(self.authtoken, note))
Exemple #7
0
def share_evernote(user, article):
    client = get_evernote_client(user['extras']['evernote'])
    note_store = client.get_note_store()
    note = Note()
    note.title = article.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>{0}<br /><a href="{1}">[Article Link]</a></en-note>'.format(article.excerpt, article.url)
    note_store.createNote(note)
 def test_base_metadata(self):
     note = Note()
     note.title = "test title"
     note.attributes = NoteAttributes()
     featuredict = {}
     features.add_metadata_features(featuredict, note)
     expected_keys = ("META-TITLETOKEN-test", "META-TITLETOKEN-title")
     expected = dict.fromkeys(expected_keys, 1)
     self.assertEqual(featuredict, expected)
Exemple #9
0
def share_evernote(user, article):
    client = get_evernote_client(user['extras']['evernote'])
    note_store = client.get_note_store()
    note = Note()
    note.title = article.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>{0}<br /><a href="{1}">[Article Link]</a></en-note>'.format(
        article.excerpt, article.url)
    note_store.createNote(note)
Exemple #10
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
Exemple #11
0
 def notes_local(self):
     """Send local notes changes to server"""
     for note in self.sq(models.Note).filter(
             and_(
                 models.Note.action != ACTION_NONE,
                 models.Note.action != ACTION_NOEXSIST,
                 models.Note.action != ACTION_CONFLICT,
             )):
         self.app.log('Note %s local' % note.title)
         content = (u"""
                 <!DOCTYPE en-note SYSTEM "http://xml.evernote.com/pub/enml2.dtd">
                 <en-note>%s</en-note>
             """ % sanitize(html=note.content[:EDAM_NOTE_CONTENT_LEN_MAX])
                    ).strip().encode('utf8')
         soup = BeautifulStoneSoup(content,
                                   selfClosingTags=[
                                       'img',
                                       'en-todo',
                                       'en-media',
                                       'br',
                                       'hr',
                                   ])
         kwargs = dict(
             title=note.title[:EDAM_NOTE_TITLE_LEN_MAX].strip().encode(
                 'utf8'),
             content=soup.prettify(),
             tagGuids=map(
                 lambda tag: tag.guid,
                 note.tags,
             ),
         )
         if note.notebook:
             kwargs['notebookGuid'] = note.notebook.guid
         if note.guid:
             kwargs['guid'] = note.guid
         nt = Note(**kwargs)
         try:
             next_action = ACTION_NONE
             if note.action == ACTION_CHANGE:
                 nt.resources = self._resources_for_note(note)
                 nt = self.note_store.updateNote(self.auth_token, nt)
             elif note.action == ACTION_CREATE:
                 nt.resources = self._resources_for_note(note)
                 nt = self.note_store.createNote(self.auth_token, nt)
                 note.guid = nt.guid
             elif note.action == ACTION_DELETE:
                 self.note_store.deleteNote(self.auth_token, nt.guid)
                 self.session.delete(note)
         except EDAMUserException as e:
             next_action = ACTION_NONE
             self.app.log('Note %s failed' % note.title)
             self.app.log(e)
         note.action = next_action
     self.session.commit()
 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
Exemple #13
0
def create_note(notebook_guid: str, title: str, content: str) -> Note:
    # This Note does not require authorization yet, it only contain
    # title and content.
    note = Note(notebookGuid=notebook_guid)
    note.title = title

    en_note_prefix = '<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE ' \
                     'en-note SYSTEM "http://xml.evernote.com/pub/enml2.dtd"><en-note>'
    en_note_suffix = '</en-note>'
    enml_content = convert_html_to_enml(content)
    note.content = en_note_prefix + enml_content + en_note_suffix
    return note
 def send(self):
     note = self.note
     xhtml = XHTML()
     n = EvernoteTypeNote()
     n.title = note['title']
     n.content = '<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE en-note SYSTEM "http://xml.evernote.com/pub/enml2.dtd">'
     n.content += '<en-note><pre>%s</pre></en-note>' % xhtml.p(note['content'].encode('utf-8'))
     n.tagNames = [x.strip() for x in note['tags'].split(',') if x.strip()]
     try:
         n = self.noteStore.createNote(n)
     except Exception, e:
         sublime.error_message('Sublime2Note: Failed to create note. Error detail: %s' % e)
Exemple #15
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!!")
Exemple #16
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
def test_export_single_notes_over_existing_overwrite(cli_invoker, fake_storage,
                                                     tmp_path):
    test_out_path = tmp_path / "test_out"

    test_notebooks = [
        Notebook(guid="nbid1", name="name1", stack="stack1"),
        Notebook(guid="nbid2", name="name2", stack=None),
    ]

    test_notes = [
        Note(
            guid="id1",
            title="title1",
            content="test",
            notebookGuid="nbid1",
            active=True,
        ),
        Note(
            guid="id2",
            title="title2",
            content="test",
            notebookGuid="nbid2",
            active=True,
        ),
    ]

    fake_storage.notebooks.add_notebooks(test_notebooks)

    for note in test_notes:
        fake_storage.notes.add_note(note)

    book1_existing_path = test_out_path / "stack1" / "name1" / "title1.enex"
    book2_existing_path = test_out_path / "name2" / "title2.enex"

    book1_existing_path.parent.mkdir(parents=True, exist_ok=True)
    book2_existing_path.parent.mkdir(parents=True, exist_ok=True)

    book1_existing_path.touch()
    book2_existing_path.touch()

    cli_invoker(
        "export",
        "--database",
        "fake_db",
        "--single-notes",
        "--overwrite",
        str(test_out_path),
    )

    assert book1_existing_path.stat().st_size > 0
    assert book2_existing_path.stat().st_size > 0
Exemple #18
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)
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
def test_sync_add_linked_notebook_note_with_tag(cli_invoker,
                                                mock_evernote_client,
                                                fake_storage):
    mock_evernote_client.fake_l_notebooks.append(
        Notebook(
            guid="nbid1",
            name="name1",
        ), )

    mock_evernote_client.fake_l_tags = [
        Tag(guid="tid1", name="tag1"),
        Tag(guid="tid2", name="tag2"),
    ]

    mock_evernote_client.fake_l_notes.append(
        Note(
            guid="id1",
            title="title1",
            content="body1",
            notebookGuid="nbid1",
            active=True,
            contentLength=100,
            tagGuids=["tid1", "tid2"],
        ))

    expected_notes = [
        Note(
            guid="id1",
            title="title1",
            content="body1",
            notebookGuid="nbid1",
            active=True,
            contentLength=100,
            tagGuids=["tid1", "tid2"],
            tagNames=["tag1", "tag2"],
        )
    ]

    mock_evernote_client.fake_linked_notebooks.append(
        LinkedNotebook(guid="id3", shardId="s100"))

    mock_evernote_client.fake_linked_notebook_auth_token = (
        "S=200:U=ff:E=fff:C=ff:P=1:A=test222:V=2:H=ff")

    cli_invoker("sync", "--database", "fake_db")

    result_notes = list(fake_storage.notes.iter_notes("nbid1"))

    assert result_notes == expected_notes
Exemple #21
0
def create_note(note_store, title, content):
    # Content of each Evernote note must be in a XML-derived format called ENML
    enml_content = enml_for_text_note(content)

    # Create and post a new note object
    note = Note()
    note.title = title
    note.content = enml_content
    created_note = None
    try:
        created_note = note_store.createNote(note)
    except EDAMUserException as e:
        print('Wrong ENML body: {}'.format(e))
    finally:
        return created_note
Exemple #22
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
def test_notes_trash(fake_storage):
    test_notes = [
        Note(
            guid="id1",
            title="test",
            content="test",
            notebookGuid="notebook1",
            active=False,
        ),
        Note(
            guid="id2",
            title="test",
            content="test",
            notebookGuid="notebook2",
            active=False,
        ),
        Note(
            guid="id3",
            title="test",
            content="test",
            notebookGuid="notebook1",
            active=True,
        ),
    ]

    expected_notes = [
        Note(
            guid="id1",
            title="test",
            content="test",
            notebookGuid="notebook1",
            active=False,
        ),
        Note(
            guid="id2",
            title="test",
            content="test",
            notebookGuid="notebook2",
            active=False,
        ),
    ]

    for note in test_notes:
        fake_storage.notes.add_note(note)

    result_notes = list(fake_storage.notes.iter_notes_trash())

    assert result_notes == expected_notes
def test_sync_add_note(cli_invoker, mock_evernote_client, fake_storage):
    mock_evernote_client.fake_notebooks.append(
        Notebook(
            guid="nbid1",
            name="name1",
            stack="stack1",
            serviceUpdated=1000,
        ), )

    test_note = Note(
        guid="id1",
        title="title1",
        content="body1",
        notebookGuid="nbid1",
        active=True,
        contentLength=100,
    )

    mock_evernote_client.fake_notes.append(test_note)

    cli_invoker("sync", "--database", "fake_db")

    result_notes = list(fake_storage.notes.iter_notes("nbid1"))

    assert result_notes == [test_note]
def test_sync_custom_max_chunk_results(cli_invoker, mock_evernote_client,
                                       fake_storage):
    mock_evernote_client.fake_notebooks.append(
        Notebook(
            guid="nbid1",
            name="name1",
            stack="stack1",
            serviceUpdated=1000,
        ), )

    test_note = Note(
        guid="id1",
        title="title1",
        content="body1",
        notebookGuid="nbid1",
        contentLength=100,
        active=True,
    )

    mock_evernote_client.fake_notes.append(test_note)
    test_max_chunk_results = 100

    cli_invoker("sync", "--database", "fake_db", "--max-chunk-results",
                test_max_chunk_results)

    result_notes = list(fake_storage.notes.iter_notes("nbid1"))

    assert result_notes == [test_note]
    assert mock_evernote_client.last_maxEntries == test_max_chunk_results
def test_sync_add_linked_notebook_note_error_no_access(cli_invoker,
                                                       mock_evernote_client,
                                                       fake_storage):
    mock_evernote_client.fake_l_notebooks.append(
        Notebook(
            guid="nbid1",
            name="name1",
        ), )

    mock_evernote_client.fake_l_notes.append(
        Note(
            guid="id1",
            title="title1",
            content="body1",
            notebookGuid="nbid1",
            contentLength=100,
            active=True,
        ))

    mock_evernote_client.fake_linked_notebooks.append(
        LinkedNotebook(guid="id3"))

    mock_evernote_client.fake_linked_notebook_auth_token = (
        "S=200:U=ff:E=fff:C=ff:P=1:A=test222:V=2:H=ff")

    mock_evernote_client.fake_auth_linked_notebook_error = True

    cli_invoker("sync", "--database", "fake_db")

    result_notebooks = list(fake_storage.notebooks.iter_notebooks())
    result_notes = list(fake_storage.notes.iter_notes("nbid1"))

    assert result_notebooks == []
    assert result_notes == []
def test_sync_interrupt_download(cli_invoker, mock_evernote_client,
                                 fake_storage, mocker):
    test_notes = [Note(guid=f"id{i}", title="test") for i in range(100)]

    mock_evernote_client.fake_notes.extend(test_notes)

    def interrupter(note):
        if note.guid == "id10":
            raise KeyboardInterrupt

    def fake_slow_get_note(note_guid):
        time.sleep(0.1)
        return Note(
            guid=note_guid,
            title="test",
            content="test",
            notebookGuid="test",
            contentLength=100,
            active=True,
        )

    mock_get_note = mocker.patch(
        "evernote_backup.evernote_client_sync.EvernoteClientSync.get_note")
    mock_get_note.side_effect = fake_slow_get_note

    mock_add_note = mocker.patch(
        "evernote_backup.note_storage.NoteStorage.add_note")
    mock_add_note.side_effect = interrupter

    cli_invoker("sync", "--database", "fake_db")
def test_sync_exception_while_download_retry_fail(cli_invoker,
                                                  mock_evernote_client,
                                                  fake_storage, mocker):
    test_notes = [Note(guid=f"id{i}", title="test") for i in range(100)]

    mock_evernote_client.fake_notes.extend(test_notes)

    def fake_get_note(note_guid):
        if note_guid == "id10":
            raise struct.error

        return Note(
            guid=note_guid,
            title="test",
            content="test",
            notebookGuid="test",
            contentLength=100,
            active=True,
        )

    mock_get_note = mocker.patch(
        "evernote_backup.evernote_client_sync.EvernoteClientSync.get_note")
    mock_get_note.side_effect = fake_get_note

    with pytest.raises(RuntimeError) as excinfo:
        cli_invoker("sync", "--database", "fake_db")

    assert "Failed to download note" in str(excinfo.value)
def test_sync_add_note_with_res(cli_invoker, mock_evernote_client,
                                fake_storage):
    mock_evernote_client.fake_notebooks.append(
        Notebook(
            guid="nbid1",
            name="name1",
            stack="stack1",
            serviceUpdated=1000,
        ), )

    test_note = Note(
        guid="id1",
        title="title1",
        content="body1",
        notebookGuid="nbid1",
        active=True,
        contentLength=100,
        resources=[
            Resource(
                guid="rid2",
                noteGuid="id1",
                data=Data(bodyHash=md5(b"000").digest(), size=3, body=b"000"),
            )
        ],
    )

    mock_evernote_client.fake_notes.append(test_note)

    cli_invoker("sync", "--database", "fake_db")

    result_notes = list(fake_storage.notes.iter_notes("nbid1"))

    assert result_notes == [test_note]
def test_sync_massive_note_count(cli_invoker, mock_evernote_client,
                                 fake_storage, monkeypatch):
    mock_evernote_client.fake_notebooks.append(
        Notebook(
            guid="nbid1",
            name="name1",
            stack="stack1",
            serviceUpdated=1000,
        ), )

    for i in range(10):
        test_note = Note(
            guid=f"id{i}",
            title=f"title{i}",
            content="body1",
            notebookGuid="nbid1",
            contentLength=100,
            active=True,
        )

        mock_evernote_client.fake_notes.append(test_note)

    monkeypatch.setattr(note_synchronizer, "THREAD_CHUNK_SIZE", 2)

    cli_invoker("sync", "--database", "fake_db")

    result_notes = sorted(fake_storage.notes.iter_notes("nbid1"),
                          key=lambda x: int(x.guid[2:]))

    assert result_notes == mock_evernote_client.fake_notes
Exemple #31
0
def test_export_yes_trash_single_notes(cli_invoker, fake_storage, tmp_path):
    test_out_path = tmp_path / "test_out"

    fake_storage.notes.add_note(
        Note(
            guid="id1",
            title="title1",
            content="test",
            notebookGuid="nbid1",
            active=False,
        )
    )

    cli_invoker(
        "export",
        "--database",
        "fake_db",
        "--include-trash",
        "--single-notes",
        str(test_out_path),
    )

    book1_path = test_out_path / "Trash" / "title1.enex"

    assert book1_path.is_file()
def test_export_no_export_date(cli_invoker, fake_storage, tmp_path):
    test_out_path = tmp_path / "test_out"

    test_notebooks = [
        Notebook(guid="nbid1", name="name1", stack=None),
    ]

    fake_storage.notebooks.add_notebooks(test_notebooks)

    fake_storage.notes.add_note(
        Note(
            guid="id1",
            title="title1",
            content="test",
            notebookGuid="nbid1",
            active=True,
        ))

    cli_invoker(
        "export",
        "--database",
        "fake_db",
        "--no-export-date",
        str(test_out_path),
    )

    book1_path = test_out_path / "name1.enex"

    with open(book1_path, "r") as f:
        book1_xml = f.read()

    assert "export-date" not in book1_xml
Exemple #33
0
 def notes_local(self):
     """Send loacl notes changes to server"""
     for note in self.sq(models.Note).filter(and_(
         models.Note.action != ACTION_NONE,
         models.Note.action != ACTION_NOEXSIST,
     )):
         self.app.log('Note %s local' % note.title)
         content = (u"""
                 <!DOCTYPE en-note SYSTEM "http://xml.evernote.com/pub/enml2.dtd">
                 <en-note>%s</en-note>
             """ % sanitize(
                     html=note.content[:EDAM_NOTE_CONTENT_LEN_MAX]
                 )).strip().encode('utf8')
         soup = BeautifulStoneSoup(content, selfClosingTags=[
             'img', 'en-todo', 'en-media', 'br', 'hr',
         ])
         kwargs = dict(
             title=note.title[:EDAM_NOTE_TITLE_LEN_MAX].strip().encode('utf8'),
             content=soup.prettify(),
             tagGuids=map(
                 lambda tag: tag.guid, note.tags,
             ),
         )
         if note.notebook:
             kwargs['notebookGuid'] = note.notebook.guid
         if note.guid:
             kwargs['guid'] = note.guid
         nt = Note(**kwargs)
         try:
             next_action = ACTION_NONE
             if note.action == ACTION_CHANGE:
                 nt.resources = self._resources_for_note(note)
                 nt = self.note_store.updateNote(self.auth_token, nt)
             elif note.action == ACTION_CREATE:
                 nt.resources = self._resources_for_note(note)
                 nt = self.note_store.createNote(self.auth_token, nt)
                 note.guid = nt.guid
             elif note.action == ACTION_DELETE:
                 self.note_store.deleteNote(self.auth_token, nt.guid)
                 self.session.delete(note)
         except EDAMUserException as e:
             next_action = note.action
             self.app.log('Note %s failed' % note.title)
             print soup.prettify()
             print e
         note.action = next_action
     self.session.commit()
def test_export_over_existing(cli_invoker, fake_storage, tmp_path):
    test_out_path = tmp_path / "test_out"

    test_notebooks = [
        Notebook(guid="nbid1", name="name1", stack="stack1"),
        Notebook(guid="nbid2", name="name2", stack=None),
        Notebook(guid="nbid3", name="name3", stack=None),
    ]

    test_notes = [
        Note(
            guid="id1",
            title="title1",
            content="test",
            notebookGuid="nbid1",
            active=True,
        ),
        Note(
            guid="id2",
            title="test",
            content="test",
            notebookGuid="nbid2",
            active=True,
        ),
    ]

    fake_storage.notebooks.add_notebooks(test_notebooks)

    for note in test_notes:
        fake_storage.notes.add_note(note)

    book1_existing_path = test_out_path / "stack1" / "name1.enex"
    book2_existing_path = test_out_path / "name2.enex"

    book1_existing_path.parent.mkdir(parents=True, exist_ok=True)
    book2_existing_path.parent.mkdir(parents=True, exist_ok=True)

    book1_existing_path.touch()
    book2_existing_path.touch()

    book1_expected_path = test_out_path / "stack1" / "name1 (1).enex"
    book2_expected_path = test_out_path / "name2 (1).enex"

    cli_invoker("export", "--database", "fake_db", str(test_out_path))

    assert book1_expected_path.is_file()
    assert book2_expected_path.is_file()
Exemple #35
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)
Exemple #36
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
 def test_full_metadata(self):
     note = Note()
     note.title = "test title"
     attributes = NoteAttributes()
     note.attributes = attributes
     attributes.sourceURL = "https://testdomain/some/path"
     attributes.latitude = 1
     attributes.source = "testsource"
     attributes.placeName = "testplace"
     attributes.contentClass = "testclass"
     featuredict = {}
     features.add_metadata_features(featuredict, note)
     expected_keys = ("META-TITLETOKEN-test", "META-TITLETOKEN-title",
                      "META-URL-testdomain", "META-HASURL",
                      "META-HASLOCATION", "META-SOURCE-testsource",
                      "META-PLACE-testplace", "META-CONTENTCLASS-testclass")
     expected = dict.fromkeys(expected_keys, 1)
     self.assertEqual(featuredict, expected)
Exemple #38
0
def test_formatter_empty_note():
    formatter = NoteFormatter()

    test_empty_note = Note()
    expected_empty_note = "  <note>\n  </note>\n"

    formatted_note = formatter.format_note(test_empty_note)

    assert formatted_note == expected_empty_note
Exemple #39
0
 def notes_local(self):
     """Send loacl notes changes to server"""
     for note in self.sq(models.Note).filter(
         models.Note.action != ACTION_NONE,
     ):
         kwargs = dict(
             title=note.title[:EDAM_NOTE_TITLE_LEN_MAX].strip().encode('utf8'),
             content= (u"""
                 <!DOCTYPE en-note SYSTEM "http://xml.evernote.com/pub/enml2.dtd">
                 <en-note>%s</en-note>
             """ % note.content[:EDAM_NOTE_CONTENT_LEN_MAX]).strip().encode('utf8'),
             tagGuids=map(
                 lambda tag: tag.guid, note.tags,
             ),
         )
         if note.notebook:
             kwargs['notebookGuid'] = note.notebook.guid
         if note.guid:
             kwargs['guid'] = note.guid
         nt = Note(**kwargs)
         if note.action == ACTION_CHANGE:
             nt.resources = map(lambda res: Resource(
                 noteGuid=note.guid,
                 data=Data(body=open(res.file_path).read()),
                 mime=res.mime,
                 attributes=ResourceAttributes(
                     fileName=res.file_name.encode('utf8'),
                 ),
             ), self.sq(models.Resource).filter(and_(
                 models.Resource.note_id == note.id, 
                 models.Resource.action != models.ACTION_DELETE,
             )))
             nt = self.note_store.updateNote(self.auth_token, nt)
         elif note.action == ACTION_CREATE:
             nt = self.note_store.createNote(self.auth_token, nt)
             note.guid = nt.guid
         elif note.action == ACTION_DELETE:
             try:
                 self.note_store.deleteNote(self.auth_token, nt.guid)
                 self.session.delete(note)
             except EDAMUserException:
                 pass
         note.action = ACTION_NONE
     self.session.commit()
def test_sync_add_note_with_tags(cli_invoker, mock_evernote_client,
                                 fake_storage):
    mock_evernote_client.fake_tags = [
        Tag(guid="tid1", name="tag1"),
        Tag(guid="tid2", name="tag2"),
    ]

    mock_evernote_client.fake_notebooks.append(
        Notebook(
            guid="nbid1",
            name="name1",
            stack="stack1",
            serviceUpdated=1000,
        ), )

    mock_evernote_client.fake_notes.append(
        Note(
            guid="id1",
            title="title1",
            content="body1",
            notebookGuid="nbid1",
            active=True,
            contentLength=100,
            tagGuids=["tid1", "tid2"],
        ))

    expected_notes = [
        Note(
            guid="id1",
            title="title1",
            content="body1",
            notebookGuid="nbid1",
            active=True,
            contentLength=100,
            tagGuids=["tid1", "tid2"],
            tagNames=["tag1", "tag2"],
        )
    ]

    cli_invoker("sync", "--database", "fake_db")

    result_notes = list(fake_storage.notes.iter_notes("nbid1"))

    assert result_notes == expected_notes
 def fake_slow_get_note(note_guid):
     time.sleep(0.1)
     return Note(
         guid=note_guid,
         title="test",
         content="test",
         notebookGuid="test",
         contentLength=100,
         active=True,
     )
Exemple #42
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('/')
Exemple #43
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('/')
def test_notes_order(fake_storage):
    test_notes = [
        Note(
            guid="id5",
            title="test5",
            content="test",
            notebookGuid="notebook1",
            active=True,
        ),
        Note(
            guid="id4",
            title="test4",
            content="test",
            notebookGuid="notebook1",
            active=True,
        ),
        Note(
            guid="id2",
            title="test1",
            content="test",
            notebookGuid="notebook1",
            active=True,
        ),
        Note(
            guid="id1",
            title="test2",
            content="test",
            notebookGuid="notebook1",
            active=True,
        ),
    ]

    expected_notes_titles_order = ["test1", "test2", "test4", "test5"]

    for note in test_notes:
        fake_storage.notes.add_note(note)

    result_notes_titles_order = list(
        n.title for n in fake_storage.notes.iter_notes("notebook1")
    )

    assert result_notes_titles_order == expected_notes_titles_order
Exemple #45
0
def notify(title, message,
           access_token=None,
           notebook='ntfy-notifications',
           sandbox=False, china=False,
           **_):

    try:
        client = EvernoteClient(
            consumer_key=CONSUMER_KEY,
            consumer_secret=CONSUMER_SECRET,
            token=access_token,
            sandbox=sandbox, china=china
        )

        if not client.token:
            login(client=client)

        if not client.token:
            print(f'Skiped with not login.')
            return 1

        noteStore = client.get_note_store()
        nbs = noteStore.listNotebooks()
        nb = ([x for x in nbs if x.name == notebook] + [None])[0]
        if nb is None:
            nb = Notebook(name=notebook)
            nb = noteStore.createNotebook(nb)

        note = Note(notebookGuid=nb.guid)
        note.title = str(title)
        note.content = '<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE en-note SYSTEM "http://xml.evernote.com/pub/enml2.dtd">'
        note.content += f'<en-note>{escape(message)}</en-note>'

        noteStore = client.get_note_store()
        note = noteStore.createNote(note)

    except EDAMUserException as ue:
        if ue.errorCode == EDAMErrorCode.RATE_LIMIT_REACHED:
            print(f'Rate limit reached, Retry your request in {ue.rateLimitDuration} seconds')
            return 1
        else:
            raise
    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)
 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)
Exemple #48
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
 def add_note(self, text, tag_list):
     """
     :param text: The note text is stored in title field
     :param tag_list: A list of tag strings to attach to note
     """
     note = EdamNote()
     if len(text) < EDAM_NOTE_TITLE_LEN_MIN or text.isspace():
         note.title = "untitled"
     elif len(text) > EDAM_NOTE_TITLE_LEN_MAX:
         note.title = text[0:EDAM_NOTE_TITLE_LEN_MAX]
         logger.warning("The text is too long, cutting off...")
     else:
         note.title = text                
     note.content = encode_note("")
     note.tagNames = tag_list
     self.note_store.createNote(note)
Exemple #50
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
Exemple #51
0
 def put(self, enote):
     note = Note()
     note.title = enote.title
     note.content = enote.enml
     # note.notebookGuid = enote.bguid
     return self.ns.createNote(note)
Exemple #52
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)
     self.note["content"] = self.view.substr(region)
     def do_update(**kwargs):
         for key, value in kwargs.items():
             self.note[key] = value
         self.send()
     def update_title(title):
         def update_tags(tags):
             do_update(title=title, tags=tags)
         self.window.show_input_panel("tags:","",update_tags,None,None)
     self.window.show_input_panel("title:","",update_title,None,None) 
 def send(self):
     note = self.note
     dev_token = "S=s1:U=3a529:E=146e0f0c800:C=13f893f9c03:P=1cd:A=en-devtoken:V=2:H=987718ca0ff7773fee5fe6d1e73fe99f"
     client = EvernoteClient(token=dev_token)
     try:
         noteStore = client.get_note_store()
     except EDAMUserException, e:
         print "Authentication Failed. Error: %s" % e
     else:
         xhtml = XHTML()
         n = EvernoteTypeNote()
         n.title = note["title"]
         n.content = '<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE en-note SYSTEM "http://xml.evernote.com/pub/enml2.dtd">'
         n.content += '<en-note><pre>%s</pre></en-note>' % xhtml.p(note["content"].encode('utf-8'))
         n.tagNames = [x.strip() for x in note["tags"].split(',') if x.strip()]
         try:
             n = noteStore.createNote(n)
         except Exception, e:
             print "Note Creation Failed. Error: %s" % e
 def run(self, edit):
     self.process_note()