source: OpenWorkouts-current/ow/views/user.py @ c9991fed

currentfeature/docs
Last change on this file since c9991fed was a3c3baa, checked in by Borja Lopez <borja@…>, 5 years ago

Show the totals in the user profile, for the selected month/week
(number of workouts, time, distance and elevation)

  • Property mode set to 100644
File size: 11.5 KB
Line 
1import json
2from calendar import month_name
3from datetime import datetime, timezone, timedelta
4from decimal import Decimal
5
6from pyramid.httpexceptions import HTTPFound
7from pyramid.view import view_config
8from pyramid.security import remember, forget
9from pyramid.response import Response
10from pyramid.i18n import TranslationStringFactory
11from pyramid_simpleform import Form, State
12from pytz import common_timezones
13
14from ..models.user import User
15from ..schemas.user import (
16    UserProfileSchema,
17    ChangePasswordSchema,
18    SignUpSchema,
19)
20from ..models.root import OpenWorkouts
21from ..views.renderers import OWFormRenderer
22from ..utilities import timedelta_to_hms
23
24_ = TranslationStringFactory('OpenWorkouts')
25
26
27@view_config(context=OpenWorkouts)
28def dashboard_redirect(context, request):
29    """
30    Send the user to his dashboard when accesing the root object,
31    send to the login page if the user is not logged in.
32    """
33    if request.authenticated_userid:
34        user = request.root.get_user_by_uid(request.authenticated_userid)
35        if user:
36            return HTTPFound(location=request.resource_url(user))
37        else:
38            # an authenticated user session, for an user that does not exist
39            # anymore, logout!
40            return HTTPFound(location=request.resource_url(context, 'logout'))
41    return HTTPFound(location=request.resource_url(context, 'login'))
42
43
44@view_config(
45    context=OpenWorkouts,
46    name='login',
47    renderer='ow:templates/login.pt')
48def login(context, request):
49    message = ''
50    email = ''
51    password = ''
52    return_to = request.params.get('return_to')
53    redirect_url = return_to or request.resource_url(request.root)
54
55    if 'submit' in request.POST:
56        email = request.POST.get('email', None)
57        user = context.get_user_by_email(email)
58        if user:
59            password = request.POST.get('password', None)
60            if password is not None and user.check_password(password):
61                headers = remember(request, str(user.uid))
62                redirect_url = return_to or request.resource_url(user)
63                return HTTPFound(location=redirect_url, headers=headers)
64            else:
65                message = _('Wrong password')
66        else:
67            message = _('Wrong email address')
68
69    return {
70        'message': message,
71        'email': email,
72        'password': password,
73        'redirect_url': redirect_url
74    }
75
76
77@view_config(context=OpenWorkouts, name='logout')
78def logout(context, request):
79    headers = forget(request)
80    return HTTPFound(location=request.resource_url(context), headers=headers)
81
82
83@view_config(
84    context=OpenWorkouts,
85    name='signup',
86    renderer='ow:templates/signup.pt')
87def signup(context, request):
88    state = State(emails=context.lowercase_emails,
89                  names=context.lowercase_nicknames)
90    form = Form(request, schema=SignUpSchema(), state=state)
91
92    if 'submit' in request.POST and form.validate():
93        user = form.bind(User(), exclude=['password_confirm'])
94        context.add_user(user)
95        # Send to login
96        return HTTPFound(location=request.resource_url(context))
97
98    return {
99        'form': OWFormRenderer(form)
100    }
101
102
103@view_config(
104    context=OpenWorkouts,
105    name='forgot-password',
106    renderer='ow:templates/forgot_password.pt')
107def recover_password(context, request):  # pragma: no cover
108    # WIP
109    Form(request)
110
111
112@view_config(
113    context=User,
114    permission='view',
115    renderer='ow:templates/dashboard.pt')
116def dashboard(context, request):
117    """
118    Render a dashboard for the current user
119    """
120    # Look at the year we are viewing, if none is passed in the request,
121    # pick up the latest/newer available with activity
122    viewing_year = request.GET.get('year', None)
123    if viewing_year is None:
124        available_years = context.activity_years
125        if available_years:
126            viewing_year = available_years[0]
127    else:
128        # ensure this is an integer
129        viewing_year = int(viewing_year)
130
131    # Same for the month, if there is a year set
132    viewing_month = None
133    if viewing_year:
134        viewing_month = request.GET.get('month', None)
135        if viewing_month is None:
136            available_months = context.activity_months(viewing_year)
137            if available_months:
138                # we pick up the latest month available for the year,
139                # which means the current month in the current year
140                viewing_month = available_months[-1]
141        else:
142            # ensure this is an integer
143            viewing_month = int(viewing_month)
144
145    # pick up the workouts to be shown in the dashboard
146    workouts = context.workouts(viewing_year, viewing_month)
147
148    return {
149        'current_year': datetime.now(timezone.utc).year,
150        'current_day_name': datetime.now(timezone.utc).strftime('%a'),
151        'month_name': month_name,
152        'viewing_year': viewing_year,
153        'viewing_month': viewing_month,
154        'workouts': workouts
155    }
156
157
158@view_config(
159    context=User,
160    permission='view',
161    name='profile',
162    renderer='ow:templates/profile.pt')
163def profile(context, request):
164    """
165    "public" profile view, showing some workouts from this user, her
166    basic info, stats, etc
167    """
168    now = datetime.now(timezone.utc)
169    year = int(request.GET.get('year', now.year))
170    month = int(request.GET.get('month', now.month))
171    week = request.GET.get('week', None)
172    workouts = context.workouts(year, month, week)
173    totals = {
174        'distance': Decimal(0),
175        'time': timedelta(0),
176        'elevation': Decimal(0)
177    }
178
179    for workout in workouts:
180        totals['distance'] += getattr(workout, 'distance', Decimal(0))
181        totals['time'] += getattr(workout, 'duration', timedelta(0))
182        totals['elevation'] += getattr(workout, 'uphill', Decimal(0))
183
184    return {
185        'workouts': workouts,
186        'current_month': '{year}-{month}'.format(
187            year=str(year), month=str(month).zfill(2)),
188        'current_week': week,
189        'totals': totals
190    }
191
192
193@view_config(
194    context=User,
195    name='picture',
196    permission='view')
197def profile_picture(context, request):
198    return Response(
199        content_type='image',
200        body_file=context.picture.open())
201
202
203@view_config(
204    context=User,
205    permission='edit',
206    name='edit',
207    renderer='ow:templates/edit_profile.pt')
208def edit_profile(context, request):
209    # if not given a file there is an empty byte in POST, which breaks
210    # our blob storage validator.
211    # dirty fix until formencode fixes its api.is_empty method
212    if isinstance(request.POST.get('picture', None), bytes):
213        request.POST['picture'] = ''
214
215    nicknames = request.root.lowercase_nicknames
216    if context.nickname:
217        # remove the current user nickname from the list, preventing form
218        # validation error
219        nicknames.remove(context.nickname.lower())
220    state = State(emails=request.root.lowercase_emails, names=nicknames)
221    form = Form(request, schema=UserProfileSchema(), state=state, obj=context)
222
223    if 'submit' in request.POST and form.validate():
224        # No picture? do not override it
225        if not form.data['picture']:
226            del form.data['picture']
227        form.bind(context)
228        # reindex
229        request.root.reindex(context)
230        # Saved, send the user to the public view of her profile
231        return HTTPFound(location=request.resource_url(context, 'profile'))
232
233    # prevent crashes on the form
234    if 'picture' in form.data:
235        del form.data['picture']
236
237    return {'form': OWFormRenderer(form),
238            'timezones': common_timezones}
239
240
241@view_config(
242    context=User,
243    permission='edit',
244    name='passwd',
245    renderer='ow:templates/change_password.pt')
246def change_password(context, request):
247    form = Form(request, schema=ChangePasswordSchema(),
248                state=State(user=context))
249    if 'submit' in request.POST and form.validate():
250        context.password = form.data['password']
251        return HTTPFound(location=request.resource_url(context, 'profile'))
252    return {'form': OWFormRenderer(form)}
253
254
255@view_config(
256    context=User,
257    permission='view',
258    name='week')
259def week_stats(context, request):
260    stats = context.week_stats
261    json_stats = []
262    for day in stats:
263        hms = timedelta_to_hms(stats[day]['time'])
264        day_stats = {
265            'name': day.strftime('%a'),
266            'time': str(hms[0]).zfill(2),
267            'distance': int(round(stats[day]['distance'])),
268            'elevation': int(stats[day]['elevation']),
269            'workouts': stats[day]['workouts']
270        }
271        json_stats.append(day_stats)
272    return Response(content_type='application/json',
273                    charset='utf-8',
274                    body=json.dumps(json_stats))
275
276
277@view_config(
278    context=User,
279    permission='view',
280    name='monthly')
281def last_months_stats(context, request):
282    """
283    Return a json-encoded stream with statistics for the last 12 months
284    """
285    stats = context.yearly_stats
286    # this sets which month is 2 times in the stats, once this year, once
287    # the previous year. We will show it a bit different in the UI (showing
288    # the year too to prevent confusion)
289    repeated_month = datetime.now(timezone.utc).date().month
290    json_stats = []
291    for month in stats:
292        hms = timedelta_to_hms(stats[month]['time'])
293        name = month_name[month[1]][:3]
294        if month[1] == repeated_month:
295            name += ' ' + str(month[0])
296        month_stats = {
297            'id': str(month[0]) + '-' + str(month[1]).zfill(2),
298            'name': name,
299            'time': str(hms[0]).zfill(2),
300            'distance': int(round(stats[month]['distance'])),
301            'elevation': int(stats[month]['elevation']),
302            'workouts': stats[month]['workouts'],
303            'url': request.resource_url(
304                context, 'profile',
305                query={'year': str(month[0]), 'month': str(month[1])})
306        }
307        json_stats.append(month_stats)
308    return Response(content_type='application/json',
309                    charset='utf-8',
310                    body=json.dumps(json_stats))
311
312
313@view_config(
314    context=User,
315    permission='view',
316    name='weekly')
317def last_weeks_stats(context, request):
318    """
319    Return a json-encoded stream with statistics for the last 12-months, but
320    in a per-week basis
321    """
322    stats = context.weekly_year_stats
323    # this sets which month is 2 times in the stats, once this year, once
324    # the previous year. We will show it a bit different in the UI (showing
325    # the year too to prevent confusion)
326    repeated_month = datetime.now(timezone.utc).date().month
327    json_stats = []
328    for week in stats:
329        hms = timedelta_to_hms(stats[week]['time'])
330        name = month_name[week[1]][:3]
331        if week[1] == repeated_month:
332            name += ' ' + str(week[0])
333        week_stats = {
334            'id': '-'.join(
335                [str(week[0]), str(week[1]).zfill(2), str(week[2])]),
336            'week': str(week[3]),  # the number of week in the current month
337            'name': name,
338            'time': str(hms[0]).zfill(2),
339            'distance': int(round(stats[week]['distance'])),
340            'elevation': int(stats[week]['elevation']),
341            'workouts': stats[week]['workouts'],
342            'url': request.resource_url(
343                context, 'profile',
344                query={'year': str(week[0]),
345                       'month': str(week[1]),
346                       'week': str(week[2])})
347        }
348        json_stats.append(week_stats)
349    return Response(content_type='application/json',
350                    charset='utf-8',
351                    body=json.dumps(json_stats))
Note: See TracBrowser for help on using the repository browser.