Exemple #1
0
def index(request):
    primary_bike_id = ''
    bikes = request.user.gear_set.all()
    for bike in bikes:
        if bike.primary:
            primary_bike_id = bike.strava_id

    gear_id = request.POST.get('gear_id', primary_bike_id)
    before = request.POST.get('before')
    after = request.POST.get('after')
    if before and after:
        before = datetime.datetime.strptime(before, '%Y-%m-%d') + timedelta(hours=23, minutes=59, seconds=59)
        after = datetime.datetime.strptime(after, '%Y-%m-%d') + timedelta(hours=23, minutes=59, seconds=59)
    else:
        before = datetime.datetime.today().replace(hour=23, minute=59, second=59, microsecond=0)
        after = before - timedelta(days=7)

    stra = strava()
    filters = [
        {'field': 'athlete.id', 'query': request.user.strava_id},
        {'field': 'start_date', 'query': {'$lt': before, '$gte': after}},
        {'field': 'gear_id', 'query': gear_id},
    ]
    activities = stra.aggregate_activities_mongo(filters, {
        '_id': None,
        'distance': {'$sum': '$distance'},
        'elapsed_time': {'$sum': '$moving_time'},
        'elevation': {'$sum': '$total_elevation_gain'},
        'average_speed': {'$avg': '$average_speed'},
        'kilojoules': {'$sum': '$kilojoules'},
    })

    template_fields = {
        'bikes': bikes,
        'gear_id':gear_id,
        'before':before.strftime('%Y-%m-%d'),
        'after':after.strftime('%Y-%m-%d'),
        'distance': unithelper.miles(unit('m')(0)),
        'time': unithelper.hours(unit('s')(0)),
        'elevation': unithelper.meters(unit('m')(0)),
        'avg_speed': unithelper.mph(unit('m')(0)/unit('s')(1)),
        'kjs': 0,
    }
    activity = None
    for agg in activities:
        if not activity:
            activity = agg

    if activity:
        merge_dict = template_fields.copy()
        merge_dict.update({
            'distance': unithelper.miles(unit('m')(activity['distance'])),
            'time': unithelper.hours(unit('s')(activity['elapsed_time'])),
            'elevation': unithelper.meters(unit('m')(activity['elevation'])),
            'avg_speed': unithelper.mph(unit('m')(activity['average_speed'])/unit('s')(1)),
            'kjs': activity['kilojoules'],
        })
        template_fields = merge_dict

    return render_to_response('strava/templates/strava_index.html', template_fields, context_instance=RequestContext(request))
Exemple #2
0
def update_ride_from_activity(strava_activity, ride):
    """
    Refactoring to just set ride properties from the Strava Activity object.

    :param strava_activity: The Strava Activyt
    :type strava_activity: stravalib.model.Activity
    :param ride: The ride model object.
    :type ride: Ride
    """
     # Should apply to both new and preexisting rides ...
    # If there are multiple instagram photos, then request syncing of non-primary photos too.

    if strava_activity.photo_count > 1 and ride.photos_fetched is None:


        log.debug("Scheduling non-primary photos sync for {!r}".format(ride))
        ride.photos_fetched = False

    ride.private = bool(strava_activity.private)
    ride.name = strava_activity.name
    ride.start_date = strava_activity.start_date_local

    # We need to round so that "1.0" miles in strava is "1.0" miles when we convert back from meters.
    ride.distance = round(float(unithelper.miles(strava_activity.distance)), 3)

    ride.average_speed = float(unithelper.mph(strava_activity.average_speed))
    ride.maximum_speed = float(unithelper.mph(strava_activity.max_speed))
    ride.elapsed_time = timedelta_to_seconds(strava_activity.elapsed_time)
    ride.moving_time = timedelta_to_seconds(strava_activity.moving_time)

    location_parts = []
    if strava_activity.location_city:
        location_parts.append(strava_activity.location_city)
    if strava_activity.location_state:
        location_parts.append(strava_activity.location_state)
    location_str = ', '.join(location_parts)

    ride.location = location_str

    ride.commute = strava_activity.commute
    ride.trainer = strava_activity.trainer
    ride.manual = strava_activity.manual
    ride.elevation_gain = float(unithelper.feet(strava_activity.total_elevation_gain))
    ride.timezone = str(strava_activity.timezone)

    # # Short-circuit things that might result in more obscure db errors later.
    if ride.elapsed_time is None:
        raise DataEntryError("Activities cannot have null elapsed time.")

    if ride.moving_time is None:
        raise DataEntryError("Activities cannot have null moving time.")

    if ride.distance is None:
        raise DataEntryError("Activities cannot have null distance.")

    log.debug("Writing ride for {athlete!r}: \"{ride!r}\" on {date}".format(athlete=ride.athlete.name,
                                                                        ride=ride.name,
                                                                        date=ride.start_date.strftime('%m/%d/%y')))
Exemple #3
0
    def test_speed_units(self):
        a = model.Activity()

        a.max_speed = 1000  # m/s
        a.average_speed = 1000  # m/s
        self.assertEquals(3600.0, float(uh.kph(a.max_speed)))
        self.assertEquals(3600.0, float(uh.kph(a.average_speed)))

        a.max_speed = uh.mph(1.0)
        # print repr(a.max_speed)

        self.assertAlmostEqual(1.61, float(uh.kph(a.max_speed)), places=2)
Exemple #4
0
def to_mph(mps):
    return float(unithelper.mph(act.average_speed))
Exemple #5
0
    if "latlng" in stream_filter:
      sdf["lat"] = [a[0] for a in sdf.latlng]
      sdf["lng"] = [a[1] for a in sdf.latlng]
      del sdf["latlng"]

    detail_fname = join(output_detail_dir, "{0}.json".format(act.id))
    sdf.to_json(detail_fname)

    # with open(join(output_detail_dir, "{0}.p".format(act.id)), "wb") as f:
    #     pickle.dump(sdf, f, 2)

    print "{0} on {1:%d %b %Y} [kudos {2}]".format(act.name, act.start_date, act.kudos_count)
    print "\tHR: {0}".format(act.average_heartrate)
    print "\tDistance: {0}".format(unithelper.miles(act.distance))
    print "\tSpeed: {0}".format(unithelper.mph(act.average_speed))

    item = dict((k, func(getattr(act, k, None))) for k, func in save_fields.iteritems())
    data.append(item)
    start_dates.append(act.start_date)

df = pd.DataFrame(data=data, index=start_dates)

summary_fname = join(output_dir, "summary.json")
df.to_json(summary_fname)

# with open(join(output_dir, "summary.p"), "wb") as f:
#     pickle.dump(df, f, 2)

df.to_csv(join(output_dir, "summary.csv"))