FitTrackee/mpwo_api/mpwo_api/activities/stats.py

134 lines
5.2 KiB
Python
Raw Normal View History

2018-06-06 13:45:39 +02:00
from datetime import datetime, timedelta
2018-06-06 00:22:24 +02:00
from flask import Blueprint, jsonify, request
from mpwo_api import appLog
from ..users.models import User
from ..users.utils import authenticate
2018-06-06 12:09:09 +02:00
from .models import Activity, Sport, convert_timedelta_to_integer
2018-06-06 00:22:24 +02:00
stats_blueprint = Blueprint('stats', __name__)
2018-06-06 12:16:52 +02:00
def get_activities(user_id, type):
2018-06-06 00:22:24 +02:00
try:
user = User.query.filter_by(id=user_id).first()
if not user:
response_object = {
2018-06-06 12:09:09 +02:00
'status': 'not found',
2018-06-06 00:22:24 +02:00
'message': 'User does not exist.'
}
return jsonify(response_object), 404
params = request.args.copy()
date_from = params.get('from')
date_to = params.get('to')
2018-06-06 12:16:52 +02:00
sport_id = params.get('sport_id')
2018-06-06 12:09:09 +02:00
time = params.get('time')
2018-06-06 12:16:52 +02:00
if type == 'by_sport':
sport_id = params.get('sport_id')
if sport_id:
sport = Sport.query.filter_by(id=sport_id).first()
if not sport:
print('not sport')
response_object = {
'status': 'not found',
'message': 'Sport does not exist.'
}
return jsonify(response_object), 404
2018-06-06 00:22:24 +02:00
activities = Activity.query.filter(
Activity.user_id == user_id,
Activity.activity_date >= datetime.strptime(date_from, '%Y-%m-%d')
if date_from else True,
Activity.activity_date <= datetime.strptime(date_to, '%Y-%m-%d')
if date_to else True,
2018-06-06 12:16:52 +02:00
Activity.sport_id == sport_id if sport_id else True,
2018-06-06 00:22:24 +02:00
).order_by(
Activity.activity_date.asc()
).all()
2018-06-06 12:16:52 +02:00
activities_list = {}
2018-06-06 00:22:24 +02:00
for activity in activities:
2018-06-06 12:16:52 +02:00
if type == 'by_sport':
sport_id = activity.sport_id
if sport_id not in activities_list:
activities_list[sport_id] = {
'nb_activities': 0,
'total_distance': 0.,
'total_duration': 0,
}
activities_list[sport_id]['nb_activities'] += 1
activities_list[sport_id]['total_distance'] += \
float(activity.distance)
activities_list[sport_id]['total_duration'] += \
convert_timedelta_to_integer(activity.duration)
2018-06-06 12:09:09 +02:00
else:
2018-06-06 12:16:52 +02:00
if time == 'week':
2018-06-06 13:45:39 +02:00
activity_date = activity.activity_date - timedelta(
days=activity.activity_date.isoweekday()
)
time_period = datetime.strftime(activity_date,
"%Y-%m-%d_W%U")
2018-06-06 12:16:52 +02:00
elif time == 'weekm': # week start Monday
2018-06-06 13:45:39 +02:00
activity_date = activity.activity_date - timedelta(
days=activity.activity_date.weekday()
)
time_period = datetime.strftime(activity_date,
"%Y-%m-%d_W%W")
2018-06-06 12:16:52 +02:00
elif time == 'month':
time_period = datetime.strftime(activity.activity_date, "%Y-%m") # noqa
elif time == 'year' or not time:
time_period = datetime.strftime(activity.activity_date, "%Y") # noqa
else:
response_object = {
'status': 'fail',
'message': 'Invalid time period.'
}
return jsonify(response_object), 400
sport_id = activity.sport_id
if time_period not in activities_list:
activities_list[time_period] = {}
if sport_id not in activities_list[time_period]:
activities_list[time_period][sport_id] = {
'nb_activities': 0,
'total_distance': 0.,
'total_duration': 0,
}
activities_list[time_period][sport_id]['nb_activities'] += 1
activities_list[time_period][sport_id]['total_distance'] += \
float(activity.distance)
activities_list[time_period][sport_id]['total_duration'] += \
convert_timedelta_to_integer(activity.duration)
2018-06-06 12:09:09 +02:00
response_object = {
'status': 'success',
'data': {
'statistics': activities_list
}
}
code = 200
except Exception as e:
appLog.error(e)
response_object = {
'status': 'error',
'message': 'Error. Please try again or contact the administrator.'
}
code = 500
return jsonify(response_object), code
2018-06-06 12:16:52 +02:00
@stats_blueprint.route('/stats/<int:user_id>/by_time', methods=['GET'])
2018-06-06 12:09:09 +02:00
@authenticate
2018-06-06 12:16:52 +02:00
def get_activities_by_time(auth_user_id, user_id):
2018-06-06 12:09:09 +02:00
"""Get activities statistics for a user"""
2018-06-06 12:16:52 +02:00
return get_activities(user_id, 'by_time')
2018-06-06 12:09:09 +02:00
2018-06-06 12:16:52 +02:00
@stats_blueprint.route('/stats/<int:user_id>/by_sport', methods=['GET'])
@authenticate
def get_activities_by_sport(auth_user_id, user_id):
return get_activities(user_id, 'by_sport')