Example #1
0
def authorization():
    code = request.args.get('code')
    client = Client()
    token_response = client.exchange_code_for_token(
        client_id=os.environ.get('CLIENT_ID'),
        client_secret=os.environ.get('CLIENT_SECRET'),
        code=code)

    access_token = token_response['access_token']

    client = Client(access_token=access_token)

    athlete = client.get_athlete()

    r_out = requests.get(API_BASE_URL + '/segments/' + LEGENDS_OUT +
                         '/all_efforts' + '?access_token=' + access_token)

    legends_out_data = r_out.json()

    r_back = requests.get(API_BASE_URL + '/segments/' + LEGENDS_BACK +
                          '/all_efforts' + '?access_token=' + access_token)

    legends_back_data = r_back.json()

    if (len(legends_out_data) == 0 or len(legends_back_data) == 0) and \
            (int(athlete.id) != 13260725 and int(athlete.id) != 18685549):
        return redirect(url_for('not_legend'))

    # user is authorized at this point
    response = redirect(url_for('chat'))
    response.set_cookie('name', athlete.firstname + ' ' + athlete.lastname)
    response.set_cookie('authcookie', os.environ.get('VERIFICATION_KEY'))
    return response
Example #2
0
def authorization():
    """
    Method called by Strava (redirect) that includes parameters.
    - state
    - code
    - error
    """
    error = request.args.get('error')
    state = request.args.get('state')
    if error:
        return render_template('authorization_error.html', error=error)
    else:
        code = request.args.get('code')
        client = Client()
        access_token = client.exchange_code_for_token(client_id=app.config['STRAVA_CLIENT_ID'],
                                                      client_secret=app.config['STRAVA_CLIENT_SECRET'],
                                                      code=code)
        # Use the now-authenticated client to get the current athlete
        strava_athlete = client.get_athlete()
        athlete_model = data.register_athlete(strava_athlete, access_token)
        multiple_teams = None
        no_teams = False
        team = None
        try:
            team = data.register_athlete_team(strava_athlete=strava_athlete, athlete_model=athlete_model)
        except bafs.exc.MultipleTeamsError as multx:
            multiple_teams = multx.teams
        except bafs.exc.NoTeamsError:
            no_teams = True


        return render_template('authorization_success.html', athlete=strava_athlete,
                               team=team, multiple_teams=multiple_teams,
                               no_teams=no_teams)
Example #3
0
    def do_GET(self):

        request_path = self.path

        parsed_path = urlparse.urlparse(request_path)

        client = Client()

        if request_path.startswith('/authorization'):
            self.send_response(200)
            self.send_header(six.b("Content-type"), six.b("text/plain"))
            self.end_headers()

            self.wfile.write(six.b("Authorization Handler\n\n"))
            code = urlparse.parse_qs(parsed_path.query).get('code')
            if code:
                code = code[0]
                token_response = client.exchange_code_for_token(client_id=self.server.client_id,
                                                              client_secret=self.server.client_secret,
                                                              code=code)
                access_token = token_response['access_token']
                self.server.logger.info("Exchanged code {} for access token {}".format(code, access_token))
                self.wfile.write(six.b("Access Token: {}\n".format(access_token)))
            else:
                self.server.logger.error("No code param received.")
                self.wfile.write(six.b("ERROR: No code param recevied.\n"))
        else:
            url = client.authorization_url(client_id=self.server.client_id,
                                           redirect_uri='http://localhost:{}/authorization'.format(self.server.server_port))

            self.send_response(302)
            self.send_header(six.b("Content-type"), six.b("text/plain"))
            self.send_header(six.b('Location'), six.b(url))
            self.end_headers()
            self.wfile.write(six.b("Redirect to URL: {}\n".format(url)))
Example #4
0
def logged_in():
    """
    Method called by Strava (redirect) that includes parameters.
    - state
    - code
    - error
    """
    error = request.args.get('error')
    state = request.args.get('state')
    if error:
        return render_template('login_error.html', error=error)
    else:

        #Requesting the authorization code to STRAVA
        code = request.args.get('code')
        client = Client()
        access_token = client.exchange_code_for_token(
            client_id='30922',
            client_secret='2791ad32fb846e9f5b567f0a0deba5bb168fe533',
            code=code)

        logger.info(access_token)
        extractDataClub(client)

        return render_template('segment_results.html',
                               segmentsPara=[],
                               segmentsNort=[],
                               segmentsCAM=[],
                               segmentsCAS=[])
def get_login_token():
    last_activity = None
    # auth_token = ""

    if not os.path.exists(STRAVA_ACCESS_TOKEN_STRING_FNAME):

        print '* Obtain a request token ...'
        strava_client = Client()
        # auth_url = strava_client.authorization_url(client_id='601', redirect_uri='http://127.0.0.1:5000/authorisation')

        client_secret = open(STRAVA_CLIENT_SECRET_STRING_FNAME).read().strip()
        print client_secret
        client_code = open(STRAVA_CLIENT_CODE_STRING_NAME).read().strip()
        print client_code

        auth_token = strava_client.exchange_code_for_token(client_id='601',
                                                           client_secret= client_secret,
                                                           code = client_code)

        print auth_token

        f = open(STRAVA_ACCESS_TOKEN_STRING_FNAME, 'w')
        f.write(auth_token)

    else:
        print '* Reading request token from file ...'
        f = open(STRAVA_ACCESS_TOKEN_STRING_FNAME)
        auth_token = f.read()

    f.close()

    print auth_token
    return auth_token
Example #6
0
def authorization():
    """
    Method called by Strava (redirect) that includes parameters.
    - state
    - code
    - error
    """
    error = request.args.get('error')
    state = request.args.get('state')
    if error:
        return render_template('authorization_error.html', error=error)
    else:
        code = request.args.get('code')
        client = Client()
        access_token = client.exchange_code_for_token(client_id=app.config['STRAVA_CLIENT_ID'],
                                                      client_secret=app.config['STRAVA_CLIENT_SECRET'],
                                                      code=code)
        # Use the now-authenticated client to get the current athlete
        strava_athlete = client.get_athlete()
        athlete_model = data.register_athlete(strava_athlete, access_token)
        multiple_teams = None
        no_teams = False
        team = None
        try:
            team = data.register_athlete_team(strava_athlete=strava_athlete, athlete_model=athlete_model)
        except bafs.exc.MultipleTeamsError as multx:
            multiple_teams = multx.teams
        except bafs.exc.NoTeamsError:
            no_teams = True


        return render_template('authorization_success.html', athlete=strava_athlete,
                               team=team, multiple_teams=multiple_teams,
                               no_teams=no_teams)
async def strava_callback(background_task: BackgroundTasks, code: str, scope: str, state: str = None):
    client = Client()
    token_response = client.exchange_code_for_token(
        client_id=STRAVA_CLIENT_ID, client_secret=STRAVA_CLIENT_SECRET,
        code=code)

    client = Client(access_token=token_response['access_token'])
    athlete = client.get_athlete()
    
    try:
        strava_athlete = await StravaAthlete.objects.get(id=athlete.id)
    except orm_exceptions.NoMatch:
        strava_athlete = await StravaAthlete.objects.create(
            id=athlete.id,
            access_token=token_response['access_token'],
            refresh_token=token_response['refresh_token'],
            token_expiration_datetime=datetime.utcfromtimestamp(token_response['expires_at']).isoformat())

        background_task.add_task(new_athlete, strava_athlete)
    
    response = RedirectResponse('/reports')
    jwt_token = create_jwt_token(sub=strava_athlete.id)
    response.set_cookie(
        key="jwt_token",
        value=jwt_token,
        httponly=True)
    return response
Example #8
0
class Strava():

    def __init__(self):
        self.client = Client()
        self.url = self.client.authorization_url(client_id=41952,
                                                 redirect_uri='https://strava2toggl.herokuapp.com/authorization')

    def get_access_token(self, code):
        self.code = code
        s3 = S3Connection(os.environ['client_id'], os.environ['client_secret'])
        self.access_token = self.client.exchange_code_for_token(client_id=os.environ['client_id'],
                                                                client_secret=os.environ['client_secret'],
                                                                code=self.code)
        self.access_token = self.access_token['access_token']
        self.client = Client(access_token=self.access_token)
        return self.access_token

    def get_activities(self, days, code):
        dt1 = datetime.now()
        dt2 = timedelta(days=days)
        dt3 = dt1 - dt2
        dt3 = dt3.strftime("%Y-%m-%dT%H:%M:%SZ")
        client = Client(access_token=code)
        activities = client.get_activities(after=dt3)
        return activities
Example #9
0
class strava_class(object):
    def __init__(self):
        self.client = Client()

    def login_vegard(self):
        MY_STRAVA_CLIENT_ID = 14139
        MY_STRAVA_CLIENT_SECRET = 'd753993b6646b15440914a6477e0d0e594b6a5b5'
        code = '3436d2f7d6b3926667097f39cb9d07eeb8fdc9d2'
        access_token = self.client.exchange_code_for_token(
            client_id=MY_STRAVA_CLIENT_ID,
            client_secret=MY_STRAVA_CLIENT_SECRET,
            code=code)
        self.client.access_token = access_token

    def login_other():
        MY_Url = 'http://127.0.0.1:5000'
        url = client.authorization_url(client_id=MY_STRAVA_CLIENT_ID,
                                       redirect_uri=self.MY_Url)
        #Start web server
        #Get the user to click the link
        #read out the code from web server
        #stop web server
        return 0

    def get_last_week(self, lim):
        for activity in self.client.get_activities(
                after="2016-08-01T00:00:00Z", limit=lim):
            print("{0.name} {0.moving_time}".format(activity))
Example #10
0
def request_user_login():
    print("Requesting user login")

    client_id = get_string_from_file('client_id')
    client_secret = get_string_from_file('client_secret')

    client=Client()
    LOGIN_URL = client.authorization_url(client_id=client_id, redirect_uri='http://localhost')
    
    print(LOGIN_URL)
    webbrowser.open(LOGIN_URL)

    try:
        auth_code = input("Enter the auth_code from the redirected URL: ")
        write_string_to_file("auth_code", auth_code)
    except EOFError:
        print("Unable to read code from stdin. Assuming `auth_code` file is manually populated")
        auth_code = get_string_from_file('auth_code')

    token_response = client.exchange_code_for_token(client_id=client_id, client_secret=client_secret, code=auth_code)

    write_string_to_file("access_token", token_response['access_token'])
    write_string_to_file("refresh_token", token_response['refresh_token'])
    print("Token expires at " + str(token_response['expires_at']))
    
    check_if_access_token_valid()
Example #11
0
 def authenticate(self, code):
     logger.info('StravaV3Backend.authenticate begging')
     client_id = settings.CLIENT_ID
     client_secret = settings.CLIENT_SECRET
     
     # Make the request to the API
     client = Client()
     access_token = client.exchange_code_for_token(client_id=client_id, client_secret=client_secret, code=code)
     athlete = client.get_athlete()
     
     # username must be unique hence use id
     username = "******" % (athlete.id , athlete.firstname, athlete.lastname)
     
     # Get or create the user (returns tuple)
     try:
         user = User.objects.get(id=athlete.id)
     except:
         logger.error('User.objects.get failed')
         user = User(id=athlete.id)
     
     # Update username
     logger.info('Update username: '******'Update token: '+access_token)         
     token_model.token = access_token
     token_model.code = code
     token_model.save()
     
     logger.info(user)
     # Return the user
     return user
Example #12
0
def logged_in():
    error = request.args.get('error')
    state = request.args.get('state')

    try:
        if error:
            return render_template('login_error.html', error=error)
        else:
            code = request.args.get('code')

            client = Client()
            access_token = client.exchange_code_for_token(
                client_id=current_app.config['STRAVA_CLIENT_ID'],
                client_secret=current_app.config['STRAVA_CLIENT_SECRET'],
                code=code)
            strava_athlete = client.get_athlete()

            session.parmanent = True
            session['access_token'] = access_token

        return render_template('login_results.html',
                               athlete=strava_athlete,
                               access_token=access_token)

    except Exception as e:
        return render_template('login_error.html', error=str(e))
Example #13
0
def authorize():
    code = request.args.get('code')
    client = Client()
    access_token = client.exchange_code_for_token(client_id=STRAVA_CLIENT_ID,
						  client_secret=STRAVA_CLIENT_SECRET,
						  code=code)
    tokens.insert_one({'token': access_token})
    return render_template('success.html', token=access_token)
Example #14
0
def authorize(request):
    code = request.GET.get('code')
    print("Code", code)
    print(settings.STATIC_URL)
    client = Client()
    access_token = client.exchange_code_for_token(client_id=11103,
                                                  client_secret=settings.MYSECRETKEY,
                                                  code=code)
    return HttpResponse('Your access token is {0}'.format(access_token))
Example #15
0
def get_strava_token_from_code_id(config: ConfigParser) -> str:
    """ Method that interchange the temporary authentication code obtained
    when `src/request_auth.py` is executed. The method reads the file
    `config/code_id.txt` that contains the temporal authentication and generates
    the POST request to obtain the final access token which is saved in
    `config/token.json`.

    This method requires the Strava application `client_id` and `secret` that
    has to be set in the configuration file (`config/config.ini`).

    Args:
        config (ConfigParser): app configuration.

    Returns:
        str: Strava access token.

    Raises:
        ValueError: If no token is found in the configuration.
    """
    code_id_path = Path(CONFIG_PATH, CODE_ID_FILE_NAME)
    if not code_id_path.is_file():
        raise ValueError(
            'The file with the temporal authentication code (`config/code_id.txt`)'
            'was NOT found. Execute `request_auth.py` to obtain the temporal access.'
        )

    with open(code_id_path, 'r') as file:
        logger.debug(
            'The file with the temporal authentication code (`config/code_id.txt`)'
            'was found.')
        code_id = file.read()

    if not code_id:
        raise ValueError(
            'No valid temporal code access found. Rerun `request_auth.py` '
            'to obtain the temporal access.')

    client = Client()
    token = client.exchange_code_for_token(client_id=get_client_id(config),
                                           client_secret=get_secret(config),
                                           code=code_id)

    logger.debug(
        'Obtained access until {}:\n'
        '- token: {}.'
        '- refresh token: {}.',
        datetime.utcfromtimestamp(int(
            token['expires_at'])).strftime('%d-%m-%Y %H:%M:%S'),
        token['access_token'], token['refresh_token'])

    # Save JSON with the response
    save_path = Path(check_folder(CONFIG_PATH), TOKEN_FILE_NAME)
    with open(save_path, 'w') as file:
        logger.info('Writing token information to `{}`.', save_path)
        json.dump(token, file, indent=4)

    return token['access_token']
Example #16
0
def main():
    """ Get access token from stravaupload.cfg """
    config = ConfigParser()
    config.read('./scripts/.stravaupload.cfg')

    if config.has_option('access', 'clientid'):
        client_id = config.get('access', 'clientid')
    else:
        print('No access/clientid found in .stravaupload.cfg')
        sys.exit(0)

    if config.has_option('access', 'token'):
        access_token = config.get('access', 'token')
    else:
        print('No access/token found in .stravaupload.cfg')
        sys.exit(0)

    if config.has_option('access', 'clientsecret'):
        client_secret = config.get('access', 'clientsecret')
    else:
        print('No access/clientsecret found in .stravaupload.cfg')
        sys.exit(0)
    """ Exchange code for token """
    stravaClient = Client()
    stravaClient.exchange_code_for_token(client_id=client_id,
                                         client_secret=str(client_secret),
                                         code=str(access_token))
    """ Check if input is a single file or a directory """
    if len(sys.argv) == 1:
        ''' Find directory where are stored TCX converted files '''
        tcxDir = os.path.join(os.getcwd(), 'TCX_exports')
        ''' Set TCX pattern to finf files ending with .tcx '''
        tcxPattern = os.path.join(tcxDir, '*.tcx')
        filenames = glob.glob(tcxPattern)

        if len(filenames) == 0:
            sys.exit('No .tcx found in ' + str(sys.argv[1]) + ' directory')
        else:
            for idx, filename in enumerate(filenames):
                uploadFile(stravaClient, filename)
    elif os.path.isfile(sys.argv[1]):
        uploadFile(stravaClient, sys.argv[1])
    else:
        sys.exit('usage: stravaupload.py <filename.tcx>')
Example #17
0
def logged_in():
    """
    Method called by Strava (redirect) that includes parameters.
    - state
    - code
    - error
    """
    error = request.args.get('error')
    state = request.args.get('state')
    if error:
        return render_template('login_error.html',
                               error=error,
                               competition_title=config.COMPETITION_TITLE)
    else:
        code = request.args.get('code')
        client = Client()
        token_dict = client.exchange_code_for_token(client_id=config.STRAVA_CLIENT_ID,
                                                    client_secret=config.STRAVA_CLIENT_SECRET,
                                                    code=code)
        # Use the now-authenticated client to get the current athlete
        strava_athlete = client.get_athlete()

        athlete_model = data.update_athlete_auth(strava_athlete, token_dict)
        if not athlete_model:
            return render_template('login_error.html',
                                   error="ATHLETE_NOT_FOUND",
                                   competition_title=config.COMPETITION_TITLE)

        multiple_teams = None
        no_teams = False
        team = None
        message = None
        try:
            team = data.register_athlete_team(
                    strava_athlete=strava_athlete,
                    athlete_model=athlete_model,
                    )
        except MultipleTeamsError as multx:
            multiple_teams = multx.teams
            message = multx
        except NoTeamsError as noteamsx:
            no_teams = True
            message = noteamsx
        if not no_teams:
            auth.login_athlete(strava_athlete)
            return redirect(url_for('user.rides'))
        else:
            return render_template(
                    'login_results.html',
                    athlete=strava_athlete,
                    team=team,
                    multiple_teams=multiple_teams,
                    no_teams=no_teams,
                    message=message,
                    competition_title=config.COMPETITION_TITLE,
                    )
Example #18
0
def authorization():
    code = request.args.get('code')
    client = Client()
    access_token = client.exchange_code_for_token(
        client_id=STRAVA_CLIENT_ID,
        client_secret=STRAVA_CLIENT_SECRET,
        code=code
    )
    bridge.token_got.emit(access_token)
    return access_token
Example #19
0
def strava_authorisation_view(request):
    code = request.GET.get("code")
    client = Client()
    client_id = request.user.profile[0].strava_client_id
    client_secret = request.registry.settings.get("strava.client_secret")
    access_token = client.exchange_code_for_token(client_id=client_id,
                                                  client_secret=client_secret,
                                                  code=code)
    request.user.profile[0].strava_access_key = access_token
    request.session.flash("Authorized client", "success")
    return HTTPFound(request.route_path("home"))
Example #20
0
    def add_user(code: str):
        """
        Takes a temporary access code returned from Strava and retrieves the
        associated user and access token. Then it checks for the user in the
        database. If they're not found, then the new user is recorded. If they are
        found, then just the access token is recorded in case it has changed.
        """
        client = Client()
        if not Config.TESTING:
            response = client.exchange_code_for_token(
                client_id=Config.CLIENT_ID,
                client_secret=Config.CLIENT_SECRET,
                code=code,
            )
            current_app.logger.debug("Response: " + str(response))
            client.access_token = response["access_token"]
            access_token = response["access_token"]
            refresh_token = response["refresh_token"]
            access_expr = datetime.fromtimestamp(response["expires_at"])
            athlete = client.get_athlete()
            user_id = athlete.id
            first_name = athlete.firstname
        else:
            access_token = "access"
            refresh_token = "refresh"
            access_expr = datetime.now() - timedelta(hours=5)
            user_id = 1
            first_name = "joe"

        # noinspection PyArgumentList

        # Check if the user is already in the db
        if User.query.get(user_id) is None:
            u = User(
                id=user_id,
                first_name=first_name,
                access_token=access_token,
                refresh_token=refresh_token,
                access_expr=access_expr,
            )
            db.session.add(u)
            db.session.commit()
            current_app.logger.info(f"New user added: {user_id}")
        else:
            u = User.query.get(user_id)
            u.access_token = access_token
            u.refresh_token = refresh_token
            u.access_expr = access_expr
            db.session.commit()
            current_app.logger.info(
                f"User {user_id} already found; updating token, logging in,"
                " and redirecting to dashboard"
            )
        return u
Example #21
0
    def do_GET(self):

        request_path = self.path

        parsed_path = urlparse.urlparse(request_path)

        client = Client()

        if request_path.startswith('/authorization'):
            self.send_response(200)
            self.send_header(six.b("Content-type"), six.b("text/plain"))
            self.end_headers()

            self.wfile.write(six.b("Authorization Handler\n\n"))
            code = urlparse.parse_qs(parsed_path.query).get('code')
            if code:
                code = code[0]
                token_response = client.exchange_code_for_token(
                    client_id=self.server.client_id,
                    client_secret=self.server.client_secret,
                    code=code)
                access_token = token_response['access_token']
                refresh_token = token_response['refresh_token']
                expires_at = token_response['expires_at']
                self.server.logger.info(
                    "Exchanged code {} for access token {}".format(
                        code, access_token))
                self.wfile.write(
                    six.b("Access Token: {}\n".format(access_token)))
                self.wfile.write(
                    six.b("Refresh Token: {}\n".format(refresh_token)))
                self.wfile.write(six.b("Expires at: {}\n".format(expires_at)))
                with open('strava_token.txt', 'w') as f:
                    f.write(self.server.client_id + '\n')
                    f.write(self.server.client_secret + '\n')
                    f.write(access_token + '\n')
                    f.write(refresh_token + '\n')
                    f.write(str(expires_at) + '\n')
            else:
                self.server.logger.error("No code param received.")
                self.wfile.write(six.b("ERROR: No code param recevied.\n"))
        else:
            url = client.authorization_url(
                client_id=self.server.client_id,
                redirect_uri='http://localhost:{}/authorization'.format(
                    self.server.server_port),
                scope='activity:write')

            self.send_response(302)
            self.send_header(six.b("Content-type"), six.b("text/plain"))
            self.send_header(six.b('Location'), six.b(url))
            self.end_headers()
            self.wfile.write(six.b("Redirect to URL: {}\n".format(url)))
Example #22
0
def getToken(MY_STRAVA_CLIENT_ID, MY_STRAVA_CLIENT_SECRET):
    access_token = session.get('access_token')
    if access_token != None:
        return access_token
    # the code is in the results thingy!
    code = request.args.get('code')
    if code == None:
        return None
    client = Client()
    access_token = client.exchange_code_for_token(client_id=MY_STRAVA_CLIENT_ID,\
                                                  client_secret=MY_STRAVA_CLIENT_SECRET,\
                                                  code=code)
    session['access_token'] = access_token
    return access_token
Example #23
0
def getToken():
    access_token = session.get('access_token')
    if access_token != None:
        return access_token
    # the code is in the results thingy!
    code = request.args.get('code')
    if code == None:
        return None
    client = Client()
    access_token = client.exchange_code_for_token(client_id=MY_STRAVA_CLIENT_ID,\
                                                  client_secret=MY_STRAVA_CLIENT_SECRET,\
                                                  code=code)
    session['access_token'] = access_token
    return access_token
Example #24
0
def authorization():
	my_client_id = app.vars['client_id']
	my_client_secret = app.vars['client_secret']

	code = request.args.get('code')

	client = Client()
	access_token = client.exchange_code_for_token(client_id = my_client_id, \
		client_secret = my_client_secret, code = code)
	app.vars['access_token'] = access_token
	
	my_client = StravaClient()
	app.vars['athlete'] = my_client.get_athlete()
	
	return redirect('power_profile')
Example #25
0
def lambda_handler(event, context):
    code = event['code']
    exchange_mode, exchange_opt = event['state'].split('-')

    client = Client()
    access_token = client.exchange_code_for_token(
        client_id=os.environ.get('STRAVA_CLIENT_ID'),
        client_secret=os.environ.get('STRAVA_CLIENT_SECRET'),
        code=code)

    if exchange_mode == 'REDIRECT':
        return {
            'location':
            f'http://127.0.0.1:{exchange_opt}?access_token={access_token}'
        }
Example #26
0
def strava_authorize(request):
    code = request.GET.get('code')
    scopes = request.GET.get('scope', '').split(',')
    if not code or 'activity:read_all' not in scopes or 'activity:write' not in scopes:
        return HttpResponseRedirect(settings.URL_FRONT+'/new')
    client = StravaClient()
    access_token = client.exchange_code_for_token(
        client_id=settings.MY_STRAVA_CLIENT_ID,
        client_secret=settings.MY_STRAVA_CLIENT_SECRET,
        code=code
    )
    user_settings = request.user.settings
    user_settings.strava_access_token = json.dumps(access_token) 
    user_settings.save()
    return HttpResponseRedirect(settings.URL_FRONT + '/new')
Example #27
0
def authorization():
    """
    Method called by Strava (redirect) that includes parameters.
    - state
    - code
    - error
    """
    error = request.args.get('error')
    if error:
        return render_template('authorization_error.html',
                               error=error,
                               competition_title=config.COMPETITION_TITLE)
    else:
        code = request.args.get('code')
        client = Client()
        token_dict = client.exchange_code_for_token(
                client_id=config.STRAVA_CLIENT_ID,
                client_secret=config.STRAVA_CLIENT_SECRET,
                code=code,
                )
        # Use the now-authenticated client to get the current athlete
        strava_athlete = client.get_athlete()
        athlete_model = data.register_athlete(strava_athlete, token_dict)
        multiple_teams = None
        no_teams = False
        team = None
        message = None
        try:
            team = data.register_athlete_team(
                    strava_athlete=strava_athlete,
                    athlete_model=athlete_model,
                    )
        except MultipleTeamsError as multx:
            multiple_teams = multx.teams
            message = multx
        except NoTeamsError as noteamx:
            no_teams = True
            message = noteamx

        return render_template(
            'authorization_success.html',
            athlete=strava_athlete,
            team=team,
            multiple_teams=multiple_teams,
            no_teams=no_teams,
            message=message,
            competition_title=config.COMPETITION_TITLE,
        )
Example #28
0
def get_activities_from_strava():
    last_activity = None
    if not os.path.exists(STRAVA_ACCESS_TOKEN_STRING_FNAME):

        print '* Obtain a request token ...'
        strava_client = Client()
        auth_url = strava_client.authorization_url(client_id='601', redirect_uri='http://127.0.0.1:5000/authorisation')
        print auth_url

        auth_token = strava_client.exchange_code_for_token(client_id='601', client_secret='600580e02b4814c75c93d3a60e15077147895776', code = '74cc257e6bc370d9da44cabc8852f3667ad95515')

        print auth_token

        # write the access token to file; next time we just read it from file
        if DEBUG:
            print 'Writing file', STRAVA_ACCESS_TOKEN_STRING_FNAME


        fobj = open(STRAVA_ACCESS_TOKEN_STRING_FNAME, 'w')
        fobj.write(auth_token)
        fobj.close()

    else:
        if DEBUG:
            print 'Reading file', STRAVA_ACCESS_TOKEN_STRING_FNAME
        fobj = open(STRAVA_ACCESS_TOKEN_STRING_FNAME)
        access_token_string = fobj.read()

        print access_token_string
        #access_token = oauth.OAuthToken.from_string(access_token_string)

        strava_client = Client(access_token=access_token_string)
        activities = strava_client.get_activities(limit=10)

        # for activity in activities:
        #     details = strava_client.get_activity(activity_id=activity.id)
        #     print details.name
        #     print unithelper.kilometers(details.distance)
        #     print details.start_date_local
        #     print details.elapsed_time
        #     print details.calories
        #     print details.type
        #     print "------"
        # fobj.close()
        for activity in activities:
            last_activity = activity

    return strava_client.get_activity(activity_id=activity.id)
Example #29
0
def authorization(request):
    '''
    Trades in the `code` sent from Strava for an `access_token`.
    Ties that `access_token` to a users session.
    '''

    code = request.GET.get('code', None)
    client = Client()
    access_token = client.exchange_code_for_token(
        client_id=os.environ.get('STRAVA_CLIENT_ID', None),
        client_secret=os.environ.get('STRAVA_CLIENT_SECRET', None),
        code=code
    )
    request.session['access_token'] = access_token

    return redirect(index)
def logged_in():
    """
    Method called by Strava (redirect) that includes parameters.
    - state
    - code
    - error
    """
    error = request.args.get('error')
    state = request.args.get('state')
    if error:
        return render_template('login_error.html', error=error)
    else:
        code = request.args.get('code')
        client = Client()
        access_token = client.exchange_code_for_token(
            client_id=app.config['STRAVA_CLIENT_ID'],
            client_secret=app.config['STRAVA_CLIENT_SECRET'],
            code=code)
        # Use the now-authenticated client to get the current athlete
        strava_athlete = client.get_athlete()

        athlete_model = meta.session_factory().query(Athlete).get(
            strava_athlete.id)
        if not athlete_model:
            return render_template('login_error.html',
                                   error="ATHLETE_NOT_FOUND")

        multiple_teams = None
        no_teams = False
        team = None
        try:
            team = data.register_athlete_team(strava_athlete=strava_athlete,
                                              athlete_model=athlete_model)
        except MultipleTeamsError as multx:
            multiple_teams = multx.teams
        except NoTeamsError:
            no_teams = True

        if not no_teams:
            auth.login_athlete(strava_athlete)
            return redirect(url_for('user.rides'))
        else:
            return render_template('login_results.html',
                                   athlete=strava_athlete,
                                   team=team,
                                   multiple_teams=multiple_teams,
                                   no_teams=no_teams)
Example #31
0
File: views.py Project: jyundt/oval
def authorize_strava():
    if request.args.get('state') and request.args.get('code'):
        id = request.args.get('state')
        strava_code = request.args.get('code')
        strava_client_id = current_app.config['STRAVA_CLIENT_ID']
        strava_client_secret = current_app.config['STRAVA_CLIENT_SECRET']
        strava_client = Client()
        try:
            access_token = (
                strava_client.exchange_code_for_token(
                    client_id=strava_client_id,
                    client_secret=strava_client_secret,
                    code=strava_code))
        except Exception:
            return redirect(url_for('racer.index'))
        else:
            racer = Racer.query.get_or_404(id)
            strava_client = Client(access_token)
            strava_athlete = strava_client.get_athlete()
            existing_racer = Racer.query\
                                  .filter_by(strava_id=strava_athlete.id)\
                                  .first()
            if existing_racer:
                flash('Racer ' + existing_racer.name +
                      ' already linked with Strava account for ' +
                      strava_athlete.firstname + ' ' +
                      strava_athlete.lastname + '!')
                current_app.logger.info('%s[%d] failed against %s[%d]',
                                        racer.name, racer.id,
                                        existing_racer.name, existing_racer.id)
                return redirect(url_for('racer.details', id=id))
            else:
                racer.strava_access_token = access_token
                racer.strava_id = strava_athlete.id
                racer.strava_email = strava_athlete.email
                racer.profile_url = strava_athlete.profile
                db.session.commit()
                current_app.logger.info('%s[%d]', racer.name, racer.id)
                flash('Racer ' + racer.name + ' linked with Strava!')
            return redirect(url_for('racer.details', id=id))

    return redirect(url_for('racer.index'))
Example #32
0
File: views.py Project: jyundt/oval
def authorize_strava():
    if request.args.get('state') and request.args.get('code'):
        id = request.args.get('state')
        strava_code = request.args.get('code')
        strava_client_id = current_app.config['STRAVA_CLIENT_ID']
        strava_client_secret = current_app.config['STRAVA_CLIENT_SECRET']
        strava_client = Client()
        try:
            access_token = (
                strava_client.exchange_code_for_token(
                    client_id=strava_client_id,
                    client_secret=strava_client_secret,
                    code=strava_code))
        except Exception:
            return redirect(url_for('racer.index'))
        else:
            racer = Racer.query.get_or_404(id)
            strava_client = Client(access_token)
            strava_athlete = strava_client.get_athlete()
            existing_racer = Racer.query\
                                  .filter_by(strava_id=strava_athlete.id)\
                                  .first()
            if existing_racer:
                flash('Racer ' + existing_racer.name +
                      ' already linked with Strava account for ' +
                      strava_athlete.firstname + ' ' +
                      strava_athlete.lastname + '!')
                current_app.logger.info('%s[%d] failed against %s[%d]',
                                        racer.name, racer.id,
                                        existing_racer.name, existing_racer.id)
                return redirect(url_for('racer.details', id=id))
            else:
                racer.strava_access_token = access_token
                racer.strava_id = strava_athlete.id
                racer.strava_email = strava_athlete.email
                racer.profile_url = strava_athlete.profile
                db.session.commit()
                current_app.logger.info('%s[%d]', racer.name, racer.id)
                flash('Racer ' + racer.name + ' linked with Strava!')
            return redirect(url_for('racer.details', id=id))

    return redirect(url_for('racer.index'))
Example #33
0
def token(request):
    # Get temporary code after the request
    code = request.GET.get("code")

    # exchange the code for an access token. 
    client = Client()
    access_token = client.exchange_code_for_token(client_id=STRAVA_CLIENT_ID,
                                              client_secret=STRAVA_CLIENT_SECRET,
                                              code=code)

    # Get Athlete 
    athlete = client.get_athlete()
    
    # See if the athlete exists in our DB
    # current_athlete = get_object_or_404(Athlete, id_strava = athlete.id)

    # current_athlete = ""
    
    try:
        current_athlete = Athlete.objects.get(id_strava = athlete.id)
    except (KeyError, Athlete.DoesNotExist):
        current_athlete = Athlete(first_name=athlete.firstname, last_name=athlete.lastname, access_token=access_token, id_strava = athlete.id )
        current_athlete.save()


    # **************************
    # Prep content for the HTML page.
    # Get Activities. 
    activities = client.get_activities()

    # Make a list of activities to send to the html page. These are all the activities for this athlete. 
    activity_list = []
    name_list = []

    for a in activities:
        temp = [a.id, a.name, a.distance, a.moving_time, a.elapsed_time, a.start_date_local] 
        activity_list.append(temp)

    # information to send to the html page
    context = { 'activity_list': activity_list,  'current_athlete': current_athlete }
    template = loader.get_template('shred/activities.html')
    return HttpResponse(template.render(context))
Example #34
0
def logged_in():
    """
    Method called by Strava (redirect) that includes parameters.
    - state
    - code
    - error
    """
    error = request.args.get('error')
    state = request.args.get('state')
    if error:
        return render_template('login_error.html', error=error)
    else:
        code = request.args.get('code')
        client = Client()
        access_token = client.exchange_code_for_token(client_id=app.config['STRAVA_CLIENT_ID'],
                                                      client_secret=app.config['STRAVA_CLIENT_SECRET'],
                                                      code=code)
        # Use the now-authenticated client to get the current athlete
        strava_athlete = client.get_athlete()

        athlete_model = db.session.query(Athlete).get(strava_athlete.id)
        if not athlete_model:
            return render_template('login_error.html', error="ATHLETE_NOT_FOUND")

        multiple_teams = None
        no_teams = False
        team = None
        try:
            team = data.register_athlete_team(strava_athlete=strava_athlete, athlete_model=athlete_model)
        except bafs.exc.MultipleTeamsError as multx:
            multiple_teams = multx.teams
        except bafs.exc.NoTeamsError:
            no_teams = True

        if not no_teams:
            auth.login_athlete(strava_athlete)
            return redirect(url_for('user.rides'))
        else:
            return render_template('login_results.html', athlete=strava_athlete,
                                   team=team, multiple_teams=multiple_teams,
                                   no_teams=no_teams)
Example #35
0
def logged_in():
    """
    Method called by Strava (redirect) that includes parameters.
    - state
    - code
    - error
    """
    error = request.args.get('error')
    state = request.args.get('state')
    if error:
        return render_template('login_error.html', error=error)
    else:

        #Requesting the authorization code to STRAVA
        code = request.args.get('code')
        client = Client()
        access_token = client.exchange_code_for_token(client_id='30922',
                                                      client_secret='2791ad32fb846e9f5b567f0a0deba5bb168fe533',
                                                      code=code)              
            
        #Defining segments area bounds
        bounds_CAM=[40.366,-4.385,41.197,-3.573]
        bounds_NORT=[40.494,-3.876,41.197,-3.573]
        bounds_PARACUELLOS=[40.499,-3.546,40.844,-3.364]
        bounds_CASAVIEJA=[40.185,-5.043,40.458,-4.475]


        eleListPara= extractData(client,bounds_PARACUELLOS)
        eleListNort= extractData(client,bounds_NORT)            
        eleListCAM = extractData(client,bounds_CAM)
        eleListCAS = extractData(client,bounds_CASAVIEJA)
        
        # Dump to carto db
        utils.dumpToCarto(eleListNort,'north')
        utils.dumpToCarto(eleListPara,'para')
        utils.dumpToCarto(eleListCAM,'cam')
        utils.dumpToCarto(eleListCAS,'cas')
        
        return render_template('segment_results.html', segmentsPara=eleListPara,
                               segmentsNort=eleListNort, segmentsCAM=eleListCAM,
                               segmentsCAS=eleListCAS)
Example #36
0
def token(request):

    code = request.GET.get("code", None)

    if not code:
        return HttpResponse('<a href=' + reverse('index') +
                            '>Failed, try again.</a>')
    else:
        client = Client()
        access_token = client.exchange_code_for_token(
            client_id=os.environ['SMOOTHIFY_ID'],
            client_secret=os.environ['SMOOTHIFY_SECRET'],
            code=code)

        request.session['SMOOTHIFY_TOKEN'] = access_token

        athlete = client.get_athlete()
        request.session['ATHLETE_FIRSTNAME'] = athlete.firstname

        request.session['ACTIVITY_ERROR'] = None
        return HttpResponseRedirect('/activity/')
Example #37
0
def display_page(query_string, strava_auth):
    if strava_auth is None:
        strava_auth = {}

    body = strava_login_layout

    if strava_auth.get('authenticated', False):
        body = app_layout
    elif query_string is not None:
        query = parse_qs(str(query_string[1:]))
        if 'code' in query:
            client = Client()
            response = client.exchange_code_for_token(
                client_id=settings.STRAVA_CLIENT_ID,
                client_secret=settings.STRAVA_CLIENT_SECRET,
                code=query['code'])
            strava_auth.update(response)
            strava_auth['authenticated'] = True
            body = app_layout

    return body, strava_auth
Example #38
0
def authenticate():
    client = Client()
    url = client.authorization_url(client_id=sm.client_id,
                                   redirect_uri='http://localhost')
    logger.info(
        'Open this URL, then paste in the code provided in the URL: '
        '%s', url)
    code = input('Paste code here: ')

    auth_dict = client.exchange_code_for_token(client_id=sm.client_id,
                                               client_secret=sm.client_secret,
                                               code=code)
    logger.debug('Auth Dict: %s', auth_dict)

    # Save the dict back to Secret manager
    try:
        sm.set_auth_dict(auth_dict)
    except PermissionDenied:
        logger.error(f'Looks like your token could not be saved. Try manually '
                     f'adding this value to your STRAVA_ACCESS_TOKEN secret:\n'
                     f'  {json.dumps(auth_dict)}')
Example #39
0
def logged_in():
    """
    Method called by Strava (redirect) that includes parameters.
    - state
    - code
    - error
    """
    error = request.args.get('error')
    state = request.args.get('state')
    if error:
        return render_template('login_error.html', error=error)
    else:
        code = request.args.get('code')
        client = Client()
        access_token = client.exchange_code_for_token(client_id=app.config['STRAVA_CLIENT_ID'],
                                                      client_secret=app.config['STRAVA_CLIENT_SECRET'],
                                                      code=code)
        # Probably here you'd want to store this somewhere -- e.g. in a database.
        strava_athlete = client.get_athlete()

        return render_template('login_results.html', athlete=strava_athlete, access_token=access_token)
Example #40
0
def login_verdict(query_string, logout_click, strava_auth):
    # https://dash.plotly.com/advanced-callbacks
    ctx = dash.callback_context
    if not ctx.triggered:
        trigger_id = 'No clicks yet'
    else:
        trigger_id = ctx.triggered[0]['prop_id'].split('.')[0]
    ctx_msg = json.dumps(
        {
            'states': ctx.states,
            'triggered': ctx.triggered,
            'inputs': ctx.inputs
        },
        indent=2)
    unauthenticated = style.SHOW
    authenticated = style.HIDE

    if trigger_id == 'strava-logout':
        return unauthenticated, authenticated, {}

    if strava_auth is None:
        strava_auth = {}

    if strava_auth.get('authenticated', False):
        unauthenticated = style.HIDE
        authenticated = style.SHOW
    elif query_string is not None:
        query = parse_qs(str(query_string[1:]))
        if 'code' in query:
            client = Client()
            response = client.exchange_code_for_token(
                client_id=settings.STRAVA_CLIENT_ID,
                client_secret=settings.STRAVA_CLIENT_SECRET,
                code=query['code'])
            strava_auth.update(response)
            strava_auth['authenticated'] = True
            unauthenticated = style.HIDE
            authenticated = style.SHOW

    return unauthenticated, authenticated, strava_auth
Example #41
0
    def do_GET(self):

        request_path = self.path

        parsed_path = urlparse.urlparse(request_path)

        client = Client()

        if request_path.startswith('/authorization'):
            self.send_response(200)
            self.send_header(six.b("Content-type"), six.b("text/plain"))
            self.end_headers()

            self.wfile.write(six.b("Authorization Handler\n\n"))
            code = urlparse.parse_qs(parsed_path.query).get('code')
            if code:
                code = code[0]
                access_token = client.exchange_code_for_token(
                    client_id=self.server.client_id,
                    client_secret=self.server.client_secret,
                    code=code)
                self.server.logger.info(
                    "Exchanged code {} for access token {}".format(
                        code, access_token))
                self.wfile.write(
                    six.b("Access Token: {}\n".format(access_token)))
            else:
                self.server.logger.error("No code param received.")
                self.wfile.write(six.b("ERROR: No code param recevied.\n"))
        else:
            url = client.authorization_url(
                client_id=self.server.client_id,
                redirect_uri='http://localhost:{}/authorization'.format(
                    self.server.server_port))

            self.send_response(302)
            self.send_header(six.b("Content-type"), six.b("text/plain"))
            self.send_header(six.b('Location'), six.b(url))
            self.end_headers()
            self.wfile.write(six.b("Redirect to URL: {}\n".format(url)))
Example #42
0
    def do_GET(self):
        # when we are called with a GET we want to get the "code" from the
        # request string
        code=""
        splits=self.path.split("&")
        for s in splits:
            if s.startswith("code="):
                code=s.split("code=")[1]

        assert code

        # Let's just do the dirty and do the auth inline with the request...
        # It's not like we expect a lot of traffic anyway.
        client = Client()
        access_token = client.exchange_code_for_token(client_id=CLIENT_ID,
                                              client_secret=CLIENT_SECRET,
                                              code=code)

        with open(".hurtlocker", "w") as thefile:
            thefile.write(json.dumps(access_token))

        if access_token:
            self.server.stop()
Example #43
0
    def do_GET(self):
        querystring = urlparse(self.path).query
        params = parse_qs(querystring)

        client = Client()
        token_data = client.exchange_code_for_token(
            client_id=CLIENT_ID,
            client_secret=CLIENT_SECRET,
            code=params['code'][0])

        # Write credentials to disk. Use the simplest pickle protocol
        # to keep it human-readable.
        with open(STRAVA_CREDENTIALS_FILE, 'wb') as f:
            pickle.dump(token_data, f, 0)

        self.send_response(200)
        self.send_header('Content-type', 'text/html')
        self.end_headers()
        self.wfile.write(
            ('This message means you have been successfully authenticated.'
             '\n\nYou can now close this page.').encode("utf-8"))
        print('Authentication succeeded')
        print('Credentials have been saved to %s' % STRAVA_CREDENTIALS_FILE)
Example #44
0
def auth(request):
    global _loginId
    print("Auth")
    code = request.GET.get('code')
    print("code=", code)
    scope = request.GET.get('scope')
    print("scope=", scope)
    login = get_object_or_404(Login, pk=_loginId)
    client = Client()
    access_token = client.exchange_code_for_token(
        client_id=login.clientID, client_secret=login.clientSecret, code=code)
    print("access_token=", access_token)
    user = client.get_athlete()
    strUser = StravaUser.objects.filter(uid=user.id)
    if not strUser.exists():
        print('create user', )
        strUser = StravaUser(uid=user.id, lastname=user.lastname, firstname=user.firstname, \
            lastUpdate=(datetime.now()-timedelta(days=30)), token=access_token)
        strUser.save()
    else:
        strUser.update(token=access_token)
    request.session['access_token'] = access_token
    #request.session['access_token'] = 'ff4f273a775a57ce1c7dcc837e18a059370d338c'
    return redirect('/strava2/activities')
from config import *

from stravalib import Client
import sys

client = Client()

if len( sys.argv ) == 1:

  url = client.authorization_url(client_id=STRAVA_CLIENT_ID,
                                           redirect_uri='http://localhost', scope='view_private,write' )
  print "Paste this URL in your browser:"
  print
  print url
  print
  print "And then re-run this script like so: "
  print "\t" + sys.argv[0] + " <code>"

elif sys.argv[1] == 'test':
  client = Client( access_token=STRAVA_ACCESS_TOKEN)
  print client.get_athlete()

else:
  code = sys.argv[1]
  access_token = client.exchange_code_for_token(client_id=STRAVA_CLIENT_ID,
                                                client_secret=STRAVA_CLIENT_SECRET,
                                                code=code)
  print "Your Strava access token is: " + access_token
Example #46
0
from stravalib import Client
client = Client()

CLIENT_ID = "CLIENT ID"
CLIENT_SECRET = "CLIENT SECRET"

url = client.authorization_url(
    client_id=CLIENT_ID,
    scope="write",
    redirect_uri='http://localhost')
# Go to that URL and retrieve the code
print(url)

CODE = "PUT THE CODE HERE"

access_token = client.exchange_code_for_token(
    client_id=CLIENT_ID,
    client_secret=CLIENT_SECRET,
    code=CODE)

print(access_token)
Example #47
0
def authorization(request):
    client = Client()
    code = request.GET['code']
    access_token = client.exchange_code_for_token(client_id=MY_STRAVA_CLIENT_ID, client_secret=MY_STRAVA_CLIENT_SECRET, code=code)   
    
    # making a global variable to be used across views. don't know how this will work in practice
    
    client = Client(access_token=access_token)
    athlete = client.get_athlete() # Get current athlete details
    
    global athleteId 
    athleteId = athlete.id
    
    # if athlete doesn't exist, add them
    if len(Athlete.objects.filter(athleteId=athleteId)) == 0:
        ath = Athlete.objects.create(name=str(athlete.firstname+' '+athlete.lastname), athleteId=athleteId, profilePic=athlete.profile, city=athlete.city, country=athlete.country, sex=athlete.sex, premium=athlete.premium, created_at=athlete.created_at, updated_at=athlete.updated_at, followers=athlete.follower_count, friends=athlete.friend_count, email=athlete.email, weight=athlete.weight, meas_pref=athlete.measurement_preference, runsSummary = DataFrame({}).to_json(orient='records'), fitLines = DataFrame({}).to_json(orient='records'), masterList = DataFrame({}).to_json(orient='records'))

        ath.profilePic.name = "rudyzPic"
        ath.save(update_fields=['profilePic'])
 
    # if athlete already exists, draw their file
    elif len(Athlete.objects.filter(athleteId=athleteId)) == 1:
        ath = Athlete.objects.get(athleteId=athleteId)
           
    ############################################ 
    ##### compiling new runs, updating summary
        
    # athlete's existing runs summary   
    existingSummary = DataFrame(pd.read_json(ath.runsSummary))
    existingFitlines = DataFrame(pd.read_json(ath.fitLines)) 
    masterList = DataFrame(pd.read_json(ath.masterList))
     
    activities = list(client.get_activities()) 
    
    # activity IDs of runs already in the system
    try:
        ids = existingSummary.activityId
    except AttributeError:
        ids = []
         
    for i in range(len(activities)):   
    #for i in range(30,37):
        # Ignoring activities already in the system 
        if (len(ids) == 0) or (float(activities[i].id) not in list(ids)):
            
            try:
                # compiling df for raw json-ization
                activityId = activities[i].id
                run = client.get_activity_streams(activityId, types=['time','latlng','distance','heartrate','altitude','cadence'])
                latlng = run['latlng'].data
                time = run['time'].data
                distance = run['distance'].data
                heartrate = run['heartrate'].data
                altitude = run['altitude'].data
                cadence = run['cadence'].data
                date = activities[i].start_date_local 
                activity = activityId   
                dfi = thresher.assemble(date, activityId, heartrate, distance, time, altitude, latlng, cadence) 
                
                
                # basic cleanup, only removing totally unreasonable values
                dfi = thresher.basicClean(dfi)


                # if we ever want to try our hand at improving strava's speed data (ie by predicting speed when GPS blanks), intervene here:
                    
                #dfi = thresher.addDistDeltas(dfi)
                             
                                        
                try: 
                    fitline = thresher.getFitlineLws(dfi) # this adds speed-shifted columns
                except:
                    fitline = pd.DataFrame({})
                    
                try:
                    mafScore = fitline[fitline.hr == 140.0].avgSpeed.iloc[0]
                    print "MAF "
                    print mafScore
                except:
                    mafScore = np.nan
                    
                fitline_json = fitline.to_json(orient='records')
                
                 # getting summary info for run (as one-entry dict)
                runSummary = thresher.getSingleSummaryDf(dfi)
                
                # adding mafScore to summary
                runSummary['mafScore'] = mafScore
                
                print runSummary
                
                # adding predicted hr and speed values
                #dfi = thresher.getPred(dfi)

                # saving entry to database
                Activity.objects.create(act_id = activityId, name=str(activities[i].name), description=activities[i].description, act_type=activities[i].type, date=activities[i].start_date_local, timezone=activities[i].timezone, df=dfi.to_json(orient='records'), avgHr=runSummary['avgHr'], hrVar=runSummary['variation'], realMiles=runSummary['realMiles'], recovery=runSummary['recovery'], easy=runSummary['easy'], stamina=runSummary['stamina'], impulse=runSummary['impulse'], totalTime=runSummary['totalTime'], totalDist=runSummary['totalDist'], climb=runSummary['climb'], fitline=fitline_json, mafScore=mafScore, athlete=ath)
                
                # updating runs summary
                existingSummary = existingSummary.append(runSummary, ignore_index=True)
                existingFitlines = existingFitlines.append(fitline, ignore_index=True)
                masterList = masterList.append(dfi, ignore_index=True)
                
            except:
                continue    
    
    
    # saving updated runs summary to athlete profile
    ath.runsSummary = existingSummary.to_json(orient='records')
    ath.save(update_fields=['runsSummary'])
    
    existingSummary.to_pickle("runsSummary.txt")
    
    # saving updated runs summary to athlete profile
    ath.fitLines = existingFitlines.to_json(orient='records')
    ath.save(update_fields=['fitLines'])
    
    ath.masterList = masterList.to_json(orient='records')
    ath.save(update_fields=['masterList'])
    
    # testing...
    existingSummary = pd.read_json(ath.runsSummary)
    #print(existingSummary)
    
    existingFitlines = pd.read_json(ath.fitLines)
    #print(existingFitlines)

    
    global path
    path = os.path.dirname(__file__)
    # updating dataframe, pickling for use in other views
    #global df
    #df = thresher.masterAssemble(client) 
    
    masterDf = pd.read_json(ath.masterList)
    #print(masterDf)
    masterDf.to_pickle(str(path)+"/"+str(athlete.id)+"masterDf.txt")

    return render(request, 'stravaChimp/authorization.html', {'code':code, 'access_token':access_token, 'athleteId':athleteId})