def set_tag(note_store, my_tags, tag_id): """ create a tag if not exists :param note_store evernote instance :param my_tags string :param tag_id id of the tag(s) to create :return: array of the tag to create """ new_tag = Types.Tag() if ',' in my_tags: for my_tag in my_tags.split(','): new_tag.name = my_tag note_tag_id = EvernoteMgr.create_tag(note_store, new_tag) if note_tag_id is not False: tag_id.append(note_tag_id) else: return False elif my_tags: new_tag.name = my_tags note_tag_id = EvernoteMgr.create_tag(note_store, new_tag) if note_tag_id is not False: tag_id.append(note_tag_id) else: return False return tag_id
def add_tag(self, *input_tags): """ This method adds tags to the current note. As such it must be called AFTER a new note is created. Takes either a single string, or a list or tuple of strings. If a list or tuple is used, it must be called using a * in front of the list/tuple. eg Wrapper.add_html(*(1,2,3)). If this is not done the method cannot loop through the tags properly. :param input_tags: :type input_tags: :return: :rtype: """ self.tag_list = self.note_store.listTags( ) # gets new list of tags that may have been created since Wrapper object creation tag_list = {} for tag in self.tag_list: # create dict of tag names: tag objects tag_list[tag.name] = tag for tag in input_tags: if tag not in tag_list: # if tag name does not exist; create it new_tag = Types.Tag() new_tag.name = tag # create tag and add it to current note guid = self.note_store.createTag( new_tag ).guid # Might want to add try block here. EN can't handle tags with different cased letters if not self.note.tagGuids: # if note has no other tags self.note.tagGuids = [guid] else: # if note already has some tags self.note.tagGuids += [guid] else: # tag already exists if not self.note.tagGuids: # if note has no other tags self.note.tagGuids = [tag_list[tag].guid] else: # if note already has other tags self.note.tagGuids += [tag_list[tag].guid] return
def createTag(self, name): tag = Types.Tag() tag.name = name logging.debug("New tag : %s", tag) result = self.getNoteStore().createTag(self.authToken, tag) return result
def updateTag(self, guid, name): tag = Types.Tag() tag.name = name tag.guid = guid logging.debug("Update tag : %s", tag) self.getNoteStore().updateTag(self.authToken, tag) return True
def set_tag(self, trigger, tag_id): """ create a tag if not exists """ # tagGUID does not exist: # create it if a tag has been provided if tag_id == 0 and trigger.tag is not '': new_tag = Types.Tag() new_tag.name = trigger.tag tag_id = self.note_store.createTag(new_tag).guid return tag_id
def test_pull_changed_tag(self): """Test pull changed tags""" tag = factories.TagFactory.create(action=const.ACTION_NONE, ) tag_name = 'name*' self.note_store.listTags.return_value = [ ttypes.Tag( name=tag_name, guid=tag.guid, ) ] self.sync.pull() self.assertEqual(tag.name, tag_name)
def _create_ttype(self, tag): """Create tag ttype""" if not regex.search(limits.EDAM_TAG_NAME_REGEX, tag.name): raise TTypeValidationFailed() kwargs = dict( name=tag.name[:limits.EDAM_TAG_NAME_LEN_MAX].strip().encode( 'utf8'), ) if tag.guid: kwargs['guid'] = tag.guid return ttypes.Tag(**kwargs)
def createAllTags(noteStore, tagsList): for tag in tagsList: try: newTag = Types.Tag() newTag.name = tag.name newTag.updateSequenceNum = tag.updateSequenceNum noteStore.createTag(newTag) except Exception as e: pass else: pass finally: pass
def makeTag(tagname): ourTag = Types.Tag() ourTag.name = tagname try: tag = nStore.createTag(ourTag) print "Tag %s :: %s successfully created" % (tag.guid, tag.name) except Errors.EDAMUserException, edue: ##BAD_DATA_FORMAT "Tag.name" - invalid length or pattern ##BAD_DATA_FORMAT "Tag.parentGuid" - malformed GUID ##DATA_CONFLICT "Tag.name" - name already in use ##LIMIT_REACHED "Tag" - at max number of tags print "EDAMUserException:", edue return None
def test_pull_new_tag(self): """Test pull new tags""" tag_name = 'name' guid = 'guid' self.note_store.listTags.return_value = [ ttypes.Tag( name=tag_name, guid=guid, ) ] self.sync.pull() tag = self.session.query(models.Tag).one() self.assertEqual(tag.name, tag_name) self.assertEqual(tag.guid, guid)
def createTag(self, tagName): """Create new tag from tag name Args: tagName (str): tag name Returns: Tag Raises: Examples: '夜神' -> Tag(guid='209e70eb-34a7-44c9-9f6d-ddd4da91054b', name='夜神', parentGuid=None, updateSequenceNum=5781064) """ existedTag = self.findTag(tagName) if existedTag: return existedTag newTag = Types.Tag() newTag.name = tagName createdTag = self.noteStore.createTag(newTag) return createdTag
def test_remote_tags(self): """Test syncing remote tags""" name = str(datetime.now()) remote = self.note_store.createTag( self.auth_token, ttypes.Tag( name=name, ), ) self.sync.tags_remote() tag = self.sq(Tag).filter( Tag.guid == remote.guid, ).one() self.assertEqual(tag.name, name) remote.name += '*' self.note_store.updateTag( self.auth_token, remote, ) self.sync.tags_remote() tag = self.sq(Tag).filter( Tag.guid == remote.guid, ).one() self.assertEqual(tag.name, name + '*')
def save_data(self, token, trigger_id, **data): """ let's save the data dont want to handle empty title nor content otherwise this will produce an Exception by the Evernote's API """ content = '' if 'content' in data: if type(data['content']) is list: if 'value' in data['content'][0]: content = data['content'][0].value else: if 'value' in data['content']: content = data['content']['value'] else: content = data['content'] elif 'summary_detail' in data: if type(data['summary_detail']) is list: if 'value' in data['summary_detail'][0]: content = data['summary_detail'][0].value else: if 'value' in data['summary_detail']: content = data['summary_detail']['value'] else: content = data['summary_detail'] elif 'description' in data: content = data['description'] # if no title provided, fallback to the URL which should be provided # by any exiting service title = (data['title'] if 'title' in data else data['link']) if token and len(title): # get the evernote data of this trigger trigger = Evernote.objects.get(trigger_id=trigger_id) client = EvernoteClient( token=token, sandbox=settings.TH_EVERNOTE['sandbox']) # user_store = client.get_user_store() note_store = client.get_note_store() # note object note = Types.Note() if trigger.notebook: notebooks = note_store.listNotebooks() listtags = note_store.listTags() notebookGuid = 0 tagGuid = [] # get the notebookGUID ... for notebook in notebooks: if notebook.name.lower() == trigger.notebook.lower(): notebookGuid = notebook.guid break #... and get the tagGUID if a tag has been provided if trigger.tag is not '': # cut the string by piece of tag with comma if ',' in trigger.tag: for my_tag in trigger.tag.split(','): for tag in listtags: # remove space before and after # thus we keep "foo bar" # but not " foo bar" nor "foo bar " if tag.name.lower() == my_tag.lower().lstrip().rstrip(): tagGuid.append(tag.guid) break else: for tag in listtags: if tag.name.lower() == my_tag.lower(): tagGuid.append(tag.guid) break # notebookGUID does not exist: # create it if notebookGuid == 0: new_notebook = Types.Notebook() new_notebook.name = trigger.notebook new_notebook.defaultNotebook = False note.notebookGuid = note_store.createNotebook( new_notebook).guid else: note.notebookGuid = notebookGuid # tagGUID does not exist: # create it if a tag has been provided if tagGuid == 0 and trigger.tag is not '': new_tag = Types.Tag() new_tag.name = trigger.tag tagGuid = note_store.createTag(new_tag).guid if trigger.tag is not '': # set the tag to the note if a tag has been provided note.tagGuids = tagGuid logger.debug("notebook that will be used %s", trigger.notebook) if 'link' in data: # add the link of the 'source' in the note # get a NoteAttributes object na = Types.NoteAttributes() # add the url na.sourceURL = data['link'] # add the object to the note note.attributes = na # will add this kind of info in the footer of the note : # "provided by FoxMaSk's News from http://domain.com" # domain.com will be the link and the text of the link provided_by = _('Provided by') provided_from = _('from') footer_from = "<br/><br/>{} <em>{}</em> {} <a href='{}'>{}</a>" footer = footer_from.format( provided_by, trigger.trigger.description, provided_from, data['link'], data['link']) content += footer # start to build the "note" # the title note.title = title # the body prolog = '<?xml version="1.0" encoding="UTF-8"?>' prolog += '<!DOCTYPE en-note SYSTEM "http://xml.evernote.com/pub/enml2.dtd">' note.content = prolog # tidy and sanitize content enml = sanitize(content) note.content += str(enml) # create the note ! try: created_note = note_store.createNote(note) sentance = str('note %s created') % created_note.guid logger.debug(sentance) except Exception as e: logger.critical(e) else: sentence = "no token provided for trigger ID {} and title {}" logger.critical(sentence.format(trigger_id, title))
def createTag(self, name): tag = Types.Tag() tag.name = name tag = self.note_store.createTag(self.auth_token, tag) return tag.guid
def main(): """ GET: gets random gif from giphy and displays it along with the option to see another gif and to save the gif to their evernote account""" if request.method == "GET": if "access_token" in session.keys(): #get random gif from giphy api response=requests.get("http://api.giphy.com/v1/gifs/random?api_key="+giphy_api_key).json() if not response: return render_template("error.html", error_message="error with connection to giphy") #get random image url and id from giphy api response giphy_url=response['data']['image_url'] giphy_id=response['data']['id'] #get tags and pass them to the page because the giphy api only show tags for random images giphy_tags='' try: response['data']['tags'] for tag in response['data']['tags']: giphy_tags+=tag+', ' giphy_tags=giphy_tags[:-2] except KeyError: pass return render_template("index.html", giphy_url=giphy_url, giphy_id=giphy_id, giphy_tags=giphy_tags) session["access_token"] #if their Evernote access_token session varible is not set redirect them to Evernote to authoirze the applicaiton else: client = EvernoteClient( consumer_key=CONSUMER_KEY, consumer_secret=CONSUMER_SECRET, sandbox= True ) try: request_token = client.get_request_token("http://localhost:8080/auth") session['oauth_token'] = request_token['oauth_token'] session['oauth_token_secret'] = request_token['oauth_token_secret'] authorize_url = client.get_authorize_url(request_token) except KeyError: return render_template("error.html", error_message="invalid API key and/or secret. Please check the values of cosumer_key and sonsumer_secret in the server.py file are valid and <a href=\'/clear'>click here</a> to reset.") else: print authorize_url return redirect(authorize_url+"&suggestedNotebookName=Giphy") #suggest notebook name of giphy to user #if we do have the access token proceed to show them a gif they can save to Evernote """POST: shows confomation of evernote gif save and presents option to return to main page or see the note in evernote""" if request.method == 'POST': if request.form['giphy_id']: #get giphy_id from post request that was to be saved giphy_id=request.form['giphy_id'] giphy_tags=request.form['giphy_tags'] response=requests.get("http://api.giphy.com/v1/gifs/"+giphy_id+"?api_key="+giphy_api_key).json() giphy_url=response['data']['images']['original']['url'] #generate Evernote client client = EvernoteClient(token=session["access_token"], sandbox=True) user_store = client.get_user_store() note_store = client.get_note_store() notebooks = note_store.listNotebooks() notebooks_dict=dict() for notebook in notebooks: notebooks_dict[notebook.name]=notebook.guid #if app notebook key use that notebok to save notes into if len(notebooks)==1 and notebooks[0].defaultNotebook==False: #assume app notebok key giphyNotebookGuid=notebooks[0].guid elif "Giphy" in notebooks_dict.keys(): #if notebook named Giphy exists use that notebook giphyNotebookGuid=notebooks_dict['Giphy'] else: #make new notebook try: notebook=Types.Notebook() notebook.name="Giphy" notebook=note_store.createNotebook(notebook) giphyNotebookGuid=notebook.guid except EDAMUserException: #single app notebok key giphyNotebookGuid=notebooks[0].guid #create note title with user name + giphy id for unique identifier note_title=response['data']['username']+"-"+response['data']['id'] #check to see if note exists already notebook_filter=NoteStoreTypes.NoteFilter() notebook_filter.guid=giphyNotebookGuid result_spec = NotesMetadataResultSpec(includeTitle=True) try: noteList = note_store.findNotesMetadata(session["access_token"], notebook_filter,0 , 40000, result_spec) for note in noteList.notes: if note.title==note_title: shardId=user_store.getUser(session["access_token"]).shardId shareKey=note_store.shareNote(session["access_token"], note.guid) evernote_url="%s/shard/%s/sh/%s/%s" % (EN_URL,shardId,note.guid,shareKey) return render_template("already_there.html", giphy_url=giphy_url, evernote_url=evernote_url) except EDAMUserException: #if the key doesn't have read permissions just move on pass #get image image= requests.get(giphy_url, stream=True).content md5 = hashlib.md5() md5.update(image) gif_hash = md5.digest() data = Types.Data() data.size = len(image) data.bodyHash = gif_hash data.body = image resource = Types.Resource() resource.mime = 'image/gif' resource.data = data hash_hex = binascii.hexlify(gif_hash) note = Types.Note() note.notebookGuid=giphyNotebookGuid #create note for our Giphy notebook note.title=note_title #name based on Giphy username and id 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><br/>' note.content += '<en-media type="image/gif" hash="' + hash_hex + '"/>' note.content += '</en-note>' #add tags to the note enTagList=note_store.listTags() enTagListNames= [tag.name for tag in enTagList] giphyTagList=giphy_tags.split(", ") if not note.tagGuids: note.tagGuids=[] for giphyTag in giphyTagList: if giphyTag in enTagListNames: for tag in enTagList: if tag.name == giphyTag: note.tagGuids.append(tag.guid) elif giphyTag=='': continue else: tag=Types.Tag() tag.name=giphyTag tag=note_store.createTag(tag) note.tagGuids.append(tag.guid) note.resources = [resource] # Now, add the new Resource to the note's list of resources note=note_store.createNote(note) # create the note user=user_store.getUser(session["access_token"]) shardId=user.shardId try: shareKey=note_store.shareNote(session["access_token"], note.guid) evernote_url="%s/shard/%s/sh/%s/%s" % (EN_URL,shardId,note.guid,shareKey) except EDAMUserException: evernote_url=EN_URL + "/Home.action" return render_template("saved.html", giphy_url=giphy_url, evernote_url=evernote_url) else: return render_template("error.html", error_message="Error finding the GIF") else: return render_template("error.html", error_message="Unsuported HTTP method. Please use GET or POST.")