-
Notifications
You must be signed in to change notification settings - Fork 3
/
CherryPyFrontEnd.py
720 lines (647 loc) · 24.8 KB
/
CherryPyFrontEnd.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
# Copyright 2022 Michael J Simms
import App
import ApiException
import Keys
import cherrypy
import json
import logging
import traceback
import sys
LOGIN_URL = '/login'
g_front_end = None
def require(*conditions):
# A decorator that appends conditions to the auth.require config variable.
def decorate(f):
if not hasattr(f, '_cp_config'):
f._cp_config = dict()
if 'auth.require' not in f._cp_config:
f._cp_config['auth.require'] = []
f._cp_config['auth.require'].extend(conditions)
return f
return decorate
def do_auth_check(*args, **kwargs):
global g_front_end
# A tool that looks in config for 'auth.require'. If found and it is not None, a login
# is required and the entry is evaluated as a list of conditions that the user must fulfill
conditions = cherrypy.request.config.get('auth.require', None)
if conditions is not None:
# Split the URL.
requested_url = cherrypy.request.request_line.split()[1]
requested_url_parts = requested_url.split('/')
requested_url_parts = filter(lambda part: part != '', requested_url_parts)
first_url_part = next(requested_url_parts)
# If the user is trying to view an activity then make sure they have permissions
# to view it. First check to see if it's a public activity.
if first_url_part == "device":
url_params = next(requested_url_parts)
if url_params is not None and len(url_params) >= 2:
activity_params = url_params[1].split("=")
if activity_params is not None and len(activity_params) >= 2:
activity_id = activity_params[1]
if g_front_end.data_mgr.is_activity_id_public(activity_id):
return
# Check conditions for the logged in user.
username = g_front_end.backend.user_mgr.get_logged_in_username()
if username:
cherrypy.request.login = username
for condition in conditions:
# A condition is just a callable that returns true or false
if not condition():
raise cherrypy.HTTPRedirect(LOGIN_URL)
else:
raise cherrypy.HTTPRedirect(LOGIN_URL)
class CherryPyFrontEnd(object):
"""Class containing the URL handlers."""
def __init__(self, backend):
global g_front_end
self.backend = backend
g_front_end = self
super(CherryPyFrontEnd, self).__init__()
def terminate(self):
"""Destructor"""
print("Terminating the cherrypy front end...")
if self.backend is not None:
self.backend.terminate()
self.backend = None
def log_error(self, log_str):
"""Writes an error message to the log file."""
logger = logging.getLogger()
logger.error(log_str)
@cherrypy.expose
def error(self, error_str=None):
"""Renders the error page."""
try:
cherrypy.response.status = 500
return self.backend.render_error(error_str)
except:
pass
return self.backend.render_error("")
@cherrypy.expose
def error_404(self, status, message, traceback, version):
"""Renders the 404 error page."""
try:
return self.backend.render_page_not_found()
except:
pass
return self.backend.render_error("")
@cherrypy.expose
@require()
def stats(self):
"""Renders the internal statistics page."""
try:
return self.backend.performance_stats()
except:
pass
return self.error()
@cherrypy.expose
def live(self, device_str):
"""Renders the map page for the current activity from a single device."""
try:
return self.backend.live_device(device_str)
except:
self.log_error(traceback.format_exc())
self.log_error(sys.exc_info()[0])
self.log_error('Unhandled exception in ' + CherryPyFrontEnd.live.__name__)
return self.error()
@cherrypy.expose
def live_user(self, user_str):
"""Renders the map page for the current activity from a specified user."""
try:
return self.backend.live_user(user_str)
except:
self.log_error(traceback.format_exc())
self.log_error(sys.exc_info()[0])
self.log_error('Unhandled exception in ' + CherryPyFrontEnd.live_user.__name__)
return self.error()
@cherrypy.expose
def activity(self, activity_id):
"""Renders the details page for an activity."""
try:
return self.backend.activity(activity_id)
except App.RedirectException as e:
raise cherrypy.HTTPRedirect(e.url)
except cherrypy.HTTPRedirect as e:
raise e
except:
self.log_error(traceback.format_exc())
self.log_error(sys.exc_info()[0])
self.log_error('Unhandled exception in ' + CherryPyFrontEnd.activity.__name__)
return self.error()
@cherrypy.expose
def edit_activity(self, activity_id):
"""Renders the edit page for an activity."""
try:
return self.backend.edit_activity(activity_id)
except App.RedirectException as e:
raise cherrypy.HTTPRedirect(e.url)
except cherrypy.HTTPRedirect as e:
raise e
except:
self.log_error(traceback.format_exc())
self.log_error(sys.exc_info()[0])
self.log_error('Unhandled exception in ' + CherryPyFrontEnd.edit_activity.__name__)
return self.error()
@cherrypy.expose
def trim_activity(self, activity_id):
"""Renders the trim page for an activity."""
try:
return self.backend.trim_activity(activity_id)
except App.RedirectException as e:
raise cherrypy.HTTPRedirect(e.url)
except cherrypy.HTTPRedirect as e:
raise e
except:
self.log_error(traceback.format_exc())
self.log_error(sys.exc_info()[0])
self.log_error('Unhandled exception in ' + CherryPyFrontEnd.trim_activity.__name__)
return self.error()
@cherrypy.expose
def merge_activity(self, activity_id):
"""Renders the merge page for an activity."""
try:
return self.backend.merge_activity(activity_id)
except App.RedirectException as e:
raise cherrypy.HTTPRedirect(e.url)
except cherrypy.HTTPRedirect as e:
raise e
except:
self.log_error(traceback.format_exc())
self.log_error(sys.exc_info()[0])
self.log_error('Unhandled exception in ' + CherryPyFrontEnd.merge_activity.__name__)
return self.error()
@cherrypy.expose
def add_photos(self, activity_id):
"""Renders the add photos page for an activity."""
try:
return self.backend.add_photos(activity_id)
except App.RedirectException as e:
raise cherrypy.HTTPRedirect(e.url)
except cherrypy.HTTPRedirect as e:
raise e
except:
self.log_error(traceback.format_exc())
self.log_error(sys.exc_info()[0])
self.log_error('Unhandled exception in ' + CherryPyFrontEnd.add_photos.__name__)
return self.error()
@cherrypy.expose
def device(self, device_str):
"""Renders the map page for a single device."""
try:
return self.backend.device(device_str)
except:
self.log_error(traceback.format_exc())
self.log_error(sys.exc_info()[0])
self.log_error('Unhandled exception in ' + CherryPyFrontEnd.device.__name__)
return self.error()
@cherrypy.expose
@require()
def my_activities(self):
"""Renders the list of the specified user's activities."""
try:
return self.backend.my_activities()
except App.RedirectException as e:
raise cherrypy.HTTPRedirect(e.url)
except cherrypy.HTTPRedirect as e:
raise e
except:
self.log_error(traceback.format_exc())
self.log_error(sys.exc_info()[0])
self.log_error('Unhandled exception in ' + CherryPyFrontEnd.my_activities.__name__)
return self.error()
@cherrypy.expose
@require()
def all_activities(self):
"""Renders the list of all activities the specified user is allowed to view."""
try:
return self.backend.all_activities()
except App.RedirectException as e:
raise cherrypy.HTTPRedirect(e.url)
except cherrypy.HTTPRedirect as e:
raise e
except:
self.log_error(traceback.format_exc())
self.log_error(sys.exc_info()[0])
self.log_error('Unhandled exception in ' + CherryPyFrontEnd.all_activities.__name__)
return self.error()
@cherrypy.expose
@require()
def record_progression(self, activity_type, record_name):
"""Renders the list of records, in order of progression, for the specified user and record type."""
try:
return self.backend.record_progression(activity_type, record_name)
except App.RedirectException as e:
raise cherrypy.HTTPRedirect(e.url)
except cherrypy.HTTPRedirect as e:
raise e
except:
self.log_error(traceback.format_exc())
self.log_error(sys.exc_info()[0])
self.log_error('Unhandled exception in ' + CherryPyFrontEnd.record_progression.__name__)
return self.error()
@cherrypy.expose
@require()
def workouts(self):
"""Renders the workouts view."""
try:
return self.backend.workouts()
except App.RedirectException as e:
raise cherrypy.HTTPRedirect(e.url)
except cherrypy.HTTPRedirect as e:
raise e
except:
self.log_error(traceback.format_exc())
self.log_error(sys.exc_info()[0])
self.log_error('Unhandled exception in ' + CherryPyFrontEnd.workouts.__name__)
return self.error()
@cherrypy.expose
@require()
def workout(self, workout_id):
"""Renders the view for an individual workout."""
try:
return self.backend.workout(workout_id)
except App.RedirectException as e:
raise cherrypy.HTTPRedirect(e.url)
except cherrypy.HTTPRedirect as e:
raise e
except:
self.log_error(traceback.format_exc())
self.log_error(sys.exc_info()[0])
self.log_error('Unhandled exception in ' + CherryPyFrontEnd.workout.__name__)
return self.error()
@cherrypy.expose
@require()
def statistics(self):
"""Renders the statistics view."""
try:
return self.backend.user_stats()
except App.RedirectException as e:
raise cherrypy.HTTPRedirect(e.url)
except cherrypy.HTTPRedirect as e:
raise e
except:
self.log_error(traceback.format_exc())
self.log_error(sys.exc_info()[0])
self.log_error('Unhandled exception in ' + CherryPyFrontEnd.statistics.__name__)
return self.error()
@cherrypy.expose
@require()
def gear(self):
"""Renders the list of all gear belonging to the logged in user."""
try:
return self.backend.gear()
except App.RedirectException as e:
raise cherrypy.HTTPRedirect(e.url)
except cherrypy.HTTPRedirect as e:
raise e
except:
self.log_error(traceback.format_exc())
self.log_error(sys.exc_info()[0])
self.log_error('Unhandled exception in ' + CherryPyFrontEnd.gear.__name__)
return self.error()
@cherrypy.expose
@require()
def service_history(self, gear_id):
"""Renders the service history for a particular piece of gear."""
try:
return self.backend.service_history(gear_id)
except App.RedirectException as e:
raise cherrypy.HTTPRedirect(e.url)
except cherrypy.HTTPRedirect as e:
raise e
except:
self.log_error(traceback.format_exc())
self.log_error(sys.exc_info()[0])
self.log_error('Unhandled exception in ' + CherryPyFrontEnd.service_history.__name__)
return self.error()
@cherrypy.expose
@require()
def friends(self):
"""Renders the list of users who are friends with the logged in user."""
try:
return self.backend.friends()
except App.RedirectException as e:
raise cherrypy.HTTPRedirect(e.url)
except cherrypy.HTTPRedirect as e:
raise e
except:
self.log_error(traceback.format_exc())
self.log_error(sys.exc_info()[0])
self.log_error('Unhandled exception in ' + CherryPyFrontEnd.friends.__name__)
return self.error()
@cherrypy.expose
@require()
def device_list(self):
"""Renders the list of a user's devices."""
try:
return self.backend.device_list()
except App.RedirectException as e:
raise cherrypy.HTTPRedirect(e.url)
except cherrypy.HTTPRedirect as e:
raise e
except:
self.log_error(traceback.format_exc())
self.log_error(sys.exc_info()[0])
self.log_error('Unhandled exception in ' + CherryPyFrontEnd.device_list.__name__)
return self.error()
@cherrypy.expose
@require()
def manual_entry(self, activity_type):
"""Called when the user selects an activity type, indicating they want to make a manual data entry."""
try:
return self.backend.manual_entry(activity_type)
except App.RedirectException as e:
raise cherrypy.HTTPRedirect(e.url)
except cherrypy.HTTPRedirect as e:
raise e
except:
self.log_error(traceback.format_exc())
self.log_error(sys.exc_info()[0])
self.log_error('Unhandled exception in ' + CherryPyFrontEnd.manual_entry.__name__)
return self.error()
@cherrypy.expose
@require()
def import_activity(self):
"""Renders the import page."""
try:
return self.backend.import_activity()
except App.RedirectException as e:
raise cherrypy.HTTPRedirect(e.url)
except cherrypy.HTTPRedirect as e:
raise e
except:
self.log_error(traceback.format_exc())
self.log_error(sys.exc_info()[0])
self.log_error('Unhandled exception in ' + CherryPyFrontEnd.import_activity.__name__)
return self.error()
@cherrypy.expose
@require()
def add_pace_plan(self):
"""Renders the add pace plan page."""
try:
return self.backend.add_pace_plan()
except App.RedirectException as e:
raise cherrypy.HTTPRedirect(e.url)
except cherrypy.HTTPRedirect as e:
raise e
except:
self.log_error(traceback.format_exc())
self.log_error(sys.exc_info()[0])
self.log_error('Unhandled exception in ' + CherryPyFrontEnd.add_pace_plan.__name__)
return self.error()
@cherrypy.expose
@require()
def pace_plans(self):
"""Renders the pace plans page."""
try:
return self.backend.pace_plans()
except App.RedirectException as e:
raise cherrypy.HTTPRedirect(e.url)
except cherrypy.HTTPRedirect as e:
raise e
except:
self.log_error(traceback.format_exc())
self.log_error(sys.exc_info()[0])
self.log_error('Unhandled exception in ' + CherryPyFrontEnd.pace_plans.__name__)
return self.error()
@cherrypy.expose
@require()
def task_status(self):
"""Renders the import status page."""
try:
return self.backend.task_status()
except App.RedirectException as e:
raise cherrypy.HTTPRedirect(e.url)
except cherrypy.HTTPRedirect as e:
raise e
except:
self.log_error(traceback.format_exc())
self.log_error(sys.exc_info()[0])
self.log_error('Unhandled exception in ' + CherryPyFrontEnd.task_status.__name__)
return self.error()
@cherrypy.expose
@require()
def profile(self):
"""Renders the user's profile page."""
try:
return self.backend.profile()
except App.RedirectException as e:
raise cherrypy.HTTPRedirect(e.url)
except cherrypy.HTTPRedirect as e:
raise e
except:
self.log_error(traceback.format_exc())
self.log_error(sys.exc_info()[0])
self.log_error('Unhandled exception in ' + CherryPyFrontEnd.profile.__name__)
return self.error()
@cherrypy.expose
@require()
def settings(self):
"""Renders the user's settings page."""
try:
return self.backend.settings()
except App.RedirectException as e:
raise cherrypy.HTTPRedirect(e.url)
except cherrypy.HTTPRedirect as e:
raise e
except:
self.log_error(traceback.format_exc())
self.log_error(sys.exc_info()[0])
self.log_error('Unhandled exception in ' + CherryPyFrontEnd.settings.__name__)
return self.error()
@cherrypy.expose
def login(self):
"""Renders the login page."""
try:
return self.backend.login()
except App.RedirectException as e:
raise cherrypy.HTTPRedirect(e.url)
except cherrypy.HTTPRedirect as e:
raise e
except:
self.log_error('Unhandled exception in ' + CherryPyFrontEnd.login.__name__)
return self.error()
@cherrypy.expose
def create_login(self):
"""Renders the create login page."""
try:
return self.backend.create_login()
except:
self.log_error('Unhandled exception in ' + CherryPyFrontEnd.create_login.__name__)
return self.error()
@cherrypy.expose
def logout(self):
"""Ends the logged in session."""
try:
return self.backend.logout()
except App.RedirectException as e:
raise cherrypy.HTTPRedirect(e.url)
except cherrypy.HTTPRedirect as e:
raise e
except:
self.log_error('Unhandled exception in ' + CherryPyFrontEnd.logout.__name__)
return self.error()
@cherrypy.expose
def about(self):
"""Renders the about page."""
try:
return self.backend.about()
except App.RedirectException as e:
raise cherrypy.HTTPRedirect(e.url)
except cherrypy.HTTPRedirect as e:
raise e
except:
self.log_error(traceback.format_exc())
self.log_error(sys.exc_info()[0])
self.log_error('Unhandled exception in ' + CherryPyFrontEnd.about.__name__)
return self.error()
@cherrypy.expose
def status(self):
"""Renders the status page. Used as a simple way to tell if the site is up."""
try:
return self.backend.status()
except:
self.log_error(traceback.format_exc())
self.log_error(sys.exc_info()[0])
self.log_error('Unhandled exception in ' + CherryPyFrontEnd.status.__name__)
return self.error()
@cherrypy.expose
def ical(self, calendar_id):
"""Returns the ical calendar with the specified ID."""
try:
handled, response = self.backend.ical(calendar_id)
if not handled:
cherrypy.response.status = 400
return response
except App.RedirectException as e:
raise cherrypy.HTTPRedirect(e.url)
except cherrypy.HTTPRedirect as e:
raise e
except:
self.log_error(traceback.format_exc())
self.log_error(sys.exc_info()[0])
self.log_error('Unhandled exception in ' + CherryPyFrontEnd.ical.__name__)
return self.error()
@cherrypy.expose
@require()
def api_keys(self):
"""Renders the api key management page."""
try:
return self.backend.api_keys()
except App.RedirectException as e:
raise cherrypy.HTTPRedirect(e.url)
except cherrypy.HTTPRedirect as e:
raise e
except:
self.log_error(traceback.format_exc())
self.log_error(sys.exc_info()[0])
self.log_error('Unhandled exception in ' + CherryPyFrontEnd.api_keys.__name__)
return self.error()
@cherrypy.expose
@require()
def admin(self):
"""Renders the admin page."""
try:
return self.backend.admin()
except App.RedirectException as e:
raise cherrypy.HTTPRedirect(e.url)
except cherrypy.HTTPRedirect as e:
raise e
except:
self.log_error(traceback.format_exc())
self.log_error(sys.exc_info()[0])
self.log_error('Unhandled exception in ' + CherryPyFrontEnd.admin.__name__)
return self.error()
def api_internal(self, verb, path, params, cookie):
"""Common code for handling API calls."""
#
# Default return values.
#
response = ""
http_status = 200
#
# Who made this request.
#
# Lookup the user using the API key.
user_id = None
if Keys.API_KEY in params:
# Session key.
key = params[Keys.API_KEY]
# Which user is associated with this key?
user_id, _, _, max_rate = self.backend.user_mgr.retrieve_user_from_api_key(key)
if user_id is not None:
# Make sure the key is not being abused.
if not self.backend.data_mgr.check_api_rate(key, max_rate):
user_id = None
response = "Excessive API requests."
http_status = 429
self.log_error(response)
# API key not provided, check the web session cookie.
if user_id == None:
username = self.backend.user_mgr.get_logged_in_username_from_cookie(cookie)
if username is not None:
user_id, _, _ = self.backend.user_mgr.retrieve_user(username)
# Web cookie not provided, check the session key.
if user_id == None:
username = self.backend.user_mgr.get_logged_in_username()
if username is not None:
user_id, _, _ = self.backend.user_mgr.retrieve_user(username)
# Process the API request.
if len(path) > 0:
api_version = path[0]
if api_version == '1.0':
method = path[1:]
handled, response = self.backend.api(user_id, verb, method[0], params)
if not handled:
response = "Failed to handle request: " + str(method)
self.log_error(response)
http_status = 400
else:
http_status = 200
else:
self.log_error("Failed to handle request for api version " + api_version)
http_status = 400
else:
http_status = 400
return response, http_status
@cherrypy.expose
def api(self, *args, **kw):
"""Endpoint for API calls."""
# Return values.
response = ""
http_status = 200
params = {}
try:
# Things we need.
verb = cherrypy.request.method
# The API params.
if verb == "GET" or verb == "DELETE":
params = kw
else:
content_len = int(cherrypy.request.headers['Content-Length'])
if content_len > 0:
params = cherrypy.request.body.read(content_len)
params = json.loads(params)
# Pass off to the internal handler, i.e. the method that doesn't use cherrypy objects.
response, http_status = self.api_internal(verb, args, params, None)
except ApiException.ApiException as e:
response = e.message
http_status = e.code
self.log_error(str(e))
except Exception as e:
response = "Unhandled error."
http_status = 500
self.log_error(str(e))
except:
response = "Unspecified error."
http_status = 500
self.log_error("Untyped exception")
cherrypy.response.status = http_status
return response
@cherrypy.expose
def google_maps(self):
"""Returns the Google Maps API key."""
raise cherrypy.HTTPRedirect("https://maps.googleapis.com/maps/api/js?key=" + self.backend.google_maps_key)
@cherrypy.expose
def index(self):
"""Renders the index page."""
return self.login()