Example #1
0
 def resolve_webhook(self, object_id: int):
     """
     Resolves a webhook event from Strava by retrieving the activity data and
     checking it against the user's existing rules. If a match is found, sends the
     request to Strava to rename it.
     """
     self.refresh()
     client = Client(access_token=self.access_token)
     activity = client.get_activity(object_id)
     # The Strava API doesn't give enough precision in its start latitude and
     # longitude values, so we have to call the raw stream of points to get what we
     # need.
     points = client.get_activity_streams(
         activity.id, types=["latlng"], resolution="low"
     )
     activity_start = points["latlng"].data[0]
     current_app.logger.info(
         f"Webhook event received: Activity {object_id}, User {self.id}, Starting"
         f"point {activity_start}, Starting time {activity.start_date_local}"
     )
     for rule in self.rules.all():
         current_app.logger.info(f"Checking {rule} against activity {object_id}")
         if rule.check_rule(activity_start, activity.start_date_local):
             # if not current_app.config.TESTING:
             client.update_activity(object_id, name=rule.activity_name)
             current_app.logger.info(
                 f"Activity {activity.id} renamed to {rule.activity_name} for {self}"
             )
             break  # No need to check any more activities
Example #2
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 #3
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 #4
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')