Exemplo n.º 1
0
    def authorize(self, storage_name):
        '''Authorize/reauthorize the app if something is wrong
		with the token or storage.
		'''
        # Start oauth flow
        client = EvernoteClient(consumer_key=self.consumer_key,
                                consumer_secret=self.consumer_secret,
                                sandbox=False)

        request_token = client.get_request_token('http://localhost')
        #Prompt the user to open the request URL in their browser
        print "Paste this URL in your browser and login\n"
        print client.get_authorize_url(request_token) + '\n'
        # Have the user paste the resulting URL so we can pull it
        # apart
        print "Paste the URL after login here:"
        authurl = raw_input()
        ## Parse the URL to get the OAuth verifier
        vals = self.parse_query_string(authurl)
        # Use the OAuth verifier and the values from request_token
        # to built the request for our authentication token, then
        # ask for it.
        auth_token = client.get_access_token(
            request_token['oauth_token'], request_token['oauth_token_secret'],
            vals['oauth_verifier'])
        # We will need it for some methods
        self.token = auth_token
        # Write it to the storage file
        try:
            storage = open(storage_name, 'w')
            storage.write(auth_token)
        except ImportError, e:
            # Should never happen
            print 'Error while saving the auth token: ', e
            print 'Your auth token is: ', auth_token
Exemplo n.º 2
0
 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,
     }
Exemplo n.º 3
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()
Exemplo n.º 4
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,
    }
Exemplo n.º 5
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)
Exemplo n.º 6
0
Arquivo: oauth.py Projeto: 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."
Exemplo n.º 7
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.")
Exemplo n.º 8
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()
Exemplo n.º 9
0
def get_oauth_data(user_id, session_key, evernote_config, access="basic",
                   sandbox=False):
    access_config = evernote_config["access"][access]
    api_key = access_config["key"]
    api_secret = access_config["secret"]
    bytes_key = f"{api_key}{api_secret}{user_id}".encode()
    callback_key = hashlib.sha1(bytes_key).hexdigest()
    url = evernote_config["oauth_callback_url"]
    callback_url = f"{url}?access={access}&key={callback_key}&"\
                   f"session_key={session_key}"
    sdk = EvernoteSdk(consumer_key=api_key, consumer_secret=api_secret,
                      sandbox=sandbox)
    oauth_data = {"callback_key": callback_key}
    try:
        request_token = sdk.get_request_token(callback_url)
    except Exception as e:
        raise EvernoteApiError() from e
    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_data["oauth_token"] = request_token["oauth_token"]
    oauth_data["oauth_token_secret"] = request_token["oauth_token_secret"]
    try:
        oauth_data["oauth_url"] = sdk.get_authorize_url(request_token)
    except Exception as e:
        raise EvernoteApiError() from e
    return oauth_data
Exemplo n.º 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.")
Exemplo n.º 11
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()
Exemplo n.º 12
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.')
Exemplo n.º 13
0
def et_get_token(**kwa):
    """
    This will re-authorize pyenote for access to my sandbox account
    """
    if kwa['d']:
        pdb.set_trace()
    ##
    # Create an instance of EvernoteClient using your API
    # key (consumer key and consumer secret)
    ##
    (key, secret) = get_consumer('full')
    client = EvernoteClient(consumer_key=key,
                            consumer_secret=secret,
                            sandbox=True)

    ##
    # Provide the URL where the Evernote Cloud API should
    # redirect the user after the request token has been
    # generated. In this example, localhost is used; note
    # that in this example, we're copying the URLs manually
    # and that, in production, this URL will need to
    # automatically parse the response and send the user
    # to the next step in the flow.
    ##
    request_token = client.get_request_token('http://integrel.org')

    ##
    # Prompt the user to open the request URL in their browser
    ##
    print "Paste this URL in your browser and login"
    print
    print '\t' + client.get_authorize_url(request_token)
    print
    print '-------'

    ##
    # Have the user paste the resulting URL so we can pull it
    # apart
    ##
    print "Paste the URL after login here:"
    authurl = raw_input()

    ##
    # Parse the URL to get the OAuth verifier
    ##
    vals = parse_query_string(authurl)

    ##
    # Use the OAuth verifier and the values from request_token
    # to built the request for our authentication token, then
    # ask for it.
    ##
    auth_token = client.get_access_token(request_token['oauth_token'],
                                         request_token['oauth_token_secret'],
                                         vals['oauth_verifier'])

    print "Your auth token is: {}".format(auth_token)
Exemplo n.º 14
0
    def getAuthToken(self, c_key, c_secret):
        ##
        # Create an instance of EvernoteClient using your API
        # key (consumer key and consumer secret)
        ##
        client = EvernoteClient(
            consumer_key=c_key,
            consumer_secret=c_secret,
            sandbox=False # Default: True
        )

        ##
        # Provide the URL where the Evernote Cloud API should 
        # redirect the user after the request token has been
        # generated. In this example, localhost is used; note
        # that in this example, we're copying the URLs manually
        # and that, in production, this URL will need to 
        # automatically parse the response and send the user
        # to the next step in the flow.
        ##
        request_token = client.get_request_token('http://localhost')

        ##
        # Prompt the user to open the request URL in their browser
        ##
        print "Paste this URL in your browser and login"
        print
        print '\t'+client.get_authorize_url(request_token)
        print
        print '-------'

        ##
        # Have the user paste the resulting URL so we can pull it
        # apart
        ##
        print "Paste the URL after login here:"
        authurl = raw_input()

        ##
        # Parse the URL to get the OAuth verifier
        ##
        vals = parse_query_string(authurl)

        ##
        # Use the OAuth verifier and the values from request_token
        # to built the request for our authentication token, then
        # ask for it.
        ##
        auth_token = client.get_access_token(
                    request_token['oauth_token'],
                    request_token['oauth_token_secret'],
                    vals['oauth_verifier']
                )
        return auth_token        
Exemplo n.º 15
0
def get_request_token(user, callback):
    '''
    Get request token
    '''
    client = EvernoteClient(consumer_key=secrets.EVERNOTE_CONSUMER_KEY,
                            consumer_secret=secrets.EVERNOTE_CONSUMER_SECRET,
                            sandbox=SANDBOX)
    request_token = client.get_request_token(callback)
    logging.debug(request_token)
    # Save secret
    memcache.set(SECRET_MCK % user.key.id(),
                 request_token['oauth_token_secret'])
    authorize_url = client.get_authorize_url(request_token)
    return authorize_url
Exemplo n.º 16
0
def request_oauth_token(sandbox=False):
    client = EvernoteClient(consumer_key=MY_CONSUMER_KEY,
                            consumer_secret=MY_CONSUMER_SECRET,
                            sandbox=sandbox)
    resp_server = CLEVERNOTE_AUTH_WEB_SERVER
    # resp_server = 'http://localhost:8090/oauth'
    req_token = client.get_request_token(resp_server)
    webbrowser.open_new_tab(client.get_authorize_url(req_token))
    auth_string64 = str(raw_input("Auth String: "))
    auth_string = base64.b64decode(auth_string64)
    auth_dict = pickle.loads(auth_string)
    oauth_token = auth_dict['token']
    verifier = auth_dict['verifier']
    access_token = client.get_access_token(oauth_token, req_token['oauth_token_secret'], verifier)
    return access_token
Exemplo n.º 17
0
def request_evernote_token():
    client = EvernoteClient(consumer_key=config.CONSUMER_KEY,
                            consumer_secret=config.CONSUMER_SECRET,
                            sandbox=config.SANDBOX)
    request_token = client.get_request_token(OAUTH_URL)
    print('Paste this URL in your browser and login')
    print(client.get_authorize_url(request_token))
    print('Paste the URL after login here:')
    auth_url = input()
    values = parse_query_string(auth_url)
    auth_token = client.get_access_token(request_token['oauth_token'],
                                         request_token['oauth_token_secret'],
                                         values['oauth_verifier'])
    print('Auth done')
    return auth_token
Exemplo n.º 18
0
def get_request_token(user, callback):
    '''
    Get request token
    '''
    from settings import secrets
    client = EvernoteClient(
        consumer_key=secrets.EVERNOTE_CONSUMER_KEY,
        consumer_secret=secrets.EVERNOTE_CONSUMER_SECRET,
        sandbox=SANDBOX
    )
    request_token = client.get_request_token(callback)
    logging.debug(request_token)
    # Save secret
    memcache.set(SECRET_MCK % user.key.id(), request_token['oauth_token_secret'])
    authorize_url = client.get_authorize_url(request_token)
    return authorize_url
Exemplo n.º 19
0
def _get_evernote_token(app_debug):
    
    client = EvernoteClient(
        consumer_key=CONSUMER_KEY,
        consumer_secret =CONSUMER_SECRET,
        sandbox=SANDBOX_ENABLE
    )    

    request_token = client.get_request_token("http://gevernote/")    

    if request_token['oauth_callback_confirmed']:
        url_callback = client.get_authorize_url(request_token)
        
        if app_debug:
            print ("URL:                 %s" % url_callback)
            print ("oauth_token:         %s" % request_token['oauth_token'])
            print ("oauth_token_secret:  %s" % request_token['oauth_token_secret'])
            
        window = AuthWindow(url_callback)
        window.show_all()
        Gtk.main()

        if app_debug:
            print ("oauth_verifier:      %s" % window.oauth_verifier)
                                
        if not (window.oauth_verifier == "None"):
        	   # get the token for authorization     
            user_token = client.get_access_token(
                request_token['oauth_token'],
                request_token['oauth_token_secret'],
                window.oauth_verifier
            )
        else:
            # handle window closed by cancel and no token            
            user_token = window.oauth_verifier	
        	        
        Gtk.main_quit
        
        if app_debug:
            print ("user_token:          %s" % user_token)
    
    elif app_debug:
        # need app error checking/message here        
        print("bad callback")    
    
    # Token available?
    return user_token
Exemplo n.º 20
0
def request_oauth_token(sandbox=False):
    client = EvernoteClient(consumer_key=MY_CONSUMER_KEY,
                            consumer_secret=MY_CONSUMER_SECRET,
                            sandbox=sandbox)
    resp_server = CLEVERNOTE_AUTH_WEB_SERVER
    # resp_server = 'http://localhost:8090/oauth'
    req_token = client.get_request_token(resp_server)
    webbrowser.open_new_tab(client.get_authorize_url(req_token))
    auth_string64 = str(raw_input("Auth String: "))
    auth_string = base64.b64decode(auth_string64)
    auth_dict = pickle.loads(auth_string)
    oauth_token = auth_dict['token']
    verifier = auth_dict['verifier']
    access_token = client.get_access_token(oauth_token,
                                           req_token['oauth_token_secret'],
                                           verifier)
    return access_token
Exemplo n.º 21
0
    def _getEverNoteOAuthURL(self):
        client = EvernoteClient(
            consumer_key=EverNoteConsumerInfo.CONSUMER_KEY,
            consumer_secret=EverNoteConsumerInfo.CONSUMER_SECRET,
            service_host = MetaData.get_evernote_host(),
            sandbox=False # Default: True ; if using yinxiang, set service_host='www.yinxiang.com' ; in using Evernote International, set  service_host='www.evernote.com'
        )

        callbackUrl = "http://"+PROGRAM_NAME
        request_token = client.get_request_token(callbackUrl)
        # Save the request token information for later
        self.__authData['oauth_token'] = request_token['oauth_token']
        self.__authData['oauth_token_secret'] = request_token['oauth_token_secret']

        # Redirect the user to the Evernote authorization URL
        url = client.get_authorize_url(request_token)
        logging.debug(url)
        return url
Exemplo n.º 22
0
def get_client():
    token = get_token()
    if not token:
        print 'Username:\t',
        username = raw_input()
        print 'Password:\t',
        password = raw_input()
        print '\n'
        client = EvernoteClient(consumer_key='freddieshoreditch-8876',
                                consumer_secret='13801fb7745664f3',
                                sandbox=False)

        req_token = client.get_request_token('http://localhost/')
        os_ = get_os()
        url_ = client.get_authorize_url(req_token)
        if (os_ == 'Mac OS X'):
            command = 'open {}'.format(url_)
        elif (os == 'Windows'):
            print 'Unimplemented for Windows.'
            sys.exit(3)
        elif (os == 'Linux or other'):
            print 'Unimplemented for Linux or other.'
            sys.exit(3)
        else:
            print 'Unimplemented for your operating system.'
            sys.exit(3)
        tries = 0
        exit_code = -1
        while (exit_code != 0 and tries < 5):
            tries += 1
            exit_code = subprocess.call(command, shell=True)
        if exit_code != 0:
            print 'Could not open authorisation url, please open it manually:',
            print url_

        print '\n\nPASTE the URL after logging in:\t'
        result = raw_input()
        vals = parse_query_string(result)
        token = client.get_access_token(req_token['oauth_token'],
                                        req_token['oauth_token_secret'],
                                        vals['oauth_verifier'])
        with open('token.json', 'w') as f:
            f.write(json.dumps(token))
    return EvernoteClient(token=token), token
def get_client():
    token = get_token()
    if not token:
        print "Username:\t",
        username = raw_input()
        print "Password:\t",
        password = raw_input()
        print "\n"
        client = EvernoteClient(
            consumer_key="freddieshoreditch-8876", consumer_secret="13801fb7745664f3", sandbox=False
        )

        req_token = client.get_request_token("http://localhost/")
        os_ = get_os()
        url_ = client.get_authorize_url(req_token)
        if os_ == "Mac OS X":
            command = "open {}".format(url_)
        elif os == "Windows":
            print "Unimplemented for Windows."
            sys.exit(3)
        elif os == "Linux or other":
            print "Unimplemented for Linux or other."
            sys.exit(3)
        else:
            print "Unimplemented for your operating system."
            sys.exit(3)
        tries = 0
        exit_code = -1
        while exit_code != 0 and tries < 5:
            tries += 1
            exit_code = subprocess.call(command, shell=True)
        if exit_code != 0:
            print "Could not open authorisation url, please open it manually:",
            print url_

        print "\n\nPASTE the URL after logging in:\t"
        result = raw_input()
        vals = parse_query_string(result)
        token = client.get_access_token(
            req_token["oauth_token"], req_token["oauth_token_secret"], vals["oauth_verifier"]
        )
        with open("token.json", "w") as f:
            f.write(json.dumps(token))
    return EvernoteClient(token=token), token
Exemplo n.º 24
0
    def get_client_oauth(self):
        client = EvernoteClient(consumer_key = self.customer_key, 
                                consumer_secret = self.customer_secret,
                                sandbox = self.is_sandbox)

        request_token = client.get_request_token(self.url)
        print request_token

        request_url = client.get_authorize_url(request_token)

        print request_url
        auth_url = raw_input()
        vals = parse_query_string(auth_url)

        auth_token = client.get_access_token(
            request_token['oauth_token'],
            request_token['oauth_token_secret'],
            vals['oauth_verifier'])
        return client
Exemplo n.º 25
0
def auth_start():
    """Makes a request to Evernote for the request token then redirects the
    user to Evernote to authorize the app using the request token.
    After authorizing, the user will be redirected back to auth_finish()."""

    # cookieがすでにあったら、承認はせず、HOMEへ飛ばす。
    if 'token' in request.cookies:
    	return redirect(url_for('get'))

    client = EvernoteClient(consumer_key=EN_CONSUMER_KEY, consumer_secret=EN_CONSUMER_SECRET,sandbox=False)

    request_token=client.get_request_token(request.url_root+'authComplete')
    url=client.get_authorize_url(request_token)

    # Save the request token information for later
    session['oauth_token'] = request_token['oauth_token']
    session['oauth_token_secret'] = request_token['oauth_token_secret']

    # Redirect the user to the Evernote authorization URL
    return redirect(url)
Exemplo n.º 26
0
    def _getEverNoteOAuthURL(self):
        client = EvernoteClient(
            consumer_key=EverNoteConsumerInfo.CONSUMER_KEY,
            consumer_secret=EverNoteConsumerInfo.CONSUMER_SECRET,
            service_host=MetaData.get_evernote_host(),
            sandbox=
            False  # Default: True ; if using yinxiang, set service_host='www.yinxiang.com' ; in using Evernote International, set  service_host='www.evernote.com'
        )

        callbackUrl = "http://" + PROGRAM_NAME
        request_token = client.get_request_token(callbackUrl)
        # Save the request token information for later
        self.__authData['oauth_token'] = request_token['oauth_token']
        self.__authData['oauth_token_secret'] = request_token[
            'oauth_token_secret']

        # Redirect the user to the Evernote authorization URL
        url = client.get_authorize_url(request_token)
        logging.debug(url)
        return url
Exemplo n.º 27
0
def get_authorize_url():
    callback = request.args.get('callback')
    if not callback:
        return jsonify(error="missing callback")

    user_id = request.args.get('user_id')
    if not user_id:
        return jsonify(error="missing user_id")

    client = EvernoteClient(consumer_key=key,
                            consumer_secret=secret,
                            sandbox=True)

    token = client.get_request_token(callback)
    cache.set(user_id, token)
    app.logger.debug('authorize - user_id: {0} token: {1}'.format(
        user_id, token))
    app.logger.debug('authorize - cache: {0}'.format(cache.data))
    url = client.get_authorize_url(token)
    return jsonify(authorize_url=url)
Exemplo n.º 28
0
def auth_evernote():
    #import evernote.edam.userstore.constants as UserStoreConstants
    #import evernote.edam.type.ttypes as Types
    from evernote.api.client import EvernoteClient
    client = EvernoteClient(
        consumer_key = 'baschtik-3522',
        consumer_secret = '9851242b79ad58cd',
        sandbox = True, 
    )
    request_token = client.get_request_token('http://always-backup.com/external_auth/evernote/')

    try:
        text = '''\
        1) Go to: \n%s 
        1a) Make sure that you have the complete URL (Scroll to te right).
        2) Click "Allow" (you might have to log in first)
        3) You will get a Code. Copy it to the Clip-board 
        ''' % client.get_authorize_url(request_token)
    except:
        d.msgbox("Sorry, Evernote reportet an error. "
                 "I quit the setup and show you the Response from Evernote.")
        print request_token
        raise

    d.scrollbox( text, height=15, width=0)
    code, verifier = d.inputbox( "Now enter the code here:", width=150 )
    if code != 0:
        sync_pairs()

    try:
        auth_token = client.get_access_token(
                    request_token['oauth_token'],
                    request_token['oauth_token_secret'],
                    verifier
                )
    except:
        d.msgbox("There was an error gernerating the access token\n"
                 "The profile will be saved, continue and edit it later."
                 "Otherwise sync will not work""", height=10, width=50)
        auth_token = False
    return auth_token
Exemplo n.º 29
0
def evernote_authorize_content():
    client = EvernoteClient(
        consumer_key=current_app.config['EVERNOTE_CONSUMER_KEY'],
        consumer_secret=current_app.config['EVERNOTE_CONSUMER_SECRET'],
        sandbox=True)
    request_token = client.get_request_token(
        url_for('main.evernote_callback', _external=True))
    auth_url = client.get_authorize_url(request_token)

    db = get_connection()
    request_token.update({'create_time': datetime.datetime.now()})
    db.get_collection(COL_REQUEST_TOKENS).insert(request_token)

    content = f"""
    <script>window.parent.postMessage(
    {{status: "302", 
     content: "\\<script\\>window.open(\\"{auth_url}\\", \\"newwindow\\", \\"height=800, width=800\\"); \\</script\\>" 
    }}, "*");
    </script>
    """
    return content
Exemplo n.º 30
0
def oauth():
    client = EvernoteClient(consumer_key=conf.key, consumer_secret=conf.sec, sandbox=conf.env)
    token = client.get_request_token(conf.url)
    url = client.get_authorize_url(token)
    c = requests.session()
    c.get(url)

    print "==> Please Sign in. Never store your PASSWORD!"
    cnt = 3
    while cnt:
        cnt -= 1
        payload = {"login": "******", "targetUrl": url}
        if hasattr(conf, "username"):
            payload["username"] = conf.username
        else:
            payload["username"] = raw_input("Username: "******"password"):
            payload["password"] = conf.password
        else:
            payload["password"] = getpass().strip()
        resp = c.post(url, data=payload)
        if resp.history:
            break
        else:
            if not cnt:
                print "Incorrect Username or Passowrd!"
                sys.exit(1)
            else:
                print "Sorry, incorrect Username or Password."
    print "<== Signed in."

    payload = {"authorize": "Authorize", "embed": "false"}
    payload["oauth_token"] = token["oauth_token"]
    payload["oauth_callback"] = conf.url
    resp = c.post(url, data=payload, allow_redirects=False)
    return client.get_access_token(
        token["oauth_token"],
        token["oauth_token_secret"],
        resp.headers["location"].split("?")[1].split("&")[1].split("=")[1],
    )
Exemplo n.º 31
0
def get_auth_token():
    """
    Run through the Evernote OAuth procedure

    :returns: User token string
    """
    # Create an HTTP server on a spare port
    httpd = MininoteHTTPServer(('127.0.0.1', 0), MininoteHTTPRequestHandler)
    callbackurl = urljoin("http://{}:{}".format(*httpd.server_address),
                          RETURN_PATH)

    client = EvernoteClient(consumer_key=EVERNOTE_CONSUMER_KEY,
                            consumer_secret=EVERNOTE_CONSUMER_SECRET,
                            sandbox=DEVELOPMENT_MODE)

    request_token = client.get_request_token(callbackurl)

    authorize_url = client.get_authorize_url(request_token)
    print 'Please login at the following url:\n{}'.format(authorize_url)

    # Open browser to auth page
    SilentWebbrowser(authorize_url).start()

    # Wait until browser is redirected
    httpd.server_activate()
    while httpd.auth_path is None:
        httpd.handle_request()
    httpd.server_close()

    def parse_query_string(authorize_url):
        query_params = urlparse(authorize_url).query
        return dict(kv.split('=') for kv in query_params.split('&'))

    vals = parse_query_string(httpd.auth_path)
    if 'oauth_verifier' not in vals:
        raise OAuthError('There was an error logging in.  Please try again.')
    return client.get_access_token(request_token['oauth_token'],
                                   request_token['oauth_token_secret'],
                                   vals['oauth_verifier'])
Exemplo n.º 32
0
def evernote_auth(client_id, client_secret, storage, sandbox=False):
  credentials = storage.get()
  if credentials is None or credentials.invalid:
    host = 'localhost'
    port = 9343
    client = EvernoteClient(
      consumer_key=client_id,
      consumer_secret=client_secret,
      sandbox=sandbox
    )
    request_token = client.get_request_token('http://{}:{}/'.format(host, port))
    authorize_url = client.get_authorize_url(request_token)
    print 'Go to the following link in your browser:'
    print
    print '    ' + authorize_url
    print
    http = tools.ClientRedirectServer((host, port), tools.ClientRedirectHandler)
    http.handle_request()
    if 'oauth_verifier' not in http.query_params:
      print "Bad Evernote Oauth, no verifier:{}".format(http.query_params)
      return

    access_token = client.get_access_token(
      request_token['oauth_token'],
      request_token['oauth_token_secret'],
      http.query_params['oauth_verifier']
    )
    token_uri = 'https://{}evernote.com/oauth'.format('sandbox.' if sandbox else '')
    credentials = OAuth2Credentials(
      access_token,
      client_id,
      client_secret,
      refresh_token=request_token['oauth_token'], # not really
      token_expiry=datetime.now() - timedelta(days=-365),
      token_uri=token_uri,
      user_agent='evernote.basic'
    )
    storage.put(credentials)
  return credentials
Exemplo n.º 33
0
def main_oauth(consumer_key, consumer_secret, sandbox):

    if not consumer_key:
        raise ValueError("No consumer_key set")

    if not consumer_secret:
        raise ValueError("No consumer_secret set")


    request_token = {}
    def callback(res):
        access_token = client.get_access_token(
            request_token['oauth_token'],
            request_token['oauth_token_secret'],
            res.query.get('oauth_verifier', '')
        )

        echo.hr()
        echo.out("Your access token is:")
        echo.out()
        echo.indent(access_token)
        echo.out()
        echo.hr()
        return access_token

    s = AuthServer(callback)

    # https://github.com/evernote/evernote-sdk-python/#oauth
    client = EvernoteClient(
        consumer_key=consumer_key,
        consumer_secret=consumer_secret,
        sandbox=sandbox
    )

    request_token = client.get_request_token(s.netloc)
    auth_url = client.get_authorize_url(request_token)
    subprocess.call(["open", auth_url])
    s.handle_request()
Exemplo n.º 34
0
def get_auth_token():
    """
    Run through the Evernote OAuth procedure

    :returns: User token string
    """
    # Create an HTTP server on a spare port
    httpd = MininoteHTTPServer(('127.0.0.1', 0), MininoteHTTPRequestHandler)
    callbackurl = urljoin("http://{}:{}".format(*httpd.server_address), RETURN_PATH)

    client = EvernoteClient(consumer_key=EVERNOTE_CONSUMER_KEY,
                            consumer_secret=EVERNOTE_CONSUMER_SECRET,
                            sandbox=DEVELOPMENT_MODE)

    request_token = client.get_request_token(callbackurl)

    authorize_url = client.get_authorize_url(request_token)
    print 'Please login at the following url:\n{}'.format(authorize_url)

    # Open browser to auth page
    SilentWebbrowser(authorize_url).start()

    # Wait until browser is redirected
    httpd.server_activate()
    while httpd.auth_path is None:
        httpd.handle_request()
    httpd.server_close()

    def parse_query_string(authorize_url):
        query_params = urlparse(authorize_url).query
        return dict(kv.split('=') for kv in query_params.split('&'))

    vals = parse_query_string(httpd.auth_path)
    if 'oauth_verifier' not in vals:
        raise OAuthError('There was an error logging in.  Please try again.')
    return client.get_access_token(request_token['oauth_token'],
                                   request_token['oauth_token_secret'],
                                   vals['oauth_verifier'])
Exemplo n.º 35
0
def get_oauth_data(user_id,
                   session_key,
                   config,
                   access='basic',
                   sandbox=False):
    access_config = config['evernote']['access'][access]
    api_key = access_config['key']
    api_secret = access_config['secret']
    bytes_key = f'{api_key}{api_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 = 'https://{host}/evernote/oauth?{query_string}'.format(
        host=config['host'], query_string=qs)
    sdk = EvernoteSdk(consumer_key=api_key,
                      consumer_secret=api_secret,
                      sandbox=sandbox)
    try:
        request_token = sdk.get_request_token(callback_url)
    except Exception as e:
        raise EvernoteApiError() from e
    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_data = {
        'callback_key': callback_key,
        'oauth_token': request_token['oauth_token'],
        'oauth_token_secret': request_token['oauth_token_secret'],
    }
    try:
        oauth_data['oauth_url'] = sdk.get_authorize_url(request_token)
    except Exception as e:
        raise EvernoteApiError() from e
    return oauth_data
# Provide the URL where the Evernote Cloud API should 
# redirect the user after the request token has been
# generated. In this example, localhost is used; note
# that in this example, we're copying the URLs manually
# and that, in production, this URL will need to 
# automatically parse the response and send the user
# to the next step in the flow.
##
request_token = client.get_request_token('http://localhost')

##
# Prompt the user to open the request URL in their browser
##
print "Paste this URL in your browser and login"
print
print '\t'+client.get_authorize_url(request_token)
print
print '-------'

##
# Have the user paste the resulting URL so we can pull it
# apart
##
print "Paste the URL after login here:"
authurl = raw_input()

##
# Parse the URL to get the OAuth verifier
##
vals = parse_query_string(authurl)
Exemplo n.º 37
0
def main():
	"""Takes the access token in the session and presents the user with notes that are tagged "template" or "Template" 

	If there are no notes tagged "template" or "Template" 4 example notes are created

	If the user is not logged in: a splash page with the option to authorize the appliction is presented
	"""

	#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 a list of tags labeled "template" or "Template"
		template_tags = get_template_tags(session["access_token"])

		#if a "template" or "Template" tag does already exist do a search for notes tagged with "templates"
		if template_tags:
			personal_search_results = []
			for tag in template_tags:
				notebook_filter=NoteStoreTypes.NoteFilter()
				notebook_filter.tagGuids= [tag]
				result_spec = NoteStoreTypes.NotesMetadataResultSpec(includeTitle=True)
				personal_search_result = note_store.findNotesMetadata(notebook_filter,0 , 40000, result_spec)

				personal_search_results+=personal_search_result.notes


			metadata_notes_list = personal_search_results

			#if the search returns less than 4 notes create 4 note templates for them:
			if len(metadata_notes_list) < 4:
				standard_template_notes = create_standard_templates(session["access_token"])
				metadata_notes_list += standard_template_notes

		#if there are no tags labeled "template" or "Template" create it and create standard template notes
		if not template_tags:
			template_tags = Types.Tag()
			template_tags.name = "template"
			template_tags = note_store.createTag(template_tags)

			#create 4 note templates for the user:
			metadata_notes_list = create_standard_templates(session["access_token"])

		#return the list of templates and their views and display them (with their links) to the user
		for note in metadata_notes_list:
			#get the user
			user = user_store.getUser()
			#Get the HTML contents of each note: 
			template_link = "evernote:///view/%s/%s/%s/%s/" % (user.id, user.shardId, note.guid, note.guid)
			#edit this template: Link to note "evernote:///view/[userId]/[shardId]/[noteGuid]/[noteGuid]/"

			#create URL that allows the user to create a new note based on the template
			in_app_link = "note/template/%s" % note.guid

			#get the thumnail for each note
			r=requests.post(EN_URL+"/shard/"+user.shardId+"/thm/note/"+note.guid+".jpg", data={"auth":session["access_token"]})
			image_data = "data:"+r.headers['Content-Type'] + ";" +"base64," + str(base64.b64encode(r.content).decode("utf-8"))

			#wrap all this data in a dictionary and put it in a list
			try:
				content_list.append({"image":image_data, "in_app_link":in_app_link, "template_link":template_link, "title":note.title})
			except NameError:
				content_list = [{"image":image_data, "in_app_link":in_app_link, "template_link":template_link, "title":note.title}]

		#render the template with the data we just retrivied
		return render_template('index.html', templates=content_list)


	#if their Evernote access_token session varible is not set, redirect them to Evernote to authoirze the applicaiton
	else:
		#Setup Evernote client
		client = EvernoteClient(
			consumer_key=CONSUMER_KEY,
			consumer_secret=CONSUMER_SECRET,
			sandbox= sandbox
			)
		try:
			request_token = client.get_request_token("http://localhost:"+str(port)+"/auth") #set callback URL
			session['oauth_token'] = request_token['oauth_token'] #Set OAuth token in the broswer session
			session['oauth_token_secret'] = request_token['oauth_token_secret'] #Set OAuth secret in the broswer session
			authorize_url = client.get_authorize_url(request_token) #get redirect URL
		except KeyError:
			#If there is an error alert the user and prompt them to reauthenticate
			return render_template("error.html", error_message="invalid API key and/or secret.  Please check the values of cosumer_key and sonsumer_secret in the server.py file are valid and <a href=\'/clear'>click here</a> to reset.")
		else:
			#Present the user with a page descibing what the appliction does, and prompt them to authorize the app to access their Evernote account
			return render_template('splash.html', auth_url = authorize_url) #suggest notebook name of giphy to user
Exemplo n.º 38
0
    def authenticate(
            self):
        """
        *authenticate*

        **Key Arguments:**
            # -

        **Return:**
            - None

        .. todo::

            - @review: when complete, clean authenticate method
            - @review: when complete add logging
        """
        self.log.info('starting the ``authenticate`` method')

        # Python OAuth example

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

        ##
        # Helper function to turn query string parameters into a
        # Python dictionary
        ##
        def parse_query_string(authorize_url):
            uargs = authorize_url.split('?')
            vals = {}
            if len(uargs) == 1:
                raise Exception('Invalid Authorization URL')
            for pair in uargs[1].split('&'):
                key, value = pair.split('=', 1)
                vals[key] = value
            return vals

        ##
        # Create an instance of EvernoteClient using your API
        # key (consumer key and consumer secret)
        ##
        client = EvernoteClient(
            consumer_key=self.settings["evernote"]["consumer_key"],
            consumer_secret=self.settings["evernote"]["consumer_secret"],
            sandbox=False
        )

        ##
        # Provide the URL where the Evernote Cloud API should
        # redirect the user after the request token has been
        # generated. In this example, localhost is used; note
        # that in this example, we're copying the URLs manually
        # and that, in production, this URL will need to
        # automatically parse the response and send the user
        # to the next step in the flow.
        ##
        request_token = client.get_request_token('http://localhost')
        print request_token

        ##
        # Prompt the user to open the request URL in their browser
        ##
        print "Paste this URL in your browser and login"
        print
        print '\t' + client.get_authorize_url(request_token)
        print
        print '-------'

        ##
        # Have the user paste the resulting URL so we can pull it
        # apart
        ##
        print "Paste the URL after login here:"
        authurl = raw_input()

        ##
        # Parse the URL to get the OAuth verifier
        ##
        vals = parse_query_string(authurl)

        ##
        # Use the OAuth verifier and the values from request_token
        # to built the request for our authentication token, then
        # ask for it.
        ##

        print request_token['oauth_token']
        print request_token['oauth_token_secret']
        print vals['oauth_verifier']

        auth_token = client.get_access_token(
            request_token['oauth_token'],
            request_token['oauth_token_secret'],
            vals['oauth_verifier']
        )

        print auth_token

        ##
        # Create a new EvernoteClient instance with our auth
        # token.
        ##
        client = EvernoteClient(
            token=auth_token,
            sandbox=False
        )

        ##
        # Test the auth token...
        ##
        userStore = client.get_user_store()
        user = userStore.getUser()

        ##
        # If our username prints, it worked.
        ##
        print "Authorised under " + user.username
        print "Please add these to the evernote section in your settings file ..."
        print "auth_token: " + auth_token

        self.log.info('completed the ``authenticate`` method')
        return None
Exemplo n.º 39
0
def main():
	""" GET: gets random gif from giphy and displays it along with the option to see another gif and to 
	save the gif to their evernote account"""
	if request.method == "GET": 
		if "access_token" in session.keys():
			#get random gif from giphy api
			response=requests.get("http://api.giphy.com/v1/gifs/random?api_key="+giphy_api_key).json()
			if not response:
				return render_template("error.html", error_message="error with connection to giphy")

			#get random image url and id from giphy api response
			giphy_url=response['data']['image_url']
			giphy_id=response['data']['id']

			#get tags and pass them to the page because the giphy api only show tags for random images
			giphy_tags=''
			try:
				response['data']['tags']
				for tag in response['data']['tags']:
					giphy_tags+=tag+', '
				giphy_tags=giphy_tags[:-2]
			except KeyError:
				pass

			return render_template("index.html", giphy_url=giphy_url, giphy_id=giphy_id, giphy_tags=giphy_tags) 
			session["access_token"]
		
		#if their Evernote access_token session varible is not set redirect them to Evernote to authoirze the applicaiton
		else:
			client = EvernoteClient(
				consumer_key=CONSUMER_KEY,
				consumer_secret=CONSUMER_SECRET,
				sandbox= True
				)
			try:
				request_token = client.get_request_token("http://localhost:8080/auth")
				session['oauth_token'] = request_token['oauth_token'] 
				session['oauth_token_secret'] = request_token['oauth_token_secret']
				authorize_url = client.get_authorize_url(request_token)
			except KeyError:
				return render_template("error.html", error_message="invalid API key and/or secret.  Please check the values of cosumer_key and sonsumer_secret in the server.py file are valid and <a href=\'/clear'>click here</a> to reset.")
			else:
				print authorize_url
				return redirect(authorize_url+"&suggestedNotebookName=Giphy") #suggest notebook name of giphy to user

		#if we do have the access token proceed to show them a gif they can save to Evernote
		
		
	"""POST: shows confomation of evernote gif save and presents option 
	to return to main page or see the note in evernote"""
	if request.method == 'POST':
		if request.form['giphy_id']:
			#get giphy_id from post request that was to be saved
			giphy_id=request.form['giphy_id']
			giphy_tags=request.form['giphy_tags']
			response=requests.get("http://api.giphy.com/v1/gifs/"+giphy_id+"?api_key="+giphy_api_key).json()
			giphy_url=response['data']['images']['original']['url']

			#generate Evernote client
			client = EvernoteClient(token=session["access_token"], sandbox=True)
			user_store = client.get_user_store()
			note_store = client.get_note_store()
			notebooks = note_store.listNotebooks()

			notebooks_dict=dict()
			for notebook in notebooks:
				notebooks_dict[notebook.name]=notebook.guid

			#if app notebook key use that notebok to save notes into
			if len(notebooks)==1 and notebooks[0].defaultNotebook==False: #assume app notebok key
				giphyNotebookGuid=notebooks[0].guid
			elif "Giphy" in notebooks_dict.keys(): #if notebook named Giphy exists use that notebook
				giphyNotebookGuid=notebooks_dict['Giphy']
			else: #make new notebook
				try:
					notebook=Types.Notebook()
					notebook.name="Giphy"
					notebook=note_store.createNotebook(notebook)
					giphyNotebookGuid=notebook.guid
				except EDAMUserException: #single app notebok key
					giphyNotebookGuid=notebooks[0].guid

			#create note title with user name + giphy id for unique identifier
			note_title=response['data']['username']+"-"+response['data']['id']

			#check to see if note exists already
			notebook_filter=NoteStoreTypes.NoteFilter()
			notebook_filter.guid=giphyNotebookGuid
			result_spec = NotesMetadataResultSpec(includeTitle=True)
			try:
				noteList    = note_store.findNotesMetadata(session["access_token"], notebook_filter,0 , 40000, result_spec)
				for note in noteList.notes:
					if note.title==note_title:
						shardId=user_store.getUser(session["access_token"]).shardId
						shareKey=note_store.shareNote(session["access_token"], note.guid)
						evernote_url="%s/shard/%s/sh/%s/%s" % (EN_URL,shardId,note.guid,shareKey)
						return render_template("already_there.html", giphy_url=giphy_url, evernote_url=evernote_url)
			except EDAMUserException: #if the key doesn't have read permissions just move on
				pass
			
			
			#get image
			image= requests.get(giphy_url, stream=True).content
			md5 = hashlib.md5()
			md5.update(image)
			gif_hash = md5.digest()

			data = Types.Data()
			data.size = len(image)
			data.bodyHash = gif_hash
			data.body = image

			resource = Types.Resource()
			resource.mime = 'image/gif'
			resource.data = data

			hash_hex = binascii.hexlify(gif_hash)

			
			note = Types.Note()
			note.notebookGuid=giphyNotebookGuid #create note for our Giphy notebook
			
			note.title=note_title #name based on Giphy username and id
			note.content = '<?xml version="1.0" encoding="UTF-8"?>'
			note.content += '<!DOCTYPE en-note SYSTEM ' \
			    '"http://xml.evernote.com/pub/enml2.dtd">'
			note.content += '<en-note><br/>'
			note.content += '<en-media type="image/gif" hash="' + hash_hex + '"/>'
			note.content += '</en-note>'

			#add tags to the note
			enTagList=note_store.listTags()
			enTagListNames= [tag.name for tag in enTagList]
			giphyTagList=giphy_tags.split(", ")

			if not note.tagGuids:
				note.tagGuids=[]

			for giphyTag in giphyTagList:
				if giphyTag in enTagListNames:
					for tag in enTagList:
						if tag.name == giphyTag:
							note.tagGuids.append(tag.guid)
				elif giphyTag=='':
					continue
				else:
					tag=Types.Tag()
					tag.name=giphyTag
					tag=note_store.createTag(tag)

					note.tagGuids.append(tag.guid)


			note.resources = [resource] # Now, add the new Resource to the note's list of resources

			note=note_store.createNote(note) # create the note
			
			user=user_store.getUser(session["access_token"])
			shardId=user.shardId
			
			try:
				shareKey=note_store.shareNote(session["access_token"], note.guid)
				evernote_url="%s/shard/%s/sh/%s/%s" % (EN_URL,shardId,note.guid,shareKey)
			except EDAMUserException:
				evernote_url=EN_URL + "/Home.action"
			return render_template("saved.html", giphy_url=giphy_url, evernote_url=evernote_url)
		else:
			return render_template("error.html", error_message="Error finding the GIF")

	else:
		return render_template("error.html", error_message="Unsuported HTTP method.  Please use GET or POST.")
host = urlparse(HOST_URL).netloc.split(':')[0]
port = int(urlparse(HOST_URL).netloc.split(':')[1])
callback_url = HOST_URL + '/callback'
makecontents_url = HOST_URL + '/makecontents'

# Set my API key
temp_client = EvernoteClient(consumer_key=app_data['consumer_key'],
                             consumer_secret=app_data['consumer_secret'],
                             sandbox=app_data['sandbox'])
temp_token = temp_client.get_request_token(callback_url)
if 'oauth_callback_confirmed' in temp_token:
    if not temp_token['oauth_callback_confirmed']:
        raise Exception('Error: oauth_callback_confirmed = False')
else:
    raise Exception('Error: No oauth_callback_confirmed')
auth_url = temp_client.get_authorize_url(temp_token)
oauth_info = {
    'oauth_token': temp_token['oauth_token'],
    'oauth_token_secret': temp_token['oauth_token_secret'],
    'oauth_verifier': '',
}


def connect_div(url):
    '''Return auth div'''
    return '<a href={}>Connect</a>'.format(url)


def makecontents_div(url):
    '''Return makecontents div'''
    return '<a href={}>\
Exemplo n.º 41
0
        vals[key] = value
    return vals


if DEV_MODE:
    sdb = True
else:
    sdb = False

# Create the Evernote Client
client = EvernoteClient(consumer_key=CONSUMER_KEY,
                        consumer_secret=CONSUMER_SECRET,
                        sandbox=sdb)

request_token = client.get_request_token(NOTE_URL)
authorize_url = client.get_authorize_url(request_token)

token_url = get_token(authorize_url)
vals = parse_query_string(token_url)

access_token = client.get_access_token(request_token['oauth_token'],
                                       request_token['oauth_token_secret'],
                                       vals['oauth_verifier'])

client = EvernoteClient(token=access_token)
client = EvernoteClient(token=access_token)
userStore = client.get_user_store()
user = userStore.getUser()
limit = user.accounting.uploadLimit
print('The username is: %s' % (user.username))
print('The current limit is %s MB' % (limit / 1024 / 1024))
Exemplo n.º 42
0
def main():
	""" GET: gets random gif from giphy and displays it along with the option to see another gif and to 
	save the gif to their evernote account"""
	if request.method == "GET": 
		#if we do have the access token proceed to show them a gif they can save to Evernote
		if "access_token" in session.keys():
			#get random gif from giphy api
			response=requests.get("http://api.giphy.com/v1/gifs/random?api_key="+giphy_api_key).json()
			if not response:
				return render_template("error.html", error_message="error with connection to giphy")

			#get random image url and id from giphy api response
			giphy_url=response['data']['image_url']
			giphy_id=response['data']['id']

			#get tags and pass them to the page because the giphy api only shows tags for random images
			giphy_tags=''
			try:
				response['data']['tags']
				for tag in response['data']['tags']:
					giphy_tags+=tag+', '
				giphy_tags=giphy_tags[:-2]
			except KeyError:
				pass

			#present the page with the GIF on it to the user with the GIF metadata (tags, id, url)
			return render_template("index.html", giphy_url=giphy_url, giphy_id=giphy_id, giphy_tags=giphy_tags) 
			session["access_token"]
		
		#if their Evernote access_token session varible is not set redirect them to Evernote to authoirze the applicaiton
		else:
			client = EvernoteClient(
				consumer_key=CONSUMER_KEY,
				consumer_secret=CONSUMER_SECRET,
				sandbox= sandbox
				)
			try:
				request_token = client.get_request_token("http://localhost:"+str(port)+"/auth")
				session['oauth_token'] = request_token['oauth_token'] 
				session['oauth_token_secret'] = request_token['oauth_token_secret']
				authorize_url = client.get_authorize_url(request_token)
			except KeyError:
				return render_template("error.html", error_message="Invalid API key and/or secret.  Please check the values of consumer_key and consumer_secret in the server.py file are valid and refresh to reset.")
			else:
				return redirect(authorize_url+"&suggestedNotebookName=Giphy") #suggest notebook name of giphy to use
		
	"""POST: shows confomation of evernote gif save and presents option 
	to return to main page or see the note in evernote"""
	if request.method == 'POST':
		if request.form['giphy_id']:
			#get giphy_id from post request that was to be saved
			giphy_id=request.form['giphy_id']
			giphy_tags=request.form['giphy_tags']
			response=requests.get("http://api.giphy.com/v1/gifs/"+giphy_id+"?api_key="+giphy_api_key).json()
			giphy_url=response['data']['images']['original']['url']

			#generate Evernote client
			client = EvernoteClient(token=session["access_token"], sandbox=sandbox)
			user_store = client.get_user_store()
			note_store = client.get_note_store()
			notebooks = note_store.listNotebooks()

			#makes a dictionary with the names for keys and the guids as values
			notebooks_dict=dict()
			for notebook in notebooks:
				notebooks_dict[notebook.name]=notebook.guid

			#if app notebook key use that notebok to save notes into
			if len(notebooks)==1 and notebooks[0].defaultNotebook==False: #assume app notebok key
				giphyNotebookGuid=notebooks[0].guid
			elif "Giphy" in notebooks_dict.keys(): #if notebook named Giphy exists use that notebook
				giphyNotebookGuid=notebooks_dict['Giphy']
			else: #make new notebook
				try:
					notebook=Types.Notebook()
					notebook.name="Giphy"
					notebook=note_store.createNotebook(notebook)
					giphyNotebookGuid=notebook.guid
				except Errors.EDAMUserException: #single app notebok key
					giphyNotebookGuid=notebooks[0].guid

			#create note title with user name + giphy id for unique identifier
			note_title=response['data']['username']+"-"+response['data']['id']

			#check to see if note exists already
			notebook_filter=NoteStoreTypes.NoteFilter()
			notebook_filter.guid=giphyNotebookGuid
			result_spec = NoteStoreTypes.NotesMetadataResultSpec(includeTitle=True)
			try:
				noteList    = note_store.findNotesMetadata(session["access_token"], notebook_filter,0 , 40000, result_spec)
				for note in noteList.notes:
					if note.title==note_title:
						shardId=user_store.getUser(session["access_token"]).shardId
						shareKey=note_store.shareNote(session["access_token"], note.guid)
						evernote_url="%s/shard/%s/sh/%s/%s" % (EN_URL,shardId,note.guid,shareKey)
						return render_template("already_there.html", giphy_url=giphy_url, evernote_url=evernote_url)
			except Errors.EDAMUserException: #if the key doesn't have read permissions just move on
				pass
			
			
			#get image
			image= requests.get(giphy_url, stream=True).content
			md5 = hashlib.md5()
			md5.update(image)
			gif_hash = md5.digest()

			#Move the data into the Evernote Data datatype
			data = Types.Data()
			data.size = len(image)
			data.bodyHash = gif_hash
			data.body = image

			#Put the data in the Evernote Resource datatype and add the metadata
			resource = Types.Resource()
			resource.mime = 'image/gif'
			resource.data = data
			hash_hex = binascii.hexlify(gif_hash)
			
			#Create a new note
			note = Types.Note()
			note.notebookGuid=giphyNotebookGuid #create note for our Giphy notebook
			
			#Set Note title and contents
			note.title=note_title #name based on Giphy username and id
			note.content = '<?xml version="1.0" encoding="UTF-8"?>'
			note.content += '<!DOCTYPE en-note SYSTEM ' \
			    '"http://xml.evernote.com/pub/enml2.dtd">'
			note.content += '<en-note><br/>'
			note.content += '<en-media type="image/gif" hash="' + hash_hex + '"/>'
			note.content += '</en-note>'

			#add tags to the note
			enTagList=note_store.listTags()
			enTagListNames= [tag.name for tag in enTagList]
			giphyTagList=giphy_tags.split(", ")

			#If there are no tags make it an empty list
			if not note.tagGuids:
				note.tagGuids=[]

			#
			for giphyTag in giphyTagList:
				if giphyTag in enTagListNames:
					for tag in enTagList:
						if tag.name == giphyTag:
							note.tagGuids.append(tag.guid)
				elif giphyTag=='':
					continue
				else:
					tag=Types.Tag()
					tag.name=giphyTag
					tag=note_store.createTag(tag)

					note.tagGuids.append(tag.guid)


			note.resources = [resource] # Now, add the new Resource to the note's list of resources
			note=note_store.createNote(note) # create the note
			
			user=user_store.getUser(session["access_token"])
			shardId=user.shardId
			
			#Share the note to present it to the user in-browser
			try:
				shareKey=note_store.shareNote(session["access_token"], note.guid)
				evernote_url="%s/shard/%s/sh/%s/%s" % (EN_URL,shardId,note.guid,shareKey)
			except Errors.EDAMUserException:
				evernote_url=EN_URL + "/Home.action" #If the note cannot be shared redirect them to the Evernote web app
			return render_template("saved.html", giphy_url=giphy_url, evernote_url=evernote_url)
		else:
			#If the GIF displayed is no loger avalible present the user with an error
			return render_template("error.html", error_message="Error finding the GIF")

	else:
		return render_template("error.html", error_message="Unsuported HTTP method.  Please use GET or POST.")
Exemplo n.º 43
0
# Provide the URL where the Evernote Cloud API should
# redirect the user after the request token has been
# generated. In this example, localhost is used; note
# that in this example, we're copying the URLs manually
# and that, in production, this URL will need to
# automatically parse the response and send the user
# to the next step in the flow.
##
request_token = client.get_request_token('http://localhost')

##
# Prompt the user to open the request URL in their browser
##
print "Paste this URL in your browser and login"
print
print '\t' + client.get_authorize_url(request_token)
print
print '-------'

##
# Have the user paste the resulting URL so we can pull it
# apart
##
print "Paste the URL after login here:"
authurl = raw_input()

##
# Parse the URL to get the OAuth verifier
##
vals = parse_query_string(authurl)
    return vals

if DEV_MODE:
    sdb = True
else:
    sdb = False
    
# Create the Evernote Client
client = EvernoteClient(
    consumer_key = CONSUMER_KEY,
    consumer_secret = CONSUMER_SECRET,
    sandbox = sdb)


request_token = client.get_request_token(NOTE_URL)
authorize_url = client.get_authorize_url(request_token)

token_url = get_token(authorize_url)
vals = parse_query_string(token_url)

access_token = client.get_access_token(
    request_token['oauth_token'],
    request_token['oauth_token_secret'],
    vals['oauth_verifier'])

client = EvernoteClient(token=access_token)
client = EvernoteClient(token=access_token)
userStore = client.get_user_store()
user = userStore.getUser()
limit = user.accounting.uploadLimit
print('The username is: %s'%(user.username))