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

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

Fixed some tests broken during the last code changes.
Fixed a bug in the calculations of the totals for the profile page
(we weren't taking in account possible None values for distance,
duration and specially elevation/uphill)

  • Property mode set to 100644
File size: 11.6 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'] += (
181            getattr(workout, 'distance', Decimal(0)) or Decimal(0))
182        totals['time'] += (
183            getattr(workout, 'duration', timedelta(0)) or timedelta(0))
184        totals['elevation'] += (
185            getattr(workout, 'uphill', Decimal(0)) or Decimal(0))
186
187    return {
188        'workouts': workouts,
189        'current_month': '{year}-{month}'.format(
190            year=str(year), month=str(month).zfill(2)),
191        'current_week': week,
192        'totals': totals
193    }
194
195
196@view_config(
197    context=User,
198    name='picture',
199    permission='view')
200def profile_picture(context, request):
201    return Response(
202        content_type='image',
203        body_file=context.picture.open())
204
205
206@view_config(
207    context=User,
208    permission='edit',
209    name='edit',
210    renderer='ow:templates/edit_profile.pt')
211def edit_profile(context, request):
212    # if not given a file there is an empty byte in POST, which breaks
213    # our blob storage validator.
214    # dirty fix until formencode fixes its api.is_empty method
215    if isinstance(request.POST.get('picture', None), bytes):
216        request.POST['picture'] = ''
217
218    nicknames = request.root.lowercase_nicknames
219    if context.nickname:
220        # remove the current user nickname from the list, preventing form
221        # validation error
222        nicknames.remove(context.nickname.lower())
223    state = State(emails=request.root.lowercase_emails, names=nicknames)
224    form = Form(request, schema=UserProfileSchema(), state=state, obj=context)
225
226    if 'submit' in request.POST and form.validate():
227        # No picture? do not override it
228        if not form.data['picture']:
229            del form.data['picture']
230        form.bind(context)
231        # reindex
232        request.root.reindex(context)
233        # Saved, send the user to the public view of her profile
234        return HTTPFound(location=request.resource_url(context, 'profile'))
235
236    # prevent crashes on the form
237    if 'picture' in form.data:
238        del form.data['picture']
239
240    return {'form': OWFormRenderer(form),
241            'timezones': common_timezones}
242
243
244@view_config(
245    context=User,
246    permission='edit',
247    name='passwd',
248    renderer='ow:templates/change_password.pt')
249def change_password(context, request):
250    form = Form(request, schema=ChangePasswordSchema(),
251                state=State(user=context))
252    if 'submit' in request.POST and form.validate():
253        context.password = form.data['password']
254        return HTTPFound(location=request.resource_url(context, 'profile'))
255    return {'form': OWFormRenderer(form)}
256
257
258@view_config(
259    context=User,
260    permission='view',
261    name='week')
262def week_stats(context, request):
263    stats = context.week_stats
264    json_stats = []
265    for day in stats:
266        hms = timedelta_to_hms(stats[day]['time'])
267        day_stats = {
268            'name': day.strftime('%a'),
269            'time': str(hms[0]).zfill(2),
270            'distance': int(round(stats[day]['distance'])),
271            'elevation': int(stats[day]['elevation']),
272            'workouts': stats[day]['workouts']
273        }
274        json_stats.append(day_stats)
275    return Response(content_type='application/json',
276                    charset='utf-8',
277                    body=json.dumps(json_stats))
278
279
280@view_config(
281    context=User,
282    permission='view',
283    name='monthly')
284def last_months_stats(context, request):
285    """
286    Return a json-encoded stream with statistics for the last 12 months
287    """
288    stats = context.yearly_stats
289    # this sets which month is 2 times in the stats, once this year, once
290    # the previous year. We will show it a bit different in the UI (showing
291    # the year too to prevent confusion)
292    repeated_month = datetime.now(timezone.utc).date().month
293    json_stats = []
294    for month in stats:
295        hms = timedelta_to_hms(stats[month]['time'])
296        name = month_name[month[1]][:3]
297        if month[1] == repeated_month:
298            name += ' ' + str(month[0])
299        month_stats = {
300            'id': str(month[0]) + '-' + str(month[1]).zfill(2),
301            'name': name,
302            'time': str(hms[0]).zfill(2),
303            'distance': int(round(stats[month]['distance'])),
304            'elevation': int(stats[month]['elevation']),
305            'workouts': stats[month]['workouts'],
306            'url': request.resource_url(
307                context, 'profile',
308                query={'year': str(month[0]), 'month': str(month[1])})
309        }
310        json_stats.append(month_stats)
311    return Response(content_type='application/json',
312                    charset='utf-8',
313                    body=json.dumps(json_stats))
314
315
316@view_config(
317    context=User,
318    permission='view',
319    name='weekly')
320def last_weeks_stats(context, request):
321    """
322    Return a json-encoded stream with statistics for the last 12-months, but
323    in a per-week basis
324    """
325    stats = context.weekly_year_stats
326    # this sets which month is 2 times in the stats, once this year, once
327    # the previous year. We will show it a bit different in the UI (showing
328    # the year too to prevent confusion)
329    repeated_month = datetime.now(timezone.utc).date().month
330    json_stats = []
331    for week in stats:
332        hms = timedelta_to_hms(stats[week]['time'])
333        name = month_name[week[1]][:3]
334        if week[1] == repeated_month:
335            name += ' ' + str(week[0])
336        week_stats = {
337            'id': '-'.join(
338                [str(week[0]), str(week[1]).zfill(2), str(week[2])]),
339            'week': str(week[3]),  # the number of week in the current month
340            'name': name,
341            'time': str(hms[0]).zfill(2),
342            'distance': int(round(stats[week]['distance'])),
343            'elevation': int(stats[week]['elevation']),
344            'workouts': stats[week]['workouts'],
345            'url': request.resource_url(
346                context, 'profile',
347                query={'year': str(week[0]),
348                       'month': str(week[1]),
349                       'week': str(week[2])})
350        }
351        json_stats.append(week_stats)
352    return Response(content_type='application/json',
353                    charset='utf-8',
354                    body=json.dumps(json_stats))
Note: See TracBrowser for help on using the repository browser.