1 | import json |
---|
2 | from calendar import month_name |
---|
3 | from datetime import datetime, timezone |
---|
4 | |
---|
5 | from pyramid.httpexceptions import HTTPFound |
---|
6 | from pyramid.view import view_config |
---|
7 | from pyramid.security import remember, forget |
---|
8 | from pyramid.response import Response |
---|
9 | from pyramid.i18n import TranslationStringFactory |
---|
10 | from pyramid_simpleform import Form, State |
---|
11 | from pytz import common_timezones |
---|
12 | |
---|
13 | from ..models.user import User |
---|
14 | from ..schemas.user import ( |
---|
15 | UserProfileSchema, |
---|
16 | ChangePasswordSchema, |
---|
17 | SignUpSchema, |
---|
18 | ) |
---|
19 | from ..models.root import OpenWorkouts |
---|
20 | from ..views.renderers import OWFormRenderer |
---|
21 | from ..utilities import timedelta_to_hms |
---|
22 | |
---|
23 | _ = TranslationStringFactory('OpenWorkouts') |
---|
24 | |
---|
25 | |
---|
26 | @view_config(context=OpenWorkouts) |
---|
27 | def 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') |
---|
47 | def 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') |
---|
77 | def 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') |
---|
86 | def 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') |
---|
106 | def 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') |
---|
115 | def 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') |
---|
162 | def 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 | return { |
---|
169 | 'current_month': now.strftime('%Y-%m') |
---|
170 | } |
---|
171 | |
---|
172 | |
---|
173 | @view_config( |
---|
174 | context=User, |
---|
175 | name='picture', |
---|
176 | permission='view') |
---|
177 | def profile_picture(context, request): |
---|
178 | return Response( |
---|
179 | content_type='image', |
---|
180 | body_file=context.picture.open()) |
---|
181 | |
---|
182 | |
---|
183 | @view_config( |
---|
184 | context=User, |
---|
185 | permission='edit', |
---|
186 | name='edit', |
---|
187 | renderer='ow:templates/edit_profile.pt') |
---|
188 | def edit_profile(context, request): |
---|
189 | # if not given a file there is an empty byte in POST, which breaks |
---|
190 | # our blob storage validator. |
---|
191 | # dirty fix until formencode fixes its api.is_empty method |
---|
192 | if isinstance(request.POST.get('picture', None), bytes): |
---|
193 | request.POST['picture'] = '' |
---|
194 | |
---|
195 | nicknames = request.root.lowercase_nicknames |
---|
196 | if context.nickname: |
---|
197 | # remove the current user nickname from the list, preventing form |
---|
198 | # validation error |
---|
199 | nicknames.remove(context.nickname.lower()) |
---|
200 | state = State(emails=request.root.lowercase_emails, names=nicknames) |
---|
201 | form = Form(request, schema=UserProfileSchema(), state=state, obj=context) |
---|
202 | |
---|
203 | if 'submit' in request.POST and form.validate(): |
---|
204 | # No picture? do not override it |
---|
205 | if not form.data['picture']: |
---|
206 | del form.data['picture'] |
---|
207 | form.bind(context) |
---|
208 | # reindex |
---|
209 | request.root.reindex(context) |
---|
210 | # Saved, send the user to the public view of her profile |
---|
211 | return HTTPFound(location=request.resource_url(context, 'profile')) |
---|
212 | |
---|
213 | # prevent crashes on the form |
---|
214 | if 'picture' in form.data: |
---|
215 | del form.data['picture'] |
---|
216 | |
---|
217 | return {'form': OWFormRenderer(form), |
---|
218 | 'timezones': common_timezones} |
---|
219 | |
---|
220 | |
---|
221 | @view_config( |
---|
222 | context=User, |
---|
223 | permission='edit', |
---|
224 | name='passwd', |
---|
225 | renderer='ow:templates/change_password.pt') |
---|
226 | def change_password(context, request): |
---|
227 | form = Form(request, schema=ChangePasswordSchema(), |
---|
228 | state=State(user=context)) |
---|
229 | if 'submit' in request.POST and form.validate(): |
---|
230 | context.password = form.data['password'] |
---|
231 | return HTTPFound(location=request.resource_url(context, 'profile')) |
---|
232 | return {'form': OWFormRenderer(form)} |
---|
233 | |
---|
234 | |
---|
235 | @view_config( |
---|
236 | context=User, |
---|
237 | permission='view', |
---|
238 | name='week') |
---|
239 | def week_stats(context, request): |
---|
240 | stats = context.week_stats |
---|
241 | json_stats = [] |
---|
242 | for day in stats: |
---|
243 | hms = timedelta_to_hms(stats[day]['time']) |
---|
244 | day_stats = { |
---|
245 | 'name': day.strftime('%a'), |
---|
246 | 'time': str(hms[0]).zfill(2), |
---|
247 | 'distance': int(round(stats[day]['distance'])), |
---|
248 | 'elevation': int(stats[day]['elevation']), |
---|
249 | 'workouts': stats[day]['workouts'] |
---|
250 | } |
---|
251 | json_stats.append(day_stats) |
---|
252 | return Response(content_type='application/json', |
---|
253 | charset='utf-8', |
---|
254 | body=json.dumps(json_stats)) |
---|
255 | |
---|
256 | |
---|
257 | @view_config( |
---|
258 | context=User, |
---|
259 | permission='view', |
---|
260 | name='yearly') |
---|
261 | def last_months_stats(context, request): |
---|
262 | """ |
---|
263 | Return a json-encoded stream with statistics for the last 12 months |
---|
264 | """ |
---|
265 | stats = context.yearly_stats |
---|
266 | # this sets which month is 2 times in the stats, once this year, once |
---|
267 | # the previous year. We will show it a bit different in the UI (showing |
---|
268 | # the year too to prevent confusion) |
---|
269 | repeated_month = datetime.now(timezone.utc).date().month |
---|
270 | json_stats = [] |
---|
271 | for month in stats: |
---|
272 | hms = timedelta_to_hms(stats[month]['time']) |
---|
273 | name = month_name[month[1]][:3] |
---|
274 | if month[1] == repeated_month: |
---|
275 | name += ' ' + str(month[0]) |
---|
276 | month_stats = { |
---|
277 | 'id': str(month[0]) + '-' + str(month[1]).zfill(2), |
---|
278 | 'name': name, |
---|
279 | 'time': str(hms[0]).zfill(2), |
---|
280 | 'distance': int(round(stats[month]['distance'])), |
---|
281 | 'elevation': int(stats[month]['elevation']), |
---|
282 | 'workouts': stats[month]['workouts'] |
---|
283 | } |
---|
284 | json_stats.append(month_stats) |
---|
285 | return Response(content_type='application/json', |
---|
286 | charset='utf-8', |
---|
287 | body=json.dumps(json_stats)) |
---|