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

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

(#7) Show year/month/weekly stats in the dashboard for the user,

including a bar chart for activity during the current week

  • Property mode set to 100644
File size: 7.8 KB
Line 
1import json
2from calendar import month_name
3from datetime import datetime
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().year,
149        'current_day_name': datetime.now().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    return {}
168
169
170@view_config(
171    context=User,
172    name='picture',
173    permission='view')
174def profile_picture(context, request):
175    return Response(
176        content_type='image',
177        body_file=context.picture.open())
178
179
180@view_config(
181    context=User,
182    permission='edit',
183    name='edit',
184    renderer='ow:templates/edit_profile.pt')
185def edit_profile(context, request):
186    # if not given a file there is an empty byte in POST, which breaks
187    # our blob storage validator.
188    # dirty fix until formencode fixes its api.is_empty method
189    if isinstance(request.POST.get('picture', None), bytes):
190        request.POST['picture'] = ''
191
192    nicknames = request.root.lowercase_nicknames
193    if context.nickname:
194        # remove the current user nickname from the list, preventing form
195        # validation error
196        nicknames.remove(context.nickname.lower())
197    state = State(emails=request.root.lowercase_emails, names=nicknames)
198    form = Form(request, schema=UserProfileSchema(), state=state, obj=context)
199
200    if 'submit' in request.POST and form.validate():
201        # No picture? do not override it
202        if not form.data['picture']:
203            del form.data['picture']
204        form.bind(context)
205        # reindex
206        request.root.reindex(context)
207        # Saved, send the user to the public view of her profile
208        return HTTPFound(location=request.resource_url(context, 'profile'))
209
210    # prevent crashes on the form
211    if 'picture' in form.data:
212        del form.data['picture']
213
214    return {'form': OWFormRenderer(form),
215            'timezones': common_timezones}
216
217
218@view_config(
219    context=User,
220    permission='edit',
221    name='passwd',
222    renderer='ow:templates/change_password.pt')
223def change_password(context, request):
224    form = Form(request, schema=ChangePasswordSchema(),
225                state=State(user=context))
226    if 'submit' in request.POST and form.validate():
227        context.password = form.data['password']
228        return HTTPFound(location=request.resource_url(context, 'profile'))
229    return {'form': OWFormRenderer(form)}
230
231
232@view_config(
233    context=User,
234    permission='view',
235    name='week')
236def week_stats(context, request):
237    stats = context.week_stats
238    json_stats = []
239    for day in stats:
240        hms = timedelta_to_hms(stats[day]['time'])
241        day_stats = {
242            'name': day.strftime('%a'),
243            'time': str(hms[0]).zfill(2),
244            'distance': int(round(stats[day]['distance'])),
245            'elevation': int(stats[day]['elevation']),
246            'workouts': stats[day]['workouts']
247        }
248        json_stats.append(day_stats)
249    return Response(content_type='application/json',
250                    charset='utf-8',
251                    body=json.dumps(json_stats))
Note: See TracBrowser for help on using the repository browser.