Beispiel #1
0
def home(request):
    if 'access_token' not in request.session:
        return redirect('auth')
    # Retrieving athlete's data from API
    client = Client(access_token=request.session.get('access_token'))
    athlete = client.get_athlete()
    # Checking if the athlete has already visited the site before
    try:
        db_athlete = Athlete.objects.get(id=athlete.id)
    except Athlete.DoesNotExist:
        db_athlete = Athlete.create(athlete)
        db_athlete.save()
    # Getting the latest activity from the current athlete
    try:
        latest_activity = Activity.objects.filter(athlete=db_athlete).latest('date')
        activities = client.get_activities(after=latest_activity.date)
    except Activity.DoesNotExist:
        activities = client.get_activities()
    # Adding new activities to the database
    for activity in activities:
        if not activity.manual:
            stream = client.get_activity_streams(activity.id, types=['latlng'], resolution='medium').get('latlng')
            db_activity = Activity.create(activity, db_athlete, stream.data)
            db_activity.save()
    return render(request, 'home.html', {'athlete': athlete, 'activities': activities, 'act_length': len(list(activities))})
Beispiel #2
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
Beispiel #3
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 #4
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)
    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_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 #7
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)
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 #9
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
Beispiel #10
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
def FetchGPSData(tokensFile,CPCdate,CPClen):
    client = Client()
    ###To get the saved access tokens below, I did the following:
    ##1. Run the following lines:
    #authorize_url = client.authorization_url(client_id=22380, redirect_uri='http://sustainability.leeds.ac.uk',approval_prompt='force')
    #print(authorize_url)
    ##2. Paste the above url into a browser, accept the request,
    ##   and copy the 'code' from the resulting url into the following line,
    ##   along with the client_secret which can be found under air pollution9 account on strava:
    #access_token = client.exchange_code_for_token(client_id=22380, client_secret='***',
    #  code='***')
    ##3. Extract token from the above variable:
    #print(access_token)
    ###Saved access tokens:
    f=open(tokensFile,'r')
    myTokens=f.read().splitlines()
    f.close()
    #Find activity which most closely matches CPC start date/time and sample length
    #All activities within 5 mins of the CPC start date are considered
    #The activity with the closest-matching elapsed time to the CPC sample length is then chosen
    validActs={}
    for i,token in enumerate(myTokens):
        client.access_token = token
        #athlete = client.get_athlete()
        #print(athlete.firstname,athlete.lastname+':')
        myActivities=client.get_activities()
        for activity in myActivities:
            startDate=activity.start_date_local
            #print('    '+activity.name+':',startDate,'Local time')
            if abs((CPCdate-startDate).total_seconds()) < 60:
                validActs.update({i:activity.id})
    assert len(validActs) > 0, "No GPS activities with a start time within 5 minutes of the CPC data file start time"
    DeltaT=1e10
    for key,value in validActs.items():
        client.access_token=myTokens[key]
        activity=client.get_activity(value)
        elap=activity.elapsed_time.seconds
        thisDT=abs(CPClen-elap)
        if thisDT < DeltaT:
            DeltaT=thisDT
            chosenAth=key
            chosenAct=value
    #Extract required data from chosen activity:
    client.access_token=myTokens[chosenAth]
    activity=client.get_activity(chosenAct)
    startDate=activity.start_date_local
    endDate=startDate+dt.timedelta(seconds=activity.elapsed_time.seconds)
    endDateCPC=CPCdate+dt.timedelta(seconds=CPClen)
    assert abs((endDateCPC-endDate).total_seconds()) < 60, "No valid GPS activities with an end time within 1 minute of the CPC data file end time"
    myTypes = ['time', 'latlng']
    myStream = client.get_activity_streams(chosenAct,types=myTypes)
    latlon=myStream['latlng'].data
    lat=[latlon[i][0] for i in range(len(latlon))]
    lon=[latlon[i][1] for i in range(len(latlon))]
    time=myStream['time'].data
    dateTime=[startDate+dt.timedelta(seconds=i) for i in time]
    GPSData=pd.DataFrame(data={'lon':lon,'lat':lat,'dateTime':dateTime})
    return GPSData
Beispiel #12
0
def get_total_miles(start, end, token):
    dotenv.load()
    client = Client(dotenv.get("STRAVA_TOKEN"))

    total_miles = 0
    for activity in client.get_activities(after=start, before=end):
        total_miles += unithelper.miles(activity.distance).num

    return int(total_miles)
Beispiel #13
0
def main():
    """this is the main function for the cycle mapping program. It calls everything else"""
    act_dict={}
    client=Client(access_token="ACCESS_TOKEN_HERE ")
    activities = client.get_activities(limit=1)
    for activity in activities:
        act_dict[activity.name]=activity.id
        streams = client.get_activity_streams(activity.id,types = ['time', 'latlng', 'altitude', 'heartrate', 'temp', ], resolution='medium')
        print(streams.keys())
    print(act_dict)
Beispiel #14
0
def pull_activities(access_token,
                    firstname,
                    lastname,
                    from_time="2018-01-01T00:00:00Z"):
    # An authorized callback is coming. Process it and add
    client = Client()
    client.access_token = access_token
    for activity in client.get_activities(after=from_time, limit=500):
        process_activity(activity, firstname, lastname)

    return True
Beispiel #15
0
def activities_to_dict(tokens):
    data = []
    for token in tokens:
        client_current = Client(access_token=token)
        activities = client_current.get_activities(limit=1000)
        for activity in activities:
            my_dict = activity.to_dict()
            data.append([my_dict.get(x) for x in cols])
        #make large dataframe for columns of interest for all tokens
    df = pd.DataFrame(data, columns=cols)
    #convert distance to miles
    df['miles_converted'] = [x/1609.3440122044242 for x in df['distance']]
    return df
Beispiel #16
0
    def get_strava_activities(self, strava_social, from_date=None):
        new_activities = []
        provider_name = 'strava'
        if self.relate_activities:
            existing_ids = self.activities.filter(
                provider=provider_name).values_list('original_id', flat=True)
        else:
            existing_ids = Activity.objects.filter(
                provider=provider_name).values_list('original_id', flat=True)

        # get access token
        token = strava_social.get_access_token(load_strategy())

        # get activity details
        client = Client()
        client.access_token = token

        query = client.get_activities(after=from_date)

        try:
            for strava_activity in query:
                strava_id = strava_activity.id
                if not strava_id in existing_ids:

                    new_activity = Activity()
                    new_activity.original_id = strava_id
                    new_activity.provider = provider_name

                else:
                    new_activity = self.activities.get(original_id=strava_id)

                new_activity.date = strava_activity.start_date_local
                new_activity.distance = strava_activity.distance
                new_activity.duration = strava_activity.elapsed_time
                new_activity.name = strava_activity.name
                new_activity.type = strava_activity.type

                if self.relate_activities:
                    new_activity.member = self
                else:
                    new_activity.member = None

                new_activity.save()

                new_activities.append(new_activity)
        except:
            print('User f{self} ha no permissions on strava')
            strava_social.delete()

        return new_activities
Beispiel #17
0
def get_strava_activities_by_user(user_id, days=None):
    user = User.objects.get(id=user_id)
    social = user.social_auth.filter(provider='strava')

    if not social.exists():
        return None

    strava = social.get()
    client = Client(access_token=strava.access_token)

    if days:
        end = arrow.utcnow()
        start = end.replace(days=(0-days))

        activity_iter = client.get_activities(
            before=end.datetime, after=start.datetime)
    else:
         activity_iter = client.get_activities()

    acts = []

    try:
        for activity in activity_iter:
            act, created = Activity.objects.get_or_create(
                external_id=activity.id, source=Activity.SOURCES.strava,
                user=user)

            act.update_with_strava(activity)
            acts.append(act)
    except HTTPError as e:
        strava.delete()

    check_for_needed_maintenance.delay(user_id)

    log_email('get_strava_activities_by_user',
              "Total {} added for user {}".format(len(acts), user.username))
Beispiel #18
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 #19
0
def index(request):

    url_strava = 'https://www.strava.com/oauth/authorize?client_id=13966&response_type=code&redirect_uri=http://maaxrun.pythonanywhere.com/authorization/&scope=write&state=mystate&approval_prompt=force'
    print(type(url_strava))
    date = datetime.now()

    username = None
    if request.user.is_authenticated():
        #username = request.user.username
        access_token = request.user.profile.user_token
        client = Client(access_token)
        athlete = client.get_athlete()
        id_runner = athlete.id

        elevation = 0
        best_speed = 0.0
        longest_run = 0.0
        # Activities can have many streams, you can request desired stream types

        for activity in client.get_activities(after="2016-01-01T00:00:00Z"):
            #print("{0.distance} {0.moving_time} {0.total_elevation_gain}".format(activity).encode('utf-8'))
            if activity.type == 'Run':
                elevation += float(activity.total_elevation_gain)
                if float(activity.distance
                         ) / activity.moving_time.total_seconds() > best_speed:
                    best_speed = float(
                        activity.distance
                    ) / activity.moving_time.total_seconds()
                if float(activity.distance) > longest_run:
                    longest_run = float(activity.distance)

        nb_everest = round(elevation / 8848, 2)
        nb_mtblanc = round(elevation / 4809, 2)
        longest_run = longest_run / 1000
        best_speed = round(best_speed * 3.6, 2)
        best_allure = 1 / (best_speed / 60)
        partie_entiere = int(best_allure)
        partie_decimale = int((best_allure - partie_entiere) * 60)
        if partie_decimale < 10:
            is_inf10 = 1
        else:
            is_inf10 = 0
        #best_allure = partie_entiere + partie_decimale
    else:
        print('error')

    return render(request, 'index.html', locals())
Beispiel #20
0
def main():
    access_token = input("access token: ")
    client = Client(access_token)

    activities = client.get_activities(limit=100)


    points = []    
    for activity in activities:
        activity = activity.to_dict()
        print("--------------")
        poly = activity['map']['summary_polyline']
        points.extend(polyline.decode(poly))


    all_routes = polyline.encode(points)
    print(all_routes)
Beispiel #21
0
def strava_last_activity(request):
    currentUser = User.objects.get(pk=request.user.id)

    client = Client()
    client.access_token = currentUser.profile.stravaAccessCode

    activities = client.get_activities(before=datetime.datetime.now(), limit=1)
    activityName = ''
    for activity in activities:
        activityName = activity.name
        downloadedActivity = client.get_activity(activity.id)
        activityStream = client.get_activity_streams(activity.id,
                                                     types=["time", "watts"])
        averageCadence = downloadedActivity.average_cadence

    return render(request, 'strava_last_activity.html',
                  {'activity_name': averageCadence})
def get_activities(access_token, output_file):
    
    """Retrieving all user activities and output them in CSV format"""

    client = Client()
    client.access_token = access_token

    filewriter = csv.writer(output_file, delimiter=",", quotechar="|", quoting=csv.QUOTE_MINIMAL)
    filewriter.writerow(["ID", "Name", "Distance", "Type", "Workout type", "Start date", "Was manually added", "Is private", "Gear ID", "Description"])

    activities_count = 0
    for activity in client.get_activities():

        filewriter.writerow([activity.id, activity.name, activity.distance, activity.type, activity.workout_type, activity.start_date, activity.manual, activity.private, activity.gear_id, activity.description])

        activities_count += 1

    print("[+] Number of saved activities: {}".format(activities_count))
Beispiel #23
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 #24
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)
Beispiel #25
0
def profileView(request):
    username = None
    if request.user.is_authenticated():
        #username = request.user.username
        access_token = request.user.profile.user_token
        client = Client(access_token)
        athlete = client.get_athlete()
        id_runner = athlete.id

        elevation = 0
        best_speed = 0.0
        longest_run = 0
        #longest_run_date;
        # Activities can have many streams, you can request desired stream types

        for activity in client.get_activities(after="2016-01-01T00:00:00Z"):
            #print("{0.distance} {0.moving_time} {0.total_elevation_gain}".format(activity).encode('utf-8'))
            if activity.type == 'Run':
                elevation += float(activity.total_elevation_gain)
                if float(activity.distance
                         ) / activity.moving_time.total_seconds() > best_speed:
                    best_speed = float(
                        activity.distance
                    ) / activity.moving_time.total_seconds()
                if activity.distance > longest_run:
                    longest_run = activity.distance

        nb_everest = round(elevation / 8848, 2)
        nb_mtblanc = round(elevation / 4809, 2)
        best_speed = round(best_speed * 3.6, 2)
        best_allure = 1 / (best_speed / 60)
        partie_entiere = int(best_allure)
        partie_decimale = int((best_allure - partie_entiere) * 60)
        if partie_decimale < 10:
            is_inf10 = 1
        else:
            is_inf10 = 0
        #best_allure = partie_entiere + partie_decimale
        longest_run = longest_run / 1000
    else:
        print('error')
    return render(request, 'profile.html', locals())
Beispiel #26
0
def main():
    """this is the main function for the cycle mapping program. It calls everything else"""
    act_dict = {}
    client = Client(access_token="ACCESS_TOKEN_HERE ")
    activities = client.get_activities(limit=1)
    for activity in activities:
        act_dict[activity.name] = activity.id
    print(act_dict)
    types = [
        'time',
        'latlng',
        'altitude',
        'heartrate',
        'temp',
    ]
    for item in act_dict:
        rawLatLong = getLatLongData(act_dict[item], client, types)
        lat, long = arrangeLatLonData(rawLatLong)
        plotData(lat, long)
    mplleaflet.show()
    def _get_athlete_summary(self, athlete_id):
        """ Get a total activity time per athlete. """
        tokens = self._get_authed_athletes()

        if athlete_id in tokens:
            times = []

            client = Client(access_token=tokens.get(athlete_id))
            activities = client.get_activities(
                after=_get_start_date(self.request),
                before=_get_end_date(self.request, include_full_day=True),
            )
            for activity in activities:
                times.append(activity.moving_time)

            total = datetime.timedelta()
            for time in times:
                total += time
        else:
            total = None

        return total
def get_data():
    load_dotenv(find_dotenv())
    # authorize_url = client.authorization_url(client_id=os.getenv("client_id"),
    #  redirect_uri='http://localhost:8282/authorized')

    # Have the user click the authorization URL, a 'code' param will be added to the
    # redirect_uri
    # .....

    # Extract the code from your webapp response
    # code = request.get('code') # or whatever your framework does
    # access_token = client.exchange_code_for_token(client_id=22120,
    # client_secret='<client_secret>', code=code)

    client = Client(access_token=os.getenv("access_token"))
    #  client.access_token = os.getenv("access_token")
    activities = client.get_activities()
    types = ['time', 'latlng', 'altitude', 'heartrate', 'temp']
    headers_written = False
    #stream_types = ['time', 'latlng', 'altitude', 'heartrate', 'temp']
    stream_types = ['heartrate']
    with open(
            os.path.join("/home/greg/repos/commute_analysis", "data", "raw",
                         'raw_strava_data.csv'), 'w') as f:
        for activity in activities:
            streams = client.get_activity_streams(activity.id,
                                                  types=stream_types,
                                                  resolution='medium')
            temp = activity.to_dict()
            for k in types:
                if k in streams:
                    temp[k] = streams[k].data
                else:
                    temp[k] = None
            if not headers_written:
                w = csv.DictWriter(f, temp.keys())
                w.writeheader()
                headers_written = True
            w.writerow(temp)
Beispiel #29
0
    def add_rides(self, start, end, nosave):
        client = Client(access_token=self.__token)

        url = 'https://social.cern.ch/community/BikeCommuters'
        opener = basic_auth_opener(url, self.__user, self.__pass)
        site = SharePointSite(url, opener)
        cal = site.lists["Calendar"]

        total = 0
        for activity in client.get_activities(before=end, after=start):
            if not activity.commute:
                continue

            print("adding ride on {}".format(activity.start_date))
            cal.append({
                'Date': activity.start_date,
                'Distance': float(activity.distance) / 1000
            })
            total += float(activity.distance) / 1000
        print("added {} km".format(total))
        if nosave:
            return
        cal.save()
 def Strava(self, choosenDate):
     '''Get data from Strava for given date. information about run is presented in markdown text. Google map polyline is saved to use in map if Moves did not record run'''
     strava_token = keychain.get_password('strava', 'api')
     client = Client(access_token=strava_token)
     strava_output = ''
     acts = client.get_activities(limit=10)
     runpaths = []
     for a in acts:
         if a.start_date.date() == choosenDate.date():
             strava_output += '\n\n**%s %s**\n' % (
                 a.start_date_local.time(), a.name)
             strava_output += '%s km in %s (%s km/u)\n' % (round(
                 float(a.distance) / 1000,
                 1), a.elapsed_time, round(float(a.average_speed) * 3.6, 1))
             strava_output += 'Splits:\n'
             lapnr = 1
             for lap in a.laps:
                 strava_output += '%s. %s\n' % (lapnr, lap.elapsed_time)
                 lapnr += 1
             try:
                 runpaths.append(a.map.summary_polyline)
             except:
                 pass
     return strava_output, runpaths
Beispiel #31
0
def get_client_activities(access_token, limit):

	client = Client(access_token=ACCESS_TOKEN)

	activities = client.get_activities(limit=limit)
	return activities
# -*- coding: utf8 -*-
from stravalib.client import Client
from datetime import timedelta
import logging

logging.basicConfig()

client = Client(access_token='f91aebddd4bc9a15e28840703966bb27d11d70f0');

friendDe = 4303495;

for activity in client.get_activities(limit=1):
    strava_id = u'{0.id}'.format(activity)
    print "no calories here"
    print "upload_id:", strava_id
    print "calories:", u'{0.calories}'.format(activity)

print "starred_segments"
starred_segments = client.get_starred_segment()

print "athletes"
me = client.get_athlete()
friend = client.get_athlete(athlete_id=friendDe)

print "list differences"
for segment in starred_segments:
    Deefforts = client.get_segment_efforts(segment.id, athlete_id=friendDe, limit=1)
    #Myefforts = client.get_segment_efforts(segment.id, athlete_id=client.get_athlete().id, limit=1)

    friendrecord = None
    myrecord = None
Beispiel #33
0
activity = cfg.get('strava', 'activity')

client = Client()
authorize_url = client.authorization_url(
    clientid, redirect_uri='http://127.0.0.0.0:8100/authorized')
# Have the user click the authorization URL, a 'code' param will be added to the redirect_uri

client = Client(access_token=token_entry)

# Currently-authenticated (based on provided token) athlete
curr_athlete = client.get_athlete()  # This is now me

# Saying hello
athlete = client.get_athlete()
print("Hello, {}".format(athlete.firstname))

# Showing the friends
athlete = client.get_athlete_clubs()
for a in athlete:
    print("{} is your club.".format(a))

# Testing the activities
# setting the athlete specific activity
activity_1 = client.get_activity(activity)

# method to take more activities and its informations
for activity in client.get_activities(after="2010-01-01T00:00:00Z", limit=1):
    print(
        "{0.name} {0.moving_time}".format(activity),
        "type={0.type} distance={1} ".format(
            activity, unithelper.kilometers(activity.distance)))
from pprint import pprint
import matplotlib.pyplot as plt
from mpl_toolkits import basemap
import numpy as np

# # import request
# code = 'bc1de4a08a69a21980171c6f0f079b8876aad740'
# client = Client()
# code = client.exchange_code_for_token(login_details['Client ID'],
#                                      login_details['Client Secret'],
#                                      code)
# print(url)

client = Client(access_token='e405704ed45de2d99d83c8e981a067e980f0aa8b')

activities = client.get_activities()
sample = list(activities)[0]
pprint(sample.to_dict())


# Get all my activities get the date and the GPS coords
# Might need to make sure there are GPS coords
activity_coords = []
for activity in activities:
    poly_coord = {'Poly': activity.to_dict()['map']['summary_polyline'],
                  'Date': activity.to_dict()['start_date'].split('T')[0]}
    if poly_coord['Poly'] is not None:
        activity_coords.append(poly_coord)
# for activity in activities:
#     print(activity.to_dict()['upload_id'])
# activity_coords
Beispiel #35
0
''' Script to grab activities from strava '''

import sys
import stravalib
from stravalib.client import Client
from configparser import SafeConfigParser

config = SafeConfigParser()
config.read('config.yaml')

client = Client()
authorize_url = client.authorization_url(
    client_id=config.get('strava', 'client_id'),
    redirect_uri='http://localhost:8282/authorized')
# Extract the code from your webapp response
# access_token = client.exchange_code_for_token(client_id=config.get('strava', 'client_id'), client_secret=config.get('strava', 'client_secret'), code=config.get('strava', 'code'))

# Now store that access token somewhere (a database?)
client.access_token = config.get('strava', 'Bearer')
athlete = client.get_athlete()

activities = client.get_activities(after="2017-11-17T00:00:00Z", limit=15)
activity_data = []
for activity in activities:
    activity_stream = client.get_activity_streams(activity.id,
                                                  types=['latlng', 'distance'])
    activity_data.append(activity_stream['latlng'].data)
Beispiel #36
0
class Strava(object):
    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

    @property
    def activity_type(self):
        return self._activity_type

    @activity_type.setter
    def activity_type(self, value):
        self._activity_type = value
        self._activities = None

    @property
    def athlete(self):
        return self.client.get_athlete()

    @property
    def activities(self):
        if not self._activities:
            # current_year = datetime.datetime.now().year
            # after = datetime.datetime(current_year - 2, 12, 25)
            self._activities = Activities(self.client.get_activities(), self.activity_type)
        return self._activities

    @classmethod
    def authorization_url(cls):
        self = cls()
        return self.client.authorization_url(client_id=self.client_id,
                                             redirect_uri=self.redirect_uri)

    def get_access_token(self, code):
        return self.client.exchange_code_for_token(client_id=self.client_id,
                                                   client_secret=self.client_secret,
                                                   code=code)

    @classmethod
    def athlete_by_code(cls, code):
        self = cls()
        self.client.access_token = self.get_access_token(code)
        return self.athlete

    @classmethod
    def athlete_by_token(cls, token):
        self = cls()
        self.client.access_token = token
        return self.athlete

    @classmethod
    def activities_by_token(cls, token):
        self = cls()
        self.client.access_token = token
        return self.activities

    @classmethod
    def by_token(cls, token):
        self = cls()
        self.client.access_token = token
        return self
Beispiel #37
0
		if (act.distance > units.unit("km")(5)):
			# Longer than usual. Where was I going?
			pass
		elif (1594398 in segments):
			ret["name"] = "Morning commute"
			ret["commute"] = True
		elif (1547949 in segments):
			ret["name"] = "Evening commute"
			ret["commute"] = True

	if "name" in ret and not (act.name.endswith("rit") or act.name.endswith(" Ride")):
		# May already not be the default name anymore.
		del ret["name"]

	return ret

seen = dbm.open("seen", "c")

after = datetime.datetime.now() - datetime.timedelta(days=2)
for act in act for act in client.get_activities(after=after, limit=5):
	if str(act.id) in seen:
		continue
	full = client.get_activity(act.id)
	print full
	updates = build_updates(full)
	print updates
	seen[str(act.id)] = "1"
	if updates:
		updates["activity_id"] = act.id
		print client.update_activity(**updates)
Beispiel #38
0
if(REAUTH):
	AccessToken = client.exchange_code_for_token(client_id=ClientId,
		client_secret=ClientSecret,
		code=clientCode)
	print(AccessToken)

client = Client(access_token=AccessToken)
athlete = client.get_athlete()

r = open('data.json', 'r')
data = json.load(r)
activities = list(d["id"] for d in data)
r.close()

stravaActivities = client.get_activities()
for activity in stravaActivities:
	if (activity.id in activities):
		print("Already have this activity!")
		continue

	a = client.get_activity(activity.id)
	if (a.type != "Run"):
		print("Activity was a run")
		continue
	print("Found a new activity!", activity.id)
	act = {}
	act["date"] = a.start_date_local.strftime("%y-%m-%d")
	act["id"] = a.id
	act["distance"] = unithelper.miles(a.distance).num
	act["duration"] = a.moving_time.seconds
Beispiel #39
0
from stravalib.client import Client

club_id = 24151

client = Client(access_token='250d33ceabfbe833376eb18885e797af14888512')


athlete = client.get_athlete() # Get John's full athlete record
print("Hello, {}. I know your email is {}".format(athlete.firstname, athlete.email))
# "Hello, John.  I know your email is [email protected]"

activities = client.get_activities(limit=10)
assert len(list(activities)) == 10

clubs = client.get_athlete_clubs()
icc_members = client.get_club_members(club_id, limit=20)
assert len(list(icc_members)) == 20

club_activities = client.get_club_activities(club_id, limit=20)
assert len(list(club_activities)) == 20

#View activities
#for x in activities:
#    print (x)
    
for x in clubs:
    print (x)

for x in icc_members:
    print (x)
    
Beispiel #40
0
import datetime
from dateutil.relativedelta import relativedelta

from jinja2 import Environment, FileSystemLoader
env = Environment(loader=FileSystemLoader('.'))
template = env.get_template('template.html')

from stravalib import unithelper
from stravalib.client import Client

from access_token import ACCESS_TOKEN

client = Client(access_token=ACCESS_TOKEN)
athlete = client.get_athlete()
start_date = datetime.date.today()+relativedelta(months=-1)
activities = client.get_activities(after=start_date)
activities_list = []
for activity in activities:
    if activity.start_date.date().month != start_date.month:
        continue
    date = activity.start_date.date().isoformat()
    distance = activity.distance
    duration = activity.elapsed_time.total_seconds()/60
    activity_type = activity.type
    activity_string = "{activity_type} for {duration:.1f} minutes ({distance:.2f} miles)".format(
        activity_type=activity_type,
        duration=duration,
        distance=unithelper.miles(activity.distance).num,
    )

    activities_list.append((date, activity_string, activity.name))
Beispiel #41
0
# activities = client.get_activities(end, start)
# gets all activities
#activity = client.get_activity(428095411, True)

#types = ['time', 'latlng', 'altitude', 'heartrate', 'temp', ]

#streams = client.get_activity_streams(428095411)
# protocol.get('/activities/{id}', id=activity_id,
  #                               include_all_efforts=include_all_efforts)
# activities = client.get_activities()

datetime.datetime(2005, 7, 14, 12, 30)
start = datetime.datetime(2016, 1, 1, 0, 0)
end = datetime.datetime(2016, 1, 3, 0, 0)

activities = client.get_activities(end, start)
STRONZO = list(activities)
types = ['time', 'latlng', 'altitude', 'heartrate', 'temp', 'segments', 'segment']

# get all streams and push efforts into array
segment_array = []
stream_types = ['time', 'latlng', 'distance', 'altitude', 'velocity_smooth', 'heartrate', 'cadence', 'watts', 'temp', 'moving', 'grade_smooth']
iterator = 0

for entry in STRONZO:
    print (float(iterator) / float(len(STRONZO)))
    iterator += 1
    activity = client.get_activity(entry.id, True)
    # stream = client.get_activity_streams(entry.id, stream_types)
    # segment_array.append(stream)
    if activity.segment_efforts:
Beispiel #42
0
def data_scraper(date_end, date_start, athletes=None):
    meters_to_miles = 0.000621371
    meters_to_feet = 3.28084
    km_to_miles = 0.621371
    if athletes:
        athlete_list = athlete.objects.filter(id=athletes)
    else:
        athlete_list = athlete.objects.all() # get list of all athletes
    for each_athlete in athlete_list: # for each athlete
        client = Client(access_token=each_athlete.access_token)
        this_athlete_activities = client.get_activities(date_end, date_start)  # get list of activities for this month
        relevant_existing_activities = [this.id for this in activity.objects.filter(athlete_id=each_athlete).filter(start_date_local__lte=date_end).filter(start_date_local__gte=date_start)]
        # print(relevant_existing_activities)
        # print(each_athlete, this_athlete_activities)
        for each_activity in this_athlete_activities:  # for each activity
            if not activity.objects.filter(pk=each_activity.id):# check if its already in the database
                new_activity = activity(
                    id=each_activity.id,
                    athlete_id=athlete.objects.filter(pk=each_activity.athlete.id)[0],
                    name=each_activity.name,
                    distance=meters_to_miles*each_activity.distance,
                    moving_time=each_activity.moving_time,
                    elapsed_time=each_activity.elapsed_time,
                    total_elevation_gain=meters_to_feet*each_activity.total_elevation_gain,
                    type=each_activity.type,
                    start_date_local=utc.localize(each_activity.start_date_local).astimezone(pst),
                    average_speed=km_to_miles*each_activity.average_speed,
                    calories=each_activity.calories,
                    day=each_activity.start_date_local.day)# if its not in the database, add it
                new_activity.save()
                get_activity_photos(client, each_activity.id)
            else:
                get_activity_photos(client, each_activity.id)
                try:
                    relevant_existing_activities.remove(each_activity.id)
                except ValueError:
                    pass  # print("item %d in black hole" % each_activity.id)
        for extra_activity in relevant_existing_activities:
            print('removing item %d from database since it doesnt exist on strava'%extra_activity)
            activity.objects.filter(id=extra_activity).delete()
        cum = 0
        # for this_activity in activity.objects.filter(athlete_id = each_athlete).order_by('start_date_local'):
        for each_day in range(1,(date_end.astimezone(pst)-date_start.astimezone(pst)).days+1):
            print(each_athlete, each_day)
            this_day = activity.objects.filter(athlete_id = each_athlete).filter(start_date_local__lte=before).filter(start_date_local__gte=after).filter(day=each_day).aggregate(daily_sum = Sum('total_elevation_gain'))
            cum += this_day['daily_sum'] or 0
            today = month.objects.filter(athlete_id = each_athlete).filter(day = each_day)
            if today:
                for existing_day in today:
                    existing_day.cum_elev = cum
                    existing_day.save()
            else:
                new_day = month(
                    athlete_id = each_athlete,
                    day = each_day,
                    cum_elev = cum
                )
                new_day.save()
        all_athlete_activities = activity.objects.filter(athlete_id=each_athlete).filter(start_date_local__lte=date_end).filter(start_date_local__gte=date_start).order_by('start_date_local')
        cum = 0
        for every_activity in all_athlete_activities:
            cum += every_activity.total_elevation_gain
            every_activity.cumulative_elevation = cum
            every_activity.save()
        month.objects.filter(day__gt=datetime.now().day).delete()
from stravalib import unithelper

client_id = os.environ.get('STRAVA_CLIENT_ID', None)
client_secret = os.environ.get('STRAVA_CLIENT_SECRET', None)
access_token = os.environ.get('STRAVA_ACCESS_TOKEN', None)

if __name__ == '__main__':

    mysegments = {}

    # get athlete
    client = Client(access_token)  # 1 -- possibly not counted
    athlete = client.get_athlete()  # 2

    # get athlete activities
    activities = client.get_activities(limit=200)  # 3
    print("number of activities returned", str(len(list(activities))))

    # per activity, get segment efforts
    for activity in activities:
        segment_efforts = client.get_activity(activity.id).segment_efforts  # 4

        # per segment effort
        for segment in segment_efforts:
            mysegments[segment.segment.id] = segment.segment  # save to db

    # check if segment leaderboard contains any friends
    for key, segment in mysegments.iteritems():
        leaderboard = client.get_segment_leaderboard(key, following=True).entries  # 12

        # get friend with time < athlete time
Beispiel #44
0
stream_filter = ["latlng", "altitude", "heartrate", "velocity_smooth", "moving", "grade_smooth"]

this_dir = getcwd()
output_dir = join(this_dir, "MAF")
output_detail_dir = join(output_dir, "detail")
from_date = datetime(2016, 2, 27)

if not exists(output_detail_dir):
  print "Creating {0}".format(output_detail_dir)
  makedirs(output_detail_dir)


# Download some activities
print "Downloading activities from {0:%d %b %Y}".format(from_date)
acts = client.get_activities(after=from_date)

for act in acts:
    total += 1

    if act.type != "Run" or act.average_heartrate is None:
        continue

    count += 1

    # Get the full data streams
    streams = client.get_activity_streams(act.id, types=stream_filter)
    sdf = pd.DataFrame(dict((stype, stream.data) for (stype, stream) in streams.iteritems()))

    if "latlng" in stream_filter:
      sdf["lat"] = [a[0] for a in sdf.latlng]
Beispiel #45
0
from stravalib.client import Client
import os
from stravalib import unithelper

client = Client()
# authorize_url = client.authorization_url(client_id=os.environ['CLIENT_ID'],
#                                redirect_uri='http://localhost:8282/authorized')

client.access_token = os.environ['ACCESS_TOKEN']

# ali = client.get_athlete()

#print(ali)

acts = client.get_activities(before=None, after=None, limit=10)

for act in acts:
    print(act.id, act.name, unithelper.miles(act.distance), act.description)

#testing
#ryan = client.get_athlete(6777976)

#print ryan.city

# Activities can have many streams, you can request n desired stream types
types = [
    'time',
    'latlng',
    'altitude',
    'heartrate',
    'temp',
Beispiel #46
0
class Strava(object):
    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

    @property
    def activity_type(self):
        return self._activity_type

    @activity_type.setter
    def activity_type(self, value):
        self._activity_type = value
        self._activities = None

    @property
    def athlete(self):
        return self.client.get_athlete()

    @property
    def activities(self):
        if not self._activities:
            # current_year = datetime.datetime.now().year
            # after = datetime.datetime(current_year - 2, 12, 25)
            self._activities = Activities(self.client.get_activities(),
                                          self.activity_type)
        return self._activities

    @classmethod
    def authorization_url(cls):
        self = cls()
        return self.client.authorization_url(client_id=self.client_id,
                                             redirect_uri=self.redirect_uri)

    def get_access_token(self, code):
        return self.client.exchange_code_for_token(
            client_id=self.client_id,
            client_secret=self.client_secret,
            code=code)

    @classmethod
    def athlete_by_code(cls, code):
        self = cls()
        self.client.access_token = self.get_access_token(code)
        return self.athlete

    @classmethod
    def athlete_by_token(cls, token):
        self = cls()
        self.client.access_token = token
        return self.athlete

    @classmethod
    def activities_by_token(cls, token):
        self = cls()
        self.client.access_token = token
        return self.activities

    @classmethod
    def by_token(cls, token):
        self = cls()
        self.client.access_token = token
        return self
from stravalib.client import Client
from stravalib import unithelper

client = Client()

# The access token is the final result from OAuth
client.access_token = ''

athlete = client.get_athlete()
activities = client.get_activities()

activity_list = list(activities)

total_activities = len(activity_list)

print("Total activities retrieved: {total}".format(total=total_activities))

def createTimestamp(ts): # creating timestamp string from timestamp object
	return '{year}-{month}-{day} {hour}:{minute}:{second}'.format(year=ts.year, month=ts.month, day=ts.day, hour=ts.hour, minute=ts.minute, second=ts.second)

def xstr(s):
	if s is None:
		return ''
	else:
		return str(s)

print 'Opening file to write...'
outputfile = open('runLogsSorted.csv', 'a') # Append the entry for each run to this file

schema = '"ID","Name","Distance (mi)","Moving time (s)","Elapsed time (s)","Elevation gain (ft)","Avg speed (mph)","Max speed (mph)","Avg cadence","Avg temp (C)","Avg HR","Max HR","Calories","Shoes","Start timestamp (local)","Start Lat","Start Lng","End Lat","End Lng","City","State","Country","Achievements","Kudos","Workout type"\n'
print 'Writing schema...'
Beispiel #48
0
def data_scraper(date_start, date_end, athletes=None):
    meters_to_miles = 0.000621371
    meters_to_feet = 3.28084
    km_to_miles = 0.621371
    if athletes:
        athlete_list = athlete.objects.filter(id=athletes)
    else:
        athlete_list = athlete.objects.all() # get list of all athletes
    for each_athlete in athlete_list: # for each athlete
        # try:
        client = Client(access_token=each_athlete.access_token)
        this_athlete_activities = client.get_activities(date_end, date_start)  # get list of activities for this month
        relevant_existing_activities = [this.id for this in activity.objects.filter(athlete_id=each_athlete).filter(start_date_local__lte=date_end).filter(start_date_local__gte=date_start)]
        # print(relevant_existing_activities)
        print(each_athlete, len(relevant_existing_activities))
        try:
            for each_activity in this_athlete_activities:  # for each activity
                if not activity.objects.filter(pk=each_activity.id):# check if its already in the database
                    new_activity = activity(
                        id=each_activity.id,
                        athlete_id=athlete.objects.filter(pk=each_activity.athlete.id)[0],
                        name=each_activity.name[0:139],
                        distance=meters_to_miles*each_activity.distance,
                        moving_time=each_activity.moving_time,
                        elapsed_time=each_activity.elapsed_time,
                        total_elevation_gain=meters_to_feet*each_activity.total_elevation_gain,
                        type=each_activity.type,
                        start_date_local=pst.localize(each_activity.start_date_local),
                        average_speed=km_to_miles*each_activity.average_speed,
                        calories=each_activity.calories,
                        day=each_activity.start_date_local.day)# if its not in the database, add it
                    new_activity.save()
                    get_activity_photos(client, each_activity.id)
                else:
                    get_activity_photos(client, each_activity.id)
                    try:
                        relevant_existing_activities.remove(each_activity.id)
                    except ValueError:
                        pass  # print("item %d in black hole" % each_activity.id)
            for extra_activity in relevant_existing_activities:
                print('removing item %d from database since it doesnt exist on strava'%extra_activity)
                activity.objects.filter(id=extra_activity).delete()
        except:
            print("Not Authorized: " + each_athlete.firstname + " " + each_athlete.lastname)
        cum = 0
        # for this_activity in activity.objects.filter(athlete_id = each_athlete).order_by('start_date_local'):
        if date_end.astimezone(pst) > utc.localize(datetime.utcnow()).astimezone(pst):
            end_date = utc.localize(datetime.utcnow()).astimezone(pst)
        else:
            end_date = date_end.astimezone(pst)
        for each_day in range(1,(end_date.astimezone(pst)-date_start.astimezone(pst)).days):
            this_day = activity.objects.filter(athlete_id = each_athlete).filter(start_date_local__lte=before).filter(start_date_local__gte=after).filter(day=each_day).aggregate(daily_sum = Sum('total_elevation_gain'))
            cum += this_day['daily_sum'] or 0
            today = month.objects.filter(athlete_id = each_athlete).filter(day = each_day)
            if today:
                for existing_day in today:
                    existing_day.cum_elev = cum
                    existing_day.save()
            else:
                new_day = month(
                    athlete_id = each_athlete,
                    day = each_day,
                    cum_elev = cum
                )
                new_day.save()
        all_athlete_activities = activity.objects.filter(athlete_id=each_athlete).filter(start_date_local__lte=date_end).filter(start_date_local__gte=date_start).order_by('start_date_local')
        cum = 0
        for every_activity in all_athlete_activities:
            cum += every_activity.total_elevation_gain
            every_activity.cumulative_elevation = cum
            every_activity.save()
        # month.objects.filter(day__gt=datetime.now().day + 1).delete()
        # except:
        #     print("Not Authorized: " + each_athlete.firstname + " " + each_athlete.lastname)

    # update the info for the types pie chart
    # find all the types
    types = activity.objects.values('type').distinct()
    elevation_by_type = activity.objects.filter(start_date_local__lte=before).filter(start_date_local__gte=after).values('type').annotate(Sum('total_elevation_gain'))
    distance_by_type = activity.objects.filter(start_date_local__lte=before).filter(start_date_local__gte=after).values('type').annotate(Sum('distance'))
    quantity_by_type = activity.objects.filter(start_date_local__lte=before).filter(start_date_local__gte=after).values('type').annotate(Count('id'))
    # for each type
    for each_value in types:
        each_type = each_value['type']
        # check to see if it already exists
        this_type = activity_type.objects.filter(pk=each_type)
        if not this_type:
            new_type = activity_type(type = each_type)
            new_type.save()
        else:
            clear = this_type[0]
            print("Clearing: %s" % clear)
            clear.elevation = 0
            clear.save()
    for each_item in elevation_by_type:
            this_type = activity_type.objects.filter(pk=each_item['type'])[0]
            this_type.elevation = each_item['total_elevation_gain__sum']
            this_type.save()
    for each_item in distance_by_type:
            this_type = activity_type.objects.filter(pk=each_item['type'])[0]
            this_type.distance = each_item['distance__sum']
            this_type.save()
    for each_item in quantity_by_type:
            this_type = activity_type.objects.filter(pk=each_item['type'])[0]
            this_type.quantity = each_item['id__count']
            this_type.save()
    junk_types = activity_type.objects.filter(elevation=0)
    junk_types.delete()

    determine_rank_delta(get_leaderboard())
    print("Done with Update")
from stravalib.client import Client, unithelper
import logging

logging.basicConfig(level=logging.ERROR)

client = Client(access_token='access_token')

total_distance = 0.0
for activity in client.get_activities(after = "2015-04-06T00:00:00Z"):
    #print dir(activity)
    #break
    print("{}: {}").format(activity.start_date_local, unithelper.kilometers(activity.distance))
    total_distance += float(unithelper.kilometers(activity.distance))

print "Total distance: %.2fkm" % total_distance