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
Example #2
0
def callback(request):
    client = get_evernote_client()
    access_token = ''
    if 'oauth_verifier' in request.GET:
        oauth_verifier = request.GET.get("oauth_verifier")
        access_token = client.get_access_token(
            request.COOKIES['oauth_token'],
            request.COOKIES['oauth_token_secret'],
            oauth_verifier
        )
        client = EvernoteClient(token=access_token)
        user_store = client.get_user_store()
        user = user_store.getUser()
        username = user.username
        shard_id = user.shardId
        privilege = user.privilege

#        request.session['shard_id'] = shard_id

        u = User(
            user_id=user.id,
            access_token=access_token)
        u.save()
    # Redirect the user to the Evernote authorization URL
    try:
        callbackUrl = request.COOKIES['_redirect_url']
    except Exception as e :
        callbackUrl = 'http://%s/' % (request.get_host())
    response = redirect(callbackUrl)
    if len(access_token) > 0 :
        response.set_cookie('access_token', access_token)
    response.delete_cookie('_redirect_url')
    return response
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
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)
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")) 
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
Example #7
0
def index():
    client = EvernoteClient(token=dev_token)
    userStore = client.get_user_store()
    user = userStore.getUser()
    print user.username
    return render_template('index.mak', name='mako', consumer_key=consumer_key,
                           consumer_secret=consumer_secret)
Example #8
0
def auth_start():
    dev_token = "S=s1:U=8f624:E=14fa3a78539:C=1484bf65560:P=1cd:A=en-devtoken:V=2:H=a71244ac77727e1a6a2fcb5286ab435a"
    client = EvernoteClient(token=dev_token)
    userStore = client.get_user_store()
    user = userStore.getUser()
    list = [1, 2, 3, 4]
    return render_template('test.html', list=list)
Example #9
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
Example #10
0
def login():
    try:
        cfgfile = str(pathlib.Path.home())+'/.evernote-search.cfg'
        config = configparser.ConfigParser()
        config.read(cfgfile)
        auth_token = config['settings']['EVERNOTE_TOKEN']
    except Exception:
        print('Failed to load Evernote token. Visit https://sandbox.evernote.com/api/DeveloperToken.action',
        'to get your developer token and save it to $HOME/.evernote-search-token.cfg like below:\n',
        '[settings]\n', 'EVERNOTE_TOKEN = YOUR_DEV_TOKEN\n')
        raise EvernoteTokenLoadError

    sandbox = False
    china = False

    client = EvernoteClient(token=auth_token, sandbox=sandbox, china=china)

    user_store = client.get_user_store()

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

    if not version_ok:
        exit(1)

    return client
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])
def get_api_key():
    oauth_verifier = request.args.get("oauth_verifier")
    if oauth_verifier:  # if this shows up, then we've been authorized.
        #
        # therefore, now it's time for:
        #
        # ***STEP 6*** (still in our callback route):
        #
        # 6a. I think the temporary token you're sent back is the same you sent, but it's not completely clear from the docs, so let's parse it anyway.
        #
        temporary_token2 = request.args.get("oauth_token")
        # but just in case that doesn't really exist and it is the one we had before:
        if temporary_token2:
            oauth_token = temporary_token2
        else:
            oauth_token = temporary_request_token
        #
        # 6b. Send yet ANOTHER request, this time for the proper authorization token
        #
        access_token = auth_client.get_access_token(oauth_token, oauth_secret,
                                                    oauth_verifier)
        #
        # And we should be authenticated!!!  Let's use our new token.
        #
        real_client = EvernoteClient(token=access_token)
        userStore = real_client.get_user_store()
        user = userStore.getUser()
        return "Hi! You're authenticated, and I can prove it, {}!".format(
            user.username)
    else:  # our request was not authorized.  throw an unfriendly error.
        abort(401)
Example #13
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)
Example #14
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
Example #15
0
def user():

    # Checking Access Token
    access_token = get_developer_token()
    if (access_token == ""):
        return safeglobals.MSG_NO_DEVTOKEN

    client = EvernoteClient(token=access_token, sandbox=False)
    userStore = client.get_user_store()
    response = userStore.getUser()

    # Setting user data
    username = response.username
    uid = response.id
    email = response.email
    privilegeLevel = safeglobals.PRIVILEGE_LEVEL[str(response.privilege)]
    premiumStatus = safeglobals.PREMIUM_STATUS[str(
        response.accounting.premiumServiceStatus)]
    privilege = response.privilege

    #return json.dumps(response)
    return render_template('user.evernote.html',
                           username=username,
                           uid=uid,
                           email=email,
                           premiumStatus=premiumStatus,
                           priv=privilegeLevel)
Example #16
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.")
Example #17
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)
Example #18
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
    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()
Example #20
0
class UserCoordinator:
    def __init__(self, auth_token, is_sandbox):
        self.client = EvernoteClient(token=auth_token, sandbox=is_sandbox)

    def get_user(self):
        user_store = self.client.get_user_store()
        return user_store.getUser()
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()
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
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
Example #24
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()
        business_store = client.get_business_note_store()

        auth_result = user_store.authenticateToBusiness()
        business_shard_id = auth_result.user.shardId
        business_user_id = auth_result.user.id
        business_token = auth_result.authenticationToken

        # Construct the evernote Link to the newly copied note
        in_app_link = "evernote:///view/%s/%s/%s/%s/" % (
            business_user_id,
            business_shard_id,
            guid,
            guid
        )

        # Redirect the user to the note (opens 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"))
Example #25
0
def auth_start():
    dev_token = "S=s1:U=8f624:E=14fa3a78539:C=1484bf65560:P=1cd:A=en-devtoken:V=2:H=a71244ac77727e1a6a2fcb5286ab435a"
    client = EvernoteClient(token=dev_token)
    userStore = client.get_user_store()
    user = userStore.getUser()
    list = [1, 2, 3, 4]
    return render_template('test.html', list = list)
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
Example #27
0
def get():
    # conn = dbConnector()
    # c = conn.cursor()
    p={}

    if 'token' not in request.cookies:
    	return redirect(url_for('auth_start'))
    else:
    	cToken = request.cookies.get('token')

	client = EvernoteClient(token=cToken,sandbox=False)
	#Evernoteからユーザー情報を取得する。
	if 'user' not in session:
		us = client.get_user_store()
		user = us.getUser()
		session['username'] = user.username
		session['uid'] = user.id

	#Evernoteからタグを取得する
	if 'tags' not in session:
	    evernoteTag(client)
	else:
		pass
	
	if 'perms' in session:
		p=session['perms']
		session['perms']=None
	else:
		perms=None

	return render_template('index.html', perms=p)
Example #28
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
Example #29
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()
Example #30
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
Example #31
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
Example #32
0
    def create_client(self, storage_name='evernote.dat'):
        '''Create an instance of EN client and set auth_token.'''
        # Try check if storage file exists
        if os.path.isfile(storage_name) is True:
            # Try to read it
            try:
                storage = open(storage_name, 'r')
                auth_token = storage.read()
                # We will need it for some methods
                self.token = auth_token
                try:
                    # NB: sandbox=False for production
                    client = EvernoteClient(token=auth_token, sandbox=False)
                    # Now try to get user_store if Exception is thrown fall
                    # back to reauthorization
                    user_store = client.get_user_store()
                    user = user_store.getUser().username
                except Exception as e:
                    print('Authorization error: ', e)
                    print('Will need to re-authorize.')
                    client = self.authorize(storage_name)

            except IOError as e:
                print('Error while reading the auth token: ', e)
                client = None
            finally:
                storage.close()
        else:
            # No storage found, we will need to authorize the app
            # to get the token
            client = self.authorize(storage_name)
        return client
Example #33
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)
Example #34
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)
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
Example #36
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
 def get_user(self, auth_token):
     sdk = EvernoteSdk(token=auth_token, sandbox=self.sandbox)
     user_store = sdk.get_user_store()
     user = user_store.getUser(auth_token)
     return {
         'id': user.id,
         'shard_id': user.shardId,
     }
def fetch_evernote_notes():
    global notes, title
    from evernote.edam.notestore import NoteStore
    from evernote.edam.userstore import constants as user_store_constants
    from evernote.api.client import EvernoteClient
    # 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
    # sandbox
    # sandbox_auth_token = \
    #     "xxx"
    # 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=sandbox_auth_token, sandbox=True)
    # original
    production_auth_token = \
        "xxxx"
    evernote_client = EvernoteClient(token=production_auth_token, sandbox=False)

    # get user store
    user_store = evernote_client.get_user_store()
    # check if API version is fine
    version_ok = user_store.checkVersion(
        "Evernote EDAMTest (Python)",
        user_store_constants.EDAM_VERSION_MAJOR,
        user_store_constants.EDAM_VERSION_MINOR
    )
    print "Is my Evernote API version up to date? ", str(version_ok)
    if not version_ok:
        exit(1)

    # get notes store
    note_store = evernote_client.get_note_store()
    # search for the notebook named ideas
    note_filter = NoteStore.NoteFilter()
    note_filter.words = 'notebook:"{}"'.format(EVERNOTE_NOTEBOOK_NAME)
    notes_metadata_result_spec = NoteStore.NotesMetadataResultSpec()
    notes_metadata_list = note_store.findNotesMetadata(note_filter, 0, NUM_EVERNOTE_NOTES, notes_metadata_result_spec)
    # get all the notes in the ideas notebook
    notes = {}
    print "Fetching notes..."
    for note_metadata in notes_metadata_list.notes:
        note_guid = note_metadata.guid

        # fetch complete note
        note = note_store.getNote(note_guid, True, True, False, False)
        title = note.title
        notes[title] = note.content

        if None != note.resources:
            print "resources are present for card: {}".format(title)

    return notes
Example #39
0
def handle(text, mic, profile):

        auth_token = profile["EVERNOTE_TOKEN"]

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

        if bool(re.search(r'\Note\b', text, re.IGNORECASE)):
                writeNote(text, mic, note_store)
Example #40
0
def handle(text, mic, profile):

    auth_token = profile["EVERNOTE_TOKEN"]

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

    if bool(re.search(r"\Note\b", text, re.IGNORECASE)):
        writeNote(text, mic, note_store)
def setup():
	#login to the evernote test server
	testclient = EvernoteClient(token=auth_token, sandbox=True)
	user_store = testclient.get_user_store()
	note_store = testclient.get_note_store()
	testuser = user_store.getUser()
	assert_equal(testuser.username, "silver97232")
	assert_not_equal(testuser.username, "made up username, should fail")
	print "SETUP!"
	print client
class EvernoteBookmarks(object):
    def __init__(self, token):
        self.token = token

        self.client = EvernoteClient(
            token=token,
            sandbox=False)

        self.user_store = self.client.get_user_store()

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

        if not version_ok:
            raise ValueError("Evernote API version not up to date")

        self.note_store = self.client.get_note_store()

    def list_notebooks(self):
        return self.note_store.listNotebooks()

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

    def create_note(self, bookmark, notebook_guid):
        date_created = bookmark['add_date']*1000

        tag_string = ', '.join(bookmark['tags'])
        if 'no_tag' in tag_string:
            tag_string = ""

        content = NOTE_TEMPLATE.format(
            title=cgi.escape(bookmark['title']),
            url=cgi.escape(bookmark['url']),
            tags=cgi.escape(tag_string),
            last_visit=cgi.escape(str(datetime.fromtimestamp(bookmark['last_visit']))),
            add_date=cgi.escape(str(datetime.fromtimestamp(bookmark['add_date']))),
            private=cgi.escape("Yes" if bookmark['private'] else "No"),
        )

        note = Types.Note()
        note.title = bookmark['title'].encode('utf-8')
        note.content = content.encode('utf-8')
        note.tagNames = [bm.encode('utf-8') for bm in bookmark['tags']]
        note.created = date_created
        note.updated = date_created
        note.notebookGuid = notebook_guid

        self.note_store.createNote(note)
class EvernoteBookmarks(object):
    def __init__(self, token):
        self.token = token

        self.client = EvernoteClient(token=token, sandbox=False)

        self.user_store = self.client.get_user_store()

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

        if not version_ok:
            raise ValueError("Evernote API version not up to date")

        self.note_store = self.client.get_note_store()

    def list_notebooks(self):
        return self.note_store.listNotebooks()

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

    def create_note(self, bookmark, notebook_guid):
        date_created = bookmark['add_date'] * 1000

        tag_string = ', '.join(bookmark['tags'])
        if 'no_tag' in tag_string:
            tag_string = ""

        content = NOTE_TEMPLATE.format(
            title=cgi.escape(bookmark['title']),
            url=cgi.escape(bookmark['url']),
            tags=cgi.escape(tag_string),
            last_visit=cgi.escape(
                str(datetime.fromtimestamp(bookmark['last_visit']))),
            add_date=cgi.escape(
                str(datetime.fromtimestamp(bookmark['add_date']))),
            private=cgi.escape("Yes" if bookmark['private'] else "No"),
        )

        note = Types.Note()
        note.title = bookmark['title'].encode('utf-8')
        note.content = content.encode('utf-8')
        note.tagNames = [bm.encode('utf-8') for bm in bookmark['tags']]
        note.created = date_created
        note.updated = date_created
        note.notebookGuid = notebook_guid

        self.note_store.createNote(note)
Example #44
0
class EvernoteAPI:
	def __init__(self):
		config = ConfigHandler('evernote.config')
		token = config.get('one-calendar', 'token')
		self.client = EvernoteClient(token=token)

	def user_store(self):
		return self.client.get_user_store()

	def note_store(self):
		return self.client.get_note_store()
Example #45
0
def yx():
    """
    测试印象笔记服务
    :return:
    """
    client = EvernoteClient(token=dev_token,sandbox=False)
    client.service_host = 'app.yinxiang.com'
    userStore = client.get_user_store()
    user = userStore.getUser()
    print user
    return "yx"
def SignInEvernote():
    global client,noteStore 
    result = False
    try:
        client = EvernoteClient(token=dev_token)
        userStore = client.get_user_store()
        user = userStore.getUser()          # here will throw an error
        logging.info(user.username)
        noteStore = client.get_note_store()
        result    = True 
    except Exception, e:
        logging.warn(e)
Example #47
0
    def __init__(self, token, notebook_guid=None):
        """
        :param str token: The Evernote auth token
        :param str notebook_guid: The Evernote notebook GUID or None if not known
        """
        client = EvernoteClient(token=token,
                                consumer_key=EVERNOTE_CONSUMER_KEY,
                                consumer_secret=EVERNOTE_CONSUMER_SECRET,
                                sandbox=DEVELOPMENT_MODE)
        self._token = token
        self._note_store_uri = client.get_user_store().getNoteStoreUrl()
        self._thread_pool = ThreadPool(processes=EVERNOTE_FETCH_THREADS)

        self.notebook_guid = notebook_guid or self._get_create_notebook()
 def get_quota_info(self, auth_token):
     sdk = EvernoteSdk(token=auth_token, sandbox=self.sandbox)
     user_store = sdk.get_user_store()
     note_store = self.get_note_store(auth_token)
     user = user_store.getUser()
     state = note_store.getSyncState()
     total_monthly_quota = user.accounting.uploadLimit
     used_so_far = state.uploaded
     quota_remaining = total_monthly_quota - used_so_far
     reset_date = datetime.datetime.fromtimestamp(user.accounting.uploadLimitEnd / 1000.0)
     return {
         'remaining': quota_remaining,
         'reset_date': reset_date, 
     }
class Evernote():
    logger = logging.getLogger('Evernote')

    def __init__(self, auth_token, NOTEBOOK):
        #authentication
        self.client = EvernoteClient(token=auth_token, sandbox=False)
        self.userStore = self.client.get_user_store()
        self.noteStore = self.client.get_note_store()
        self.NOTEBOOK = NOTEBOOK
        self.tags = self.noteStore.listTags()

    def addNote(self, entry, notebook=None):
        '''
        adds a note (title, content) to the standard Notebook
        '''
        if notebook == None:
            notebook = self.NOTEBOOK
        note = Types.Note()
        note.notebookGuid = notebook
        note.title = entry['title'].replace(' ', '')
        if note.title == '':
            note.title = 'RedNotebookEntry'
        note.content = '<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE en-note SYSTEM "http://xml.evernote.com/pub/enml2.dtd">'
        note.content += '<en-note>%s</en-note>' % transformContent(
            entry['content'])
        note = self.noteStore.createNote(note)
        logger.info('added note:%s, with guid:%s' %
                    (entry['title'], str(note.guid)))
        return note.guid

    def addNotebook(self, notebookname):
        '''
        adds a Notebook to the noteStore if needed(to store all Rednotebook entries)
        '''
        notebook = Types.Notebook()
        notebook.name = notebookname
        notebook = self.noteStore.createNotebook(notebook)
        logger.info('added notebook:%s, with guid:%s' %
                    (notebookname, str(notebook.guid)))
        return notebook.guid

    def CheckVersion(self):
        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 ""
        return version_ok
Example #50
0
class Evernote_Poster(object):
	'''Post notes to evernote'''
	
	def __init__(self, token):
		self.token = token
		self.client = EvernoteClient(token=EN_TOKEN, sandbox=False)
		self.user_store = self.client.get_user_store()
		self.note_store = self.client.get_note_store()	

	def check_version(self):
		'''Check for version'''
		version_ok = self.user_store.checkVersion(
			"Version check",
			UserStoreConstants.EDAM_VERSION_MAJOR,
			UserStoreConstants.EDAM_VERSION_MINOR
		)
		if not version_ok:
			return -1
		else: 
			return 0
	
	def _make_note(self, title, content, url):
		'''Prepare a note to be posted'''
		note = Types.Note()
		note.title = title
		# Set up note attributes
		attrs = Types.NoteAttributes()
		attrs.sourceURL = url
		note.attributes = attrs
		note.content = '<?xml version="1.0" encoding="UTF-8"?>'
		note.content += '<!DOCTYPE en-note SYSTEM ' \
			'"http://xml.evernote.com/pub/enml2.dtd">'
		# Wrap content in <en-note>
		note.content += '<en-note>'
		note.content += content
		note.content += '</en-note>'
		return note
	
	def post_note(self, title, note, url):
		'''Post a note to Evernote'''
		ver = self.check_version()
		if ver < 0:
			print('*** VERSION ERROR: Update client to the latest version.')
		else:
			note = self._make_note(title, note, url)
			created_note = self.note_store.createNote(note)	
		return created_note.guid
Example #51
0
    def __init__(self, token, notebook_name='default'):
        """
        Initializes the evernote client for uploading notes.
        :param token: the developer token needed for access to the account
        :type token: str
        :param notebook_name: name of notebook to add the new notes to.
        :type notebook_name: str
        """
        self.logger = logging.getLogger(__name__)
        self.logger.info("Initializing Evernote client")
        client = None
        try:  # Should make sandbox a debug option
            client = EvernoteClient(token=token, sandbox=False)
        except evernote.edam.error.ttypes.EDAMUserException:
            print("Please provide correct evernote credentials")
            if input(
                    "Abort (y/n): "
            ) == 'y':  # Might be best to just silently try again or continue rather than ask.
                raise SystemExit
        self.user_store = client.get_user_store()
        self.note_store = client.get_note_store()
        self.tag_list = self.note_store.listTags()
        self.notebooks = self.note_store.listNotebooks()
        self.notebook_name = notebook_name  # for use in other functions.
        self.notebook_guid = None
        self.error_count = 0
        self.warning_count = 0

        self.quota_remaining()

        if notebook_name != 'default':  # ie we want to specify the notebook to save the notes to
            notebook_dic = {}
            for notebook in self.notebooks:  # create dict of notebook names: notebook objects
                notebook_dic[notebook.name] = notebook

            if notebook_name in notebook_dic:  # if notebook exists, set persistant guid as existing guid
                self.notebook_guid = notebook_dic[notebook_name].guid
            else:  # if it doesn't exist, create it.
                new_notebook = Types.Notebook()
                new_notebook.name = notebook_name
                new_notebook.defaultNotebook = False
                self.notebook_guid = self.note_store.createNotebook(
                    new_notebook).guid

        self.note = None
Example #52
0
def upload_shopping_list():
    shopping_list = open_shopping_list()
    dev_token = "S=s1:U=94a8d:E=16b12ef7476:C=163bb3e4778:P=1cd:A=en-devtoken:V=2:H=597dbf9724fbc184e2d5b1eced891761"
    client = EvernoteClient(token=dev_token)
    userStore = client.get_user_store()
    noteStore = client.get_note_store()
    note = ttypes.Note()
    note.title = 'Shopping list ' + str(datetime.date.today())
    body = '<?xml version="1.0" encoding="UTF-8"?>'
    body += '<!DOCTYPE en-note SYSTEM "http://xml.evernote.com/pub/enml2.dtd">'
    body += '<en-note>'
    for item in set(shopping_list["items"]):
        body += '<div><en-todo/> %d %s</div>' % (shopping_list["items"][item],
                                                 item)
    body += '</en-note>'

    note.content = body
    noteToUpload = noteStore.createNote(dev_token, note)
Example #53
0
    def _init_network(self):
        """Init connection to remote server"""
        
        logger.debug("Execute _init_network")        
        
        while True:
            try:
            	 # pull token from keyring
                logger.debug("init network auth_token")
                self.auth_token = get_auth_token( )
                                             
                # use EvernoteClient() to get userstore and notestore
                client = EvernoteClient(token=self.auth_token, sandbox=False)
                self.user_store = client.get_user_store()
                self.note_store = client.get_note_store()
                
                # self.note_store = tools.get_note_store(self.auth_token)
                # self.user_store = tools.get_user_store(self.auth_token)

                break
            except EDAMSystemException, e:
                if e.errorCode == EDAMErrorCode.RATE_LIMIT_REACHED:
                    logger.error(
                        "Rate limit _init_network: %d minutes - sleeping" % 
                        (e.rateLimitDuration/60)
                    )
                    self.status = const.STATUS_RATE
                    # nothing I can think of doing other than sleeping here
                    # until the rate limit clears
                    time.sleep(e.rateLimitDuration)
                    self.status = const.STATUS_NONE
            except socket.error, e:
                logger.error(
                    "Couldn't connect to remote server. Got: %s" %
                        traceback.format_exc()
                )
                SyncStatus.connect_error_count+=1
                logger.error(
                    "Total connect errors: %d" % SyncStatus.connect_error_count)
                time.sleep(30)
Example #54
0
class EvernoteModule(BaseModule):
    def __init__(self, *args):
        super(EvernoteModule, self).__init__(*args)
        self.auth_token = self.get_configuration('evernote_auth_token')
        if self.auth_token:
            self.client = EvernoteClient(token=self.auth_token, sandbox=False)
            self.user_store = self.client.get_user_store()
            self.note_store = self.client.get_note_store()
        else:
            return False

    def write_note(self):
        note = NoteType.Note()  # Creates a new note
        note.title = "Stephanie Note"

        self.assistant.say("What would you like me to write down?")
        the_note = self.assistant.listen().decipher()  # Listens to the input and stores it

        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>Note:<br/>'
        note.content += ('%s' % the_note)
        note.content += '</en-note>'

        try:
            created_note = self.note_store.createNote(note)  # Stores the new note in Evernote
        except:
            response = ("Note wasn't created successfully, you probably didn't spelled anything or spelled really "
                        "bad, Not my fault okay? It's never a program's fault.")
            print(response)
            return response
        if created_note:
            return "I successfully wrote down your note."
        else:
            response = ("Note wasn't created successfully, you probably didn't spelled anything or spelled really "
                        "bad, Not my fault okay? It's never a program's fault. /s Refer back to docs.")
            print(response)
            return response
Example #55
0
class EvernoteModule(BaseModule):
    def __init__(self, *args):
        super(EvernoteModule, self).__init__(*args)
        self.auth_token = self.get_configuration('evernote_auth_token')
        if self.auth_token:
            self.client = EvernoteClient(token=self.auth_token, sandbox=False)
            self.user_store = self.client.get_user_store()
            self.note_store = self.client.get_note_store()
        else:
            return False

    def write_note(self):
        note = NoteType.Note()  # Creates a new note
        note.title = "Stephanie Note"

        self.assistant.say("What would you like me to write down?")
        the_note = self.assistant.listen().decipher(
        )  # Listens to the input and stores it

        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>Note:<br/>'
        note.content += ('%s' % the_note)
        note.content += '</en-note>'

        try:
            created_note = self.note_store.createNote(
                note)  # Stores the new note in Evernote
        except:
            response = (_("error.note.create"))
            print(response)
            return response
        if created_note:
            return _("note.create.success")
        else:
            response = (_("error.note.create"))
            print(response)
            return response
Example #56
0
def get_source_urls(auth_token):
    client = EvernoteClient(token=auth_token, sandbox=True)

    user_store = client.get_user_store()

    version_ok = 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)

    note_store = client.get_note_store()

    # List all of the notebooks in the user's account
    notebooks = note_store.listNotebooks()

    # get all notes tagged 'beek'
    filter = NoteStore.NoteFilter()
    filter.words = "tag:beek"
    filter.ascending = False

    spec = NoteStore.NotesMetadataResultSpec()
    spec.includeTitle = True

    ourNoteList = note_store.findNotesMetadata(auth_token, filter, 0, 100,
                                               spec)

    wholeNotes = []
    urls_and_contents = []
    for note in ourNoteList.notes:
        share_url = shareSingleNote(auth_token, note_store, user_store,
                                    note.guid)
        wholeNote = note_store.getNote(auth_token, note.guid, True, False,
                                       False, False)

        urls_and_contents.append((share_url, wholeNote))
    return (note_store, urls_and_contents)
def retrieve_tags_and_note_collection_counts(auth_token, sandbox, note_filter):
    """Uses the Evernote API to retrieve tags and note collection counts

    Args:
        auth_token (str): the Evernote API authentication token
        sandbox (bool): sandbox flag, indicates whether Evernote API calls should be made against the production or sandbox environment
        note_filter (evernote.edam.notestore.ttypes.NoteFilter): the filter applied to the search query on the Evernote API

    Returns:
        evernote.edam.type.ttypes.Tag: list of tags in the Evernote acccount
        evernote.edam.notestore.ttypes.NoteCollectionCounts: number of notes for each notebook and tag with a non-zero set of applicable notes
    """
    try:
        client = EvernoteClient(token=auth_token, sandbox=sandbox)
        user_store = client.get_user_store()
        user = user_store.getUser()
        logging.info(
            "Retrieving tags and noteCollectionCounts for Evernote user [%s]%s",
            user.username, " from sandbox environment" if sandbox else "")

        note_store = client.get_note_store()
        tags = note_store.listTags()
        note_collection_counts = note_store.findNoteCounts(note_filter, False)
        logging.info(
            "Retrieved [%d] tags and [%d] noteCollectionCounts from Notes of user [%s]",
            len(tags), len(note_collection_counts.tagCounts), user.username)

        return tags, note_collection_counts
    except EDAMSystemException as e:
        logging.error(
            "Failed to retrieve tags and noteCollectionCounts from Evernote API: %s",
            EDAMErrorCode._VALUES_TO_NAMES[e.errorCode])
        raise
    except EDAMUserException as e:
        logging.error(
            "Failed to retrieve tags and noteCollectionCounts from Evernote API: %s",
            EDAMErrorCode._VALUES_TO_NAMES[e.errorCode])
        raise
Example #58
0
class Sync(object):
    token = "S=s245:U=1e2f5ee:E=15ce321c571:C=1558b709860:P=1cd:A=en-devtoken:V=2:H=bd15150c522ef2489eb5a0fe88d86f51"

    def __init__(self, token=None):
        self.client = None
        self.is_authenticated = None
        if token:
            self.token = token

    def get_client(self):
        self.is_authenticated = self._connect_to_evernote(self.token)
        return self.client

    def _connect_to_evernote(self, dev_token):
        user = None
        try:
            self.client = EvernoteClient(token=dev_token, sandbox=False)
            user_store = self.client.get_user_store()
            user = 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

    def get_token(self):
        return self.token