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 collect_ride_data(self, challenge): """ Pull the latest ride data from Strava via the API """ client = Client() client.access_token = self.strava_config['access-token'] #activities = client.get_club_activities(165009) activities = client.get_club_activities(challenge.get_group_id()) act_list = [] for activity in activities: if not activity.type == 'Ride' and not activity.type == 'VirtualRide': print 'Non-ride activity: %s, type: %s' % (activity.name, activity.type) continue act = Activity(activity.id) act.set_athlete(activity.athlete.id) act.set_name(activity.name) act.set_gmt_date(activity.start_date) # GMT Start date act.set_elapsed_time(activity.elapsed_time) act.set_distance(round(unithelper.kilometers(activity.distance).num, 2)) act.set_elevation(unithelper.meters(activity.total_elevation_gain).num) act.set_ride_type(activity.type) act.set_trainer_ride(activity.trainer) act_list.append(act) db_store = GTDataStore(challenge.get_db_path(), self.verbose) db_store.store_if_new(act_list)
def test_get_segment(self): segment = self.client.get_segment(229781) self.assertIsInstance(segment, model.Segment) print(segment) self.assertEquals('Hawk Hill', segment.name) self.assertAlmostEqual(2.68, float(uh.kilometers(segment.distance)), places=2) # Fetch leaderboard lb = segment.leaderboard self.assertEquals(10, len(lb)) # 10 top results, 5 bottom results
def strava_lastact(bot, trigger, client): act = next(client.get_activities()) name = act.name act_type = act.type distance = unithelper.kilometers(act.distance) start = act.start_date_local.strftime('%-d %B %-H:%m') time = '{:02}:{:02}:{:02}'.format(*seconds_to_time(act.moving_time.seconds)) achievements = act.achievement_count tokens = [trigger.nick, name, act_type, distance, time, start, achievements] out = '{}\'s last activity: {} ({}) {} ({}) on {} ({} ☺️)'.format(*tokens) bot.say(out) bot.say('https://www.strava.com/activities/{}'.format(act.id))
def test_distance_units(self): # Gear g = model.Gear() g.distance = 1000 self.assertEquals(1.0, float(uh.kilometers(g.distance))) # Metric Split split = model.Split() split.distance = 1000 # meters split.elevation_difference = 1000 # meters self.assertIsInstance(split.distance, Quantity) self.assertIsInstance(split.elevation_difference, Quantity) self.assertEquals(1.0, float(uh.kilometers(split.distance))) self.assertEquals(1.0, float(uh.kilometers(split.elevation_difference))) split = None # Segment s = model.Segment() s.distance = 1000 s.elevation_high = 2000 s.elevation_low = 1000 s.pr_distance = 1000 self.assertIsInstance(s.distance, Quantity) self.assertIsInstance(s.elevation_high, Quantity) self.assertIsInstance(s.elevation_low, Quantity) self.assertEquals(1.0, float(uh.kilometers(s.distance))) self.assertEquals(2.0, float(uh.kilometers(s.elevation_high))) self.assertEquals(1.0, float(uh.kilometers(s.elevation_low))) self.assertEquals(1.0, float(uh.kilometers(s.pr_distance))) # Activity a = model.Activity() a.distance = 1000 # m a.total_elevation_gain = 1000 # m self.assertIsInstance(a.distance, Quantity) self.assertIsInstance(a.total_elevation_gain, Quantity) self.assertEquals(1.0, float(uh.kilometers(a.distance))) self.assertEquals(1.0, float(uh.kilometers(a.total_elevation_gain)))
def test_get_activity(self): """ Test basic activity fetching. """ activity = self.client.get_activity(96089609) self.assertEquals('El Dorado County, CA, USA', activity.location_city) self.assertIsInstance(activity.start_latlng, attributes.LatLon) self.assertAlmostEquals(-120.4357631, activity.start_latlng.lon, places=2) self.assertAlmostEquals(38.74263759999999, activity.start_latlng.lat, places=2) self.assertIsInstance(activity.map, model.Map) self.assertIsInstance(activity.athlete, model.Athlete) self.assertEquals(1513, activity.athlete.id) #self.assertAlmostEqual(first, second, places, msg, delta) # Ensure that iw as read in with correct units self.assertEquals(22.5308, float(uh.kilometers(activity.distance)))
def strava_koms(bot, trigger, client): athlete = client.get_athlete() koms = client.get_athlete_koms(athlete.id) for kom in koms: name = kom.name kom_type = kom.segment.activity_type distance = unithelper.kilometers(kom.distance) time = kom.moving_time printtime = '{:02}:{:02}:{:02}'.format(*seconds_to_time(time.seconds)) efforts = kom.segment.leaderboard.effort_count if len(kom.segment.leaderboard.entries) > 1: next_time = kom.segment.leaderboard.entries[1].moving_time diff = next_time - time else: diff = time - time printdiff = '{:02}:{:02}:{:02}'.format(*seconds_to_time(diff.seconds)) tokens = [name, kom_type, efforts, distance, printtime, printdiff] bot.say('{} ({}): 1/{} - {} in {} - {} faster'.format(*tokens))
def post_activity(self, activity): payload = {} if (activity.athlete.firstname is None): activity.athlete = self.client.get_athlete(activity.athlete.id) first_name = activity.athlete.firstname last_name = activity.athlete.lastname distance = kilometers(activity.distance) activity_duration = activity.moving_time speed = kilometers_per_hour(activity.average_speed) climbing = meters(activity.total_elevation_gain) activity_id = activity.id description = activity.name if (len(description) > 100): description = description[:97] + "..." payload = {'username': '******', 'icon_url': 'https://raw.githubusercontent.com/patoupatou/pymatterstrava/master/icon-strava.png', 'text': u':bicyclist: *{} {} : distance: {}, moving time duration: {}, speed: {}, climbing: {}* [{}](http://strava.com/activities/{}) :bicyclist:'.format(first_name, last_name, distance, activity_duration, speed, climbing, description, activity_id)} r = self.http.request('POST', self.mattermostUrl, headers={'Content-Type': 'application/json'}, body=json.dumps(payload)) print(time.ctime() + ': New activity posted') print('payload: ' + str(payload) + '\n')
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)))
def strava_bikes(bot, trigger, client): athlete = client.get_athlete() for i in athlete.bikes: bot.say('{}: {}'.format(i.name, unithelper.kilometers(i.distance)))
def activity_dict(athlete, a): elapsed_time = unithelper.seconds(a.elapsed_time.total_seconds()) if athlete.measurement_preference == 'feet': distance = str(unithelper.miles(a.distance)) gain = str(unithelper.feet(a.total_elevation_gain)) if a.type == 'Ride': speed = str(unithelper.mph(a.average_speed)) elapsed_speed = str(unithelper.mph(a.distance / elapsed_time)) else: try: speed = "{0:.2f} /mi".format( 60 / (unithelper.mph(a.average_speed).num)) elapsed_speed = "{0:.2f} /mi".format( 60 / unithelper.mph(a.distance / elapsed_time).num) except ZeroDivisionError: speed = 'NaN' elapsed_speed = 'NaN' else: distance = str(unithelper.kilometers(a.distance)) gain = str(unithelper.meters(a.total_elevation_gain)) if a.type == 'Ride': speed = str(unithelper.kph(a.average_speed)) elapsed_speed = str(unithelper.kph(a.distance / elapsed_time)) else: try: speed = "{0:.2f} /km".format( 60 / (unithelper.kph(a.average_speed).num)) elapsed_speed = "{0:.2f} /km".format( 60 / unithelper.kph(a.distance / elapsed_time).num) except ZeroDivisionError: speed = 'NaN' elapsed_speed = 'NaN' date = a.start_date_local.strftime(athlete.date_preference or "%a, %d %b %Y") weekday = calendar.day_name[a.start_date_local.weekday()] workout_type = '' if a.type == 'Run': workout_type = ['', 'Race', 'Long Run', 'Workout'][int(a.workout_type or 0)] garmin_link = '' if a.external_id: if a.external_id.startswith('garmin_push_'): garmin_id = a.external_id.split('_')[2] garmin_link = 'https://connect.garmin.com/modern/activity/{}'.format( garmin_id) return { 'id': a.id, 'link': url_for('query.show_activity', id=a.id), 'strava_link': 'https://www.strava.com/activities/{}'.format(a.id), 'garmin_link': garmin_link, 'name': a.name, 'type': a.type, 'workout_type': workout_type, 'date': date, 'weekday': weekday, 'distance': distance, 'gain': gain, 'elapsed_time': str(a.elapsed_time), 'moving_time': str(a.moving_time), 'speed': speed, 'elapsed_speed': elapsed_speed, 'start_latlng': [a.start_latitude, a.start_longitude], 'polyline': a.map.polyline or a.map.summary_polyline }
def create_club_workbook(filename: str, athlete_map: dict): workbook = Workbook(filename, {'default_date_format':'dd/mm/yy'}) worksheet = workbook.add_worksheet() bold = workbook.add_format({'bold': True}) row = 0 col = 0 worksheet.write(row, col, 'Name', bold) worksheet.write(row, col+1, 'Distance (km)', bold) worksheet.write(row, col+2, 'Moving Time (s)', bold) worksheet.write(row, col+3, 'Elapsed Time (s)', bold) worksheet.write(row, col+4, 'Total Elevation Gain (m)', bold) worksheet.write(row, col+5, 'Activity Type', bold) worksheet.set_column('A:A', 14) worksheet.set_column('B:B', 20) worksheet.set_column('C:C', 20) worksheet.set_column('D:D', 20) worksheet.set_column('E:E', 28) worksheet.set_column('F:F', 18) row += 1 total_distance_kilometers = float(0) for key in athlete_map: athlete_distance_kilometers = 0 athlete_moving_time_seconds = 0 athlete_elapsed_time_seconds = 0 athlete_total_elevation_gain_meters = 0 for idx, activity in enumerate(athlete_map[key]): distance_kilometers = unithelper.kilometers(activity['distance']) athlete_distance_kilometers += float(distance_kilometers) moving_time = activity['moving_time'] athlete_moving_time_seconds += moving_time.seconds elapsed_time = activity['elapsed_time'] athlete_elapsed_time_seconds += elapsed_time.seconds total_elevation_gain_meters = unithelper.meters(activity['total_elevation_gain']) athlete_total_elevation_gain_meters += float(total_elevation_gain_meters) worksheet.write(row, col, key) worksheet.write(row, col+1, round(float(distance_kilometers), util.DEFAULT_DECIMAL_PLACES)) worksheet.write(row, col+2, moving_time.seconds) worksheet.write(row, col+3, elapsed_time.seconds) worksheet.write(row, col+4, float(total_elevation_gain_meters)) worksheet.write(row, col+5, activity['type']) row += 1 col = 0 total_distance_kilometers += athlete_distance_kilometers print( '=> Total distance is {total_distance_kilometers} km'.format( total_distance_kilometers=round(total_distance_kilometers, util.DEFAULT_DECIMAL_PLACES), ) ) workbook.close() print( '\n=> Wrote "{filename}"\n'.format( filename=filename, ) )
def add_run(user, activity): return add_activity(user, RUN_GOAL_SLUG, activity, unithelper.kilometers(activity.distance))