Example #1
0
def strava_send_song_activities(act_id_s):
    if len(act_id_s) != 1 or act_id_s[0] == None:
        return (None, )

    act_id = act_id_s[0]
    act = Activity.objects.filter(activity_id=act_id)

    if not act:
        return (None, )

    act = act[0]

    if not act.athlete.share_activity_songs:
        return (None, )

    # act.athlete.save()
    ath = strava_get_user_info(id=act.athlete.athlete_id)

    client = stravalib.client.Client()
    client.access_token = ath.strava_token
    client.refresh_token = ath.strava_refresh_token
    client.token_expires_at = ath.strava_token_expires_at

    activity = client.get_activity(act_id)
    description = activity.description

    if description:
        start = description.find("Songs listened during activity:")
        end = description.rfind("https://effortly.run/activity/" + str(act_id))
        if start != -1 and end != -1:
            end += len("https://effortly.run/activity/" + str(act_id))
            description = description[:start] + description[end:]
        start = description.find("Songs listened during activity:")
        end = description.rfind("https://effortly.run")
        if start != -1 and end != -1:
            end += len("https://effortly.run/")
            description = description[:start] + description[end:]
        start = description.find("No songs found")
        end = description.rfind("https://effortly.run")
        if start != -1 and end != -1:
            end += len("https://effortly.run/")
            description = description[:start] + description[end:]
        description = act.activity_share_message + '\n' + description
    else:
        description = act.activity_share_message

    client.update_activity(act_id, description=description.strip())
    return (None, )
Example #2
0
def sync_one_activity_spotify(activity_id, athlete_id, delay=0):
    athlete = strava_get_user_info(id=athlete_id)

    client = stravalib.client.Client()
    client.access_token = athlete.strava_token
    client.refresh_token = athlete.strava_refresh_token
    client.token_expires_at = athlete.strava_token_expires_at

    if not athlete.strava_token_expires_at:
        return "00000000-0000-0000-0000-000000000000", 0

    act_p = strava_parse_base_activity(client.get_activity(activity_id))
    download_chain = chain(
        strava_task.si('strava_download_activity', (act_p, )),
        spotify_task.s('spotify_download_activity_tracks', (True, )),
        activity_to_efforts.s(),
        strava_task.s('strava_send_song_activities', ()))
    job_result = download_chain.apply_async(countdown=delay)

    return job_result.id, 1
Example #3
0
def move(id):
    move = Move.query.filter_by(id=id).first_or_404()

    if not move.public and move.user != current_user:
        return app.login_manager.unauthorized()

    samples = move.samples.order_by(Sample.time.asc()).all()
    events = [sample for sample in samples if sample.events]

    filtered_events = []
    pauses = []
    laps = []
    pause_begin = None
    for sample in events:
        assert len(sample.events.keys()) == 1
        if 'pause' in sample.events:
            state = sample.events['pause']['state'].lower() == 'true'
            if state:
                pause_begin = sample
            elif not state and pause_begin:
                pauses.append([pause_begin, sample])
        elif 'lap' in sample.events:
            laps.append(sample)
        else:
            filtered_events.append(sample)

    model = {
        'BING_MAPS_API_KEY':
        app.config['BING_MAPS_API_KEY']
        if 'BING_MAPS_API_KEY' in app.config else None,
        'move':
        move,
        'samples':
        samples,
        'events':
        filtered_events,
        'pauses':
        pauses,
        'laps':
        laps
    }

    gps_samples = [
        sample for sample in samples if sample.sample_type
        and sample.sample_type.startswith('gps-') and sample.latitude
    ]
    model['gps_samples'] = gps_samples

    if gps_samples:
        if not move.location_address:
            postprocess_move(move)
            flash(
                "got %d GPS samples but no location. recalculated" %
                len(gps_samples), 'warning')
            db.session.commit()

        calculate_distances(model, move.samples)

    if 'swimming' in move.activity:
        swimming_events = [
            sample for sample in filtered_events if 'swimming' in sample.events
        ]
        model['swimming_events'] = swimming_events

        model['swimming_style_changes'] = [
            sample for sample in swimming_events
            if sample.events['swimming']['type'] == 'StyleChange'
        ]
        model['swimming_turns'] = [
            sample for sample in swimming_events
            if sample.events['swimming']['type'] == 'Turn'
        ]

        swimming_strokes = [
            sample for sample in swimming_events
            if sample.events['swimming']['type'] == 'Stroke'
        ]
        model['swimming_strokes'] = swimming_strokes

        pause_samples = list(itertools.chain.from_iterable(pauses))
        model['swimming_strokes_and_pauses'] = sorted(
            swimming_strokes + pause_samples, key=lambda sample: sample.time)

        model['swim_pace'] = timedelta(seconds=move.duration.total_seconds() /
                                       move.distance)

        if move.stroke_count:
            assert len(model['swimming_strokes']) == move.stroke_count

    if current_user.is_authenticated:
        if current_user.has_strava() and move.strava_activity_id is not None:
            client = strava.get_strava_client(current_user)
            strava_activity = client.get_activity(
                activity_id=move.strava_activity_id)
            model['strava_activity_name'] = strava_activity.name

    # eg. 'Pool swimming' → 'pool_swimming'
    activity_name = move.activity.lower().replace(' ', '_')
    try:
        return render_template("move/%s.html" % activity_name, **model)
    except TemplateNotFound:
        # Fall-back to generic template
        return render_template("move/_move.html", **model)
Example #4
0
def move(id):
    move = Move.query.filter_by(id=id).first_or_404()

    if not move.public and move.user != current_user:
        return app.login_manager.unauthorized()

    samples = move.samples.order_by(Sample.time.asc()).all()
    events = [sample for sample in samples if sample.events]

    filtered_events = []
    pauses = []
    laps = []
    pause_begin = None
    for sample in events:
        assert len(sample.events.keys()) == 1
        if 'pause' in sample.events:
            state = sample.events['pause']['state'].lower() == 'true'
            if state:
                pause_begin = sample
            elif not state and pause_begin:
                pauses.append([pause_begin, sample])
        elif 'lap' in sample.events:
            laps.append(sample)
        else:
            filtered_events.append(sample)

    model = {
        'BING_MAPS_API_KEY': app.config['BING_MAPS_API_KEY'] if 'BING_MAPS_API_KEY' in app.config else None,
        'move': move,
        'samples': samples,
        'events': filtered_events,
        'pauses': pauses,
        'laps': laps
    }

    gps_samples = [sample for sample in samples if sample.sample_type and sample.sample_type.startswith('gps-')]
    model['gps_samples'] = gps_samples

    if gps_samples:
        if not move.location_address:
            postprocess_move(move)
            flash(u"got %d GPS samples but no location. recalculated" % len(gps_samples), u'warning')
            db.session.commit()

        calculate_distances(model, move.samples)

    if 'swimming' in move.activity:
        swimming_events = [sample for sample in filtered_events if 'swimming' in sample.events]
        model['swimming_events'] = swimming_events

        model['swimming_style_changes'] = [sample for sample in swimming_events if sample.events['swimming']['type'] == 'StyleChange']
        model['swimming_turns'] = [sample for sample in swimming_events if sample.events['swimming']['type'] == 'Turn']

        swimming_strokes = [sample for sample in swimming_events if sample.events['swimming']['type'] == 'Stroke']
        model['swimming_strokes'] = swimming_strokes

        pause_samples = list(itertools.chain.from_iterable(pauses))
        model['swimming_strokes_and_pauses'] = sorted(swimming_strokes + pause_samples, key=lambda sample: sample.time)

        model['swim_pace'] = timedelta(seconds=move.duration.total_seconds() / move.distance)

        if move.stroke_count:
            assert len(model['swimming_strokes']) == move.stroke_count

    if current_user.is_authenticated:
        if current_user.has_strava() and move.strava_activity_id is not None:
            client = strava.get_strava_client(current_user)
            strava_activity = client.get_activity(activity_id=move.strava_activity_id)
            model['strava_activity_name'] = strava_activity.name

    # eg. 'Pool swimming' → 'pool_swimming'
    activity_name = move.activity.lower().replace(' ', '_')
    try:
        return render_template("move/%s.html" % activity_name, **model)
    except TemplateNotFound:
        # Fall-back to generic template
        return render_template("move/_move.html", **model)
    except Exception as e:
        if app.debug or app.testing:
            raise e
        else:
            flash("Failed to load move template of activity '%s'." % activity_name)
            return redirect(url_for('index'))