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

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

(#7) Show workouts in the profile page related to the highlighted/current month

selected in the yearly chart.

Also, allow users to click on the monthly bars on the chart, to choose that month.

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