Exemplo n.º 1
0
def index():
    # If we have an access_token, we may interact with the Nylas Server
    if 'access_token' in session:
        client = APIClient(APP_ID, APP_SECRET, session['access_token'])
        message = None
        while not message:
            try:
                # Get the latest message from namespace zero.
                message = client.messages.first()
                if not message:  # A new account takes a little time to sync
                    print "No messages yet. Checking again in 2 seconds."
                    time.sleep(2)
            except Exception as e:
                print(e.message)
                return Response("<html>An error occurred.</html>")
        # Format the output
        text = "<html><h1>Here's a message from your inbox:</h1><b>From:</b> "
        for sender in message["from"]:
            text += "{} &lt;{}&gt;".format(sender['name'], sender['email'])
        text += "<br /><b>Subject:</b> " + message.subject
        text += "<br /><b>Body:</b> " + message.body
        text += "</html>"

        # Return result to the client
        return Response(text)
    else:
        # We don't have an access token, so we're going to use OAuth to
        # authenticate the user

        # Ask flask to generate the url corresponding to the login_callback
        # route. This is similar to using reverse() in django.
        redirect_uri = url_for('.login_callback', _external=True)

        client = APIClient(APP_ID, APP_SECRET)
        return redirect(client.authentication_url(redirect_uri))
Exemplo n.º 2
0
def login():
    if request.endpoint != 'login_callback':
        if 'access_token' not in session:
            redirect_uri = url_for('.login_callback', _external=True)
            client = APIClient(APP_ID, APP_SECRET)
            return redirect(client.authentication_url(redirect_uri))
        else:
            create_todo_tag()
Exemplo n.º 3
0
def index(pagenr):
    session['contact_mails'] = []
    session['contact_addresses'] = []
    offset = pagenr
    # If we have an access_token, we may interact with the Nylas Server
    if 'access_token' in session:
        client = APIClient(APP_ID, APP_SECRET, session['access_token'])
        message = None
        while len(session['contact_addresses']) + 1 < pagenr * 10:
            try:
                # Get the latest message from namespace zero.
                messages = client.messages.where(**{'in': 'all', 'limit': 20, 'offset':offset})
                for message in messages:
                    #print message['from'][0]['email']
                    if message['from'][0]['email'] not in session['contact_addresses']:
                        contact_mail = {
                        'id': len(session['contact_addresses']),
                        'date': message['date'],
                        'name': message['from'][0]['name'],
                        'email': message['from'][0]['email'],
                        'snippet': message['snippet'],
                        'unread': message['unread']
                        }
                        session['contact_mails'].append(contact_mail)
                        session['contact_addresses'].append(message['from'][0]['email'])
                #if messages.sender[0]['email'] not in session['emails']:
                if not messages:  # A new account takes a little time to sync
                    print "No messages yet. Checking again in 2 seconds."
                    time.sleep(2)
            except Exception as e:
                print(e.message)
                return Response("<html>An error occurred.</html>")
            offset += 1
        if pagenr - 1 == 0:
            start = 0
            end = 10
        else:
            start = (pagenr - 1) * 10
            end = pagenr * 10


        response = {'contacts': session['contact_mails'][start:end]}
        js = json.dumps(response)
        resp = Response(js, status=200, mimetype='application/json')
        return resp

    else:
        # We don't have an access token, so we're going to use OAuth to
        # authenticate the user

        # Ask flask to generate the url corresponding to the login_callback
        # route. This is similar to using reverse() in django.
        redirect_uri = url_for('.login_callback', _external=True)

        client = APIClient(APP_ID, APP_SECRET)
        return redirect(client.authentication_url(redirect_uri))
Exemplo n.º 4
0
def index():
    # We don't have an access token, so we're going to use OAuth to
    # authenticate the user

    # Ask flask to generate the url corresponding to the login_callback
    # route. This is similar to using reverse() in django.
    redirect_uri = url_for('.login_callback', _external=True)

    client = APIClient(APP_ID, APP_SECRET)
    return redirect(client.authentication_url(redirect_uri))
Exemplo n.º 5
0
def index():
    # We don't have an access token, so we're going to use OAuth to
    # authenticate the user

    # Ask flask to generate the url corresponding to the login_callback
    # route. This is similar to using reverse() in django.
    redirect_uri = url_for('.login_callback', _external=True)

    client = APIClient(APP_ID, APP_SECRET)
    return redirect(client.authentication_url(redirect_uri))
Exemplo n.º 6
0
def index(pagenr):
    session['contact_mails'] = []
    session['contact_addresses'] = []
    offset = pagenr
    # If we have an access_token, we may interact with the Nylas Server
    if 'access_token' in session:
        client = APIClient(APP_ID, APP_SECRET, session['access_token'])
        threads = None
        while not threads:
            try:
                # Get the latest message from namespace zero.
                threads = client.threads.where(**{'in': 'all', 'limit': 20, 'offset':0, 'view':'expanded' })
                if not threads:  # A new account takes a little time to sync
                    print "No messages yet. Checking again in 2 seconds."
                    time.sleep(2)
            except Exception as e:
                print(e.message)
                return Response("<html>An error occurred.</html>")
        # Format the output
        text = 'mit navn det står med prikker'
        for thread in threads:
                    text += thread.snippet
        #text = "<html><h1>Here's a message from your inbox:</h1><b>From:</b> "
        #for sender in message["from"]:
        #    text += "{} &lt;{}&gt;".format(sender['name'], sender['email'])
        #text += "<br /><b>Subject:</b> " + message.subject
        #text += "<br /><b>Body:</b> " + message.body
        #text += "</html>"

        # Return result to the client
        return Response(text)
    else:
        # We don't have an access token, so we're going to use OAuth to
        # authenticate the user

        # Ask flask to generate the url corresponding to the login_callback
        # route. This is similar to using reverse() in django.
        redirect_uri = url_for('.login_callback', _external=True)

        client = APIClient(APP_ID, APP_SECRET)
        return redirect(client.authentication_url(redirect_uri))
Exemplo n.º 7
0
def authorize():
    """
    This API authenticate for a chosen scope, and saves the nylas access code to cloud sql.
    Note: this API is the single entry point for authorization flow, and it will deactivate all previous access tokens
    for the given Nylas id.
    :return: flask response, 200 if success, 400 if failed.
    """
    from cloud_sql import sql_handler
    nylas_code = flask.request.args.get('code')
    error = flask.request.args.get('error')

    uid = flask.session['uid']
    logging.info(f'verifying auth sync status for uid {uid}')
    access_token = sql_handler.get_nylas_access_token(uid)

    # this is to handle potential authorization errors including access denied by customers.
    if error:
        logging.error(f'Authorization failed due to error: {error}')
        response = flask.jsonify(error)
        response.status_code = 400
        return response
    nylas_client = APIClient(app_id=app.config["NYLAS_OAUTH_CLIENT_ID"],
                             app_secret=app.config["NYLAS_OAUTH_CLIENT_SECRET"])
    if not nylas_code:
        scope = flask.request.args.get('scope')
        if not scope:
            logging.error('Need a valid scope string, currently supporting: calendar,email.send,email.modify')
            scope = 'calendar,email.send,email.modify'
        redirect_url = 'http://auth.lifo.ai/authorize'
        logging.info(f'receiving request for scope {scope}, and redirect to {redirect_url}')
        flask.session['scope'] = scope

        # Redirect your user to the auth_url
        auth_url = nylas_client.authentication_url(
            redirect_url,
            scopes=scope
        )
        return flask.redirect(auth_url)
    else:
        # note, here we have not handled the declined auth case
        logging.info(f'authentication success with code: {nylas_code}')
        access_token = nylas_client.token_for_code(nylas_code)
        nylas_client = APIClient(
            app_id=app.config["NYLAS_OAUTH_CLIENT_ID"],
            app_secret=app.config["NYLAS_OAUTH_CLIENT_SECRET"],
            access_token=access_token,
        )

        # Revoke all tokens except for the new one
        nylas_client.revoke_all_tokens(keep_access_token=access_token)

        account = nylas_client.account
        nylas_account_id = account.id
        nylas_email = account.email_address

        uid = flask.session['uid']
        scope = flask.session['scope']
        logging.info(f'handling auth for firebase uid: {uid} for scope {scope} and nylas id {nylas_account_id}')

        # Note: here we automatically handle the Nylas id changing case, as each user is recognized by their firebase
        # uid, and any new Nylas ids will be overwritten. This does bring in limitations: a user can only authorize one
        # Calendar account, which is not an issue for foreseeable future.
        sql_handler.save_nylas_token(uid, nylas_access_token=access_token, nylas_account_id=nylas_account_id, email=nylas_email)
    return render_template("authorize_succeed.html")
Exemplo n.º 8
0
def threads_contacts(offset):
    # If we have an access_token, we may interact with the Nylas Server
    #session['access_token'] = 'aC8stzQsDBR0ywlOmhCuyIBdu5uJYc'
    if 'access_token' in session:
        client = APIClient(APP_ID, APP_SECRET, session['access_token'])
        print session['access_token']
        if 'threads_contacts' not in session:
            session['threads_contacts'] = []
        if 'threads_contacts_addresses' not in session:
            session['threads_contacts_addresses'] = []
        if 'threads_contacts_offset' not in session:
            session['threads_contacts_offset'] = 0
        if 'threads_contacts_ids' not in session:
            session['threads_contacts_ids'] = []
        last_thread = False
        #session['threads_contacts'] = []
        #session['threads_contacts_addresses'] = []
        #session['threads_contacts_offset'] = 0
        #session['threads_contacts_ids'] = []
        while (len(session['threads_contacts']) + 1 < (offset + 1) * 10):
            threadcounter = 0

            for thread in client.threads.where(offset=session['threads_contacts_offset'], limit=99, in_='inbox'): #**{'in':'all', 'limit':40, 'offset':2}:
                threadcounter = threadcounter + 1
                if len(thread.participants) <= 2:
                    if len(thread.participants) == 1:
                        name = thread.participants[0]['name']
                        email = thread.participants[0]['email']
                    if len(thread.participants) == 2:
                        for participant in thread.participants:
                            if participant['email'] != '*****@*****.**':
                                name = participant['name']
                                email = participant['email']

                    if email not in session['threads_contacts_addresses'] and thread['id'] not in session['threads_contacts_ids']:
                                contact_thread = {
                                'id': thread['id'],
                                'date': thread['last_message_timestamp'],
                                'name': name, #thread.participants[0]['name'],
                                'email': email, #thread.participants[0]['email'],
                                'snippet': thread['snippet'],
                                'unread': thread['unread'],
                                'type': 'email'
                                }
                                session['threads_contacts'].append(contact_thread)
                                session['threads_contacts_addresses'].append(email)
                                session['threads_contacts_ids'].append(thread['id'])

                if (len(thread.participants) > 2) and (thread['id'] not in session['threads_contacts_ids']):
                    name = ''
                    emails = ''
                    for participant in thread.participants:
                        if participant['name']:
                            name += participant['name'] + ', '
                            emails += participant['email'] + ', '
                        else:
                            name += participant['email'] + ', '
                            emails += participant['email'] + ', '

                    contact_thread = {
                                'id': thread['id'],
                                'date': thread['last_message_timestamp'],
                                'name': name,
                                'email': emails,
                                'snippet': thread['snippet'],
                                'unread': thread['unread'],
                                'type': 'thread'
                                }
                    session['threads_contacts'].append(contact_thread)
                    session['threads_contacts_ids'].append(thread['id'])


            session['threads_contacts_offset'] = session['threads_contacts_offset'] + 1
            if threadcounter < 99:
                last_thread = True
                break

            # Return result to the client
        if offset == 0:
            start = 0
            end = 10
        else:
            start = offset * 10
            end = (offset + 1) * 10
        response = {'contacts': session['threads_contacts'][start:end], 'lastThread': last_thread}
        js = json.dumps(response)
        resp = Response(js, status=200, mimetype='application/json')
        return resp
    else:
        # We don't have an access token, so we're going to use OAuth to
        # authenticate the user

        # Ask flask to generate the url corresponding to the login_callback
        # route. This is similar to using reverse() in django.
        redirect_uri = url_for('.login_callback', _external=True)

        client = APIClient(APP_ID, APP_SECRET)
        return redirect(client.authentication_url(redirect_uri))