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