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 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 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 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)
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 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 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)
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 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('&', '&') 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))
def init_note(guid, content): # Initializing the note object note = Note() note.content = content note.guid = guid # Getting note title soup = BeautifulSoup(content, "html.parser") note.title = soup.title.text # Initializing variables resources = [] resource = None data = None binaryData = None hash = None # Getting note resources path = safeglobals.path_note % (guid, "") for filename in os.listdir(path): if "content.json" not in filename: # Reading binary data with open(os.path.join(path, filename), "rb") as f: binaryData = f.read() # Calculating hash md5 = hashlib.md5() md5.update(binaryData) hash = md5.digest() # Creating data data = Data() data.size = len(binaryData) data.bodyHash = hash data.body = binaryData # Create a new resource resource = Resource() resource.mime = getMime(filename) resource.data = data # Creating attributes attributes = ResourceAttributes() attributes.fileName = filename # Adding the resource to resource collection resource.attributes = attributes resources.append(resource) # Adding resources to the specified note note.resources = resources return note
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 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)
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
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!!")
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 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 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
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
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 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)
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
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)
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 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_note_with_image(note_store, title, content, image_path): # To include an attachment such as an image in a note, first create a Resource # for the attachment. The Resource must contain the binary attachment # data, an MD5 hash of such data, and the attachment MIME type. # read image data with open(image_path, 'rb') as f: img = f.read() # create image data hash md5 = hashlib.md5() md5.update(img) h = md5.hexdigest() # now create an Evernote's Data object... data = Data() data.size = len(img) data.bodyHash = h data.body = img # ...that gets packed into a Resource object img_resource = Resource() img_resource.mime = 'image/png' img_resource.data = data # Now, create ENML content for the note enml_content = enml_for_note_with_attachments(content, [img_resource]) # Create and post a new note object note = Note() note.title = title note.content = enml_content note.resources = [img_resource] # don't forget to attach resources! created_note = None try: created_note = note_store.createNote(note) except EDAMUserException as e: print('Wrong ENML body: {}'.format(e)) finally: return created_note
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_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)
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 put(self, enote): note = Note() note.title = enote.title note.content = enote.enml # note.notebookGuid = enote.bguid return self.ns.createNote(note)
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()
userStore = client.get_user_store() user = userStore.getUser() print(user.username) # --- 加笔记本 # 第一件事,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) # 迁移备份 笔记本
token = f.read() client = EvernoteClient(token=token, service_host='app.yinxiang.com') # 获取笔记本 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_bak # TODO 之后改回去 spec = NoteStore.NotesMetadataResultSpec() spec.includeTitle = True notes = noteStore.findNotesMetadata(filter, 0, 200, spec).notes for noteMeta in notes: # 先备份一下 noteStore.copyNote(noteMeta.guid, guid_notebook_bak) # 开始改内容 note = noteStore.getNote(noteMeta.guid, True, True, True, True) content = note.content new_content = clean_content(content) # 更新笔记 new_note = Note() new_note.guid = note.guid new_note.title = note.title new_note.content = new_content noteStore.updateNote(new_note)
def imglist2note(notestore, imglist, noteguid, notetitle, neirong=''): """ 更新note内容为图片列表 :param notestore: :param imglist: :param noteguid: :param notetitle: :param neirong:object :return: """ # global log note = Note() # print(type(note)) note.guid = noteguid note.title = notetitle # To include an attachment such as an image in a note, first create a Resource # for the attachment. At a minimum, the Resource contains the binary attachment # data, an MD5 hash of the binary data, and the attachment MIME type. # It can also include attributes such as filename and location. # Now, add the new Resource to the note's list of resources # print(len(note.resources)) # print(noteguid) # note.resources = notestore.getNote(token, noteguid, True, True, True,True).resources # evernoteapijiayi() # if not note.resources: # note.resources = [] note.resources = [] # print(len(note.resources)) # for img, imgtitle in imglist: for img in imglist: image = open(img, 'rb').read() md5 = hashlib.md5() md5.update(image) imghash = md5.digest() data = Data() # 必须要重新构建一个Data(),否则内容不会变化 data.size = len(image) data.bodyHash = imghash data.body = image resource = Resource() resource.mime = 'image/png' resource.data = data note.resources.append(resource) # The content of an Evernote note is represented using Evernote Markup Language # (ENML). The full ENML specification can be found in the Evernote API Overview # at http://dev.evernote.com/documentation/cloud/chapters/ENML.php nbody = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" nbody += "<!DOCTYPE en-note SYSTEM \"http://xml.evernote.com/pub/enml2.dtd\">" nbody += "<en-note>" if note.resources: # To display the Resource as part of the note's content, include an <en-media> # tag in the note's ENML content. The en-media tag identifies the corresponding # Resource using the MD5 hash. # nBody += "<br />" * 2 for resource in note.resources: if resource.guid or True: hexhash = binascii.hexlify(resource.data.bodyHash) str1 = "%s" % hexhash # b'cd34b4b6c8d9279217b03c396ca913df' # print (str1) str1 = str1[2:-1] # cd34b4b6c8d9279217b03c396ca913df # print (str1) nbody += "<en-media type=\"%s\" hash=\"%s\" align=\"center\" /><br />" % ( resource.mime, str1) nbody += neirong nbody += "</en-note>" note.content = nbody # print (note.content) # Finally, send the new note to Evernote using the updateNote method # The new Note object that is returned will contain server-generated # attributes such as the new note's unique GUID. @trycounttimes2('evernote服务器') def updatenote(notesrc): updated_note = get_notestore().updateNote(notesrc) evernoteapijiayi() log.info('成功更新了笔记《%s》,guid:%s。' % (updated_note.title, updated_note.guid)) updatenote(note)