Exemple #1
0
def move_import():
    xmlfiles = request.files.getlist('files')
    imported_moves = []

    for xmlfile in xmlfiles:
        filename = xmlfile.filename
        if filename:
            app.logger.info("importing '%s'" % filename)
            move_id = imports.move_import(xmlfile, filename, current_user,
                                          request.form)
            if move_id:
                imported_moves.append(move_id)

    if imported_moves and current_user.has_strava():
        after = min(imported_moves, key=lambda move: move.date_time
                    ).date_time - strava.MAX_DATE_TIME_OFFSET
        before = max(imported_moves, key=lambda move: move.date_time
                     ).date_time + strava.MAX_DATE_TIME_OFFSET
        app.logger.debug("trying to find Strava activities in (%s, %s)" %
                         (before, after))
        associated_activities, known_activities, new_activities = strava.associate_activities(
            current_user, before=before, after=after)
        if len(associated_activities) == 1:
            flash("associated with Strava activity %d" %
                  associated_activities[0][0].id)
        elif len(associated_activities) > 1:
            flash("associated %d Strava activities" %
                  len(associated_activities))
        else:
            flash('found no Strava activities to associate with', 'warning')

    if imported_moves:
        if len(imported_moves) == 1:
            move_id = imported_moves[0]
            flash("imported '%s': move %d" % (xmlfile.filename, move_id.id))
            return redirect(url_for('move', id=move_id.id))
        else:
            flash("imported %d moves" % len(imported_moves))
            return redirect(url_for('moves'))
    else:
        model = {'has_strava': current_user.has_strava()}
        if current_user.has_strava():
            associated_activities, known_activities, new_activities = strava.associate_activities(
                current_user)

            model['new_strava_activities'] = new_activities
            model['associated_strava_activities'] = associated_activities
            model['known_strava_activities'] = known_activities

        elif 'STRAVA_CLIENT_ID' in app.config:
            client = stravalib.client.Client()
            client_id_ = app.config['STRAVA_CLIENT_ID']
            strava_authorize_url = client.authorization_url(
                client_id=client_id_,
                redirect_uri=url_for('strava_authorized', _external=True),
                scope='activity:read_all')
            model['strava_authorize_url'] = strava_authorize_url

        return render_template('import.html', **model)
Exemple #2
0
def move_import():
    xmlfiles = request.files.getlist('files')
    imported_moves = []

    for xmlfile in xmlfiles:
        filename = xmlfile.filename
        if filename:
            app.logger.info("importing '%s'" % filename)
            move_id = imports.move_import(xmlfile, filename, current_user, request.form)
            if move_id:
                imported_moves.append(move_id)

    if imported_moves and current_user.has_strava():
        after = min(imported_moves, key=lambda move: move.date_time).date_time - strava.MAX_DATE_TIME_OFFSET
        before = max(imported_moves, key=lambda move: move.date_time).date_time + strava.MAX_DATE_TIME_OFFSET
        app.logger.debug("trying to find Strava activities in (%s, %s)" % (before, after))
        associated_activities, known_activities, new_activities = strava.associate_activities(current_user, before=before, after=after)
        if len(associated_activities) == 1:
            flash(u"associated with Strava activity %d" % associated_activities[0][0].id)
        elif len(associated_activities) > 1:
            flash(u"associated %d Strava activities" % len(associated_activities))
        else:
            flash(u'found no Strava activities to associate with', 'warning')

    if imported_moves:
        if len(imported_moves) == 1:
            move_id = imported_moves[0]
            flash("imported '%s': move %d" % (xmlfile.filename, move_id.id))
            return redirect(url_for('move', id=move_id.id))
        else:
            flash("imported %d moves" % len(imported_moves))
            return redirect(url_for('moves'))
    else:
        model = {'has_strava': current_user.has_strava()}
        if current_user.has_strava():
            associated_activities, known_activities, new_activities = strava.associate_activities(current_user)

            model['new_strava_activities'] = new_activities
            model['associated_strava_activities'] = associated_activities
            model['known_strava_activities'] = known_activities

        elif 'STRAVA_CLIENT_ID' in app.config:
            client = stravalib.client.Client()
            client_id_ = app.config['STRAVA_CLIENT_ID']
            strava_authorize_url = client.authorization_url(client_id=client_id_,
                                                            redirect_uri=url_for('strava_authorized', _external=True),
                                                            scope='view_private')
            model['strava_authorize_url'] = strava_authorize_url

        return render_template('import.html', **model)
Exemple #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)
Exemple #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'))