Beispiel #1
0
class Strava:
    def __init__(self, token):
        self._token = token
        self._client = None
        self._verbose = True

    def connect(self):
        self._client = Client()
        token = self._token

        refresh_response = self._client.refresh_access_token(
            client_id=token['client_id'],
            client_secret=token['client_secret'],
            refresh_token=token['refresh_token'])

        token.update(refresh_response)
        self._token = token

        athlete = self._client.get_athlete()
        if self._verbose:
            logger.info("Connected to STRAVA as athelete \"{} {}\"".format(
                athlete.firstname, athlete.lastname))

        return self._token

    def set_weight(self, weight):
        self._client.update_athlete(weight=weight)

    @property
    def client(self):
        return self._client
Beispiel #2
0
def map():
    #return to index if user has no session cookie
    if not session:
        return redirect(request.url_root+'authenticate', code=302)
    
    #redirect to reauthenticate if token has expired
    if time.time() > session['expires_at']:
        return redirect(request.url_root+'authenticate', code=302)

    # create strava client and pull activities
    client = Client(session['access_token'])
    activities=list(client.get_activities())

    # add polylines
    gmap = gmplot.GoogleMapPlotter(0,0, 12,config.google_api_key)
    for i in reversed(range(len(activities))):
        try:
            pl=polyline.decode(activities[i].to_dict()['map']['summary_polyline'])
            lats,longs=zip(*pl)
            gmap.plot(lats,longs, 'cornflowerblue', edge_width=4)#,edge_alpha=0.3)
        except:
            print('no polyline for '+activities[i].to_dict()['name'])
    gmap.center = (mean(lats),mean(longs))

    #output maps html file and load back in as string form(kinda hacky since the draw() function only outputs files)
    file_name=str(session['athlete_id'])+'.html'
    os.chdir('/tmp')
    gmap.draw(file_name)
    with open(file_name, 'r') as map_file:
        html_string = map_file.read()
    os.remove(file_name)
    return html_string
    def handle(self, *args, **options):
        self.stdout.write("Updating the Acacia event miles")

        client = Client()
        rides_after = datetime(2018, 9, 1)
        rides_before = datetime(2018, 9, 3)

        participants = BigBulletRider.objects.exclude(
            access_token__isnull=True)
        for particpant in participants:
            self.stdout.write("Looking up activities for " +
                              str(particpant.name))

            client.access_token = particpant.access_token
            activities = client.get_activities(before=rides_before,
                                               after=rides_after)

            for activity in activities:
                km = unithelper.kilometers(activity.distance).num
                self.stdout.write("Got activity " + str(activity.id) +
                                  " distance = " + str(km) + " = " +
                                  str(activity))
                ride, created = BigBulletRide.objects.get_or_create(
                    activity_id=activity.id,
                    bullet=particpant,
                    distance=km,
                    start_date=activity.start_date)
                self.stdout.write("Created = " + str(created))
    def get(request):
        """ Request -and store- a strava access token. """
        client = Client()

        # Extract the code from the response
        code = request.GET.get('code')
        access_token = client.exchange_code_for_token(
            client_id=settings.STRAVA_CLIENT_ID,
            client_secret=settings.STRAVA_CLIENT_SECRET,
            code=code
        )
        strava_athlete = client.get_athlete()

        try:
            athlete = Athlete.objects.get(strava_id=strava_athlete.id)
            athlete.strava_token = access_token
        except Athlete.DoesNotExist:
            athlete = Athlete(strava_id=strava_athlete.id, strava_token=access_token)
        athlete.save()

        cache_key = _get_cache_key(request)
        cache.delete(cache_key)
        redir_url = '{}?start_date={}&end_date={}'.format(
            reverse_lazy('strava-summary'),
            _get_start_date(request),
            _get_end_date(request)
        )
        return HttpResponseRedirect(redir_url)
Beispiel #5
0
def freshness():
    c = Client(access_token=session['token'])
    try:
        limit = int(request.args.get("limit"))
    except (TypeError, ValueError):
        limit = None

    activities = list(c.get_activities(limit=limit))

    date = activities[-1].start_date.date()
    dates = []
    week_vals = []
    month_vals = []
    while date <= datetime.datetime.now().date():
        dates.append(datetime.datetime.combine(date, datetime.datetime.min.time()))
        min_week_date = date - datetime.timedelta(days=7)
        min_month_date = date - datetime.timedelta(days=30)
        M_PER_MILE = 1609
        week_vals.append(sum(float(a.distance) / M_PER_MILE for a in activities if a.start_date.date() <= date and a.start_date.date() > min_week_date))
        month_vals.append((7 / 30.0) * sum(float(a.distance) / M_PER_MILE for a in activities if a.start_date.date() <= date and a.start_date.date() > min_month_date))

        date += datetime.timedelta(days=1)

    data = [dates, week_vals, month_vals]
    return render_template('freshness.html', data=data)
Beispiel #6
0
def api_profiles_activities_id(player_id, activity_id):
    if not request.stream:
        return '', 400
    activity_id = int(activity_id) & 0xffffffffffffffff
    activity = activity_pb2.Activity()
    activity.ParseFromString(request.stream.read())
    update_protobuf_in_db('activity', activity, activity_id)

    response = '{"id":%s}' % activity_id
    if request.args.get('upload-to-strava') != 'true':
        return response, 200
    try:
        from stravalib.client import Client
    except ImportError:
        logger.warn(
            "stravalib is not installed. Skipping Strava upload attempt.")
        return response, 200
    strava = Client()
    try:
        with open('%s/strava_token.txt' % STORAGE_DIR, 'r') as f:
            strava.access_token = f.read().rstrip('\r\n')
    except:
        logger.warn(
            "Failed to read %s/strava_token.txt. Skipping Strava upload attempt."
        )
        return response, 200
    try:
        # See if there's internet to upload to Strava
        strava.upload_activity(BytesIO(activity.fit),
                               data_type='fit',
                               name=activity.name)
        # XXX: assume the upload succeeds on strava's end. not checking on it.
    except:
        logger.warn("Strava upload failed. No internet?")
    return response, 200
def get_runs(request, n):
    """ Get most recent n runs associated with an account.
    """

    # Our admin object
    admin = _get_admin(request)

    # Be sure it exists
    if not admin.exists_document('strava_access_token'):
        request.response.status_int = 403
        return

    # Get the access token
    access_token = admin.get_document('strava_access_token')

    running_docs = {
        a: admin.get_document(a)
        for a in admin.list_documents() if a.startswith('run_')
    }

    strava_client = StravaClient(
        access_token=access_token['strava_access_token'])

    runs = []
    for a in strava_client.get_activities():
        if 'run_' + str(a.id) in running_docs:
            run = running_docs['run_' + str(a.id)]
        else:
            run = {
                'id': a.id,
                'timestamp': a.start_date_local.isoformat(),
                'duration': a.elapsed_time.total_seconds(),
                'distance': unithelper.miles(a.distance).num,
                'name': a.name,
                'description': a.description
            }
            if a.map.summary_polyline is not None:
                run['map_polyline'] = a.map.summary_polyline
            if a.start_latlng is not None and a.start_date is not None and 'darksky' in request.registry.settings[
                    'secrets']:
                fio = ForecastIO.ForecastIO(
                    request.registry.settings['secrets']['darksky']
                    ['darksky_secret'],
                    units=ForecastIO.ForecastIO.UNITS_US,
                    latitude=float(a.start_latlng[0]),
                    longitude=float(a.start_latlng[1]),
                    time=str(int(time.mktime(a.start_date.timetuple()))))
                if fio.has_currently():
                    currently = FIOCurrently.FIOCurrently(fio)
                    run['temperature'] = currently.temperature
                    run['weather_icon'] = currently.icon
            admin.create_document(run, doc_id='run_' + str(a.id))

        runs.append(run)
        if n is not None and len(runs) == n:
            break

    # Return appropriately
    request.response.status_int = 200
    return {'runs': runs}
Beispiel #8
0
def login():
    client = Client()
    authorize_url = client.authorization_url(
        client_id=CONSTANTS.CLIENT_ID, redirect_uri=CONSTANTS.CALLBACK_URL)
    # Have the user click the authorization URL,
    # a 'code' param will be added to the redirect_uris
    return jsonify({"status": "success", "url": authorize_url})
Beispiel #9
0
def make_authorization_url():
    client = Client()
    authorize_url = client.authorization_url(client_id=CLIENT_ID,
                                             redirect_uri=REDIRECT_URI,
                                             scope='view_private,write')
    print(authorize_url)
    return authorize_url
Beispiel #10
0
    def __init__(self):
        self.client = Client()
        self.API_CALL_PAUSE_SECONDS = 1.5  # 40 requests per minute

        # the self-authorization is NOT working right now -- using hard-coded URL / ACCESS_CODE right now
        #url = self.client.authorization_url(client_id=CLIENT_ID,
        #                       redirect_uri='http://localhost:5000/authorization')
        #code = request.args.get('code') # or whatever flask does

        #url = 'http://www.strava.com/oauth/authorize?client_id=16424&response_type=code&redirect_uri=http://localhost/5001&approval_prompt=force&scope=write'
        #print(url)

        access_token = self.client.exchange_code_for_token(
            client_id=CLIENT_ID, client_secret=CLIENT_SECRET, code=ACCESS_CODE)
        # Now store that access token somewhere (a database?)
        self.client.access_token = access_token

        # retrieve the athlete
        self.athlete = self.client.get_athlete()
        print("For {}, I now have an access token".format(self.athlete.id))

        # name of tables in model
        self.user_TBL = 'users'
        self.activity_TBL = 'activities'
        self.streams_TBL = 'streams'
        self.gear_TBL = 'gear'

        # streams to extract from strava
        self.streams = [
            'time', 'latlng', 'distance', 'altitude', 'velocity_smooth',
            'heartrate', 'cadence', 'temp', 'moving', 'grade_smooth'
        ]
def get_runs(request, n):
    """ Get most recent n runs associated with an account.
    """

    # Our admin object
    admin = _get_admin(request)

    # Be sure it exists
    if not admin.exists_document('strava_access_token'):
        request.response.status_int = 403
        return

    # Get the access token
    access_token = admin.get_document('strava_access_token')

    running_docs = {
        a:admin.get_document(a) for a in admin.list_documents() if a.startswith('run_')
    }

    strava_client = StravaClient(access_token=access_token['strava_access_token'])

    runs = []
    for a in strava_client.get_activities():
        if 'run_' + str(a.id) in running_docs:
            run = running_docs['run_' + str(a.id)]
        else:
            run = {
                'id': a.id,
                'timestamp': a.start_date_local.isoformat(),
                'duration': a.elapsed_time.total_seconds(),
                'distance': unithelper.miles(a.distance).num,
                'name': a.name,
                'description': a.description
            }
            if a.map.summary_polyline is not None:
                run['map_polyline'] = a.map.summary_polyline
            if a.start_latlng is not None and a.start_date is not None and 'darksky' in request.registry.settings['secrets']:
                fio = ForecastIO.ForecastIO(
                    request.registry.settings['secrets']['darksky']['darksky_secret'],
                    units=ForecastIO.ForecastIO.UNITS_US,
                    latitude=float(a.start_latlng[0]),
                    longitude=float(a.start_latlng[1]),
                    time=str(int(time.mktime(a.start_date.timetuple())))
                )
                if fio.has_currently():
                    currently = FIOCurrently.FIOCurrently(fio)
                    run['temperature'] = currently.temperature
                    run['weather_icon'] = currently.icon
            admin.create_document(run, doc_id='run_' + str(a.id))

        runs.append(run)
        if n is not None and len(runs) == n:
            break

    # Return appropriately
    request.response.status_int = 200
    return {
        'runs':
            runs
    }
Beispiel #12
0
def strava_upload(tcxfiles, login=None):
    logging.basicConfig(level=logging.DEBUG)

    client = Client()

    creds = read_strava_auth_file()
    if login == None:
      if len(creds) > 0:
        print("found strava credentials for: " )
        n = 0
        for email in creds.keys():
          print(str(n) + " " + email)
          n += 1
   
        index_input = raw_input("enter the number corresponding to your email address.  Or just press enter to use your default browser to login\n")
        if re.match("\A\d+\Z", index_input):
          index = int(index_input)
          if index < len(creds):
            login = creds.keys()[index]
    
    if login and creds.has_key(login):
      client.access_token = creds[login]
    else:
      strava_authorize(client)

    for tcxfile in tcxfiles:
      r = post_file_to_strava(client, tcxfile)
      if(r.status_code == 401):
        print("invalid auth token, rerequesting authorization")
        strava_authorize(client)
        r = post_file_to_strava(client, tcxfile)

      if(r.status_code not in [200,201]):
        print("error uploading file.  HTTP response code: " + str(r.status_code))
        print(str(r.text))
Beispiel #13
0
def rides(request):

    if (not request.user.is_authenticated):
        return JsonResponse({"user_auth": False})

    client = Client()
    user = AuthUser.objects.get(user_id=request.user.id)
    client.access_token = user.auth_code

    _before = datetime.now()
    _after = datetime(2018, 4, 1)

    batched_activities = client.get_activities(before=_before, after=_after)
    list_activities = list(batched_activities)
    rtn_activity_list = []

    for a in list_activities:
        detailed_activity = client.get_activity(a.id)
        _new_activity = JsonActivity(detailed_activity.id, detailed_activity.map.polyline, a.distance, a.start_date)
        rtn_activity_list.append(_new_activity.toJson())
    
    rtn = {
        "user_auth": True,
        "activities": rtn_activity_list
    }

    return JsonResponse(rtn)
Beispiel #14
0
def create_context():
    token_struct = session.get('token_struct')
    if token_struct == None:
        raise NoToken

    try:
        access_token = token_struct['access_token']
    except KeyError:
        raise NoToken

    client = Client(access_token=access_token)
    try:
        refresh_token(client)
        athlete = client.get_athlete()
    except AccessUnauthorized:
        raise

    athlete_dir = os.path.join(current_app.instance_path, 'athletes',
                               str(athlete.id))
    if not os.path.isdir(athlete_dir):
        make_dirs(athlete_dir)

    with open(os.path.join(athlete_dir, 'athlete.json'), 'w') as f:
        json.dump(athlete.to_dict(), f)

    return client, athlete
Beispiel #15
0
def strava_authorize_url(page=None):
    client = Client()
    url = url_for('query.authorized', _external=True, page=page)
    return client.authorization_url(
        scope=['profile:read_all', 'activity:read_all'],
        client_id=CLIENT_ID,
        redirect_uri=url)
    def handle(self, *args, **options):
        settings_obj = Site.objects.get_current().settings

        self.stdout.write("Updating the Strava cache...")
        if settings.STRAVA_ACCESS_TOKEN == None:
            self.stdout.write("You must set STRAVA_ACCESS_TOKEN")
            return

        client = Client()
        client.access_token = settings.STRAVA_ACCESS_TOKEN

        if settings.STRAVA_CYCLING_CLUB != 0:
            cycling_club = client.get_club(settings.STRAVA_CYCLING_CLUB)
            self.stdout.write("Got this many cyclists = " +
                              str(cycling_club.member_count))
            settings_obj.cyclists = cycling_club.member_count

    #        self.stdout.write("Getting cycling activities")
    #        cycling_activities = client.get_club_activities(settings.STRAVA_CYCLING_CLUB)	# Just get all of them, database can dedupe
    #        self.insert_into_db(cycling_activities, ActivityCache.RIDE)

        if settings.STRAVA_RUNNING_CLUB != 0:
            running_club = client.get_club(settings.STRAVA_RUNNING_CLUB)
            self.stdout.write("Got this many runners = " +
                              str(running_club.member_count))
            settings_obj.runners = running_club.member_count

    #        self.stdout.write("Getting running activities")
    #        running_activities = client.get_club_activities(settings.STRAVA_RUNNING_CLUB)
    #        self.insert_into_db(running_activities, ActivityCache.RUN)

        settings_obj.save()
Beispiel #17
0
def upload_activity(uid=None, file_name=None):
    try:
        strava_token = ref.child("users").child(uid).child(
            "strava_token").get().val()
        print(strava_token)

        c = StravaClient(access_token=strava_token)

        file_name += ".gpx"

        url = storageRef.child("users").child(uid).child("gpx").child(
            file_name).get_url(None)
        gcontext = ssl.SSLContext(ssl.PROTOCOL_TLSv1)  # Only for gangstars
        url_response = urllib.request.urlopen(url, context=gcontext)
        data = url_response.read()
        parsed_data = data.decode('utf-8')

        c.upload_activity(parsed_data, 'gpx')

        return json.dumps({'locationSuccess': True}), 200, {
            'Content-Type': 'text/javascript; charset=utf-8'
        }

    except KeyError:
        return json.dumps({'locationSuccess': False}), 403, {
            'Content-Type': 'text/javascript; charset=utf-8'
        }
Beispiel #18
0
def index():
    #if the user has already used the app(and has a cookie saved)
    if session:
        #if user is already authenticated and not expired
        if (time.time() < session['expires_at']):
            return render_template('index.html',auth_link=request.url_root+'map') 
        #if the user's token is expired, refresh the oken  
        else:
           token = refresh_token(session['refresh_token'])
    
    #if a code is being returned
    if request.args.get('code'):
        #take code and convert to token
        code = request.args.get('code')
        token = token_exchange(code)

    # if this is the user's first visit, load page for authentication
    else: 
        return render_template('index.html',auth_link=request.url_root+'authenticate')
    
    #store token and athlete_id in flask session
    session.clear()
    client = Client(token['access_token'])
    athlete_id = client.get_athlete().id
    session['athlete_id'] = athlete_id
    session['expires_at'] = token['expires_at']
    session['access_token'] = token['access_token']
    session['refresh_token'] = token['refresh_token']
    session['code'] = code
       
    #send to map page
    return redirect(request.url_root+'map', code=302)  
    def collect_ride_data(self, challenge):
        """
        Pull the latest ride data from Strava via the API
        """
        client = Client()
        client.access_token = self.strava_config['access-token']
        #activities = client.get_club_activities(165009)
        activities = client.get_club_activities(challenge.get_group_id())

        act_list = []
        for activity in activities:
            if not activity.type == 'Ride' and not activity.type == 'VirtualRide':
                print 'Non-ride activity: %s, type: %s' % (activity.name, activity.type)
                continue
            act = Activity(activity.id)
            act.set_athlete(activity.athlete.id)
            act.set_name(activity.name)
            act.set_gmt_date(activity.start_date) # GMT Start date
            act.set_elapsed_time(activity.elapsed_time)
            act.set_distance(round(unithelper.kilometers(activity.distance).num, 2))
            act.set_elevation(unithelper.meters(activity.total_elevation_gain).num)
            act.set_ride_type(activity.type)
            act.set_trainer_ride(activity.trainer)
            act_list.append(act)
        db_store = GTDataStore(challenge.get_db_path(), self.verbose)
        db_store.store_if_new(act_list)
def authenticate():

    ## Strava API uses OAuth2, which requires users to manually allow permission, which generates
    ## a token only valid for a number of hours.

    ## get API client id and secret from config file

    config = configparser.ConfigParser()
    config.read("credentials.cfg")
    client_id = config.get('credentials', 'client_id')
    client_secret = config.get('credentials', 'client_secret')

    client = Client(rate_limiter=limiter.DefaultRateLimiter())
    authorize_url = client.authorization_url(
        client_id=client_id, redirect_uri='http://localhost:8282/authorized')

    ## getting token -- pretty manual process for now

    webbrowser.open_new_tab(authorize_url)

    code = input('Enter Temporary Code: ')
    code = str(code)

    ## authenticate using API credntials + token

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

    return client
Beispiel #21
0
def login():
    c = Client()
    url = c.authorization_url(client_id=app.config['STRAVA_CLIENT_ID'],
                              redirect_uri=url_for('.logged_in',
                                                   _external=True),
                              approval_prompt='auto')
    return render_template('login.html', authorize_url=url)
Beispiel #22
0
def get_authorization_url():
    client = Client()
    return client.authorization_url(
        client_id=STRAVA_CLIENT_ID,
        redirect_uri=url_for("authenticate", _external=True),
        scope=["activity:write", "activity:read_all"],
    )
Beispiel #23
0
def get_strava_api(secret, ID):
    all_act = []
    client = Client(access_token=secret)
    tot = total_num(client)

    me = client.get_athlete(ID)
    activities = client.get_activities()

    for i in trange(tot):
        df = pd.DataFrame()
        _a = activities.next()

        _streams = client.get_activity_streams(_a.id, types=types)
        for item in types:
            if item in _streams.keys():
                df[item] = pd.Series(_streams[item].data, index=None)
            df['act_id'] = _a.id
            df['act_name'] = _a.name
            df['act_type'] = _a.type

        df['lat'] = map(split_lat, (df['latlng']))
        df['lon'] = map(split_long, (df['latlng']))
        df['time'] = df['distance'] / (df['velocity_smooth'])
        df.fillna(0)
        all_act.append(df)
        del df

    with open(save_file + '.pkl', 'wb') as fp:
        pickle.dump(all_act, fp)

    pd.concat(all_act, ignore_index=True).to_csv(save_file + '.csv')

    return all_act
Beispiel #24
0
def parse_input_to_map(access_token):
    client = Client(access_token)
    all_activities = client.get_activities()
    date_activities_map = {}
    for activity in all_activities:
        date = str(activity.start_date)[0:10]
        date_formated = datetime.datetime.strptime(str(date),
                                                   "%Y-%m-%d").date()
        # group activities by weeks with monday date as a key
        monday = date_formated - datetime.timedelta(date_formated.weekday())
        if monday in date_activities_map:
            date_found = False
            for day_activity in date_activities_map[monday]:
                if date_formated in day_activity:
                    day_activity[date_formated].append(activity)
                    date_found = True
                    break
            if not date_found:
                date_activities_map[monday].append({date_formated: [activity]})
        else:
            date_activities_map[monday] = [{
                date_formated: [activity]
            }]
            # [{"2020-03-03": [Activity]}]
    print("Success! Activities from strava retrieved, start building table")
    print("Total number of weeks with at least 1 training:" +
          str(len(date_activities_map)))
    return date_activities_map
    def __init__(self, api_key=None, csv_path=None, df=None):
        self.api_key = api_key
        self.csv_path = csv_path
        self.df = df

        if self.api_key:
            self.client = Client(access_token=self.api_key)
Beispiel #26
0
class StravaData:
    RUNNER_ID = None
    ACCESS_TOKEN = None
    client = None

    def __init__(self, runner_id, access_token):
        self.RUNNER_ID = runner_id
        self.ACCESS_TOKEN = access_token
        self.client = Client()
        self.client.access_token = access_token

    def getAthlete(self):
        athlete = self.client.get_athlete()
        return athlete

    def getActivities(self):
        activities = self.client.get_activities()
        return activities

    def getActivity(self, id):
        activity = self.client.get_activity(id)
        return activity

    def getActivityStreams(self, id, types):
        streams = self.client.get_activity_streams(id,
                                                   types=types,
                                                   resolution='medium')
        return streams
Beispiel #27
0
    def __fetch_token(self):
        host = '127.0.0.1'
        port = 5000

        client = Client()
        url = client.authorization_url(
            client_id=self.__client_id,
            redirect_uri='http://127.0.0.1:5000/authorization')
        print("follow this link (ctrl-c to cancel): {}".format(url))

        client_id = self.__client_id
        secret = self.__secret

        class Handler(http.server.BaseHTTPRequestHandler):
            def do_GET(self):
                code = urllib.parse.parse_qs(
                    urllib.parse.urlparse(self.path).query).get('code',
                                                                None)[0]
                token = client.exchange_code_for_token(client_id=client_id,
                                                       client_secret=secret,
                                                       code=code)
                keyring.set_password('bike2cern', 'strava', token)

        s = http.server.HTTPServer((host, port), Handler)
        try:
            s.handle_request()
        except KeyboardInterrupt:
            pass
        s.server_close()
Beispiel #28
0
def send_run_to_strava():
    '''Ask whether to send a run to strava if it hasn't already.  Option to
    add a description.  Update on_strava field in database if successfully
    sent or prompted to do so if not sent.'''
    cfg.read(os.path.join(os.getenv('HOME'), '.config/strava.cfg'))
    access_token = cfg.get('Strava', 'access_token')
    client = Client()
    client.access_token = access_token
    runs = get_list_of_runs_not_on_strava()
    for run in runs:
        print run
        send = raw_input("Send this run to Strava? (Y|N): ")
        if (send[0] in ['Y', 'y']):
            start_time = raw_input(
                "What time did the activity start HH:MM:SS: ")
            date_of_activity = "%sT%sZ", (run.run_date, start_time)
            description = raw_input("Add an optional description: ")
            client.create_activity(run.name,
                                   ACTIVITY_TYPE,
                                   date_of_activity,
                                   run.time,
                                   description,
                                   unithelper.miles(run.distance))
            mark_run_as_on_strava(run.run_date, run.route_id, run.athlete_id)
            logging.info("Sent this activity to Strava: %s", run)
        else:
            update = raw_input("Update this run as on Strava (Y|N): ")
            if (update[0] in ['Y', 'y']):
                mark_run_as_on_strava(
                    run.run_date, run.route_id, run.athlete_id)
def get_token(client_id, client_secret, code):

    """Exchange a temporary code for a permanent token"""

    client = Client()
    response = client.exchange_code_for_token(client_id = client_id, client_secret = client_secret, code = code)

    print("[+] A new permanent token was generated, with the following details:\n\t- access token: {}\n\t- refresh access token: {}\n\t- expireS at: {}".format(response["access_token"], response["refresh_token"], response["expires_at"]))
Beispiel #30
0
def get_followers(request, id):
    followers = []
    if (request.user.userinfo != None):
        followers += [str(request.user.userinfo.athlete_id)]
        client = Client(access_token=request.user.userinfo.strava_code)
        for f in client.get_athlete_friends():
            followers += [str(f.id)]
    return HttpResponse(json.dumps(followers), content_type="application/json")
Beispiel #31
0
def make_client(client_id, client_secret, refresh_token):
    client = Client()

    refresh_response = client.refresh_access_token(
        client_id=client_id, client_secret=client_secret, refresh_token=refresh_token
    )
    client.access_token = refresh_response["access_token"]
    return client
Beispiel #32
0
    def get(self):
        code = self.request.get('code')

        client = Client()
        access_token = client.exchange_code_for_token(client_id=conf.SV_CLIENT_ID, client_secret=conf.SV_CLIENT_SECRET, code=code)

        user_id = UserManager().AddUserToken(access_token)
        self.redirect('/user/{0}'.format(user_id))
Beispiel #33
0
def auth_done(request):
    code = request.GET.get('code')
    client = Client()
    access_token = client.exchange_code_for_token(client_id=CLIENT_ID,
                                                  client_secret=CLIENT_SECRET,
                                                  code=code)
    request.session['access_token'] = access_token
    return redirect('home')
Beispiel #34
0
def login():
    params = {
        'client_id': CLIENT_ID,
        'redirect_uri': HOSTNAME + '/oauth_authorized/'
    }
    client = Client()
    url = client.authorization_url(**params)
    return redirect(url)
Beispiel #35
0
def main(ctx):
    client = Client()
    client.access_token = get_access_token()

    ctx.obj['client'] = client
    ctx.obj['athlete'] = client.get_athlete()

    ctx.obj['bikes'] = get_bikes(ctx.obj['athlete'])
Beispiel #36
0
def auth(request):
    client = Client()
    auth_link = client.authorization_url(
        5928, 'https://elevation-challenge.herokuapp.com/auth_success/')
    return render(request, 'auth.html', {
        'leaderboard': get_leaderboard(),
        'auth_link': auth_link
    })
Beispiel #37
0
def __get_strava_client(request):
    client = Client()
    if request.user:
        if request.user.social_auth:
            provider = request.user.social_auth.get(provider='strava')
            if provider:
                if 'access_token' in provider.extra_data.keys():
                    client.access_token = provider.extra_data['access_token']
    return client
    def _get_club_members():
        """ Get all athletes belonging to our club. """

        athlete = Athlete.objects.order_by('?').first()
        if not athlete:
            return []

        client = Client(access_token=athlete.strava_token)
        return client.get_club_members(settings.STRAVA_CHALLENGE_CLUB_ID)
Beispiel #39
0
def oauth_authorized():
    client = Client()
    code = request.args.get('code')
    access_token = client.exchange_code_for_token(
        client_id=CLIENT_ID,
        client_secret=CLIENT_SECRET,
        code=code)
    session['access_token'] = access_token
    return redirect(url_for('index'))
Beispiel #40
0
def authorization():
    code = request.args.get('code')
    client = Client()
    access_token = client.exchange_code_for_token(client_id=MY_STRAVA_CLIENT_ID,
                                                  client_secret=MY_STRAVA_CLIENT_SECRET,
                                                  code=code)
    response = redirect("/")
    response.set_cookie('access_token', access_token)
    return response
Beispiel #41
0
def get_images(segment_id):
    access_token = request.cookies.get('access_token')
    if not access_token:
        return redirect("/")
    client = Client(rate_limiter=limiter.DefaultRateLimiter())
    client.access_token = access_token

    # look into this: https://github.com/saimn/sigal/
    images = get_images_from_segment(segment_id, client)
    return render_template('test.html', images=images)
Beispiel #42
0
def auth():
    access_token = request.cookies.get('access_token')
    if access_token:
        # Success!
        return show_images_demo()
    else:
        client = Client()
        url = client.authorization_url(client_id=MY_STRAVA_CLIENT_ID, redirect_uri=DOMAIN + '/authorization')
        print("DEBUG: auth url :" + url)
        return redirect(url, code=302)
Beispiel #43
0
 def check_oauth_token(cls, access_token):
     if not access_token:
         return False
     c = Client()
     c.access_token = access_token
     try:
         c.get_athlete()
     except HTTPError:
         return False
     else:
         return True
Beispiel #44
0
def index():
    """Home authentication page
    """ 
    conn = get_conn()
    client_id, client_secret = get_app_credentials(conn)
    client    = Client() # stravalib v3
    auth_link = client.authorization_url(client_id, REDIRECT_URI, scope=AUTH_SCOPE)
    title = "STRAVA buddies | Please log in to STRAVA"
    
    conn.close()
    return render_template("index.html", title=title, auth_link=auth_link,
                           tab="authenticate", examples=cached_athletes)
Beispiel #45
0
def get_emails():
    email_list = []
    athletes = athlete.objects.all()
    for each_athlete in athletes: # for each athlete
        client = Client(access_token=each_athlete.access_token)
        this_athlete_email = client.get_athlete().email
        email_list.append(this_athlete_email)
    string_of_emails = ""
    for value in email_list:
        string_of_emails += str(value)
        string_of_emails += "; "
    print(string_of_emails)
Beispiel #46
0
    def get_user(self):
        client = Client()
        token = self.accessToken()

        if token is None:
            return None

        client.access_token = token
        athlete = client.get_athlete()
        return dict(first_name=athlete.firstname,
                    last_name=athlete.lastname,
                    email=athlete.email)
Beispiel #47
0
def auth():
    try:
        code = request.args["code"]
        c = Client()
        token = c.exchange_code_for_token(app.config['STRAVA_ID'], app.config['STRAVA_SECRET'], code)
    except (KeyError, requests.exceptions.HTTPError):
        return redirect("/")

    session["token"] = c.access_token = token
    a = c.get_athlete()  # Technically shouldn't be needed as the athlete details are returned in the oauth call
    session["athlete"] = {"firstname": a.firstname, "picture": a.profile_medium}
    return redirect("/")
Beispiel #48
0
    def get(self):
        client = Client()
        authorize_url = client.authorization_url(client_id=conf.SV_CLIENT_ID, redirect_uri=conf.SV_AUTH_URL)


        template_values = {
            'url': authorize_url,
            'url_linktext': 'Connect with STAVA'
        }

        template = JINJA_ENVIRONMENT.get_template('index.html')
        self.response.write(template.render(template_values))
def set_access_token(request):
    """ Exchange the provided code for an access token and store it
    """

    # Our strava code
    json = request.json_body
    code = json['code']

    # If we don't have a strava secret, we can't make the key exchange
    if 'strava' not in request.registry.settings['secrets']:
        request.response.status_int = 500
        return

    # Exchange the code for an access token
    # The API will throw an unspecified error if code is invalid.
    # Catch that rather than taking down the server.
    access_token = ""

    try:
        client = StravaClient()
        access_token = client.exchange_code_for_token(client_id=request.registry.settings['secrets']['strava']['strava_id'],
            client_secret=request.registry.settings['secrets']['strava']['strava_secret'],
            code=code)
    except:
        # Return an error
        request.response.status_int = 502
        return

    # Our admin object
    admin = _get_admin(request)

    #Create the access token if it doesn't exist, or update the stored one
    if not admin.exists_document('strava_access_token'):
        # Store the access token
        admin.create_document({'strava_access_token': access_token}, doc_id='strava_access_token')
    else:
        # Update the stored access token
        stored_access_token = admin.get_document('strava_access_token')
        try:
            admin.update_document({'strava_access_token': access_token, '_id':'strava_access_token', '_rev':stored_access_token['_rev']})
        except:
            # We likely hit a race condition where the _rev is no longer valid. Return accordingly.
            request.response.status_int = 409
            return
        

    # Return appropriately
    request.response.status_int = 200
    return {
        'access_token':
            access_token
    }
Beispiel #50
0
    def AddUserToken(self, token):
        client = Client(token)
        athlete = client.get_athlete()

        # Simplified logic not to add duplicate user tokens.
        # todo: check the user is not in the user token table.
        if self.GetMemcacheToken(athlete.id) is None:
            rider = UserToken(strava_id=athlete.id, strava_token=token)
            rider.put()

            memcache.add(self.GetMemcacheKey(athlete.id), token, 60)

        return athlete.id
Beispiel #51
0
def index(request):
	# Get KM cycled from Strava API 
	from stravalib.client import Client 
	from stravalib import unithelper
	strava = Client(settings.STRAVA_TOKEN)
	profile = strava.get_athlete(settings.STRAVA_ID)
	cycled = 0
	for b in profile.bikes: 
		cycled += float(b.distance) / 1000

	return render_to_response(
		'cv/index.html', 
		locals(),
		context_instance=RequestContext(request)
	)
    def get(request):
        """ Request oauth via strava. """

        client = Client()

        return_uri = 'http://{}{}?start_date={}&end_date={}'.format(
            request.META['HTTP_HOST'],
            reverse_lazy('strava-authorized'),
            request.GET.get('start_date'),
            request.GET.get('end_date'),
        )
        authorize_url = client.authorization_url(
            client_id=settings.STRAVA_CLIENT_ID,
            redirect_uri=return_uri
        )
        return HttpResponseRedirect(authorize_url)
Beispiel #53
0
def authorized():
	# get access token to make requests
	client = Client()
	code = request.args.get('code')
	client.access_token = client.exchange_code_for_token(client_id=creds.client_id, client_secret=creds.client_secret, code=code) # add id and secret

	# get data
	today = datetime.datetime.strptime(str(datetime.date.today()), "%Y-%m-%d")
	one_month_ago = today - dateutil.relativedelta.relativedelta(months=1)
	athlete = client.get_athlete()
	activities = client.get_activities(after=one_month_ago)
	rides = toolkit.get_activity_types(activities, 'ride')
	runs = toolkit.get_activity_types(activities, 'run')
	ride_set = ActivitySet("Rides", rides)
	run_set = ActivitySet("Runs", runs)
	return render_template('main.html', athlete=athlete, activity_sets=[ride_set, run_set])
Beispiel #54
0
    def __init__(self):
        self.client_id = current_app.config['STRAVA_CLIENT_ID']
        self.client_secret = current_app.config['STRAVA_CLIENT_SECRET']
        self.redirect_uri = url_for('strava.confirm_auth', _external=True)

        self.client = StravaClient()

        self._activity_type = 'ride'  # rides or runs
        self._activities = None
 def setUp(self):
     if not os.path.exists(TEST_CFG):
         raise Exception("Unable to run the write tests without a tests.ini that defines an access_token with write privs.")
     
     cfg = ConfigParser.SafeConfigParser()
     with open(TEST_CFG) as fp:
         cfg.readfp(fp, 'test.ini')  
         access_token = cfg.get('write_tests', 'access_token')
     
     self.client = Client(access_token=access_token)
Beispiel #56
0
def index():
    access_token = session.get('access_token')

    if access_token is None:
        return redirect(url_for('login'))

    client = Client(access_token=access_token)
    athlete = client.get_athlete() # client.protocol.get('/athletes/your_id')
    athlete_id = athlete.id
    # bo = 'hi'
    # kim = 'yo'
    # c = bo + kim
    stats_m = client.protocol.get('/athletes/' + str(athlete_id) + '/stats')

    stats_mi = {
        'run_distance': m_to_mi(stats_m['recent_run_totals']['distance']),
        'run_count': stats_m['recent_run_totals']['count'],
        'run_elevation': el(stats_m['recent_run_totals']['elevation_gain']),
        'run_pace': average_pace(stats_m['recent_run_totals']['distance'], stats_m['recent_run_totals']['moving_time']),
        'run_distance_ytd': m_to_mi(stats_m['ytd_run_totals']['distance']),
        'run_count_ytd': stats_m['ytd_run_totals']['count'],
        'run_elevation_ytd': el(stats_m['ytd_run_totals']['elevation_gain']),
        'run_pace_ytd': average_pace(stats_m['ytd_run_totals']['distance'], stats_m['ytd_run_totals']['moving_time']),
        'run_distance_all': m_to_mi(stats_m['all_run_totals']['distance']),
        'run_count_all': stats_m['all_run_totals']['count'],
        'run_elevation_all': el(stats_m['all_run_totals']['elevation_gain']),
        'run_pace_all': average_pace(stats_m['all_run_totals']['distance'], stats_m['all_run_totals']['moving_time']),
        'ride_distance': m_to_mi(stats_m['recent_ride_totals']['distance']),
        'ride_count': stats_m['recent_ride_totals']['count'],
        'ride_elevation': el(stats_m['recent_ride_totals']['elevation_gain']),
        'ride_speed': average_mph(stats_m['recent_ride_totals']['distance'], stats_m['recent_ride_totals']['moving_time']),
        'ride_distance_ytd': m_to_mi(stats_m['ytd_ride_totals']['distance']),
        'ride_count_ytd': stats_m['ytd_ride_totals']['count'],
        'ride_elevation_ytd': el(stats_m['ytd_ride_totals']['elevation_gain']),
        'ride_speed_ytd': average_mph(stats_m['ytd_ride_totals']['distance'], stats_m['ytd_ride_totals']['moving_time']),
        'ride_distance_all': m_to_mi(stats_m['all_ride_totals']['distance']),
        'ride_count_all': stats_m['all_ride_totals']['count'],
        'ride_elevation_all': el(stats_m['all_ride_totals']['elevation_gain']),
        'ride_speed_all': average_mph(stats_m['all_ride_totals']['distance'], stats_m['all_ride_totals']['moving_time']),
    }
    # raise Exception(stats_mi['run_distance'])

    return render_template('index.html', athlete=athlete, stats=stats_mi, athlete_id=athlete)
Beispiel #57
0
def mileage():
    c = Client(access_token=session["token"])
    limit = int(request.args.get("limit", 200))
    activity_models = list(c.get_activities(limit=limit))

    activities = []
    for a in activity_models:
        activities.append({
                           "name": a.name,
                           "distance": float(a.distance),
                           "time": a.moving_time.seconds,
                           "type": a.type,
                           "date": a.start_date.isoformat(),
                           "day": a.start_date.weekday()
                          })

    data = json.dumps(activities)

    return render_template('mileage.html', data=data)
Beispiel #58
0
	def handle(self, *args, **options):
		client = Client()
		client.access_token = '20bf9e2864c1411d17d9cab8c11aa8dbe626aedd'
		cityEntries = City.objects.all()
		resetPlaceChanges = False
		if not cityEntries:
			cityEntries = createDefaultCitySegments()
			resetPlaceChanges = True

		for city in cityEntries:
			updater = CityLeaderboardUpdater(city, client)
			updater.update()

		# Delete placement changes if data has just been reset
		if resetPlaceChanges:
			placementChanges = PlacementChange.objects.all()
			for pc in placementChanges.iterator():
				pc.delete()
		print("Updated at " + str(timezone.now()))
Beispiel #59
0
def fitness():
    c = Client(access_token=session["token"])

    try:
        limit = int(request.args.get("limit"))
    except (TypeError, ValueError):
        limit = None
    try:
        smooth = int(request.args.get("smooth")) / 2
    except (ValueError, TypeError):
        smooth = 3

    activities = list(c.get_activities(limit=limit))

    # Bit of a mess. Long run is 2. Old activities are 0, new activities are None
    ALLOWED_ACTIVITIES = [None, 0, 2, u"0", u"2"]

    activities = list(reversed([a for a in activities if a.average_heartrate and a.workout_type in ALLOWED_ACTIVITIES and a.type == "Run"]))

    activities = [a for a in activities if a.average_heartrate > 100 and 1000 * float(a.average_speed) / (a.average_heartrate - 60) < 80]  # Sanity for me

    vals = [1000 * float(a.average_speed) / (a.average_heartrate - 60) for a in activities]
    names = ["{} {}".format(a.name, a.start_date) for a in activities]

    smoothed_vals = []
    for index, val in enumerate(vals):
        slice = vals[max(0, index-smooth):index+smooth+1]
        smoothed_vals.append(sum(slice) / (0.0 + len(slice)))

    vals_and_dist = [(1000 * float(a.average_speed) / (a.average_heartrate - 60), float(a.distance)) for a in activities]
    dist_smoothed_vals = []
    for index, val in enumerate(vals):
        slice = vals_and_dist[max(0, index-smooth):index+smooth+1]
        tot = 0
        dist = 0
        for run in slice:
            tot += run[0] * run[1]
            dist += run[1]
        dist_smoothed_vals.append(tot / float(dist))

    data = [names, vals, smoothed_vals, dist_smoothed_vals]
    return render_template('fitness.html', data=data)