def main():
    # Checking if we have Lynx / phantomJS for optional features
    #Is Lynx installed?
    print "Can we use lynx to extract text?"
    lynx_exe = canhaslynx()
    if lynx_exe:
        print "yes"
    else:
        print "no"
    #Is phantomJS installed?
    print "Can we use phantomJS to extract screenshots?"
    phantom_exe = canhasphantom()
    if phantom_exe:
        print "yes"
    else:
        print "no"

    print "connecting to Evernote…"
    client = EvernoteClient(token=evernote_token, sandbox=False)
    user_store = client.get_user_store()
    try:
        note_store = client.get_note_store()
    except Errors.EDAMSystemException, e:
        if e.errorCode == 19: # rate limit reached
            print "Rate limit reached"
            print "Retry your request in %d seconds" % e.rateLimitDuration
            time.sleep(e.rateLimitDuration+1)
            note_store = client.get_note_store()
Exemplo n.º 2
0
class Snipe():
    def __init__(self, token, sandbox=True):
        self.client = EvernoteClient(token=token, sandbox=sandbox)
        self.client_note_store = self.client.get_note_store()
        self.tag = sys_config.note_default_tag
        self.limit = sys_config.note_max_limit

    def setMetaNotes(self):
        filter = NoteStore.NoteFilter()
        filter.order = NoteSortOrder.TITLE
        filter.tagGuids = [self.getTagGuid(self.tag)]
        filter.ascending = True
        spec = NoteStore.NotesMetadataResultSpec()
        spec.includeTitle = True
        notes_metadata = self.client_note_store.findNotesMetadata(filter, 0, int(self.limit), spec)
        meta_notes = [x for x in notes_metadata.notes]
        meta_notes = dict(zip(range(1, len(meta_notes)+1), meta_notes))
        Snipe.saveNotes(sys_config.filepath_dump, meta_notes)
        return meta_notes

    def getNoteContent(self, number):
        meta_notes = Snipe.getNotes(sys_config.filepath_dump)
        number = int(number)
        note = self.client_note_store.getNote(meta_notes[number].guid, True, True, True, True)
        return note.content.decode("utf-8")

    def getTagGuid(self, name):
        for v in self.client.get_note_store().listTags():
            if v.name == name:
                return v.guid
        return False

    @staticmethod
    def saveNotes(filepath, notes):
        f = open(filepath, 'w')
        pickle.dump(notes, f)
        f.close()

    @staticmethod
    def getNotes(filepath):
        f = open(filepath, 'r')
        notes = pickle.load(f)
        f.close()
        return notes

    @staticmethod
    def enexParse(node):
        n = node.firstChild
        while n:
            if n.nodeType is XmlNode.ELEMENT_NODE:
                Snipe.enexParse(n)
            elif n.nodeType is XmlNode.TEXT_NODE and len(n.nodeValue.rstrip('\n')) is not 0:
                print n.nodeValue.replace('!br!', '').encode('utf_8')
            n = n.nextSibling
class EvernoteApp:
    def __init__(self, token, use_sandbox):
        self.token = token
        self.use_sandbox = use_sandbox
        self.client = EvernoteClient(token=self.token,
                                     sandbox=self.use_sandbox)
        self.note_store = self.client.get_note_store()

    def create_notebook(self, name):
        notebook = Types.Notebook()
        notebook.name = name
        self.note_store.createNotebook(notebook)

    @property
    def all_notebooks(self):
        return self.note_store.listNotebooks()

    def filter_notebook(self, keyword):
        notebooks = []
        for notebook in self.all_notebooks:
            if keyword in notebook.name:
                notebooks.append(notebook)
        return notebooks

    def create_note(self, notebook, title, content):
        note = Types.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>{}</en-note>'.format(content)
        note.notebookGuid = notebook.guid
        return self.note_store.createNote(note)
Exemplo n.º 4
0
def create_standard_templates(auth_token):
	"""takes an auth token and creates templates notes in the users default notebook

	returns a list of the notes created"""

	#setup Evernote client
	client = EvernoteClient(token=auth_token, sandbox=sandbox)
	note_store = client.get_note_store()

	notes=[]
	default_notebook = note_store.getDefaultNotebook()
	template_tags = get_template_tags(auth_token)

	# add all template note ENML from templates_enml.py file
	for template in templates_enml.templates:
		note = Types.Note()			
		note.title = template['title']
		note.content = template['enml']
		note.tagGuids = template_tags
		note.notebooksGuid = default_notebook.guid
		try:
			notes.append(note_store.createNote(note))
		except NameError:
			notes = [note_store.createNote(note)]

	return notes
Exemplo n.º 5
0
def new_template_note(guid):
	"""Copies the note specified by the GUID in the URL

	redirects the user to open the note in their client"""

	#check to see the user has logged in
	if "access_token" in session.keys():
		#setup Evernote Client
		client = EvernoteClient(token=session["access_token"], sandbox=sandbox)
		user_store = client.get_user_store()
		note_store = client.get_note_store()
		
		#get the default notebook
		default_notebook = note_store.getDefaultNotebook()
		
		#copy the note to the default notebook
		note = note_store.copyNote(session['access_token'], guid, default_notebook.guid)

		#Remove "template" and "Template" tags
		for tag in get_template_tags(session['access_token']):
			try:
				note.tagGuids.remove(tag)
			except ValueError:
				pass
		note = note_store.updateNote(note)

		#construct the evernote Link to the newly copied note
		in_app_link = "evernote:///view/%s/%s/%s/%s/" % (user_store.getUser().id, user_store.getUser().shardId, note.guid, note.guid)

		#redirect the user to the note (will open up in Evernote client)
		return redirect(in_app_link)
	else:
		#if the user is not logged in redirect them to do so
		return redirect(url_for("main")) 
Exemplo n.º 6
0
def get_template_tags(auth_token):
	"""finds a tag with the name 'template' or 'Template'

	returns a list of tag GUIDs or None"""

	#setup the Evernote Client
	client = EvernoteClient(token=session["access_token"], sandbox=sandbox)
	user_store = client.get_user_store()
	note_store = client.get_note_store()

	#get a list of tags in the user's account
	tags = note_store.listTags()

	#Check to see if there are tags named 'template' or 'Template' and put them in a list
	template_tags = None
	for tag in tags:
		tag_name = tag.name
		if tag_name == 'template':
			if template_tags:
				template_tags.append(tag.guid)
			else:
				template_tags = [tag.guid]
		if tag_name == 'Template':
			if template_tags:
				template_tags.append(tag.guid)
			else:
				template_tags = [tag.guid]
	
	return template_tags #return a list of tags GUIDs (or None)
Exemplo n.º 7
0
def main(name, plugin_config, global_config, updateState, direction):
    global config_name
    config_name = name

    global local_cfg
    local_cfg = plugin_config

    global cfg
    cfg = global_config

    global job
    job = direction

    if cfg['verbose']:
        print "Init Evernote..."

    #Connect to Evernote
    global client
    client = EvernoteClient(token=local_cfg['auth_token'], sandbox=local_cfg['sandbox'])

    global note_store
    try:
        note_store = client.get_note_store()
        #Check if we neet to sync
        if job == "source":
            sync_state = get_sync_state()
            if sync_state != updateState:
                if cfg['verbose']:
                    print "New Data, we have to sync (%s)" % sync_state
                return True, sync_state
            return False, sync_state

    except Exception as e:
        print "Error getting notes from evernote: %s" % e.message
        return False
Exemplo n.º 8
0
class EvernoteController(object):
    def __init__(self, token, isSpecialToken=False, sandbox=False, isInternational=False, notebooks=None):
        self.token = token
        if sandbox:
            self.client = EvernoteClient(token=self.token, service_host='sandbox.yinxiang.com')
        elif isInternational:
            self.client = EvernoteClient(token=self.token, service_host='www.evernote.com')
        else:
            self.client = EvernoteClient(token=self.token, service_host='app.yinxiang.com')
        self.isSpecialToken = isSpecialToken
        self.userStore = self.client.get_user_store()
        self.noteStore = self.client.get_note_store()
        self.storage = Storage(notebooks)

    def get_upload_limit(self):
        return {
            1: 25 * 1024 * 1024,
            3: 100 * 1024 * 1024,
            5: 200 * 1024 * 1024,
        }.get(self.userStore.getUser().privilege, 0)

    def create_notebook(self, noteFullPath):
        if self.get(noteFullPath): return False
        notebook = Types.Notebook()
        notebook.name = noteFullPath
        try:
            notebook = self.noteStore.createNotebook(notebook)
        except EDAMUserException, e:
            if e.errorCode == 10 and e.parameter == 'Notebook.name':
                self.storage.update(self.token, self.noteStore)
                return True
            else:
                raise e
        self.storage.create_notebook(notebook)
        return True
Exemplo n.º 9
0
def main():
    evernote_token = os.getenv('EVERNOTE_TOKEN')
    client = EvernoteClient(token=evernote_token, sandbox=True)
    validate_version(client)

    note_store = client.get_note_store()
    list_notebooks(note_store)
Exemplo n.º 10
0
def getToDos(day):
    dev_token = getToken(False)
    client = EvernoteClient(token=dev_token, sandbox=False)
    notestore = client.get_note_store()
    ToDoTags = getToDoTags(dev_token, notestore)
    dayGuid = getDayTag(day, notestore)
    myfilter = NoteFilter()
    spec = NotesMetadataResultSpec()
    spec.includeTitle = True
    mylist = []
    noteguids = {}
    TODOLIST = dict()

    notebody = ""

    for tag, guid in ToDoTags.iteritems():
        mylist = []
        mylist.append(guid)
        mylist.append(dayGuid)
        myfilter.tagGuids = mylist
        notes = notestore.findNotesMetadata(dev_token, myfilter, 0, 100, spec)
        TODOLIST[tag] = []
        for note in notes.notes:
            TODOLIST[tag].append(note.title)

    return TODOLIST
def make_first_note(url_l):
    dev_token = "x"
    client = EvernoteClient(token=dev_token, sandbox=False)
    note_store = client.get_note_store()

    message = ''
    for i in url_l:
        message += '<br>' + i + '</br>'

    #message='<br>'+url+'</br>'

    note = Types.Note()
    note.title = "Article Editing + Theme Editing Job (%s)" % (
        time.strftime("%d/%m/%Y"))
    note.content = """<?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE en-note SYSTEM "http://xml.evernote.com/pub/enml2.dtd">
    <en-note><br>1. Please go to all URL's and check if the formatting of the articles are OK</br>
<br>2. Insert 1-2 relevant images for the articles, that don't have any images.</br>
<br>3. Publish ONE article now. Publish every other article +7 or +14 or +21 days</br>
<br>4. Change theme settings, create a logo and upload that logo to the blog</br>
<br>Here are the article urls:</br>
<br></br>
%s</en-note>
    """ % (message)

    try:
        createdNote = note_store.createNote(note)
    except Exception, e:
        print type(e)
        print e
        raise SystemExit
class myEvernote(object):
    def __init__(self, kontoname):
        if kontoname == "loipe":
            self._connect_to_evernote(evernoteApiKeys.dev_tokenLoipe,
                                      istSandbox=False)
        else:
            self._connect_to_evernote(evernoteApiKeys.dev_tokenSandbox,
                                      istSandbox=True)

    def _connect_to_evernote(self, dev_token, istSandbox=True):
        user = None
        try:
            self.client = EvernoteClient(token=dev_token, sandbox=istSandbox)
            self.user_store = self.client.get_user_store()
            self.notestore = self.client.get_note_store()
            user = self.user_store.getUser()
        except EDAMUserException as e:
            err = e.errorCode
            print("Error attempting to authenticate to Evernote: %s - %s" %
                  (EDAMErrorCode._VALUES_TO_NAMES[err], e.parameter))
            return False
        except EDAMSystemException as e:
            err = e.errorCode
            print("Error attempting to authenticate to Evernote: %s - %s" %
                  (EDAMErrorCode._VALUES_TO_NAMES[err], e.message))
            sys.exit(-1)

        if user:
            print("Authenticated to evernote as user %s" % user.username)
            return True
        else:
            return False
Exemplo n.º 13
0
    def login(cls, ):
        '''
        Get the notebook name and guid, get note_store
        Returns:
          STATUS_OK              : Everything is fine
          STATUS_NO_AUTH_TOKEN   : No auth token can be found in keying, user should authorize this application
          STATUS_AUTH_EXPIRED    : auth expired, need auth again.

        For mote information about "app notebooks": http://dev.yinxiang.com/doc/articles/app_notebook.php
        '''
        auth_token = KeyRing.get_auth_token()
        if auth_token is not None:
            client = EvernoteClient(
                consumer_key=EverNoteConsumerInfo.CONSUMER_KEY,
                consumer_secret=EverNoteConsumerInfo.CONSUMER_SECRET,
                service_host=MetaData.get_evernote_host(),
                token=auth_token,
                sandbox=False)
            try:
                cls.note_store = client.get_note_store()
            except ErrorTypes.EDAMUserException:
                return cls.STATUS_LOGIN_AUTH_EXPIRED
            notebooks = cls.note_store.listNotebooks()
            len_notebooks = len(notebooks)
            if len_notebooks == 0:
                logging.error("Application notebook has been deleted")
                return cls.STATUS_LOGIN_NOTEBOOK_DELETED
            cls.notebook_name = notebooks[0].name
            cls.notebook_guid = notebooks[0].guid
            return cls.STATUS_LOGIN_OK
        else:
            return cls.STATUS_LOGIN_NO_AUTH_TOKEN
Exemplo n.º 14
0
class Collector(object):
    """Note collector."""
    def __init__(self, notebookName):
        """@param notebookName str Notebook name (or name fragment)."""
        self.notebookName = notebookName
        self.client = EvernoteClient(
            consumer_key=settings.consumerKey,
            consumer_secret=settings.consumerSecret,
            token=settings.developerToken,
            sandbox=False
        )
        self.noteStore = self.client.get_note_store()
        self.tagCache = {}
        self._loadTagCache()

    def _loadTagCache(self):
        """Try to load tag cache from disk."""
        print 'info: loading tag cache..'

        try:
            with open(TAG_CACHE_FILENAME, 'r') as fh:
                self.tagCache = pickle.loads(fh.read())
            print 'info: tag cache successfully loadded'

        except Exception, e:
           print 'error: failed to load tag cache: {0}'.format(e)
Exemplo n.º 15
0
def _create_new_note(title, url):
    # Real applications authenticate with Evernote using OAuth, but for the
    # purpose of exploring the API, you can get a developer token that allows
    # you to access your own Evernote account. To get a developer token, visit
    # https://sandbox.evernote.com/api/DeveloperToken.action
    auth_token = AUTH_TOKEN

    # Initial development is performed on our sandbox server. To use the production
    # service, change sandbox=False and replace your
    # developer token above with a token from
    # https://www.evernote.com/api/DeveloperToken.action
    client = EvernoteClient(token=auth_token, sandbox=False)

    user_store = client.get_user_store()

    version_ok = user_store.checkVersion(
        "linkToEver",
        UserStoreConstants.EDAM_VERSION_MAJOR,
        UserStoreConstants.EDAM_VERSION_MINOR
    )
    if not version_ok:
        logger.error("My Evernote API version is not up to date")
        exit(1)

    note_store = client.get_note_store()

    logger.info("Creating a new note in the default notebook(%s)", title)

    note = Types.Note()
    note.title = title

    note_attribute = Types.NoteAttributes(sourceURL=url)
    note.attributes = note_attribute

    return note_store, note
Exemplo n.º 16
0
def listnotes():
    client = EvernoteClient(token=settings.TOKEN)
    notestore = client.get_note_store()

    note_filter = ttypes.NoteFilter()
    # TODO: read notebookGuid from options
    note_filter.notebookGuid = '6ccaa7d7-cbdb-4190-8c28-121e603f0b8c'
    note_result_spc = ttypes.NotesMetadataResultSpec(
        True,
        True,
        True,
        True,
        True,
    )

    notecount = notestore.findNoteCounts(note_filter, True)
    print '==========='
    print notecount.notebookCounts
    print notecount.tagCounts
    print notecount.trashCount
    total_count = sum(notecount.notebookCounts.values(), 0)
    print total_count
    note_list = notestore.findNotesMetadata(
        note_filter,
        0,
        total_count,
    )
Exemplo n.º 17
0
class Note(object):
    def __init__(self):
        # consumer_key = 'wanghan0307171', consumer_secret = '7ce3360054d137a3'
        self.dev_token = "sandbox key"
        self.app_token = "production key"
        self.client = EvernoteClient(token=self.app_token, sandbox=False)
        self.noteStore = self.client.get_note_store()

    def createEvernote(self, title, html, notebook_guid='d7900482-362b-4424-a698-99c1833fb81c'):
        note = Types.Note()
        #note.notebookGUID = 'd7900482-362b-4424-a698-99c1833fb81c'
        note.notebookGuid = notebook_guid
        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>"
        note.content += html
        note.content += "</en-note>"
        note = self.noteStore.createNote(note)
        return note

    def updateNote(self, note_guid, title, html):
        note = self.noteStore.getNote(note_guid, False, False, False, False)
        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>"
        note.content += html
        note.content += "</en-note>"
        note = self.noteStore.updateNote(note)
        return note
Exemplo n.º 18
0
    def login(cls,):
        '''
        Get the notebook name and guid, get note_store
        Returns:
          STATUS_OK              : Everything is fine
          STATUS_NO_AUTH_TOKEN   : No auth token can be found in keying, user should authorize this application
          STATUS_AUTH_EXPIRED    : auth expired, need auth again.

        For mote information about "app notebooks": http://dev.yinxiang.com/doc/articles/app_notebook.php
        '''
        auth_token = KeyRing.get_auth_token()
        if auth_token is not None:
            client = EvernoteClient(
                consumer_key=EverNoteConsumerInfo.CONSUMER_KEY,
                consumer_secret=EverNoteConsumerInfo.CONSUMER_SECRET,
                service_host = MetaData.get_evernote_host(),
                token=auth_token,
                sandbox=False)
            try:
                cls.note_store = client.get_note_store()
            except ErrorTypes.EDAMUserException:
                return cls.STATUS_LOGIN_AUTH_EXPIRED
            notebooks = cls.note_store.listNotebooks()
            len_notebooks = len(notebooks)
            if len_notebooks == 0:
                logging.error("Application notebook has been deleted")
                return cls.STATUS_LOGIN_NOTEBOOK_DELETED
            cls.notebook_name = notebooks[0].name
            cls.notebook_guid = notebooks[0].guid
            return cls.STATUS_LOGIN_OK
        else:
            return cls.STATUS_LOGIN_NO_AUTH_TOKEN
Exemplo n.º 19
0
 def wraps(*args, **kwargs):
     client = EvernoteClient(token=current_app.config["PRODTOKEN"], sandbox=current_app.config["SANDBOX"])
     noteStore = client.get_note_store()
     userStore = client.get_user_store()
     kwargs["userStore"] = userStore
     kwargs["noteStore"] = noteStore
     return func(*args, **kwargs)
Exemplo n.º 20
0
    def __init__(self, evernote_token):
        client = EvernoteClient(
            token = evernote_token,
            sandbox=False
        )

        self.noteStore = client.get_note_store()
Exemplo n.º 21
0
class EvernoteSession:
    
    def __init__(self, dev_token):
        self.token = dev_token
        self.client = EvernoteClient(token=dev_token)
        self.userStore = self.client.get_user_store()
        self.noteStore = self.client.get_note_store()
        
    def internalNoteLink(self, noteGuid):
        # Original: evernote:///view/13708770/s129/abe5f3b4-b305-4172-b5c9-985cc2ba5e78//
        # Stripped: evernote:///view/0/s129/abe5f3b4-b305-4172-b5c9-985cc2ba5e78/00000000-0000-0000-0000-000000000000/
        # Template: evernote:///view/<ownerid>/<shardid>/<noteguid>/<localvalue>/<linkedNotebookValue>
        user = self.userStore.getUser()
        shardId = user.shardId   
        userId = user.id
        localWTF = "00000000-0000-0000-0000-000000000000"
        return "%sview/%d/%s/%s/%s/" % ("evernote:///", userId, shardId, noteGuid, localWTF)

    def listAllNotes(self):
        noteFilter = NoteStore.NoteFilter()
        # http://dev.evernote.com/documentation/reference/NoteStore.html#Struct_NoteFilter
        # notebook = self.noteStore.getDefaultNotebook()
        # noteFilter.notebookGuid = notebook.guid
        searchResults = self.noteStore.findNotes(self.token, noteFilter, 0, 50)
        return searchResults.notes
Exemplo n.º 22
0
class EvernoteSession:
    
    def __init__(self, dev_token):
        self.token = dev_token
        self.client = EvernoteClient(token=dev_token)
        self.userStore = self.client.get_user_store()
        self.noteStore = self.client.get_note_store()
        
    # def listAllNotes(self, notebookGuid=None):
    #     noteFilter = NoteStore.NoteFilter()
    #     # http://dev.evernote.com/documentation/reference/NoteStore.html#Struct_NoteFilter
    #     if notebookGuid:
    #         noteFilter.notebookGuid = notebookGuid
    #     searchResults = self.noteStore.findNotes(self.token, noteFilter, 0, 50)
    #     return searchResults.notes

    def shareNotebook(self, notebookGuid, email=None):
        sharedNotebook = Types.SharedNotebook()
        sharedNotebook.requireLogin = True
        sharedNotebook.notebookGuid = notebookGuid
        sharedNotebook.email = email
        sharedNotebook.privilege = Types.SharedNotebookPrivilegeLevel.READ_NOTEBOOK_PLUS_ACTIVITY

        newSharedNotebook = c.noteStore.createSharedNotebook(c.token, sharedNotebook)

        user = self.userStore.getUser()
        shardId = user.shardId

        url = "%s/shard/%s/share/%s/" % (EN_URL, shardId, newSharedNotebook.shareKey)
        return url
Exemplo n.º 23
0
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
Exemplo n.º 24
0
class EvernoteSession:
    def __init__(self, dev_token):
        self.token = dev_token
        self.client = EvernoteClient(token=dev_token)
        self.userStore = self.client.get_user_store()
        self.noteStore = self.client.get_note_store()

    def shareNotebook(self, notebookGuid, email=None):
        sharedNotebook = Types.SharedNotebook()
        sharedNotebook.requireLogin = True
        sharedNotebook.notebookGuid = notebookGuid
        sharedNotebook.email = email
        sharedNotebook.privilege = Types.SharedNotebookPrivilegeLevel.READ_NOTEBOOK_PLUS_ACTIVITY

        user = self.userStore.getUser()
        shardId = user.shardId
        newSharedNotebook = c.noteStore.shareNotebook(sharedNotebook,
                                                      "Test message")

        # linkedNotebook = Types.LinkedNotebook()
        # linkedNotebook.sharedNotebookGlobalId = newSharedNotebook.globalId
        # linkedNotebook.shareName = notebookName
        # linkedNotebook.username = "******"
        # linkedNotebook.shardId = shardId
        # newLinkedNotebook = c.noteStore.createLinkedNotebook(dev_token2, linkedNotebook)

        # old way: url = "%s/shard/%s/share/%s/" % (EN_URL, shardId, newSharedNotebook.shareKey)
        url = ""
        return url
Exemplo n.º 25
0
def main_evernote(session):
    """
    Synchronizes Lectio homework and assignments with Evernote.
    """
    token = get_evernote_token()

    logger.info("Creating Evernote client.")
    client = EvernoteClient(token=token, sandbox=False)
    user_store = client.get_user_store()
    note_store = client.get_note_store()

    logger.info("Getting Lectio assignments.")
    assignments = session.get_assignments()

    for assignment in assignments:
        title = EVERNOTE_ASSIGNMENT_PREFIX + assignment.title

        content = ""

        if assignment.note:
            content += assignment.note
            content += "\n\n" + "-" * 30 + "\n\n"

        content += "Hold: {}.\n".format(assignment.group)
        content += "Elevtid: {} timer.\n".format(assignment.student_hours)
        content += "Afleveringsfrist: {}.".format(assignment.deadline)

        content = content.replace("\n", "<br/>")

        note = make_note(token, note_store, title, content)
Exemplo n.º 26
0
def create_note(entry):
    """ ブックマーク情報からEvernoteのNoteを作成
    """
    client = EvernoteClient(token=global_config['evernote']['token'],
                            sandbox=False)
    note_store = client.get_note_store()
    note = Types.Note()
    note.title = entry['title']
    note.title = note.title.replace(unichr(int('2028', 16)), ' ')
    note.title = note.title.replace(unichr(int('2029', 16)), ' ')
    note.title = note.title.encode('utf-8')
    content = (
        u'<?xml version="1.0" encoding="UTF-8"?>'
        u'<!DOCTYPE en-note SYSTEM "http://xml.evernote.com/pub/enml2.dtd">')
    content += u'<en-note>'
    if entry['summary']:
        content += u'%s<hr />' % entry['summary']
    content += to_enml(entry['content'], url=entry['url'])
    content += u'</en-note>'
    soup = BeautifulSoup(content)
    note.content = str(soup)
    attrs = Types.NoteAttributes(sourceURL=entry['url'])
    note.attributes = attrs
    note.tagNames = [e.encode('utf-8') for e in entry['tags']]
    # 時間がミリ秒単位になるので1000を乗算する
    note.created = entry['created'] * 1000
    note = img_to_resource(note)
    note_store.createNote(note)
    return note
class Library(object):

	def __init__(self, auth_token):
		"""
		Initialize access to the Evernote library.

		Arguments:
			auth_token (string) Evernote authentication token

		Implements the following Evernote client components:
			client (EvernoteClient)
			noteStore (NoteStore)
			userStore (UserStore)
			notebooks (list of Notebook)
			tags (list of Tag)
		"""

		self.auth_token = auth_token
		self.client = EvernoteClient(token = self.auth_token, sandbox = False)
		self.noteStore = self.client.get_note_store()
		self.userStore = self.client.get_user_store()
		self.notebooks = {}
		for notebook in self.noteStore.listNotebooks(self.auth_token):
			self.notebooks[notebook.name] = notebook.guid
		self.tags = {}
		for tag in self.noteStore.listTags(self.auth_token):
			self.tags[tag.name] = tag.guid
def make_second_note(url_l):
    dev_token = "x"
    client = EvernoteClient(token=dev_token, sandbox=False)
    note_store = client.get_note_store()

    message = ''
    for i in url_l:
        message += '<br>' + i + '</br>'

    #message='<br>'+url+'</br>'

    note = Types.Note()
    note.title = "Backlinks(%s)" % (time.strftime("%d/%m/%Y"))
    note.content = """<?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE en-note SYSTEM "http://xml.evernote.com/pub/enml2.dtd">
    <en-note><br>Insert Backlinks for the following articles:</br>
<br></br>
%s</en-note>
    """ % (message)

    now = int(round(time.time() * 1000))
    then = now + 864000000  # ten days after now

    # init NoteAttributes instance
    note.attributes = Types.NoteAttributes()
    note.attributes.reminderOrder = now
    note.attributes.reminderTime = then
    try:
        createdNote = note_store.createNote(note)
    except Exception, e:
        print type(e)
        print e
        raise SystemExit
Exemplo n.º 29
0
def home():
    form = PostForm()
    if form.validate_on_submit() and form.save_evernote:
        db.drop_all()
        db.create_all()

    elif form.validate_on_submit():
        n = Notes(title=form.title.data, body=form.body.data, user_id=current_user.id)
        n.save()
        db.session.add(n)
        db.session.commit()
        if form.save_evernote:
            client = EvernoteClient(token=DEV_TOKEN)

            noteStore = client.get_note_store()
            note = ttypes.Note()
            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>' % form.body.data
            note.title = form.title.data
            note.content = nBody
            noteStore.createNote(DEV_TOKEN, note)


    return render_template('page/home.html', form=form)
Exemplo n.º 30
0
def photoupload():
    file = request.files['photo']
    token = request.form['token']
    filename = request.form['filename']
    conn = boto.connect_s3(AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY)
    bucket = conn.get_bucket('noteable-paf14')
    k = Key(bucket)
    k.key =  hashlib.sha224(file.read()).hexdigest() + '.jpg'
    file.seek(0)
    k.set_contents_from_string(file.read())
    k.make_public()
    url = k.generate_url(expires_in=0, query_auth=False)
    u = User.objects.get(token=token)
    # Evernote stuff
    dev_token = os.environ['EVERNOTE_KEY']
    client = EvernoteClient(token=dev_token)
    file.seek(0)
    ret = sendImageToEvernote(client, filename, u.evernote_id, file.read())
    file.seek(0)
    Note(name=filename, original_photo_url=url, evernote_guid=ret.guid, author=u).save()
    chunks = findRectangle(create_opencv_image_from_file(file))
    noteStore = client.get_note_store()
    result = noteStore.getNote(dev_token, ret.guid, False, False, True, False)
    widgets = identifyWidgets(chunks, xml = result.resources[0].recognition.body[result.resources[0].recognition.body.find('<recoIndex'):-1])
    thread = threading.Thread(target=getTextChunks, args=(client, dev_token, ret.guid, widgets))
    thread.start()
    return jsonify(imageurl=url, success=True)
Exemplo n.º 31
0
class ZKClient(object):
    def __init__(self, **kwargs):
        self._en_client = EvernoteClient(
            consumer_key=kwargs.get('consumer_key'),
            consumer_secret=kwargs.get('consumer_secret'),
            token=kwargs.get('token'),
            sandbox=kwargs.get('sandbox', False))

        self._user_store = None
        self._note_store = None

        self.user = user.ZKUserClient(self)
        self.notebooks = notebook.ZKNotebookClient(self)
        self.notes = note.ZKNoteClient(self)
        self.tags = tag.ZKTagClient(self)

    def get_user_store(self):
        if not self._user_store:
            self._user_store = self._en_client.get_user_store()
        return self._user_store

    def get_note_store(self):
        if not self._note_store:
            self._note_store = self._en_client.get_note_store()
        return self._note_store
Exemplo n.º 32
0
def create_note(entry):
    """ ブックマーク情報からEvernoteのNoteを作成
    """
    client = EvernoteClient(
        token=global_config['evernote']['token'], sandbox=False)
    note_store = client.get_note_store()
    note = Types.Note()
    note.title = entry['title']
    note.title = note.title.replace(unichr(int('2028', 16)), ' ')
    note.title = note.title.replace(unichr(int('2029', 16)), ' ')
    note.title = note.title.encode('utf-8')
    content = (
        u'<?xml version="1.0" encoding="UTF-8"?>'
        u'<!DOCTYPE en-note SYSTEM "http://xml.evernote.com/pub/enml2.dtd">'
    )
    content += u'<en-note>'
    if entry['summary']:
        content += u'%s<hr />' % entry['summary']
    content += to_enml(entry['content'], url=entry['url'])
    content += u'</en-note>'
    soup = BeautifulSoup(content)
    note.content = str(soup)
    attrs = Types.NoteAttributes(sourceURL=entry['url'])
    note.attributes = attrs
    note.tagNames = [e.encode('utf-8') for e in entry['tags']]
    # 時間がミリ秒単位になるので1000を乗算する
    note.created = entry['created'] * 1000
    note = img_to_resource(note)
    note_store.createNote(note)
    return note
Exemplo n.º 33
0
def get_random_note(token, notebook_guid=None, debug=False, verbose=False):
    global client, note_store
    
    if not client:
        client = EvernoteClient(token=token, sandbox=False)
        note_store = client.get_note_store()

    if not notebook_guid:
        notebooks = note_store.listNotebooks()
        notebook = random.choice(notebooks)
        notebook_guid = notebook.guid

    filter = NoteStore.NoteFilter()
    filter.notebookGuid = notebook_guid
    spec = NoteStore.NotesMetadataResultSpec()
    spec.includeCreated = True
    spec.includeTitle = True
    note_infos = note_store.findNotesMetadata(filter,
                    0,
                    LimitConstants.EDAM_USER_NOTES_MAX,
                    spec)
    #filter=filter,
    #offset=0,
    #maxNotes=LimitConstants.EDAM_USER_NOTES_MAX,
    #resultSpec=spec)
    
    #print note_infos.totalNotes, len(note_infos.notes)

    note_guid = random.choice(note_infos.notes).guid

    return get_note(token, note_guid)
Exemplo n.º 34
0
    def __init__(self, key, config, sand_box=False):

        self.key = key
        self.logger = logging.getLogger('root')
        self.cfg = {
            "gardening_tag": config['evernote']['GARDENING_TAG'],
            "notebook": config['evernote']['NOTEBOOK'],
            "plant_tag_id": config['evernote']['PLANT_TAG_ID'],
            "location_tag_id": config['evernote']['LOCATION_TAG_ID'],
            "state_tag_id": config['evernote']['STATE_TAG_ID'],
            "plant_no_id": '+plants',  #config['evernote']['PLANT_NO_TAG_ID'],
            "sand_box": sand_box,
            "force_sync": False
        }

        #------------------------------------------------------------------------
        # Get Account Info
        #------------------------------------------------------------------------
        client = EvernoteClient(token=self.key['AUTH_TOKEN'], sandbox=sand_box)
        self.note_store = client.get_note_store()
        self.user_store = client.get_user_store()

        #------------------------------------------------------------------------
        # Check evernote API
        #------------------------------------------------------------------------
        version_ok = self.user_store.checkVersion(
            "Evernote EDAMTest (Python)",
            UserStoreConstants.EDAM_VERSION_MAJOR,
            UserStoreConstants.EDAM_VERSION_MINOR)

        if not version_ok:
            self.logger.warning("Evernote API version is not up to date.")
Exemplo n.º 35
0
def makeNoteFromLastCommit(dev_token):
  client = EvernoteClient(token=dev_token, sandbox=True)
  userStore = client.get_user_store()
  user = userStore.getUser()
  #print user.username

  noteStore = client.get_note_store()
  notebooks = noteStore.listNotebooks()
  #for n in notebooks:
  #  print n.name

  note = Types.Note()
  note.title = sys.argv[1] + " " + sys.argv[2]
  note.content = '<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE en-note SYSTEM "http://xml.evernote.com/pub/enml2.dtd">'
  content = ""
  content1 = ""
  content2 = ""
  parts = sys.argv[1:3]
  date = sys.argv[3:10]
  msg = sys.argv[10:]
  for s in parts:
    content += s+" "
  for s in date:
    content1 += s+" "
  for s in msg:
    content2 += s+" "
  note.content += '<en-note>'+ content + '<br/><br/>' + content1 + '<br/><br/>' + content2  +'</en-note>'
  note = noteStore.createNote(note)
Exemplo n.º 36
0
def profile():
    """Fetching a protected resource using an OAuth 1 token.
    """

    import hashlib
    import binascii
    import evernote.edam.userstore.constants as UserStoreConstants
    import evernote.edam.type.ttypes as Types

    from evernote.api.client import EvernoteClient

    auth_token = session['oauth_token']
    client = EvernoteClient(token=auth_token,
         sandbox=True if EVERNOTE_PRODUCTION == 'False' else False)

    user_store = client.get_user_store()

    version_ok = user_store.checkVersion(
        "Evernote EDAMTest (Python)",
        UserStoreConstants.EDAM_VERSION_MAJOR,
        UserStoreConstants.EDAM_VERSION_MINOR
    )

    note_store = client.get_note_store()

    # List all of the notebooks in the user's account
    notebooks = note_store.listNotebooks()
    return "<br/>" .join([notebook.name for notebook in notebooks])
Exemplo n.º 37
0
def mdever():
    # Open markdown file
    mdfile = sys.argv[1]
    while True:
        try:
            f = open(mdfile, "r")
            break
        except:
            print("ERROR: Can't open file: {filename}".format(filename=mdfile))
            quit()
    markdown_content = f.read()
    f.close()

    # Trans markdown -> enml
    enml = convertENML(markdown_content)
    # Connect Evernote
    dev_token = "S=s1:U=93787:E=162439a6ac8:C=15aebe93e40:P=1cd:A=en-devtoken:V=2:H=227be9400f1886b4fa570e0cb012fcab"
    client = EvernoteClient(token=dev_token)
    noteStore = client.get_note_store()

    # Create new note
    note = Types.Note()
    note.title = "1st test note"
    note.content = enml
    note = noteStore.createNote(note)
def clippings2evernote(filename, token, notebook_guid, debug=False, verbose=False):
    parser = MyClippingsParser(filename)

    client = EvernoteClient(token=token, sandbox=False)
    note_store = client.get_note_store()

    notes = {}

    for c in parser.parse():
        if c and c['type'] == 'surlignement':
            k = c['title'] + ' | ' + c['author']
            if k not in notes:
                notes[k] = []

            notes[k].append(c['content'])

    # FIXME:
    # en regroupant par clé, on perd l'ordre chronologique

    for k in sorted(notes.keys()):
        title = '#kindle ' + k
        content = '\n--\n'.join(notes[k])
        content = content.replace('\n', '<br/>').replace('&', '&amp;')

        if verbose:
            print title, content

        if debug:
            continue

        try:
            create_note(note_store, notebook_guid, title, content)
        except Exception, e:
            print 'Error:', title, content
            print e
Exemplo n.º 39
0
    def init_evernote(self):
        self.auth_token = get_local_key("evernote_key.auth_token", "django_local_apps")
        # Real applications authenticate with Evernote using OAuth, but for the
        # purpose of exploring the API, you can get a developer token that allows
        # you to access your own Evernote account. To get a developer token, visit
        # https://sandbox.evernote.com/api/DeveloperToken.action
        if self.auth_token == "your developer token":
            print "Please fill in your developer token"
            print "To get a developer token, visit " \
                  "https://sandbox.evernote.com/api/DeveloperToken.action"
            exit(1)

        # Initial development is performed on our sandbox server. To use the production
        # service, change sandbox=False and replace your
        # developer token above with a token from
        # https://www.evernote.com/api/DeveloperToken.action
        client = EvernoteClient(token=self.auth_token,
                                sandbox=False
                                )
        # Ref: https://github.com/evernote/evernote-sdk-python/issues/39
        client.service_host = 'app.yinxiang.com'
        self.user_store = client.get_user_store()
        version_ok = self.user_store.checkVersion(
            "Evernote EDAMTest (Python)",
            UserStoreConstants.EDAM_VERSION_MAJOR,
            UserStoreConstants.EDAM_VERSION_MINOR
        )
        print "Is my Evernote API version up to date? ", str(version_ok)
        print ""
        if not version_ok:
            exit(1)
        self.note_store = client.get_note_store()
def lambda_handler(event, context):

    #setting environment variables
    user = os.environ['GKEEP_USERNAME']
    pw = os.environ['GKEEP_APP_PASSWORD']
    noteId = os.environ['GKEEP_NOTE_ID']
    authToken = os.environ['EVERNOTE_DEV_TOKEN']
    noteGuid = os.environ['EVERNOTE_NOTE_ID']

    #keep login
    keep = gkeepapi.Keep()
    keep.login(user, pw)

    #getting keep note contents and converting to html
    syncnote = keep.get(noteId)
    syncnotebody = syncnote.text
    enotepayload = textile.textile(syncnotebody)

    #evernote login
    client = EvernoteClient(token=authToken)
    userStore = client.get_user_store()
    user = userStore.getUser()

    #updating the evernote note with the keep note contents
    noteStore = client.get_note_store()
    note = ttypes.Note()
    note.guid = noteGuid
    note.title = 'Shopping List'  #not sure if I should make this a variable
    note.content = '<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE en-note SYSTEM "http://xml.evernote.com/pub/enml2.dtd"><en-note>' + enotepayload + '</en-note>'
    noteStore.updateNote(authToken, note)

    return 0
Exemplo n.º 41
0
def get_note(user, note_id):
    STRIP_WORDS = ["Pocket:"]
    title = url = content = None
    access_token = user_access_token(user)
    if access_token:
        client = EvernoteClient(token=access_token, sandbox=SANDBOX)
        noteStore = client.get_note_store()
        note = noteStore.getNote(access_token, note_id, True, False, False,
                                 False)
        if note:
            logging.debug(note)
            content = extract_clipping_content(note.content)
            title = note.title
            for sw in STRIP_WORDS:
                if sw in title:
                    title = title.replace(sw, '')
            title = title.strip()
            attrs = note.attributes
            if attrs:
                url = attrs.sourceURL
        else:
            logging.debug("Note not found")
    else:
        logging.warning("Access token not available")
    return (title, content, url)
Exemplo n.º 42
0
def main(notebookName):
    
    #Get your developer token here: https://www.evernote.com/api/DeveloperToken.action and put it here
    dev_token = 'yourEvernoteDevKey'
    
    #Put your Shotgun script details here
    sg = Shotgun('https://yourSite.shotgunstudio.com','evernote-shotgun','yourScriptKey')
    
    #Put the Shotgun HumanUser ID here for the person you want to appear as the Note's author in Shotgun
    sgUserId = 45
    
    sgUser = sg.find_one("HumanUser",[['id', 'is', sgUserId]])

    #Establish a connection to Evernote and store note and user data
    client = EvernoteClient(token=dev_token, sandbox=False)
    userStore = client.get_user_store()
    user = userStore.getUser()

    noteStore = client.get_note_store()

    #Check if the supplied notebook exists, and if it does, send to processNotebook()
    print('\nFinding notebook')
    notebooks = noteStore.listNotebooks()
    notebookNames = [notebook.name for notebook in notebooks]
    if notebookName not in notebookNames:
            print('\nSorry, there are no notebooks in your account named {0}'.format(notebookName))
    else:
        for notebook in notebooks:
            if notebook.name == notebookName:
                print('\nProcessing notebook - BEGIN')
                processNotebook(noteStore, notebook, sg, sgUser)
                print('\nProcessing notebook - DONE\n')
            else:
                continue
Exemplo n.º 43
0
def get_note(user, note_id):
    STRIP_WORDS = ["Pocket:"]
    title = url = content = None
    access_token = user_access_token(user)
    if access_token:
        client = EvernoteClient(token=access_token, sandbox=SANDBOX)
        noteStore = client.get_note_store()
        note = noteStore.getNote(access_token, note_id, True, False, False, False)
        if note:
            logging.debug(note)
            content = extract_clipping_content(note.content)
            title = note.title
            uid = note.guid
            for sw in STRIP_WORDS:
                if sw in title:
                    title = title.replace(sw, '')
            title = title.strip()
            attrs = note.attributes
            if attrs:
                url = attrs.sourceURL
        else:
            logging.debug("Note not found")
    else:
        logging.warning("Access token not available")
    return (uid, title, content, url)
Exemplo n.º 44
0
 def write_to_evernote(self, item_list):
     client = EvernoteClient(token=self.dev_token,
                             sandbox=False,
                             service_host='app.yinxiang.com')
     note_store = client.get_note_store()
     for item in item_list:
         body = ET.tostring(item['body']).decode()
         pretty_body = parseString(body).toprettyxml(indent='    ')
         if 'evernote_id' in item:
             note = note_store.getNote(item['evernote_id'], True, False,
                                       False, False)
             note.content = self.template.format(body='\n'.join(
                 pretty_body.split('\n')[1:]),
                                                 workflowy_id=item['id'])
             received_note = self.update_note(note_store, note)
         else:
             note = Types.Note()
             note.title = item['title']
             note.content = self.template.format(body='\n'.join(
                 pretty_body.split('\n')[1:]),
                                                 workflowy_id=item['id'])
             received_note = self.create_note(note_store, note)
         print(item['title'])
         item['evernote_id'] = received_note.guid
         item['body'] = body
Exemplo n.º 45
0
class EvernoteController(object):
    def __init__(self, token, isSpecialToken = False, sandbox = False, isInternational = False, notebooks = None):
        self.token = token
        if sandbox:
            self.client = EvernoteClient(token=self.token)
        elif isInternational:
            self.client = EvernoteClient(token=self.token, service_host='www.evernote.com')
        else:
            self.client = EvernoteClient(token=self.token, service_host='app.yinxiang.com')
        self.isSpecialToken = isSpecialToken
        self.userStore = self.client.get_user_store()
        self.noteStore = self.client.get_note_store()
        self.storage = Storage(notebooks)
    def get_upload_limit(self):
        return {
            1: 25 * 1024 * 1024,
            3: 100 * 1024 * 1024,
            5: 200 * 1024 * 1024,
        }.get(self.userStore.getUser().privilege, 0)
    def create_notebook(self, noteFullPath):
        if self.get(noteFullPath): return False
        notebook = Types.Notebook()
        notebook.name = noteFullPath
        try:
            notebook = self.noteStore.createNotebook(notebook)
        except EDAMUserException, e:
            if e.errorCode == 10 and e.parameter == 'Notebook.name':
                self.storage.update(self.token, self.noteStore)
                return True
            else:
                raise e
        self.storage.create_notebook(notebook)
        return True
Exemplo n.º 46
0
 def connect(self, token=''):
     if token:
         self.token = token
     client = EvernoteClient(token=self.token)
     self.client = client
     self.note_store = client.get_note_store()
     self.user_store = client.get_user_store()
Exemplo n.º 47
0
def get_notes():
    auth_token = request.args.get('auth_token')
    if not auth_token:
        return

    notebook = request.args.get('notebook')
    if not notebook:
        return

    client = EvernoteClient(token=auth_token)
    note_store = client.get_note_store()

    offset = 0
    max_notes = 1000
    filter = NoteFilter(order=Types.NoteSortOrder.UPDATED,
                        notebookGuid=notebook)
    result_spec = NotesMetadataResultSpec(includeTitle=True)
    metadata = note_store.findNotesMetadata(auth_token, filter, offset,
                                            max_notes, result_spec)

    notes = []
    for n in metadata.notes:
        content = note_store.getNoteContent(auth_token, n.guid)
        notes.append({
            'guid': n.guid,
            'content': unicode(ENMLToHTML(content)),
            'title': n.title
        })

    return jsonify(notes=notes)
Exemplo n.º 48
0
def getNoteBooks():
    dev_token = getToken(False)
    client = EvernoteClient(token=dev_token, sandbox=False)
    notestore = client.get_note_store()
    notebooks = notestore.listNotebooks()
    for book in notebooks:
        print book.name + " " + book.guid
Exemplo n.º 49
0
def get_ev_note(guid):
    dev_token = app.config['EN_DEV_TOKEN']

    client = EvernoteClient(token=dev_token)
    note_store = client.get_note_store()

    note = note_store.getNote(dev_token, guid, True, True, True, True)

    title = note.title
    author = note.attributes.author
    date = note.updated
    url = note.attributes.sourceURL
    cont = note.content
    note_tags = []

    tag_guids = note.tagGuids
    if tag_guids is not None:
        for tag_guid in tag_guids:
            tag = note_store.getTag(dev_token, tag_guid)
            note_tags.append({'guid': tag_guid, 'name': tag.name})

    return dumps({
        'guid': guid,
        'title': title,
        'date_modified': date,
        'author': author,
        'content': cont,
        'tags': note_tags
    })
Exemplo n.º 50
0
class EvernoteWrapper(object):
    """A wrapper class around the EvernoteClient and friends"""

    @staticmethod
    def get_dev_token():
        """FIXME: When done with development, figure out the proper way to get Evernote access."""
        return open(os.path.expanduser('~/evernote.devtoken'), 'r').read().rstrip()

    def __init__(self):
        self.client = EvernoteClient(token=self.get_dev_token(), sandbox=False)
        user_store = self.client.get_user_store()
        self.user = user_store.getUser()

        self.note_store = self.client.get_note_store()

        # find "Action-Pending" notebook
        notebooks = self.note_store.listNotebooks()
        self.action_pending = [n for n in notebooks if n.name == "Action-Pending"][0]

        # collect all tags
        self.tags = {t.name: t for t in self.note_store.listTags()}
        self.tag_names = {t.guid: t.name for t in self.note_store.listTags()}

    @property
    def context_tag_names(self):
        return sorted([key for key in self.tags.keys() if key.startswith('@')])

    def get_notes(self, *tag_names):
        """Return a list of notes matching the tag_names"""
        note_filter = NoteFilter()
        note_filter.tagGuids = [self.tags[tn].guid for tn in tag_names if tn]
        result_spec = NotesMetadataResultSpec()
        result_spec.includeTitle = True
        result_spec.includeTagGuids = True
        notes = self.note_store.findNotesMetadata(note_filter, 0, 100, result_spec)
        for note in notes.notes:
            yield note

    def next_actions(self, level='1-Now', context='all'):
        """return a list of NextAction objects"""
        context = '@' + context

        if not context in self.tags.keys():
            context = None

        assert level in self.tags.keys(), 'Unknown level tag: %s' % level
        assert len(level.split('-')) == 2, 'Not a level tag: %s' % level
        # FIXME: maybe do some more checking here...

        return [NextAction(note, self.user, level) for note in self.get_notes(level, context)]

    def replace_tag(self, note_guid, old_tag, new_tag):
        """Update a note by replacing the old tag with the new tag"""
        note = self.note_store.getNote(note_guid, True, True, True, True)
        old_tag = self.tags[old_tag]
        new_tag = self.tags[new_tag]
        note.tagGuids = list((set(note.tagGuids) | {new_tag.guid}) - {old_tag.guid})
        self.note_store.updateNote(note)
        print(note.title)
Exemplo n.º 51
0
class EverCode:

     def __init__(self, Settings):
          self._settings = Settings
          self._token = self._settings.developer_token

     def setClient(self):
          self._client = EvernoteClient(token=self._token, sandbox=self._settings.sandbox)
          self._userStore = self._client.get_user_store()
          self._user = self._userStore.getUser()
          self._noteStore = self._client.get_note_store()
          self._notebooks = self._noteStore.listNotebooks()
     '''
     def login(self):
          self._client = EvernoteClient(
               consumer_key = self._settings.consumer_key,
               consumer_secret = self._settings.consumer_secret,
               sandbox=self._settings.sandbox
          )
          request_token = self._client.get_request_token('YOUR CALLBACK URL')
          self._client.get_authorize_url(request_token)
          access_token = self._client.get_access_token(
               request_token['oauth_token'],
               request_token['oauth_token_secret'],
               request_token.GET.get('oauth_verifier', '')
          )
          self._token = access_token
     '''

     def makeNote(self, noteTitle, noteBody, parentNotebook=None):
 
          result = noteBody.replace('class="highlight"', '')
      
          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>" % result
      
          ## Create note object
          ourNote = Types.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 = self._noteStore.createNote(self._token, ourNote)
          except Errors.EDAMUserException, edue:
               ## 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 "EDAMUserException:", edue
               return None
          except Errors.EDAMNotFoundException, ednfe:
               ## Parent Notebook GUID doesn't correspond to an actual notebook
               print "EDAMNotFoundException: Invalid parent notebook GUID"
               return None
Exemplo n.º 52
0
def update_note(accessToken,note):

    # Connecting to Evernote
    client = EvernoteClient(token=accessToken,sandbox=False)
    note_store = client.get_note_store()

    # Updating the note
    note_store.updateNote(accessToken,note)
Exemplo n.º 53
0
 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
Exemplo n.º 54
0
def createToDoList(todos):
    dev_token = getToken(False)
    client = EvernoteClient(token=dev_token, sandbox=False)
    notestore = client.get_note_store()
    notebody = contructNoteBody(todos)
    notetitle = datetime.date.today().strftime("%Y-%m-%d")
    notetitle = notetitle + " TODO"
    makeNote(dev_token, notestore, notetitle, notebody, parentNotebook=None)
Exemplo n.º 55
0
def connect2Ev(check=False):
    client = EvernoteClient(token=DEV_TOKEN, sandbox=False)
    if check:
        userStore = client.get_user_store()
        user = userStore.getUser()
        print "Connected to user account %s" % user.username
    noteStore = client.get_note_store()
    return noteStore
Exemplo n.º 56
0
def get_all_note_guid(access_token):
    client = EvernoteClient(token=access_token)
    note_store = client.get_note_store()
    board_filter = NoteFilter()
    result_spec = NotesMetadataResultSpec()
    result_list = note_store.findNotesMetadata(access_token, board_filter, 0, 100, result_spec)
    # High-level info of notes obtained  in result_list
    note_guid_list = [note.guid for note in result_list.notes]
    return note_guid_list
Exemplo n.º 57
0
def main():
    client = EvernoteClient(token=authToken, sandbox=False)
    noteStore = client.get_note_store()
    writeupList = getWriteupList(client, noteStore)

    title = '[Scoreboard] %s' % str(datetime.datetime.now())
    content = json.dumps(writeupList)
    noticeNotebook = noteStore.getNotebook(noticeGuid)
    makeNote(authToken, noteStore, title, content, noticeNotebook)
Exemplo n.º 58
0
def get_todos(auth_token):
    client = EvernoteClient(token=auth_token,
                            sandbox=settings.EVERNOTE_IS_SANDBOX)
    note_store = client.get_note_store()

    # check token has basic auth by listing notes (allowed without full auth)
    try:
        notebooks = note_store.listNotebooks()
        # print '[OK] Evernote API working, %s notebooks' % len(notebooks)
    except Exception as e:
        print '[FAIL] Evernote API failure: %s' % e

    # search for notes which have #todo content
    # see http://dev.evernote.com/doc/articles/search.php
    notefilter = NoteStore.NoteFilter()
    notefilter.words = '#todo'
    spec = NoteStore.NotesMetadataResultSpec()
    spec.includeTitle = True
    note_list = note_store.findNotesMetadata(auth_token, notefilter, 0, 100,
                                             spec)
    # print 'Search for #todo found %d notes' % note_list.totalNotes

    # for each note, pull the #todo lines
    todos = []
    for note_search_result in note_list.notes:
        # pull note content
        note = note_store.getNote(
            auth_token,
            note_search_result.guid,
            True,
            False,
            False,
            False,
        )
        note_updated = datetime.datetime.fromtimestamp(note.updated / 1000)

        # find <li>'s with #todo text and print
        tree = ET.fromstring(note.content)
        elems = tree.findall('.//li') or []

        # can be empty as #todo search omits the # . Use .lower() to icase
        todo_elems = filter(lambda e: '#todo' in ET.tostring(e).lower(),
                            elems) or []
        for elem in todo_elems:
            title = convert_to_unicode(note_search_result.title)

            # sometimes the <li>s contain <div>s which makes elem.text empty
            if not elem.text and list(elem):
                elem = list(elem)[0]

            element_text = convert_to_unicode(elem.text)
            s = u'%s :: %s' % (title, element_text)
            todos.append(ToDo(note_updated, s))

    # sort in reverse chrono of update time
    return sorted(todos, key=lambda t: t.note_update_timestamp, reverse=True)