示例#1
0
    def __init__(self):

        if USE_APPLESCRIPT is False:

            if not mw.col.conf.get(SETTING_TOKEN, False):
                # First run of the Plugin we did not save the access key yet
                client = EvernoteClient(
                    consumer_key='scriptkiddi-2682',
                    consumer_secret='965f1873e4df583c',
                    sandbox=False
                )
                request_token = client.get_request_token('https://fap-studios.de/anknotes/index.html')
                url = client.get_authorize_url(request_token)
                showInfo("We will open a Evernote Tab in your browser so you can allow access to your account")
                openLink(url)
                oauth_verifier = getText(prompt="Please copy the code that showed up, after allowing access, in here")[0]
                auth_token = client.get_access_token(
                    request_token.get('oauth_token'),
                    request_token.get('oauth_token_secret'),
                    oauth_verifier)
                mw.col.conf[SETTING_TOKEN] = auth_token
            else:
                auth_token = mw.col.conf.get(SETTING_TOKEN, False)

            self.token = auth_token
            self.client = EvernoteClient(token=auth_token, sandbox=False)
            self.noteStore = self.client.get_note_store()
示例#2
0
    def _connect_to_evernote(self, dev_token):
        user = None
        try:
            self.client = EvernoteClient(token=dev_token, sandbox=False)
            self.user_store = self.client.get_user_store()
            user = self.user_store.getUser()
            self.user_id = user.id
            self.shared_id = user.shardId
        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:
            self.console_log(
                "Authenticated to evernote as user %s" % user.username)
            return True
        else:
            return False
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
示例#4
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
示例#5
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
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
def get_evernote_client(token=None):
    if token:
        return EvernoteClient(token=token, sandbox=True)
    else:
        return EvernoteClient(consumer_key=EN_CONSUMER_KEY,
                              consumer_secret=EN_CONSUMER_SECRET,
                              sandbox=True)
示例#8
0
    def on_navigation_requested(self, view, frame, req, data=None):
        logging.debug('Requesting new page')
        self.__spinner.show()
        self.__status_label.set_text(AuthDialog.STATUS_MESSAGE_CONNECTING)
        url = req.get_uri()
        if PROGRAM_NAME.lower() in url:
            query = urlparse.urlparse(url).query
            data = dict(urlparse.parse_qsl(query))
            
            try:
                self.__authData['oauth_verifier'] = data['oauth_verifier']
            except KeyError:
                logging.error('authorization failed')
                return False

            client = EvernoteClient(
                consumer_key=EverNoteConsumerInfo.CONSUMER_KEY,
                consumer_secret=EverNoteConsumerInfo.CONSUMER_SECRET,
                service_host = MetaData.get_evernote_host(),
                sandbox=False # Default: True
            )
            self.__auth_token = client.get_access_token(
                self.__authData['oauth_token'],
                self.__authData['oauth_token_secret'],
                self.__authData['oauth_verifier']
            )
            self.__dialog.response(100)
        return False
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])
示例#10
0
def setup():
    """
    oauth flow for new users or updating users
    adapted from https://gist.github.com/inkedmn/5041037
    """
    client = EvernoteClient(
        consumer_key=CONSUMER_KEY,
        consumer_secret=CONSUMER_SECRET,
        sandbox=False
    )

    request_token = client.get_request_token('http://localhost:10668')
    print(
        "Paste this URL in your browser and login:"******"-> {url}  \n\n"
        "Be advised, this will save your oauth token in plaintext to ~/.not_token !"
        "if you aren't cool with that, ctrl-c now and never return!".format(
            url=client.get_authorize_url(request_token)
        )
    )
    single_server = single_serve()
    single_server.handle_request()
    auth_url = path  # noqa
    vals = parse_query_string(auth_url)
    auth_token = client.get_access_token(
        request_token['oauth_token'],
        request_token['oauth_token_secret'],
        vals['oauth_verifier']
    )
    with open(os.path.join(os.environ['HOME'], '.not_token'), 'w') as f:
        f.write(auth_token)
        print("Token saved.")
示例#11
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
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
示例#13
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"))
示例#14
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)
示例#15
0
    def _SyncNoteTOC(self, maxEntries: int):
        '''
            同步笔记的目录结构
        '''

        db = ENDBOperator()

        # 获取最后一次更新的内容
        self._client = EvernoteClient(token = self._token, service_host = 'app.yinxiang.com')
        noteStore = self._client.get_note_store()


        state = noteStore.getSyncState(self._client.token)
        updateCount = state.updateCount

        # 如果和数据库中的一致,就不需要更新了
        localUSN = db.GetEvernoteLocalUSN()

        logging.info("Evernote USN:%d, local USN:%d",
                     updateCount,
                     localUSN)
        if updateCount > localUSN:
            # 更新100条信息
            logging.info("需要更新数据啦")
            self._SyncNoteInfo(noteStore, localUSN, maxEntries)
        else:
            logging.info("暂时不用更新数据")

        pass
示例#16
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)
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()
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
示例#19
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()
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
示例#21
0
def get_access_token(user, oauth_token, oauth_verifier):
    '''
    Get request token
    '''
    from settings import secrets
    client = EvernoteClient(
        consumer_key=secrets.EVERNOTE_CONSUMER_KEY,
        consumer_secret=secrets.EVERNOTE_CONSUMER_SECRET,
        sandbox=SANDBOX
    )
    access_token = en_user_id = None
    access_token_dict = {}
    oauth_token_secret = memcache.get(SECRET_MCK % user.key.id())
    if oauth_token_secret:
        try:
            access_token_dict = client.get_access_token_dict(
                oauth_token,
                oauth_token_secret,
                oauth_verifier
            )
        except KeyError:
            logging.warning("KeyError getting Evernote access token")
        en_user_id = access_token_dict.get('edam_userId')
        access_token = access_token_dict.get('oauth_token')
    else:
        logging.warning("oauth_token_secret unavailable")
    return (access_token, en_user_id)
示例#22
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)
示例#23
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
    })
示例#24
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)
示例#25
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
 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()
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
示例#28
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
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)
示例#30
0
 def __init__(self):
     if not mw.col.conf.get(SETTING_TOKEN, False):
         # First run of the Plugin we did not save the access key yet
         client = EvernoteClient(
             consumer_key='scriptkiddi-2682',
             consumer_secret='965f1873e4df583c',
             sandbox=False
         )
         request_token = client.get_request_token('http://brunomart.in/anknotes/index.html')
         url = client.get_authorize_url(request_token)
         showInfo("We will open a Evernote Tab in your browser so you can allow access to your account")
         openLink(url)
         oauth_verifier = getText(prompt="Please copy the code that showed up, after allowing access, in here")[0]
         secret_key = getText(prompt="protect your value with a password, it will be asked each time you import your notes")[0]
         auth_token = client.get_access_token(
             request_token.get('oauth_token'),
             request_token.get('oauth_token_secret'),
             oauth_verifier)
         mw.col.conf[SETTING_TOKEN] = encode(secret_key, auth_token)
     else:
         secret_key = getText(prompt="password")[0]
         auth_token_encoded = mw.col.conf.get(SETTING_TOKEN, False)
         auth_token = decode(secret_key, auth_token_encoded)
     self.token = auth_token
     self.client = EvernoteClient(token=auth_token, sandbox=False)
     self.noteStore = self.client.get_note_store()
示例#31
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()
示例#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
示例#33
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)
示例#34
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)
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 __init__(self):
        self._dev_token = 'S=s1:U=8fa4c:E=1505408518e:C=148fc572290:P=1cd:A=en-devtoken:V=2:H=971b5b78f110bdc8cd1579f3e0f5e6cb'
        self._evernote_client = EvernoteClient(token=self._dev_token)
        self._user_store = self._evernote_client.get_user_store()
        self._note_store = self._evernote_client.get_note_store()

        self._default_notebook_guid = None
示例#37
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)
示例#38
0
文件: oauth.py 项目: jodv/not
def setup():
    '''
    oauth flow for new users or updating users
    most of this was shamelessly copied from :
    https://gist.github.com/inkedmn/5041037
    '''
    client = EvernoteClient(
                consumer_key = config.CONSUMER_KEY,
                consumer_secret = config.CONSUMER_SECRET,
                sandbox = False
            )
    request_token = client.get_request_token('http://localhost:10668')
    print "Paste this URL in your browser and login:"******"Token saved."
示例#39
0
class OAuthView(QWebView):
    accessTokenChanged = Signal(str)
    def __init__(self, parent=None):
        QWebView.__init__(self)
        self.urlChanged.connect(self.pageChanged)
        conf = ConfigParser.SafeConfigParser()
        conf.read(CONFIG_FILE)
        consumer_key = conf.get('API', 'consumer_key')
        consumer_secret = conf.get('API', 'consumer_secret')
        self.client = EvernoteClient(
                consumer_key=consumer_key,
                consumer_secret=consumer_secret,
                sandbox=True)
        self.request_token = self.client.get_request_token('https://www.google.co.jp/')
        url = self.client.get_authorize_url(self.request_token)
        self.load(url)

    @Slot(QUrl)
    def pageChanged(self, url):
        queries = url.queryItems()
        if len(queries) == 2 and queries[1][0] == u'oauth_verifier':
            self.hide()
            self.access_token = self.client.get_access_token(
                    self.request_token['oauth_token'],
                    self.request_token['oauth_token_secret'],
                    queries[1][1]
                    )
            self.accessTokenChanged.emit(self.access_token)
示例#40
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
示例#41
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
示例#42
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)
示例#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)
示例#44
0
def setup():
    """
    oauth flow for new users or updating users
    adapted from https://gist.github.com/inkedmn/5041037
    """
    client = EvernoteClient(consumer_key=CONSUMER_KEY,
                            consumer_secret=CONSUMER_SECRET,
                            sandbox=False)

    request_token = client.get_request_token('http://localhost:10668')
    print(
        "Paste this URL in your browser and login:"******"-> {url}  \n\n"
        "Be advised, this will save your oauth token in plaintext to ~/.not_token !"
        "if you aren't cool with that, ctrl-c now and never return!".format(
            url=client.get_authorize_url(request_token)))
    single_server = single_serve()
    single_server.handle_request()
    auth_url = path  # noqa
    vals = parse_query_string(auth_url)
    auth_token = client.get_access_token(request_token['oauth_token'],
                                         request_token['oauth_token_secret'],
                                         vals['oauth_verifier'])
    with open(os.path.join(os.environ['HOME'], '.not_token'), 'w') as f:
        f.write(auth_token)
        print("Token saved.")
示例#45
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)
    def __init__(self, auth_token, notebook=None):

        self.auth_token = auth_token
        self.notebook = notebook
        self.client = EvernoteClient(token=self.auth_token, sandbox=False)
        self.logger = logging.getLogger('whispernote')
        self.logger.info('Initializing EverNote API')

        for i in range(1, 4):
            self.logger.info('Attempting to retrieve Note Store')
            try:
                self.note_store = self.client.get_note_store()
                self.logger.info('Note Store retrieved')
                break
            except Errors.EDAMSystemException as e:
                if e.errorCode == Errors.EDAMErrorCode.RATE_LIMIT_REACHED:
                    self._handle_rate_limit(e)
                else:
                    raise e
                self.logger.info('Retry no. %d' % i)
                continue
            except socket.error:
                self.logger.warn('Socket error: Retrying in 1 minute')
                sleep(60)
                self.logger.info('Retry no. %d' % i)
                continue

        self.notebook_map = self.map_notebook_guids()
示例#47
0
文件: main.py 项目: jacalsas/zou-note
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)
示例#48
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)
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
示例#50
0
def get_oauth_data(user_id: int,
                   key: str,
                   secret: str,
                   oauth_callback: str,
                   access='basic',
                   sandbox=False):

    symbols = string.ascii_letters + string.digits
    session_key = ''.join([random.choice(symbols) for _ in range(32)])
    bytes_key = f'{key}{secret}{user_id}'.encode()
    callback_key = hashlib.sha1(bytes_key).hexdigest()
    qs = urllib.parse.urlencode({
        'access': access,
        'key': callback_key,
        'session_key': session_key,
    })
    callback_url = f'{oauth_callback}?{qs}'
    sdk = EvernoteSdk(consumer_key=key,
                      consumer_secret=secret,
                      sandbox=sandbox)
    try:
        request_token = sdk.get_request_token(callback_url)
        if 'oauth_token' not in request_token or 'oauth_token_secret' not in request_token:
            raise EvernoteApiError("Can't obtain oauth token from Evernote")
        oauth_url = sdk.get_authorize_url(request_token)
    except Exception as e:
        raise EvernoteApiError() from e
    return {
        'callback_key': callback_key,
        'oauth_token': request_token['oauth_token'],
        'oauth_token_secret': request_token['oauth_token_secret'],
        'oauth_url': oauth_url,
    }
示例#51
0
def evernote_callback():
    oauth_token, oauth_verifier, sandbox_lnb = map(
        request.args.get, ['oauth_token', 'oauth_verifier', 'sandbox_lnb'])
    if not oauth_token or not sandbox_lnb:
        return '无效请求'
    if not oauth_verifier:
        return '您没有同意我们访问您的 Evernote 账户,授权失败。'
    else:
        if not session.get('client_id', None):
            return 'cookie 不正确'

        db = get_connection()
        request_tokens = db.get_collection(COL_REQUEST_TOKENS).find_one(
            {'oauth_token': oauth_token})

        client = EvernoteClient(
            consumer_key=current_app.config['EVERNOTE_CONSUMER_KEY'],
            consumer_secret=current_app.config['EVERNOTE_CONSUMER_SECRET'],
            sandbox=current_app.config['EVERNOTE_SANDBOX'])
        access_token = client.get_access_token(
            oauth_token, request_tokens['oauth_token_secret'], oauth_verifier)

        # save access token to database
        db.get_collection(COL_ACCESS_TOKENS).update_one(
            {'client_id': session['client_id']}, {
                '$set': {
                    'auth_time': datetime.datetime.now(),
                    'access_token': access_token,
                    'sandbox_lnb': sandbox_lnb
                }
            },
            upsert=True)

        return 'Evernote 授权成功,您可以关闭此页面并再次点击保存按钮。'
示例#52
0
    def _connect_to_evernote(self, dictUserInfo):
        """
            Establish a connection to evernote and authenticate.

            :param dictUserInfo: Dict of user info like user/password.
               For now, just the dev token
            :returns success: Return wheter connection succeeded
            :rtype bool:
        """
        print("Authenticating to Evernote")
        dev_token = dictUserInfo['dev_token']
        logging.debug("Authenticating using token %s", dev_token)
        user = None
        try:
            self.client = EvernoteClient(token=dev_token, sandbox=False)
            self.user_store = self.client.get_user_store()
            user = self.user_store.getUser()
        except EDAMUserException as err:
            err_code = err.errorCode
            print("Error attempting to authenticate to Evernote: %s - %s" %
                  (EDAMErrorCode._VALUES_TO_NAMES[err_code], err.parameter))
        except EDAMSystemException as err:
            err_code = err.errorCode
            print("Error attempting to authenticate to Evernote: %s - %s" %
                  (EDAMErrorCode._VALUES_TO_NAMES[err_code], err.message))
            sys.exit(-1)

        if user:
            print("Authenticated to evernote as user %s" % user.username)
        return True
示例#53
0
def login(client: EvernoteClient):
    server = OAuthCallbackListener()
    server.start()
    try:
        # 1. Generate a Temporary Token
        request_token = client.get_request_token(f'http://localhost:{server.server.server_port}')

        # 2. Request User Authorization
        authorize_url = client.get_authorize_url(request_token)
        webbrowser.open_new_tab(authorize_url)
        print('listening for authorization callback, press `CTRL+C` wait 3 minutes to cancel...')
        if not server.waiter.wait(60*3):
            # timeout
            return
    finally:
        server.stop()

    oauth_token = getattr(server.server, 'oauth_token', None)
    if oauth_token:
        assert oauth_token == request_token['oauth_token']
    oauth_verifier = getattr(server.server, 'oauth_verifier', None)

    if oauth_token is None or oauth_verifier is None:
        return

    # 3. Retrieve Access Token
    oauth_token = client.get_access_token(
        oauth_token=oauth_token,
        oauth_verifier=oauth_verifier,
        oauth_token_secret=request_token['oauth_token_secret'])
    print(f'your `access_token` is: \n{oauth_token}')
    print(f'you can save it in your config file.')
示例#54
0
def auth():
	"""Takes a callback for Evernote's OAuth process 

	Redirect to main after login is confirmed an token is stored in the session"""
	
	#check to make sure the user approved the appliction (oauth_verifier will not be present if they declined)
	if "oauth_verifier" in request.args:
		#setup client
		client = EvernoteClient(
		consumer_key=CONSUMER_KEY,
		consumer_secret=CONSUMER_SECRET,
		sandbox= sandbox
		)
		
		#get access token
		try:
			auth_token = client.get_access_token(session['oauth_token'], session['oauth_token_secret'], request.args['oauth_verifier'])
		except:
			return render_template("error.html", error_message="OAuth Error: Please approve access to the appliction %s" % CONSUMER_KEY)	
		
		#attach the user's access token to the session
		session["access_token"]=auth_token

		#redirect to main
		return redirect(url_for("main"))
	
	#If the user did not approve access to our application let the user know
	else:
		return render_template("error.html", error_message="OAuth Error: Please approve access to the appliction %s" % CONSUMER_KEY)
示例#55
0
    def on_navigation_requested(self, view, frame, req, data=None):
        logging.debug('Requesting new page')
        self.__spinner.show()
        self.__status_label.set_text(AuthDialog.STATUS_MESSAGE_CONNECTING)
        url = req.get_uri()
        if PROGRAM_NAME.lower() in url:
            query = urlparse.urlparse(url).query
            data = dict(urlparse.parse_qsl(query))

            try:
                self.__authData['oauth_verifier'] = data['oauth_verifier']
            except KeyError:
                logging.error('authorization failed')
                return False

            client = EvernoteClient(
                consumer_key=EverNoteConsumerInfo.CONSUMER_KEY,
                consumer_secret=EverNoteConsumerInfo.CONSUMER_SECRET,
                service_host=MetaData.get_evernote_host(),
                sandbox=False  # Default: True
            )
            self.__auth_token = client.get_access_token(
                self.__authData['oauth_token'],
                self.__authData['oauth_token_secret'],
                self.__authData['oauth_verifier'])
            self.__dialog.response(100)
        return False
示例#56
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.")
 def get_oauth_data(self, user_id, session_key, evernote_config, access='basic'):
     access_config = evernote_config['access'][access]
     api_key = access_config['key']
     api_secret = access_config['secret']
     bytes_key = '{0}{1}{2}'.format(api_key, api_secret, user_id).encode()
     callback_key = hashlib.sha1(bytes_key).hexdigest()
     callback_url = "{url}?access={access}&key={key}&session_key={session_key}".format(
         access=access,
         url=evernote_config['oauth_callback_url'],
         key=callback_key,
         session_key=session_key
     )
     sdk = EvernoteSdk(consumer_key=api_key, consumer_secret=api_secret, sandbox=self.sandbox)
     try:
         request_token = sdk.get_request_token(callback_url)
         if not request_token.get('oauth_token'):
             logging.getLogger().error('[X] EVERNOTE returns: {}'.format(request_token))
             raise EvernoteApiError("Can't obtain oauth token from Evernote")
         oauth_url = sdk.get_authorize_url(request_token)
     except Exception as e:
         raise EvernoteApiError(e)
     return {
         'oauth_url': oauth_url,
         'oauth_token': request_token['oauth_token'],
         'oauth_token_secret': request_token['oauth_token_secret'],
         'callback_key': callback_key,
     }
示例#58
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