Example #1
0
    def load_strava_tracks(self, strava_config: str) -> typing.List[Track]:
        tracks = []
        tracks_names = []
        if self.cache_dir:
            self.strava_cache_file = os.path.join(self.cache_dir,
                                                  strava_config)
            if os.path.isfile(self.strava_cache_file):
                with open(self.strava_cache_file) as f:
                    strava_cache_data = json.load(f)
                    tracks = [
                        self._strava_cache_to_track(i)
                        for i in strava_cache_data
                    ]
                    tracks_names = [track.file_names[0] for track in tracks]

        with open(strava_config) as f:
            strava_data = json.load(f)
        client = Client()
        response = client.refresh_access_token(**strava_data)
        client.access_token = response["access_token"]
        fliter_dict = {"before": datetime.datetime.utcnow()}
        if tracks:
            max_time = max(track.start_time for track in tracks)
            if max_time:
                fliter_dict = {"after": max_time - datetime.timedelta(days=2)}
        for activate in client.get_activities(**fliter_dict):
            # tricky to pass the timezone
            if str(activate.id) in tracks_names:
                continue
            t = Track()
            t.load_strava(activate)
            tracks.append(t)
        self._store_strava_tracks_to_cache(tracks)
        return self._filter_and_merge_tracks(tracks)
Example #2
0
def main():
    access_token = getToken()
    if access_token == None:
        return redirectAuth()
    client = Client(access_token=access_token)
    athlete = client.get_athlete() # Get current athlete details
    #if you want a simple output of first name, last name, just use this line:
    #return athlete.firstname + ' ' + athlete.lastname
    #now get most recent activity for this athlete...
    names = []
    maps = []
    for a in client.get_activities(before = "2016-08-12T00:00:00Z",  limit=1):
        names.append(a.name)
        maps.append(a.map)
    # another simple output for this bit is to return the name of the route
    #return names[0]

    # but a sightly more complicated output is this matplotlib figure --
    m = maps[0]
    summary_lat_lon = polyline.decode(m.summary_polyline)
    lats = [i[0] for i in summary_lat_lon]
    lons = [i[1] for i in summary_lat_lon]
    session['name']=names[0]
    session['lats']=lats
    session['lons']=lons
    return redirect('/simple.png')
Example #3
0
def main():

    token = get_token()
    if not token:
        print("No API token available, can't continue")
        return

    client = Client(token)
    activities = client.get_activities()

    print("Looking for activites that have 'commute' in the title, but don't "
          "have the commute property set on them...")

    interactive = True
    for a in activities:
        if not a.commute and "commute" in a.name.lower():
            print(
                "Found activity '{}' on {} - https://www.strava.com/activities/{}"
                "".format(a.name, a.start_date.astimezone(tz=None), a.id))
            i = ""
            if not interactive:
                i = "y"

            while i not in ("y", "n", "a", "q"):
                i = input("Add the commute tag to this activity? [y/n/a/q]: "
                          ).lower()

            if i == "y":
                client.update_activity(a.id, commute=True)
                print("Added commute tag")
            elif i == "q":
                break
            elif i == "a":
                interactive = False
    print("Done")
Example #4
0
    def load_strava_tracks(self, strava_config: str) -> typing.List[Track]:
        tracks = []
        tracks_names = []
        if self.cache_dir:
            self.strava_cache_file = os.path.join(self.cache_dir, strava_config)
            if os.path.isfile(self.strava_cache_file):
                with open(self.strava_cache_file) as f:
                    strava_cache_data = json.load(f)
                    tracks = [self._strava_cache_to_track(i) for i in strava_cache_data]
                    tracks_names = [track.file_names[0] for track in tracks]

        with open(strava_config) as f:
            strava_data = json.load(f)
        filter_type = strava_data.pop("activity_type", None)
        client = Client()
        response = client.refresh_access_token(**strava_data)
        client.access_token = response["access_token"]
        filter_dict = {"before": datetime.datetime.utcnow()}
        if tracks:
            max_time = max(track.start_time() for track in tracks)
            filter_dict = {"after": max_time - datetime.timedelta(days=2)}
        for activity in client.get_activities(**filter_dict):
            # tricky to pass the timezone
            if str(activity.id) in tracks_names:
                continue
            if filter_type and activity.type not in (
                [filter_type] if isinstance(filter_type, str) else filter_type
            ):  # pylint: disable=superfluous-parens
                continue
            t = Track()
            t.load_strava(activity)
            tracks.append(t)
        self._store_strava_tracks_to_cache(tracks)
        return self._filter_and_merge_tracks(tracks)
Example #5
0
def process():
    token = session.get('access_token', None)
    if token is None:
        return redirect(url_for('login'))
    client = Client(token)
    athlete = client.get_athlete()
    activities = client.get_activities()
    points = [pnt for a in activities for pnt in (a.end_latlng, a.start_latlng) if pnt]

    #temp = [pnt for ints in point_intercepts(points) for pnt in ints]

    #temp = filter_close_points(points)

    seg = []
    for grps in group_points(points):

        out = []
        for pnt in grps:
            out.append("<trkpt lat=\"{0.lat}\" lon=\"{0.lon}\"></trkpt>".format(pnt))
        seg.append("<trkseg>{}</trkseg>".format("".join(out)))

    return """<?xml version="1.0" encoding="UTF-8"?>
        <gpx version="1.0">
        <name>TEST</name>
        <trk>{}</trk>
        </gpx>""".format("".join(seg))

    return "<html><body><img src='{}'/>{} {}</body></html>".format(athlete.profile, athlete.firstname, athlete.lastname)
Example #6
0
 def get(self, request, athlete_id):
     if request.user.is_authenticated():
         template = loader.get_template('athlete.html')
         try:
             token = StravaToken.objects.get(user=request.user.id)
         except ObjectDoesNotExist:
             logger.error("Either the entry or blog doesn't exist.")
         client_id = settings.CLIENT_ID
         client_secret = settings.CLIENT_SECRET
         client = Client(access_token=token.token)
         logger.info(token.user)
         logger.info(token.token)
         athlete = client.get_athlete()
         logger.info(athlete.city)
         activities = client.get_activities(limit=10)
         for activity in activities:
             logger.info(
                 u"{0.name} {0.moving_time} {0.suffer_score}".format(
                     activity))
         context = {
             #        'latest_question_list': latest_question_list,
         }
         return HttpResponse(template.render(context, request))
     else:
         raise Http404("user is not login.")
Example #7
0
class strava_class(object):
    def __init__(self):
        self.client = Client()

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

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

    def get_last_week(self, lim):
        for activity in self.client.get_activities(
                after="2016-08-01T00:00:00Z", limit=lim):
            print("{0.name} {0.moving_time}".format(activity))
Example #8
0
def get_activity_data(access_token):
    client = Client(access_token)

    athlete = client.get_athlete()

    activity_stats = client.get_athlete_stats()

    run_count = activity_stats.all_run_totals.count
    bike_count = activity_stats.all_ride_totals.count
    swim_count = activity_stats.all_swim_totals.count

    total_count = run_count + bike_count + swim_count 

    all_activities = client.get_activities()

    run_activities = []
    swim_activities = []
    bike_activities = []

    calorie_count = 0.0
    for activity in all_activities:
        if (activity.type == "Run"):
            run_activities.append(activity) 
            calorie_count += (float(activity.distance) / 1000) * float(athlete.weight) * 1.036
        if (activity.type == "Swim"):
            swim_activities.append(activity)
        if (activity.type == "Ride"):
            bike_activities.append(activity)

    return ({"Runs": run_activities, "Swims" : swim_activities, "Rides": bike_activities, "Calorie_Count" : calorie_count})
Example #9
0
def fetch_runs(user):
    client = Client(access_token=user['strava_token'])
    runs = []
    for activity in client.get_activities(limit=10):
        if activity.type != 'Run':
            continue
        runs.append(activity2run(activity))
    return runs
Example #10
0
def get_activitys(LIMIT):
    TOKEN = retreve_token(c['client_id'], c['client_secret'])
    data = list()
    client = Client(access_token=TOKEN)
    activitys = client.get_activities(limit=LIMIT)
    for activ in activitys:
        data.append(activ.to_dict())
    return data
Example #11
0
 def get_activities(self, days, code):
     dt1 = datetime.now()
     dt2 = timedelta(days=days)
     dt3 = dt1 - dt2
     dt3 = dt3.strftime("%Y-%m-%dT%H:%M:%SZ")
     client = Client(access_token=code)
     activities = client.get_activities(after=dt3)
     return activities
Example #12
0
def segment_ids_from_activities(client, max_activities=5):
    # get segment ids from most recent runs
    client = Client(access_token=session['access_token'])

    segment_ids = []
    for a in client.get_activities(limit=max_activities):
        # this is jank but I can't pass include_all_efforts to get_activities
        activity = client.get_activity(
            a.id, include_all_efforts=True)  # return all segment efforts
        for effort in activity.segment_efforts:
            segment_ids.append(effort.segment.id)
    session['segment_ids_unique'] = list(set(segment_ids))
    session['uniques'] = len(session['segment_ids_unique'])
    return
Example #13
0
    def fetch_runs(user):
        client = Client(access_token=user.strava_token)
        runs = 0
        for activity in client.get_activities(limit=5):
            if activity.type != "Run":
                continue
            q = db.session.query(Run).filter(Run.strava_id == activity.id)
            run = q.first()
            if run is None:
                db.session.add(activity2run(activity))
                runs += 1

        db.session.commit()
        return runs
Example #14
0
def process():
    token = session.get('access_token', None)
    if token is None:
        return redirect(url_for('login'))
    client = Client(token)
    athlete = client.get_athlete()
    activities = client.get_activities()

    for a in activities:
        if not a.commute and "commute" in a.name.lower():
            print(a)
            client.update_activity(a.id, commute=True)

    return "<html><body>processed</body></html>"
Example #15
0
def should_unlock(lock_time_of_day):
    """Determine whether the person registered an activity since lock time."""
    token = get_strava_token()
    client = Client(access_token=token)
    today = datetime.date.today()
    afterdate = datetime.datetime.combine(today, lock_time_of_day)

    activities = client.get_activities(after=afterdate.isoformat())
    activity_list = [a for a in activities]

    # Did the locked person record at least one activity since the lock time?
    if len(activity_list) > 0:
        return True
    return False
def get_activity_map():
# just to see if i can plot my own activity map!
   f = open('secrets.txt', 'r')
   MY_STRAVA_CLIENT_ID = f.readline().strip()
   MY_STRAVA_CLIENT_SECRET = f.readline().strip()
   STORED_ACCESS_TOKEN = f.readline().strip()
   f.close()
   from stravalib import Client
   client = Client(access_token=STORED_ACCESS_TOKEN)
   client.get_athlete(7656735) # Get current athlete details
   #now get most recent activity for this athlete...
   a=client.get_activities(before = "2016-08-11T00:00:00Z",  limit=1)
   session['map']=a.map
   session['name']=a.name   
Example #17
0
def get_activities_from_strava():
    last_activity = None
    if not os.path.exists(STRAVA_ACCESS_TOKEN_STRING_FNAME):

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

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

        print auth_token

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


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

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

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

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

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

    return strava_client.get_activity(activity_id=activity.id)
Example #18
0
class StravaHelper:
    def __init__(self, token=''):
        self.client = Client(access_token=token)

    def get_last_activities(self, before=None, after=None, limit=None):
        """
        Récupére les dernieres activités
        :param before:
        :param after:
        :param limit: nombre limite d'activité
        :return:
        """
        return [
            activity
            for activity in self.client.get_activities(before, after, limit)
        ]
Example #19
0
async def new_athlete(athlete):
    # This is a hack to have the callback response return before the reports are generated
    await asyncio.sleep(1)

    client = Client(athlete.access_token)

    for activity in client.get_activities(limit=STRAVA_BACKFILL_COUNT):
        # This is a hack to have this job not block all other requests
        await asyncio.sleep(1)
        if athlete.token_expiration_datetime < datetime.now() + timedelta(
                minutes=5):
            athlete = await refresh_access_token(athlete)

        await generate_report(athlete, activity.id)

    await athlete.update(backfilled=True)
Example #20
0
def load_strava_data(user_id):
    user = User.objects.get(id=user_id)
    token = user.social_auth.get(provider='strava').tokens

    c = StravaClient(token)
    # fetch 200 activities
    activities = c.get_activities(limit=200)

    for track in activities:
        activity, created = Activity.objects.get_or_create(
            guID=track.id,
            user=user
        )
        print track.id
        activity.provider = Activity.STRAVA_PROVIDER
        activity.location_city = track.location_city
        activity.location_country = track.location_country

        full_activity = c.get_activity(track.id)
        activity.polyline = full_activity.map.polyline
        activity.moving_time = full_activity.moving_time
        activity.start_date = full_activity.start_date

        activity.distance = float(
            unithelper.meters(
                track.distance
            )
        )

        activity.total_elevation_gain = float(
            unithelper.meters(
                track.total_elevation_gain
            )
        )
        activity.resource_state = track.resource_state
        activity.description = track.description
        if hasattr(track, 'start_latlng') and track.start_latlng is not None:
            activity.start_point = Point(
                track.start_latlng.lon,
                track.start_latlng.lat
            )

        activity.save()

        if activity.polyline:
            activity.route = LineString(polyline_decode(activity.polyline))
        activity.save()
Example #21
0
def load_activities():
    users_id = session['athlete']['id']
    c = Client(access_token=session['token'])
    activities = list(c.get_activities())
    cur = g.db.cursor()

    # Delete activities before loading to prevent id clashes
    cur.execute('delete from activities where users_id = ?', [users_id])
    g.db.commit()

    # TODO: bulk create
    for a in activities:
        cur.execute('insert into activities (id, name, distance, start_time, users_id) values (?, ?, ?, ?, ?)',
                    (a.id, a.name, int(a.distance) / 1609, a.start_date, users_id))
        g.db.commit()
    cur.close()

    return redirect('/activities')
Example #22
0
def get_activity_list(strava_auth, selected_year, activities_limit):
    if not 'access_token' in strava_auth:
        raise PreventUpdate
    client = Client(access_token=strava_auth['access_token'])

    start_date = f"{selected_year}-01-01T00:00:00Z"
    end_date = f"{selected_year+1}-01-01T00:00:00Z"

    activities = client.get_activities(
        after=start_date,
        before=end_date,
        limit=activities_limit,
    )
    store_activities = [{
        "id":
        activity.id,
        "name":
        activity.name,
        "max_heartrate":
        activity.max_heartrate,
        "has_heartrate":
        activity.has_heartrate,
        "kudos_count":
        activity.kudos_count,
        "average_heartrate":
        activity.average_heartrate,
        "start_date":
        str(activity.start_date).replace("+00:00", ""),
        "elapsed_time":
        str(activity.elapsed_time).replace(" ", ""),
        "distance":
        str(activity.distance).replace(" ", ""),
        "calories":
        str(activity.calories).replace(" ", ""),
        "average_speed":
        str(activity.average_speed).replace(" ", ""),
        "max_speed":
        str(activity.max_speed).replace(" ", ""),
    } for activity in activities][::-1]

    return [{
        "activities": store_activities
    }, store_activities,
            store_activities[0] if len(store_activities) > 0 else None]
Example #23
0
def update_trainable(request, sport, start, end, commute):
    """Will update and create new trainable entries based on the data on
    strava."""
    client = Client(access_token=get_access_token(request))
    activities = []
    count_synced = 0
    count_ignored = 0
    for sactivity in client.get_activities():
        activity = strava2trainable(sactivity)
        # Activity date is YYYY-mm-DD HH:MM. As the daterange for the
        # filter is only date we need to strip the time.
        adate = activity["date"].split(" ")[0]
        # Filter activities based on settings.
        if activity["commute"] and not commute:
            count_ignored += 1
            continue
        if start and adate < str(start):
            count_ignored += 1
            continue
        if end and adate > str(end):
            count_ignored += 1
            continue
        if str(activity["sport"]) not in sport:
            count_ignored += 1
            continue
        else:
            count_synced += 1
            activities.append(activity)

    _ = request.translate
    msg_ignored = _("Ingnored {} activities on sync because of filter settings"
                    ).format(count_ignored)
    msg_synced = _("Synced {} activities").format(count_synced)

    log.info(msg_ignored)
    log.info(msg_synced)
    request.session.flash(msg_synced, "success")
    request.session.flash(msg_ignored, "info")

    importer = JSONImporter(Activity, db=request.db)
    items = importer.perform(json.dumps(activities),
                             request.user,
                             load_key="strava_id")
    return _handle_save(request, items, None)
Example #24
0
def token(request):
    # Get temporary code after the request
    code = request.GET.get("code")

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

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

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


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

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

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

    # information to send to the html page
    context = { 'activity_list': activity_list,  'current_athlete': current_athlete }
    template = loader.get_template('shred/activities.html')
    return HttpResponse(template.render(context))
Example #25
0
def dave():
    config = configparser.ConfigParser()
    config.read(BEE42_INI)

    ini_beeminder = config[BEE42_INI_BEEMINDER]
    username = ini_beeminder[BEE42_INI_USERNAME]
    token = ini_beeminder[BEE42_INI_TOKEN]
    strava_token = ini_beeminder[BEE42_INI_STRAVA_TOKEN]

    user = User(username, token)
    print("Username:"******"tz:", user.timezone, "update:", user.updated_at, "goals", user.goalslugs, "db:", user.deadbeat)

    strava_client = Client(access_token=strava_token)
    strava_athlete = strava_client.get_athlete()
    print(strava_athlete.firstname)

    strava_activities = strava_client.get_activities(limit=15)

    for a in strava_activities:
        if (a.type == "Run"):
            print(add_run(user, a))
        elif (a.type == "Ride"):
            print(add_ride(user, a))
Example #26
0
def getactivity(activity_id=0, client=None):
    if client == None:
        token = gettoken()
        client = Client(access_token=token)

    if activity_id == 0:
        activities = client.get_activities(limit=1)
        for i in activities:
            activity = i

    else:
        try:
            activity = client.get_activity(activity_id)
        except:
            print('Activity not found')
            return int(0), client

    athlete = activity.athlete

    if not athlete.is_authenticated_athlete():
        print('Activity does not belong to user')
        return int(1), client

    return activity, client
Example #27
0
def load_strava_data(user_id):
    user = User.objects.get(id=user_id)
    token = user.social_auth.get(provider='strava').tokens

    c = StravaClient(token)
    # fetch 200 activities
    activities = c.get_activities(limit=200)

    for track in activities:
        activity, created = Activity.objects.get_or_create(guID=track.id,
                                                           user=user)
        print track.id
        activity.provider = Activity.STRAVA_PROVIDER
        activity.location_city = track.location_city
        activity.location_country = track.location_country

        full_activity = c.get_activity(track.id)
        activity.polyline = full_activity.map.polyline
        activity.moving_time = full_activity.moving_time
        activity.start_date = full_activity.start_date

        activity.distance = float(unithelper.meters(track.distance))

        activity.total_elevation_gain = float(
            unithelper.meters(track.total_elevation_gain))
        activity.resource_state = track.resource_state
        activity.description = track.description
        if hasattr(track, 'start_latlng') and track.start_latlng is not None:
            activity.start_point = Point(track.start_latlng.lon,
                                         track.start_latlng.lat)

        activity.save()

        if activity.polyline:
            activity.route = LineString(polyline_decode(activity.polyline))
        activity.save()
Example #28
0
    def import_strava_api(self):

        self._init_database_handler()

        st = StravaTokenHandler()
        st.set_db_handler(self.dbh, self.core_info.get("db_hash"))
        st.update_token()
        del st

        user = self.dbh.list_user_by_hash(
            user_hash=self.core_info.get("db_hash"))

        client = Client(access_token=user["strava_bearer"]["access_token"])
        athlete = client.get_athlete()
        athlete_id = athlete.id

        activity_stream_types = [
            "time", "latlng", "distance", "altitude", "velocity_smooth",
            "heartrate", "cadence", "watts", "temp", "moving", "grade_smooth"
        ]

        for activity in client.get_activities(
                before=self.activity_raw_date_end.strftime(
                    "%Y-%m-%dT%H:%M:%SZ"),
                after=self.activity_raw_date_beg.strftime(
                    "%Y-%m-%dT%H:%M:%SZ"),
                limit=100):
            # The first order task is to form a common branch description
            # from the Strava API activity (aka. activity -> branch/track)
            write_success, hash_str = self._handle_activity_from__strava_api(
                activity=activity)

            if write_success is False:
                print(
                    "We do not need to continue when creating the branch/track creation fails."
                )
                break

            #Extract more details from the activity via the API
            activity_stream = client.get_activity_streams(
                activity_id=activity.id,
                types=activity_stream_types,
                resolution="high",
                # series_type=None
            )

            #continue
            # Create a GPS data leaf
            self._handle_activity_from_strava_api_gps(
                activity=activity,
                activity_stream=activity_stream,
                hash_str=hash_str)

            # Create a strava based distance leaf
            self._handle_activity_from_strava_api_distances(
                activity=activity,
                activity_stream=activity_stream,
                hash_str=hash_str)

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

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


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

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

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

    return render(request, 'stravaChimp/authorization.html', {'code':code, 'access_token':access_token, 'athleteId':athleteId})
Example #30
0
def massive_test(access_token, athlete_id):
    client = Client(access_token=access_token)

    mysegments = {}  # all segments a user has ridden

    # get athlete activities
    athlete_from_db = Athlete.objects.get(strava_id=athlete_id)
    activities = client.get_activities(limit=5, before=athlete_from_db.oldest_activity_date)  # API call

    # per activity, get segment efforts
    for activity in activities:
        if activity.type not in ['Ride', 'ride']:
            continue

        try:
            # if activity already exists in db, skip it
            Activity.objects.get(strava_id=activity.id)
            continue
        except Activity.DoesNotExist:
            new_activity = Activity()
            new_activity.strava_id = activity.id
            new_activity.start_lat = activity.start_latitude
            new_activity.start_long = activity.start_longitude
            new_activity.start_date = activity.start_date
            new_activity.save()

            # update newest / oldest activity dates
            if athlete_from_db.newest_activity_date is None:
                athlete_from_db.newest_activity_date = activity.start_date
                athlete_from_db.oldest_activity_date = activity.start_date
            else:
                if activity.start_date > athlete_from_db.newest_activity_date:
                    athlete_from_db.newest_activity_date = activity.start_date
                elif activity.start_date < athlete_from_db.oldest_activity_date:
                    athlete_from_db.oldest_activity_date = activity.start_date
            athlete_from_db.save()

        segment_efforts = client.get_activity(activity.id).segment_efforts   # API call

        # 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   # API call (possibly lots, depends on number of segments)

        # get friend with time < athlete time
        for i, entry in enumerate(leaderboard):
            if entry.athlete_id == athlete_id:
                me = entry

                if i == 0:
                    # I'm already the winner!
                    break

                j = 1
                while j <= i and leaderboard[i - j].elapsed_time == me.elapsed_time:
                    # check for ties, compare each entry from i to zero (possibly)
                    j += 1
                if leaderboard[i - j].elapsed_time == me.elapsed_time:
                    # if they're still tied at the end of the loop, I don't want to see it
                    break

                other = leaderboard[i - j]

                try:
                    new_segment = ChallengedSegment.objects.get(my_id=athlete_id, segment_id=segment.id)
                except ChallengedSegment.DoesNotExist:
                    new_segment = ChallengedSegment()

                new_segment.my_id = athlete_id
                new_segment.their_id = other.athlete_id
                new_segment.their_name = other.athlete_name

                new_segment.my_pr = me.activity_id
                new_segment.their_pr = other.activity_id

                new_segment.my_time = str(me.elapsed_time)
                new_segment.their_time = str(other.elapsed_time)
                new_segment.difference = str(me.elapsed_time - other.elapsed_time)

                new_segment.segment_id = segment.id
                new_segment.segment_name = segment.name
                new_segment.segment_distance = str(unithelper.miles(segment.distance))
                new_segment.save()

                break  # we already found my entry, why keep looking through the list?
Example #31
0
class artbot(PyBot):
    def bot_init(self):
        """
        Custom initialization. Specify any configuration options you want to
        override, as in particular your OAuth credentials.
        """

        #############################
        #                           #
        # Twitter OAuth Credentials #
        #                           #
        #      FILL THESE IN!       #
        #                           #
        #############################

        self.config['api_key'] = 'your_api_key'
        self.config['api_secret'] = 'your_api_secret'
        self.config['access_key'] = 'your_access_key'
        self.config['access_secret'] = 'your_access_secret'

        #############################
        #                           #
        #   Other config options    #
        #                           #
        # Fill these in if you want #
        #   or otherwise need to.   #
        #                           #
        #############################

        self.config['strava_access_token'] = 'your_strava_token'
        self.config['update_day'] = 0
        self.config['update_hour'] = 13
        self.config['update_minute'] = 13
        self.config['tweet_interval'] = self._compute_interval

        # Create the Strava client.
        self.client = Client(access_token=self.config['strava_access_token'])

    def on_tweet(self):
        # First, pull in the stats from Strava.
        current = datetime.datetime.now()
        last_week = current + datetime.timedelta(weeks=-1)
        after = datetime.datetime(last_week.year, last_week.month,
                                  last_week.day)
        activities = self.client.get_activities(after=after)

        # Second, filter by activity type and time frame.
        lf = [a for a in activities if a.start_date_local.day != current.day]
        num_activities = len(lf)
        l = [a.id for a in lf if a.type == 'Run']

        # Third, tabulate up the stats for mileage and calories.
        mileage = 0.0
        calories = 0.0
        for activity_id in l:
            activity = self.client.get_activity(activity_id)
            distance = unithelper.miles(activity.distance)
            mileage += round(distance.num, 2)  # Rounds to 2 sig figs.
            calories += activity.calories
        calories = int(calories)

        # Finally, use the stats to craft a tweet. This can be any format
        # you want, but I'll use the example one from the start of the post.
        tweet = "My training last week: {:d} workouts for {:.2f} miles and {:d} calories burned.".format(
            num_activities, mileage, calories)
        self.update_status(tweet)

    def _compute_interval(self):
        """
        This is a little more sophisticated than the method in the original
        blog post. This is to provide for *exactly* specifying when we want
        a post to be made, down to the minute.
        """
        now = datetime.datetime.now()
        target = datetime.datetime(year=now.year,
                                   month=now.month,
                                   day=now.day,
                                   hour=self.config['update_hour'],
                                   minute=self.config['update_minute'])
        days_ahead = self.config['update_day'] - now.weekday()
        if (days_ahead < 0) or (days_ahead == 0 and (target - now).days < 0):
            days_ahead += 7
        td = target + datetime.timedelta(days=days_ahead)
        interval = int((td - datetime.datetime.now()).total_seconds())
        return interval
Example #32
0
# My data
my_data = client.get_athlete() # athlete details
me = {}
me["id"] = my_data.id
me["name"] = my_data.firstname + " " + my_data.lastname
me["city"] = my_data.city
my_bikes = my_data.bikes
bikes = {}
for b in my_bikes:
    bike = {}
    bike[b.id] = b.name
    bikes.update(bike)
me["bikes"] = bikes

# Fetch activities this year
my_activities = client.get_activities(after=datetime(2015, 1, 1)) #(limit=5)
act = []
for a in my_activities:
    act.append(a)

# Fetch every activity % make collections
cycling_collection = []
swimming_collection = []

for i in range(len(act)):
    print "fetching activity " + str(i)
    id = act[i].id
    activity = client.get_activity(id)

    # Activity collections
    if activity.type == "Ride":
Example #33
0
from stravalib import Client
import csv

client_id = '28201'
my_token = '06e91657960068f2c92e2e02419934f6493fe5b6'

client = Client(access_token=my_token)

activities = client.get_activities(limit=100)
rides = list(activities)

with open("activities.csv", "w", newline="") as file:
    csv_writer = csv.writer(file)
    for ride in rides:
        date = str(ride.start_date_local)[:10]
        distance = str(ride.distance)[:-5]
        elevation = str(ride.total_elevation_gain).rstrip(" m")
        csv_writer.writerow([date, distance, elevation])

# activity = client.get_activity(1801822008)

# print(activity.distance)
# print(activity.moving_time)
# print(activity.average_speed)
# print(activity.total_elevation_gain)

Example #34
0
def get_activities(self, token):

    client = Client(token)
    user = client.get_athlete()

    # Update StavaUser
    lastUpdate = datetime.now()
    strUser = StravaUser.objects.filter(uid=user.id)
    print('strUser='******'lastUpdate=', lastUpdate)

    #d = datetime(2018, 5, 5)
    date_1_day_ago = lastUpdate - timedelta(days=1)

    activities = client.get_activities(after=date_1_day_ago, limit=50)
    #activities = client.get_activities(after=d,limit=15)
    act = None
    nbItem = 0
    nbAct = 0
    for activity in activities:
        nbAct += 1

    print('NbAct=', nbAct)
    initNewActivities = False
    newUser = False
    segment = 15
    begin = 0
    end = begin + segment
    currentList = Activity.objects.filter(
        uid=client.get_athlete().id).order_by('-strTime')[begin:end]
    if not currentList.exists():
        newUser = True
    while (currentList.exists() or newUser):
        print('currentList=', currentList)
        print('begin=', begin)
        print('end=', end)
        actList = []
        for actItem in currentList:
            #print (actItem)
            serializer = ActivityItemSerializer(actItem)
            #print ('serializer.data: ',serializer.data)
            actList.append(serializer.data)

        data = {'nbAct': nbAct, 'currentAct': nbItem, 'activities': actList}
        sendMessage('actList', data, strUser[0].channel_name)
        actList.clear()

        if not initNewActivities:
            for activity in activities:
                StravaUser.objects.filter(uid=user.id).update(
                    currentActIndex=nbItem, nbActToRetreive=nbAct)
                act = client.get_activity(activity.id)
                strDate = act.start_date.strftime("%Y-%m-%d %H:%M:%S")
                #print ('uid=',user.id)
                #print ('start_date=',strDate)
                #print ('act.distance=',act.distance)
                #print ('act.type=',act.type)
                dist = re.sub(' .*$', '', str(act.distance))
                #print ('dist=',dist)
                strDistance = format(float(dist) / 1000, '.2f')
                #print ('distance=',strDistance)
                #print ('stravaId=',act.upload_id)
                print('name=', act.name)
                #print ('time=',act.elapsed_time)
                #print ('splits_metric=',act.splits_metric)
                if not Activity.objects.filter(stravaId=activity.id).exists():
                    workout = Workout.objects.create(name=act.name)
                    print('wid=', workout.id)
                    print('stravaId=', activity.id)
                    activity.wid = workout.id
                    stravaAct = Activity(strTime=strDate,strDist=strDistance,distance=act.distance,\
                        time=act.elapsed_time,label=act.name,stravaId=activity.id,wid=workout.id,workout_id=workout.id,\
                        resolution=strUser[0].resolution,uid=user.id,type=act.type,state="c",progress=0)
                    stravaAct.save()
                    Workout.objects.filter(id=workout.id).update(
                        actId=stravaAct.id)
                    split = Split.objects.filter(workout__id=workout.id)
                    print('Split first element=', split.count())
                    if not split.count():
                        if split is not None:
                            objs = [
                                Split(split_index=i,
                                      split_distance=split.distance,
                                      split_time=split.elapsed_time,
                                      workout=workout)
                                for i, split in enumerate(act.splits_metric)
                            ]
                            split = Split.objects.bulk_create(objs)

                    # Send result list to client
                    for actItem in Activity.objects.filter(
                            stravaId=activity.id):
                        #print (actItem)
                        serializer = ActivityItemSerializer(actItem)
                        # pre-process Json for client response to get workout
                        self.result = processJsonDataBackup.delay(
                            token, workout.id, json.dumps(serializer.data))
                        #print ('serializer.data: ',serializer.data)
                        actList.insert(0, serializer.data)
                else:
                    Activity.objects.filter(stravaId=activity.id).update(
                        strTime=strDate,
                        strDist=strDistance,
                        resolution=strUser[0].resolution)

                nbItem += 1

                data = {
                    'nbAct': nbAct,
                    'currentAct': nbItem,
                    'activities': actList
                }
                sendMessage('actList', data, strUser[0].channel_name)
                initNewActivities = True

        begin = end
        end = begin + segment
        currentList = Activity.objects.filter(
            uid=client.get_athlete().id).order_by('-strTime')[begin:end]
        newUser = False

    if act is not None:
        print('Update user last_date')
        strUser.update(lastUpdate=datetime.now())

    return {'current': nbItem, 'total': nbAct}
Example #35
0
class Tracker:

    def __init__(self):
        # Strava client to hold information for tracker.
        self.client = Client()

        # Time token expires at.
        self.token_expires_at_ = None

        # Client information.
        self.client_id = None
        self.client_secret = None

        # Time in seconds between refreshes.
        self.sleep_time_ = 300

        # Number of target activities per week.
        self.target_ = 4

        # Private display object.
        self.display_ = Display()

        # Activity tracking variables.
        self.start_date = datetime.datetime.utcnow().date()
        self.next_week  = self.start_date + datetime.timedelta(weeks=1)
        self.week_streak = 0
        self.num_activities = 0

        # Filename of save file.
        self.save_file_ = 'streak.yaml'


    def set_expiration(self, token_expires_at):
        self.token_expires_at_ = token_expires_at

    def set_client_info(self, client_id, client_secret):
        self.client_id = client_id
        self.client_secret = client_secret

    def save_status(self):
        save_obj = {'start_date' : self.start_date, 'next_week' : self.next_week, 
                'week_streak' : self.week_streak, 'num_activities' : self.num_activities}
        with open(self.save_file_, 'wb') as save_file:
            pickle.dump(save_obj, save_file)

    def load_status(self):
        save_obj = None
        try:
            with open(self.save_file_, 'rb') as save_file:
                save_obj = pickle.load(save_file)
            self.start_date = save_obj['start_date']
            self.next_week = save_obj['next_week']
            self.week_streak = save_obj['week_streak']
            self.num_activities = save_obj['num_activities']
        except (OSError, IOError, EOFError) as e:
            print('Nothing in this save file, going to save defaults.')
            self.save_status()

    def update(self):
        self.save_status()
        self.display_.show(self.week_streak, self.target_ - self.num_activities, self.target_)



    def run(self):
        # Save start date/time
        # Ask Strava for activities since 1 week ago
        # If len(activities) >= goal increment streak
        # Check that token won't expire in 12 hours
        # If token needs refreshing, refresh it
        # Sleep for sleep_time
        self.load_status()
        self.update()
        while(True):
            # Refresh token if necessary.
            if time.time() > self.token_expires_at_:
                refresh_response = self.client.refresh_access_token(client_id=self.client_id,
                                                      client_secret=self.client_secret,
                                                      refresh_token=self.client.refresh_token)
                self.token_expires_at_ = refresh_response['expires_at']
                print('Refreshing token, new one expires at {}'
                        .format(str(refresh_response['expires_at'])))

            new_activities = len(list(self.client.get_activities(after = self.start_date.isoformat())))

            # Handle null return from Strava servers.
            if not new_activities:
                new_activities = 0
            print(new_activities)

            if new_activities != self.num_activities:
                print("New activities detected!")
                self.num_activities = new_activities
                self.update()

            for activity in self.client.get_activities(after = self.start_date.isoformat()):
                print("{0.name} {0.moving_time}".format(activity))


            # Check if we've hit the target for this week.
            if self.num_activities >= self.target_:
                self.week_streak += 1
                self.update()

            cur_date = datetime.datetime.utcnow().date()

            # Check if it's next week.
            if cur_date == self.next_week:

                # Check if we haven't hit our target and reset.
                if self.num_activities < self.target_:
                    self.week_streak = 0

                # Advance the date to a week from now.
                self.start_date = cur_date
                self.next_week = cur_date + datetime.timedelta(weeks=1)
                self.update()

            time.sleep(self.sleep_time_)
Example #36
0
def access_token_and_database():
    """Check user authorization, get temporary authorization code, exchange code for token,
    and manage database."""

    # If user authorizes, "code" will be included in query string
    # If user denies, error message "access_denied" will be included in query string

    error = request.args.get('error', '')
    if error:
        return "Error: " + error
    code = request.args.get("code")
    access_token = client.exchange_code_for_token(
        client_id=oauth_credentials["CLIENT_ID"],
        client_secret=oauth_credentials["CLIENT_SECRET"],
        code=code)
    authenticated_athlete = Client(access_token=access_token)

    # Get authenticated athlete firstname (http://strava.github.io/api/v3/athlete/).
    name = authenticated_athlete.get_athlete().firstname

    # Check whether authenticated_athlete already exists in database. If true, delete activities.
    # If false, add athlete.
    athlete_in_database = Athlete.query.filter_by(
        access_token=access_token).first()
    if athlete_in_database:
        activities_to_delete = Activity.query.filter_by(
            athlete_id=athlete_in_database.id)
        for activity in activities_to_delete:
            db.session.delete(activity)
        db.session.commit()
    else:
        athlete_in_database = Athlete(access_token=access_token,
                                      name=name,
                                      activities=[])
        db.session.add(athlete_in_database)
        db.session.commit()

    ######################################################################
    # Get authenticated athlete list of activities and store to database #
    ######################################################################

    # Define variable for the last year of activities
    one_year_ago = datetime.datetime.utcnow() - datetime.timedelta(days=365)

    activities = authenticated_athlete.get_activities(after=one_year_ago)
    for activity in activities:
        if activity.has_heartrate and activity.average_speed.num > 0:
            value = (activity.average_speed / activity.average_heartrate)
            # Stravalib is returning Activity classes that work with units, requiring ".num" for some
            entry = Activity(
                distance=activity.distance.num,
                moving_time=activity.moving_time,
                total_elevation_gain=activity.total_elevation_gain.num,
                type=activity.type,
                start_date=activity.start_date,  # Column = 4
                start_date_local=activity.start_date_local,
                average_speed=activity.average_speed.num,
                average_heartrate=activity.average_heartrate,
                aerobic_value=value.num,  # Column = 8
                athlete_id=athlete_in_database.id)
            db.session.add(entry)
        db.session.commit()

    message = "<center>" \
              "<p>Hello, {}. Thank you for authorizing with Strava.<br/><br/>"\
              "<a href=http://0.0.0.0:8080/visualization.png>" \
              "Ready to analyze your activities?</a><br/><br/>" \
              "<a><img src='static/img/api_logo_pwrdBy_strava_stack_gray.png'></a></p>" \
              "</center>".format(name)

    return message
Example #37
0
class Strava(object):
    def __init__(self, cfg):
        self.token = cfg.get('token')
        self.convert_swim = cfg.get('convert_swim')

        self.client = Client(access_token=self.token)
        self.athlete = self.client.get_athlete()
        self.activities = self.client.get_activities()

        print('Loading data for: {} {}'.format(self.athlete.firstname.encode('utf8'), self.athlete.lastname.encode('utf8')))

    def json(self):
        out = []

        for a in self.activities:
            out.append(self._format_activity(a))

        return out

    def _format_activity(self, a):
        out = {
            'measurement': 'activity',
            'time': a.start_date.isoformat(),
            'fields': {
                'distance': a.distance.num,
                'moving_time': a.moving_time.total_seconds(),
                'elapsed_time': a.elapsed_time.total_seconds(),
                'total_elevation_gain': a.total_elevation_gain.num,
            },
            'tags': {
                'type': a.type,
                'athlete': a.athlete.id,
            },
        }

        return out

    def _get_param_from_activity(self, a):
        return {
            'name': a.name,
            'activity_type': a.type,
            'start_date_local': a.start_date_local.isoformat(),
            'elapsed_time': int(a.elapsed_time.total_seconds()),
            'description': a.description,
            'distance': a.distance,
            'private': a.private,
        }

    def convert_swimming(self):
        print(self.convert_swim)

        lap_time_min = self.convert_swim['lap_time_min']
        lap_time_max = self.convert_swim['lap_time_max']
        lap_distance = self.convert_swim['lap_distance']

        for a in self.activities:
            if a.type == 'Swim' and a.distance.num == 0 and not a.description and not re.match('DELETE:.*', a.name):
                print(self._format_activity(a))

                problem = 0
                distance = 0
                # count laps and distances
                for lap in a.laps:
                    if lap_time_min < lap.elapsed_time.total_seconds() < lap_time_max:
                        distance += lap_distance
                    else:
                        problem += 1
                        break

                if problem == 0 and distance > 0:
                    print('Fine:')

                    new_activity = self._get_param_from_activity(a)
                    new_activity['distance'] = float(distance)

                    if not new_activity['description']:
                        new_activity['description'] = 'Converted by Sport Sucker.\nActivity #{}'.format(a.id)

                    print('Create new')
                    print(new_activity)

                    new_activity_saved = self.client.create_activity(**new_activity)

                    if not a.description:
                        self.client.update_activity(
                            a.id,
                            name='DELETE: {}'.format(a.name),
                            description='Should be deleted, replaced by #{}'.format(new_activity_saved.id)
                        )

                else:
                    print('UNABLE to convert swimming')
debug = False

METERS_IN_A_MILE = 1609.34

pacific_timezone = timezone('America/Los_Angeles')

#mmf = MapMyFitness(api_key=MMF_CLIENT_KEY, access_token=MMF_ACCESS_TOKEN)

strava = Client( access_token=STRAVA_ACCESS_TOKEN)

fitbit_client = fitbit.Fitbit( FITBIT_CLIENT_KEY, FITBIT_CLIENT_SECRET, user_key=FITBIT_USER_KEY, user_secret=FITBIT_USER_SECRET)

# Only grab the last 10 activities

activities = strava.get_activities( limit = 10 )

#for activity in activities:
#    print activity.type

# Iterate through all valid activity types
#for activity_id in MMF_BIKE_ACTIVITY_TYPES: 
#  workouts = workouts + mmf.workout.search( user=MMF_USER_ID, activity_type=activity_id, started_after=started_after )

for activity in activities:
  start_datetime = activity.start_date_local

  start_date = start_datetime.strftime( '%Y-%m-%d' )
  start_time = start_datetime.strftime( '%H:%M' )
  duration_milliseconds = int( 1000 * activity.moving_time.total_seconds() )
  distance = unithelper.miles( activity.distance ).num
Example #39
0
import os
import sys
sys.path.insert(0,os.path.join('..','Resources','AccessInformation'))
from accessinformation import access_token

from flask import Flask, render_template,jsonify
from stravalib import Client , unithelper

import json

client = Client(access_token )
print(client.get_athlete())
print([float(unithelper.miles(i.distance)) for i in client.get_activities()])
print([i.segment_efforts for i in client.get_activities()])

with open('../Data/JSONData/MainDataset.json') as f:
    data = json.load(f)

app = Flask(__name__)

@app.route("/")
def homepage():
    return(render_template('index.html'))

@app.route("/data")
def dataset():
    return(jsonify(data))

if __name__ == '__main__':
    app.run()
Example #40
0
from stravalib import Client
import matplotlib.pyplot as plt, numpy as np
import api

client = Client(access_token=api.access_token)

activities = list(client.get_activities())  # Get current athlete details

id = activities[0].id

types = ['time', 'altitude', 'latlng', 'moving', 'distance']

s = client.get_activity_streams(id, types=types)
distance = s['distance']
altitude = s['altitude']
latlng = s['latlng']
y, x = zip(*latlng.data)

fig, ax = plt.subplots(2)
ax[0].plot(distance.data, altitude.data, 'k')  # elevation profile
ax[1].plot(x, y, 'k')  # route overview
ax[1].set_aspect('equal')
plt.show()

# Elevation heatmap
fig, ax = plt.subplots()

points = np.array([x, y]).T.reshape(-1, 1, 2)
segments = np.concatenate([points[:-1], points[1:]], axis=1)

lc = LineCollection(segments,
Example #41
0
class artbot(PyBot):

    def bot_init(self):
        """
        Custom initialization. Specify any configuration options you want to
        override, as in particular your OAuth credentials.
        """

        #############################
        #                           #
        # Twitter OAuth Credentials #
        #                           #
        #      FILL THESE IN!       #
        #                           #
        #############################

        self.config['api_key'] = 'your_api_key'
        self.config['api_secret'] = 'your_api_secret'
        self.config['access_key'] = 'your_access_key'
        self.config['access_secret'] = 'your_access_secret'

        #############################
        #                           #
        #   Other config options    #
        #                           #
        # Fill these in if you want #
        #   or otherwise need to.   #
        #                           #
        #############################

        self.config['strava_access_token'] = 'your_strava_token'
        self.config['update_day'] = 0
        self.config['update_hour'] = 13
        self.config['update_minute'] = 13
        self.config['tweet_interval'] = self._compute_interval

        # Create the Strava client.
        self.client = Client(access_token = self.config['strava_access_token'])

    def on_tweet(self):
        # First, pull in the stats from Strava.
        current = datetime.datetime.now()
        last_week = current + datetime.timedelta(weeks = -1)
        after = datetime.datetime(last_week.year, last_week.month, last_week.day)
        activities = self.client.get_activities(after = after)

        # Second, filter by activity type and time frame.
        lf = [a for a in activities if a.start_date_local.day != current.day]
        num_activities = len(lf)
        l = [a.id for a in lf if a.type == 'Run']

        # Third, tabulate up the stats for mileage and calories.
        mileage = 0.0
        calories = 0.0
        for activity_id in l:
            activity = self.client.get_activity(activity_id)
            distance = unithelper.miles(activity.distance)
            mileage += round(distance.num, 2)  # Rounds to 2 sig figs.
            calories += activity.calories
        calories = int(calories)

        # Finally, use the stats to craft a tweet. This can be any format
        # you want, but I'll use the example one from the start of the post.
        tweet = "My training last week: {:d} workouts for {:.2f} miles and {:d} calories burned.".format(num_activities, mileage, calories)
        self.update_status(tweet)

    def _compute_interval(self):
        """
        This is a little more sophisticated than the method in the original
        blog post. This is to provide for *exactly* specifying when we want
        a post to be made, down to the minute.
        """
        now = datetime.datetime.now()
        target = datetime.datetime(year = now.year, month = now.month, day = now.day,
            hour = self.config['update_hour'], minute = self.config['update_minute'])
        days_ahead = self.config['update_day'] - now.weekday()
        if (days_ahead < 0) or (days_ahead == 0 and (target - now).days < 0):
            days_ahead += 7
        td = target + datetime.timedelta(days = days_ahead)
        interval = int((td - datetime.datetime.now()).total_seconds())
        return interval
Example #42
0
def authorization(request):
    client = Client()
    code = request.GET['code']
    access_token = client.exchange_code_for_token(
        client_id=MY_STRAVA_CLIENT_ID,
        client_secret=MY_STRAVA_CLIENT_SECRET,
        code=code)

    # making a global variable to be used across views. don't know how this will work in practice

    client = Client(access_token=access_token)
    athlete = client.get_athlete()  # Get current athlete details

    global athleteId
    athleteId = athlete.id

    # if athlete doesn't exist, add them
    if len(Athlete.objects.filter(athleteId=athleteId)) == 0:
        ath = Athlete.objects.create(
            name=str(athlete.firstname + ' ' + athlete.lastname),
            athleteId=athleteId,
            profilePic=athlete.profile,
            city=athlete.city,
            country=athlete.country,
            sex=athlete.sex,
            premium=athlete.premium,
            created_at=athlete.created_at,
            updated_at=athlete.updated_at,
            followers=athlete.follower_count,
            friends=athlete.friend_count,
            email=athlete.email,
            weight=athlete.weight,
            meas_pref=athlete.measurement_preference,
            runsSummary=DataFrame({}).to_json(orient='records'),
            fitLines=DataFrame({}).to_json(orient='records'),
            masterList=DataFrame({}).to_json(orient='records'))

        ath.profilePic.name = "rudyzPic"
        ath.save(update_fields=['profilePic'])

    # if athlete already exists, draw their file
    elif len(Athlete.objects.filter(athleteId=athleteId)) == 1:
        ath = Athlete.objects.get(athleteId=athleteId)

    ############################################
    ##### compiling new runs, updating summary

    # athlete's existing runs summary
    existingSummary = DataFrame(pd.read_json(ath.runsSummary))
    existingFitlines = DataFrame(pd.read_json(ath.fitLines))
    masterList = DataFrame(pd.read_json(ath.masterList))

    activities = list(client.get_activities())

    # activity IDs of runs already in the system
    try:
        ids = existingSummary.activityId
    except AttributeError:
        ids = []

    for i in range(len(activities)):
        #for i in range(30,37):
        # Ignoring activities already in the system
        if (len(ids) == 0) or (float(activities[i].id) not in list(ids)):

            try:
                # compiling df for raw json-ization
                activityId = activities[i].id
                run = client.get_activity_streams(activityId,
                                                  types=[
                                                      'time', 'latlng',
                                                      'distance', 'heartrate',
                                                      'altitude', 'cadence'
                                                  ])
                latlng = run['latlng'].data
                time = run['time'].data
                distance = run['distance'].data
                heartrate = run['heartrate'].data
                altitude = run['altitude'].data
                cadence = run['cadence'].data
                date = activities[i].start_date_local
                activity = activityId
                dfi = thresher.assemble(date, activityId, heartrate, distance,
                                        time, altitude, latlng, cadence)

                # basic cleanup, only removing totally unreasonable values
                dfi = thresher.basicClean(dfi)

                # if we ever want to try our hand at improving strava's speed data (ie by predicting speed when GPS blanks), intervene here:

                #dfi = thresher.addDistDeltas(dfi)

                try:
                    fitline = thresher.getFitlineLws(
                        dfi)  # this adds speed-shifted columns
                except:
                    fitline = pd.DataFrame({})

                try:
                    mafScore = fitline[fitline.hr == 140.0].avgSpeed.iloc[0]
                    print "MAF "
                    print mafScore
                except:
                    mafScore = np.nan

                fitline_json = fitline.to_json(orient='records')

                # getting summary info for run (as one-entry dict)
                runSummary = thresher.getSingleSummaryDf(dfi)

                # adding mafScore to summary
                runSummary['mafScore'] = mafScore

                print runSummary

                # adding predicted hr and speed values
                #dfi = thresher.getPred(dfi)

                # saving entry to database
                Activity.objects.create(act_id=activityId,
                                        name=str(activities[i].name),
                                        description=activities[i].description,
                                        act_type=activities[i].type,
                                        date=activities[i].start_date_local,
                                        timezone=activities[i].timezone,
                                        df=dfi.to_json(orient='records'),
                                        avgHr=runSummary['avgHr'],
                                        hrVar=runSummary['variation'],
                                        realMiles=runSummary['realMiles'],
                                        recovery=runSummary['recovery'],
                                        easy=runSummary['easy'],
                                        stamina=runSummary['stamina'],
                                        impulse=runSummary['impulse'],
                                        totalTime=runSummary['totalTime'],
                                        totalDist=runSummary['totalDist'],
                                        climb=runSummary['climb'],
                                        fitline=fitline_json,
                                        mafScore=mafScore,
                                        athlete=ath)

                # updating runs summary
                existingSummary = existingSummary.append(runSummary,
                                                         ignore_index=True)
                existingFitlines = existingFitlines.append(fitline,
                                                           ignore_index=True)
                masterList = masterList.append(dfi, ignore_index=True)

            except:
                continue

    # saving updated runs summary to athlete profile
    ath.runsSummary = existingSummary.to_json(orient='records')
    ath.save(update_fields=['runsSummary'])

    existingSummary.to_pickle("runsSummary.txt")

    # saving updated runs summary to athlete profile
    ath.fitLines = existingFitlines.to_json(orient='records')
    ath.save(update_fields=['fitLines'])

    ath.masterList = masterList.to_json(orient='records')
    ath.save(update_fields=['masterList'])

    # testing...
    existingSummary = pd.read_json(ath.runsSummary)
    #print(existingSummary)

    existingFitlines = pd.read_json(ath.fitLines)
    #print(existingFitlines)

    global path
    path = os.path.dirname(__file__)
    # updating dataframe, pickling for use in other views
    #global df
    #df = thresher.masterAssemble(client)

    masterDf = pd.read_json(ath.masterList)
    #print(masterDf)
    masterDf.to_pickle(str(path) + "/" + str(athlete.id) + "masterDf.txt")

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