-
Notifications
You must be signed in to change notification settings - Fork 3
/
App.py
1209 lines (999 loc) · 55.1 KB
/
App.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
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8 -*-
#
# # MIT License
#
# Copyright (c) 2017-2020 Michael J Simms
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
"""Main application, contains all web page handlers"""
import inspect
import json
import logging
import markdown
import os
import sys
import time
import traceback
import cProfile
import pstats
import Keys
import Api
import Config
import Dirs
import IcalServer
import InputChecker
import Perf
import Units
from io import StringIO ## for Python 3
from mako.template import Template
# Locate and load the Distance calculations module.
currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
distancedir = os.path.join(currentdir, 'LibMath', 'python', 'distance')
sys.path.insert(0, distancedir)
import distance
PRODUCT_NAME = 'OpenWorkout'
LOGIN_URL = '/login'
DEFAULT_LOGGED_IN_URL = '/all_activities'
ZWIFT_WATOPIA_MAP_FILE_NAME = 'watopia.png'
ZWIFT_CRIT_CITY_MAP_FILE_NAME = 'crit_city.png'
ZWIFT_MAKURI_ISLANDS_MAP_FILE_NAME = 'makuri_islands.png'
class RedirectException(Exception):
"""This is thrown when the app needs to redirect to another page."""
def __init__(self, url):
self.url = url
super(RedirectException, self).__init__()
class App(object):
"""Class containing the URL handlers."""
def __init__(self, config, user_mgr, data_mgr, root_dir, root_url, google_maps_key, enable_profiling, debug):
"""Constructor"""
self.config = config
self.user_mgr = user_mgr
self.data_mgr = data_mgr
self.root_dir = root_dir
self.root_url = root_url
self.tempfile_dir = os.path.join(self.root_dir, 'tempfile')
self.tempmod_dir = os.path.join(self.root_dir, 'tempmod3')
self.google_maps_key = google_maps_key
self.debug = debug
self.zwift_watopia_map_file = os.path.join(root_dir, Dirs.MEDIA_DIR, ZWIFT_WATOPIA_MAP_FILE_NAME)
self.zwift_crit_city_map_file = os.path.join(root_dir, Dirs.MEDIA_DIR, ZWIFT_CRIT_CITY_MAP_FILE_NAME)
self.zwift_makuri_islands_map_file = os.path.join(root_dir, Dirs.MEDIA_DIR, ZWIFT_MAKURI_ISLANDS_MAP_FILE_NAME)
self.zwift_html_file = os.path.join(root_dir, Dirs.HTML_DIR, 'zwift.html')
self.unmapped_activity_html_file = os.path.join(root_dir, Dirs.HTML_DIR, 'unmapped_activity.html')
self.map_single_osm_html_file = os.path.join(root_dir, Dirs.HTML_DIR, 'map_single_osm.html')
self.map_single_google_html_file = os.path.join(root_dir, Dirs.HTML_DIR, 'map_single_google.html')
self.map_multi_html_file = os.path.join(root_dir, Dirs.HTML_DIR, 'map_multi_google.html')
self.error_logged_in_html_file = os.path.join(root_dir, Dirs.HTML_DIR, 'error_logged_in.html')
self.error_activity_html_file = os.path.join(root_dir, Dirs.HTML_DIR, 'error_activity.html')
self.ical_server = IcalServer.IcalServer(user_mgr, data_mgr, self.root_url)
self.logged_in_navbar = "<nav>\n\t<ul>\n" \
"\t\t<li><a href=\"" + self.root_url + "/my_activities/\">My Activities</a></li>\n" \
"\t\t<li><a href=\"" + self.root_url + "/all_activities/\">All Activities</a></li>\n" \
"\t\t<li><a href=\"" + self.root_url + "/workouts/\">Workouts</a></li>\n" \
"\t\t<li><a href=\"" + self.root_url + "/pace_plans/\">Pace Plans</a></li>\n" \
"\t\t<li><a href=\"" + self.root_url + "/statistics/\">Statistics</a></li>\n" \
"\t\t<li><a href=\"" + self.root_url + "/gear/\">Gear</a></li>\n" \
"\t\t<li><a href=\"" + self.root_url + "/device_list/\">Devices</a></li>\n" \
"\t\t<li><a href=\"" + self.root_url + "/friends/\">Friends</a></li>\n" \
"\t\t<li><a href=\"" + self.root_url + "/import_activity/\">Import</a></li>\n" \
"\t\t<li><a href=\"" + self.root_url + "/profile/\">Profile</a></li>\n" \
"\t\t<li><a href=\"" + self.root_url + "/settings/\">Settings</a></li>\n" \
"\t\t<li><a href=\"" + self.root_url + "/logout/\">Log Out</a></li>\n" \
"\t</ul>\n"
self.logged_out_navbar = "<nav>\n\t<ul>\n" \
"\t\t<li><a href=\"" + self.root_url + "/login/\">Log In</a></li>\n" \
"\t</ul>\n"
self.tempfile_dir = os.path.join(root_dir, 'tempfile')
if not os.path.exists(self.tempfile_dir):
os.makedirs(self.tempfile_dir)
if enable_profiling:
print("Start profiling...")
self.pr = cProfile.Profile()
self.pr.enable()
else:
self.pr = None
super(App, self).__init__()
def terminate(self):
"""Destructor"""
print("Terminating the application...")
print("Terminating data management...")
self.data_mgr.terminate()
self.data_mgr = None
print("Terminating session management...")
self.user_mgr.terminate()
self.user_mgr = None
if self.pr is not None:
print("Stop profiling...")
self.pr.disable()
s = StringIO.StringIO()
sortby = 'cumulative'
ps = pstats.Stats(self.pr, stream=s).sort_stats(sortby)
ps.print_stats()
print(s.getvalue())
def log_error(self, log_str):
"""Writes an error message to the log file."""
logger = logging.getLogger()
logger.error(log_str)
def create_navbar(self, logged_in):
"""Helper function for building the navigation bar."""
if logged_in:
return self.logged_in_navbar
return self.logged_out_navbar
def performance_stats(self):
"""Renders the application's performance statistics."""
# Get the logged in user.
username = self.user_mgr.get_logged_in_username()
if username is None:
raise RedirectException(LOGIN_URL)
# Get the details of the logged in user.
user_id, _, user_realname = self.user_mgr.retrieve_user(username)
if user_id is None:
self.log_error('Unknown user ID')
raise RedirectException(LOGIN_URL)
# Make a copy of the data so we don't have to hold the lock.
Perf.g_stats_lock.acquire()
temp_stats_count = Perf.g_stats_count
temp_stats_time = Perf.g_stats_time
Perf.g_stats_lock.release()
# Build a list of table rows from the device information.
page_stats_str = "<td><b>Page</b></td><td><b>Num Accesses</b></td><td><b>Avg Time (secs)</b></td><tr>\n"
for key, count_value in temp_stats_count.items():
page_stats_str += "\t\t<tr><td>"
page_stats_str += str(key)
page_stats_str += "</td><td>"
page_stats_str += str(count_value)
page_stats_str += "</td><td>"
if key in temp_stats_time and count_value > 0:
total_time = temp_stats_time[key]
avg_time = total_time / count_value
page_stats_str += str(avg_time)
page_stats_str += "</td></tr>\n"
# The number of users and activities.
total_users_str = ""
total_activities_str = ""
try:
total_users_str = str(self.data_mgr.total_users_count())
total_activities_str = str(self.data_mgr.total_activities_count())
except:
self.log_error("Exception while getting counts.")
# Render from template.
html_file = os.path.join(self.root_dir, Dirs.HTML_DIR, 'stats.html')
my_template = Template(filename=html_file, module_directory=self.tempmod_dir)
return my_template.render(nav=self.create_navbar(True), product=PRODUCT_NAME, root_url=self.root_url, email=username, name=user_realname, page_stats=page_stats_str, total_activities=total_activities_str, total_users=total_users_str)
def render_simple_page(self, template_file_name, **kwargs):
"""Renders a basic page from the specified template. This exists because a lot of pages only need this to be rendered."""
# Get the logged in user.
username = self.user_mgr.get_logged_in_username()
if username is None:
raise RedirectException(LOGIN_URL)
# Get the details of the logged in user.
user_id, _, user_realname = self.user_mgr.retrieve_user(username)
if user_id is None:
self.log_error('Unknown user ID')
raise RedirectException(LOGIN_URL)
# Render from template.
html_file = os.path.join(self.root_dir, Dirs.HTML_DIR, template_file_name)
my_template = Template(filename=html_file, module_directory=self.tempmod_dir)
return my_template.render(nav=self.create_navbar(True), product=PRODUCT_NAME, root_url=self.root_url, email=username, name=user_realname, **kwargs)
def render_tags(self, activity, activity_user_id, belongs_to_current_user):
"""Helper function for building the tags string."""
activity_tags = []
if Keys.ACTIVITY_TAGS_KEY in activity:
activity_tags = activity[Keys.ACTIVITY_TAGS_KEY]
if activity_user_id is not None and Keys.ACTIVITY_TYPE_KEY in activity:
default_tags = self.data_mgr.list_available_tags_for_activity_type_and_user(activity_user_id, activity[Keys.ACTIVITY_TYPE_KEY])
else:
default_tags = self.data_mgr.list_default_tags()
all_tags = []
all_tags.extend(activity_tags)
all_tags.extend(default_tags)
all_tags = list(set(all_tags))
all_tags.sort()
tags_str = ""
if all_tags is not None:
for tag in all_tags:
if tag in activity_tags:
tags_str += "<option selected=true"
else:
tags_str += "<option"
if not belongs_to_current_user:
tags_str += " disabled"
tags_str += ">"
tags_str += tag
tags_str += "</option>\n"
return tags_str
def render_comments(self, activity, logged_in):
"""Helper function for building the comments string."""
comments_str = ""
comments = []
if Keys.ACTIVITY_COMMENTS_KEY in activity:
comments = activity[Keys.ACTIVITY_COMMENTS_KEY]
for comment_entry in comments:
decoded_entry = json.loads(comment_entry)
commenter_id = decoded_entry[Keys.ACTIVITY_COMMENTER_ID_KEY]
_, commenter_name = self.user_mgr.retrieve_user_from_id(commenter_id)
comments_str += "<td><b>"
comments_str += commenter_name
comments_str += "</b> says \""
comments_str += decoded_entry[Keys.ACTIVITY_COMMENT_KEY]
comments_str += "\"</td><tr>\n"
if logged_in:
comments_str += "<td><textarea rows=\"4\" id=\"comment\"></textarea></td><tr>\n"
comments_str += "<td><button type=\"button\" onclick=\"return create_comment()\">Post</button></td><tr>\n"
elif len(comments_str) == 0:
comments_str = "None"
return comments_str
@staticmethod
def render_export_control(has_location_data, has_accel_data):
"""Helper function for building the exports string that appears on the activity details screens."""
if not (has_location_data or has_accel_data):
return ""
exports_str = "<td><select id=\"format\" >\n"
if has_location_data:
exports_str += "\t<option value=\"tcx\" selected>TCX</option>\n"
exports_str += "\t<option value=\"gpx\">GPX</option>\n"
if has_location_data or has_accel_data:
exports_str += "\t<option value=\"csv\">CSV</option>\n"
exports_str += "</select>\n</td><tr>\n"
exports_str += "<td><button type=\"button\" onclick=\"return export_activity()\">Export</button></td><tr>\n"
return exports_str
def render_page_for_unmapped_activity(self, user_realname, activity_id, activity, activity_user_id, activity_user_resting_hr, activity_user_max_hr, logged_in_username, belongs_to_current_user, is_live):
"""Helper function for rendering the page corresonding to a specific un-mapped activity."""
# Is the user logged in?
logged_in = logged_in_username is not None
# Retrieve cached summary data. It is possible that the summary data has not yet been computed.
if Keys.ACTIVITY_SUMMARY_KEY in activity:
summary_data = activity[Keys.ACTIVITY_SUMMARY_KEY]
else:
summary_data = {}
# Find the sets data.
sets = None
if Keys.APP_SETS_KEY in activity:
sets = activity[Keys.APP_SETS_KEY]
elif Keys.APP_SETS_KEY in summary_data:
sets = summary_data[Keys.APP_SETS_KEY]
# Build the details view.
details = ""
if sets is not None:
details = "<table>\n<td><b>Set</b></td><td><b>Rep Count</b></td><tr>\n"
set_num = 1
for current_set in sets:
details += "<td>"
details += str(set_num)
details += "</td><td>"
details += str(current_set)
details += "</td><tr>\n"
set_num = set_num + 1
details += "</table>\n"
# Build the summary data view.
summary = "<ul>\n"
# Add the activity type.
activity_type = App.render_activity_type(activity)
summary += "\t<li>Activity Type: " + activity_type + "</li>\n"
# Add the activity date.
name = App.render_activity_name(activity)
summary += "\t<li>Name: " + name + "</li>\n"
# Add the activity date.
if Keys.ACTIVITY_START_TIME_KEY in activity:
summary += "\t<li>Start Time: <script>document.write(unix_time_to_local_string(" + str(activity[Keys.ACTIVITY_START_TIME_KEY]) + "))</script></li>\n"
# Close the summary list.
summary += "</ul>\n"
# Get the description.
description_str = self.render_description_for_page(activity)
# List the tags.
tags_str = self.render_tags(activity, activity_user_id, belongs_to_current_user)
# List the comments.
comments_str = self.render_comments(activity, logged_in)
# Somethings will only be shown if the activity belongs to the logged in user.
if belongs_to_current_user:
visibility_str = ""
else:
visibility_str = "display:none;"
# List the export options.
exports_str = ""
if logged_in:
exports_str = App.render_export_control(False, Keys.APP_ACCELEROMETER_KEY in activity)
# Build the page title.
if is_live:
page_title = "Live Tracking"
else:
page_title = "Activity"
my_template = Template(filename=self.unmapped_activity_html_file, module_directory=self.tempmod_dir)
return my_template.render(nav=self.create_navbar(logged_in), product=PRODUCT_NAME, root_url=self.root_url, name=user_realname, pagetitle=page_title, description=description_str, details=details, summary=summary, activity_id=activity_id, user_id=activity_user_id, max_hr=activity_user_max_hr, tags=tags_str, comments=comments_str, exports=exports_str, visibility=visibility_str)
def render_description_for_page(self, activity):
"""Helper function for processing the activity description and formatting it for display."""
description = ""
if Keys.ACTIVITY_DESCRIPTION_KEY in activity:
description = activity[Keys.ACTIVITY_DESCRIPTION_KEY].replace('\n', '<br>')
if len(description) == 0:
description = "None"
return description
@staticmethod
def render_intervals_str(intervals):
"""Helper function for building a description from the raw intervals description."""
if intervals is None:
return "None"
num_intervals = len(intervals)
if num_intervals <= 0:
return "None"
avg_interval_duration = 0.0
avg_interval_length = 0.0
avg_interval_speed = 0.0
for interval in intervals:
avg_interval_duration = avg_interval_duration + interval[2]
avg_interval_length = avg_interval_length + interval[3]
avg_interval_speed = avg_interval_speed + interval[4]
avg_interval_duration = (avg_interval_duration / num_intervals) / 1000.0
avg_interval_length = avg_interval_length / num_intervals
avg_interval_speed = avg_interval_speed / num_intervals
intervals_str = str(num_intervals) + " intervals averaging {:.2f}".format(avg_interval_length) + " meters at {:.2f}".format(avg_interval_duration) + " seconds/each."
return intervals_str
@staticmethod
def render_activity_name(activity):
"""Helper function for getting the activity name."""
if Keys.ACTIVITY_NAME_KEY in activity:
activity_name = activity[Keys.ACTIVITY_NAME_KEY]
else:
activity_name = Keys.UNNAMED_ACTIVITY_TITLE
if len(activity_name) == 0:
activity_name = Keys.UNNAMED_ACTIVITY_TITLE
return activity_name
@staticmethod
def render_activity_type(activity):
"""Helper function for getting the activity type."""
if Keys.ACTIVITY_TYPE_KEY in activity:
activity_type = activity[Keys.ACTIVITY_TYPE_KEY]
else:
activity_type = Keys.TYPE_UNSPECIFIED_ACTIVITY_KEY
if len(activity_type) == 0:
activity_type = Keys.TYPE_UNSPECIFIED_ACTIVITY_KEY
return activity_type
@staticmethod
def render_difference_array(array):
"""Helper function for converting an array (list) to a comma-separated string."""
result = ""
last = 0
for item in array:
if len(result) > 0:
result += ", "
result += str(item - last)
last = item
return result
@staticmethod
def render_array_reversed(array):
"""Helper function for converting an array (list) to a comma-separated string."""
result = ""
for item in reversed(array):
if len(result) > 0:
result += ", "
result += str(item)
return result
@staticmethod
def is_activity_in_zwift_watopia(activity_type, lat, lon):
"""Zwift's Watopia is mapped over the Solomon Islands."""
if activity_type == Keys.TYPE_VIRTUAL_CYCLING_KEY or activity_type == Keys.TYPE_VIRTUAL_RUNNING_KEY:
distance_to_watopia_meters = distance.haversine_distance_ignore_altitude(lat, lon, -11.6364607214928, 166.972435712814)
return (distance_to_watopia_meters < 25000)
return False
@staticmethod
def is_activity_in_zwift_crit_city(activity_type, lat, lon):
"""Zwift's Crit City is mapped over the Solomon Islands."""
if activity_type == Keys.TYPE_VIRTUAL_CYCLING_KEY or activity_type == Keys.TYPE_VIRTUAL_RUNNING_KEY:
distance_to_watopia_meters = distance.haversine_distance_ignore_altitude(lat, lon, -10.383856371045113, 165.80203771591187)
return (distance_to_watopia_meters < 10000)
return False
@staticmethod
def is_activity_in_zwift_makuri_islands(activity_type, lat, lon):
"""Zwift's Makuri Islands is mapped over the Santa Cruz Islands in the Solomon Islands chain."""
if activity_type == Keys.TYPE_VIRTUAL_CYCLING_KEY or activity_type == Keys.TYPE_VIRTUAL_RUNNING_KEY:
distance_to_watopia_meters = distance.haversine_distance_ignore_altitude(lat, lon, -10.74387788772583, 165.8565080165863)
return (distance_to_watopia_meters < 25000)
return False
def render_page_for_errored_activity(self, activity_id, logged_in, belongs_to_current_user):
"""Helper function for rendering an error page when attempting to view an activity with bad data."""
delete_str = ""
if belongs_to_current_user is not None:
delete_str = "<td><button type=\"button\" onclick=\"return delete_activity()\" style=\"color:red\">Delete</button></td><tr>\n"
my_template = Template(filename=self.error_activity_html_file, module_directory=self.tempmod_dir)
return my_template.render(nav=self.create_navbar(logged_in), product=PRODUCT_NAME, root_url=self.root_url, error="There is no data for the specified activity.", activity_id=activity_id, delete=delete_str)
def render_page_for_mapped_activity(self, user_realname, activity_id, activity, activity_user_id, activity_user_resting_hr, activity_user_max_hr, logged_in_user_id, belongs_to_current_user, is_live):
"""Helper function for rendering the map corresonding to a specific activity."""
# Is the user logged in?
logged_in = logged_in_user_id is not None
# User's preferred unit system.
if logged_in:
unit_system = self.user_mgr.retrieve_user_setting(logged_in_user_id, Keys.USER_PREFERRED_UNITS_KEY)
else:
unit_system = Keys.UNITS_STANDARD_KEY
# Get all the things.
description_str = self.render_description_for_page(activity)
name = App.render_activity_name(activity)
activity_type = App.render_activity_type(activity)
if activity_user_id is not None:
ftp = self.user_mgr.estimate_ftp(activity_user_id)
else:
ftp = 0.0
is_foot_based_activity = activity_type in Keys.FOOT_BASED_ACTIVITIES
is_foot_based_activity_str = "false"
if is_foot_based_activity:
is_foot_based_activity_str = "true"
# Retrieve cached summary data. It is possible that the summary data has not yet been computed.
if Keys.ACTIVITY_SUMMARY_KEY in activity:
summary_data = activity[Keys.ACTIVITY_SUMMARY_KEY]
else:
summary_data = {}
# Start with the activity type.
summary = "\t<li>" + activity_type + "</li>\n"
# Add the location description.
if Keys.ACTIVITY_LOCATION_DESCRIPTION_KEY in summary_data:
location_description = summary_data[Keys.ACTIVITY_LOCATION_DESCRIPTION_KEY]
if len(location_description) > 0:
summary += "\t<li>" + App.render_array_reversed(location_description) + "</li>\n"
# Add the activity date.
if Keys.ACTIVITY_START_TIME_KEY in activity:
summary += "\t<li>Start: <script>document.write(unix_time_to_local_string(" + str(activity[Keys.ACTIVITY_START_TIME_KEY]) + "))</script></li>\n"
# Add the activity name.
summary += "\t<li>Name: " + name + "</li>\n"
# Build the detailed analysis table from data that was computed out-of-band and cached.
details_str = ""
excluded_keys = Keys.UNSUMMARIZABLE_KEYS
excluded_keys.append(Keys.LONGEST_DISTANCE)
for key in sorted(summary_data):
if is_foot_based_activity and key == Keys.BEST_SPEED:
details_str += "<td><b>" + Keys.BEST_PACE + "</b></td><td>"
value = summary_data[key]
details_str += Units.convert_to_string_in_specified_unit_system(unit_system, value, Units.UNITS_DISTANCE_METERS, Units.UNITS_TIME_SECONDS, Keys.BEST_PACE)
details_str += "</td><tr>\n"
elif key == Keys.ACTIVITY_INTERVALS_KEY:
details_str += "<td><b>Intervals</b><td>"
details_str += App.render_intervals_str(summary_data[key])
details_str += "</td><tr>\n"
elif key not in excluded_keys:
details_str += "<td><b>"
details_str += key
details_str += "</b></td><td>"
value = summary_data[key]
details_str += Units.convert_to_string_in_specified_unit_system(unit_system, value, Units.UNITS_DISTANCE_METERS, Units.UNITS_TIME_SECONDS, key)
details_str += "</td><tr>\n"
if len(details_str) == 0:
details_str = "<td><b>No data</b></td><tr>\n"
# Append the hash (for debugging purposes).
if self.debug and Keys.ACTIVITY_HASH_KEY in summary_data:
details_str += "<td><b>Activity Hash</b></td><td>"
details_str += summary_data[Keys.ACTIVITY_HASH_KEY]
details_str += "</td><tr>\n"
# List the tags.
tags_str = self.render_tags(activity, activity_user_id, belongs_to_current_user)
# List the comments.
comments_str = self.render_comments(activity, logged_in)
# List the export options.
exports_str = ""
if logged_in:
exports_str = App.render_export_control(True, Keys.APP_ACCELEROMETER_KEY in activity)
# Somethings will only be shown if the activity belongs to the logged in user.
if belongs_to_current_user:
visibility_str = ""
else:
visibility_str = "display:none;"
# Build the page title.
if is_live:
page_title = "Live Tracking"
else:
page_title = "Activity"
# Was this a virtual activity in Zwift's Watopia?
is_in_watopia = False
is_in_crit_city = False
is_in_makuri_islands = False
if activity_type == Keys.TYPE_VIRTUAL_CYCLING_KEY:
locations = activity[Keys.ACTIVITY_LOCATIONS_KEY]
if locations is None or len(locations) == 0:
return self.render_page_for_errored_activity(activity_id, logged_in, belongs_to_current_user)
last_loc = locations[-1]
last_lat = last_loc[Keys.LOCATION_LAT_KEY]
last_lon = last_loc[Keys.LOCATION_LON_KEY]
is_in_watopia = App.is_activity_in_zwift_watopia(activity_type, last_lat, last_lon)
is_in_crit_city = App.is_activity_in_zwift_crit_city(activity_type, last_lat, last_lon)
is_in_makuri_islands = App.is_activity_in_zwift_makuri_islands(activity_type, last_lat, last_lon)
# If a google maps key was provided then use google maps, otherwise use open street map.
if is_in_watopia and os.path.isfile(self.zwift_watopia_map_file) > 0:
my_template = Template(filename=self.zwift_html_file, module_directory=self.tempmod_dir)
return my_template.render(nav=self.create_navbar(logged_in), product=PRODUCT_NAME, root_url=self.root_url, name=user_realname, pagetitle=page_title, unit_system=unit_system, is_foot_based_activity=is_foot_based_activity_str, summary=summary, activity_id=activity_id, user_id=activity_user_id, ftp=ftp, resting_hr=activity_user_resting_hr, max_hr=activity_user_max_hr, description=description_str, details=details_str, tags=tags_str, comments=comments_str, exports=exports_str, visibility=visibility_str, map_file_name=ZWIFT_WATOPIA_MAP_FILE_NAME)
elif is_in_crit_city and os.path.isfile(self.zwift_crit_city_map_file) > 0:
my_template = Template(filename=self.zwift_html_file, module_directory=self.tempmod_dir)
return my_template.render(nav=self.create_navbar(logged_in), product=PRODUCT_NAME, root_url=self.root_url, name=user_realname, pagetitle=page_title, unit_system=unit_system, is_foot_based_activity=is_foot_based_activity_str, summary=summary, activity_id=activity_id, user_id=activity_user_id, ftp=ftp, resting_hr=activity_user_resting_hr, max_hr=activity_user_max_hr, description=description_str, details=details_str, tags=tags_str, comments=comments_str, exports=exports_str, visibility=visibility_str, map_file_name=ZWIFT_CRIT_CITY_MAP_FILE_NAME)
elif is_in_makuri_islands and os.path.isfile(self.zwift_makuri_islands_map_file) > 0:
my_template = Template(filename=self.zwift_html_file, module_directory=self.tempmod_dir)
return my_template.render(nav=self.create_navbar(logged_in), product=PRODUCT_NAME, root_url=self.root_url, name=user_realname, pagetitle=page_title, unit_system=unit_system, is_foot_based_activity=is_foot_based_activity_str, summary=summary, activity_id=activity_id, user_id=activity_user_id, ftp=ftp, resting_hr=activity_user_resting_hr, max_hr=activity_user_max_hr, description=description_str, details=details_str, tags=tags_str, comments=comments_str, exports=exports_str, visibility=visibility_str, map_file_name=ZWIFT_MAKURI_ISLANDS_MAP_FILE_NAME)
elif self.google_maps_key:
my_template = Template(filename=self.map_single_google_html_file, module_directory=self.tempmod_dir)
return my_template.render(nav=self.create_navbar(logged_in), product=PRODUCT_NAME, root_url=self.root_url, name=user_realname, pagetitle=page_title, unit_system=unit_system, is_foot_based_activity=is_foot_based_activity_str, summary=summary, activity_id=activity_id, user_id=activity_user_id, ftp=ftp, resting_hr=activity_user_resting_hr, max_hr=activity_user_max_hr, description=description_str, details=details_str, tags=tags_str, comments=comments_str, exports=exports_str, visibility=visibility_str)
else:
my_template = Template(filename=self.map_single_osm_html_file, module_directory=self.tempmod_dir)
return my_template.render(nav=self.create_navbar(logged_in), product=PRODUCT_NAME, root_url=self.root_url, name=user_realname, pagetitle=page_title, unit_system=unit_system, is_foot_based_activity=is_foot_based_activity_str, summary=summary, activity_id=activity_id, user_id=activity_user_id, ftp=ftp, resting_hr=activity_user_resting_hr, max_hr=activity_user_max_hr, description=description_str, details=details_str, tags=tags_str, comments=comments_str, exports=exports_str, visibility=visibility_str)
def render_page_for_activity(self, activity, user_realname, activity_user_id, activity_user_resting_hr, activity_user_max_hr, logged_in_user_id, belongs_to_current_user, is_live):
"""Helper function for rendering the page corresonding to a specific activity."""
try:
# Does the activity contain accelerometer data, as with lifting activities recorded from the companion app?
if activity[Keys.ACTIVITY_TYPE_KEY] in Keys.STRENGTH_ACTIVITIES or activity[Keys.ACTIVITY_TYPE_KEY] in Keys.SWIM_WORKOUTS:
return self.render_page_for_unmapped_activity(user_realname, activity[Keys.ACTIVITY_ID_KEY], activity, activity_user_id, activity_user_resting_hr, activity_user_max_hr, logged_in_user_id, belongs_to_current_user, is_live)
# Assume it's a location based activity.
return self.render_page_for_mapped_activity(user_realname, activity[Keys.ACTIVITY_ID_KEY], activity, activity_user_id, activity_user_resting_hr, activity_user_max_hr, logged_in_user_id, belongs_to_current_user, is_live)
except:
self.log_error(traceback.format_exc())
self.log_error(sys.exc_info()[0])
self.log_error('Unhandled exception in ' + App.activity.__name__)
return self.render_error()
def render_page_for_multiple_mapped_activities(self, email, user_realname, device_id_strs, user_id, logged_in):
"""Helper function for rendering the map to track multiple devices."""
if device_id_strs is None:
my_template = Template(filename=self.error_logged_in_html_file, module_directory=self.tempmod_dir)
return my_template.render(nav=self.create_navbar(logged_in), product=PRODUCT_NAME, root_url=self.root_url, error="No device IDs were specified.")
last_lat = 0.0
last_lon = 0.0
for device_id_str in device_id_strs:
activity_id = self.data_mgr.retrieve_most_recent_activity_id_for_device(device_id_str)
if activity_id is None:
continue
locations = self.data_mgr.retrieve_activity_locations(activity_id)
if locations is None:
continue
if len(locations) > 0:
last_loc = locations[-1]
last_lat = last_loc[Keys.LOCATION_LAT_KEY]
last_lon = last_loc[Keys.LOCATION_LON_KEY]
my_template = Template(filename=self.map_multi_html_file, module_directory=self.tempmod_dir)
return my_template.render(nav=self.create_navbar(logged_in), product=PRODUCT_NAME, root_url=self.root_url, email=email, name=user_realname, lastLat=last_lat, lastLon=last_lon, user_id=str(user_id))
def render_error(self, error_str=None):
"""Renders the error page."""
try:
error_html_file = os.path.join(self.root_dir, Dirs.HTML_DIR, 'error.html')
my_template = Template(filename=error_html_file, module_directory=self.tempmod_dir)
if error_str is None:
error_str = "Internal Error."
return my_template.render(product=PRODUCT_NAME, root_url=self.root_url, error=error_str)
except:
pass
return ""
def render_no_live_data_error(self, user_str):
"""Renders the error page."""
try:
error_html_file = os.path.join(self.root_dir, Dirs.HTML_DIR, 'no_live_data.html')
my_template = Template(filename=error_html_file, module_directory=self.tempmod_dir)
return my_template.render(product=PRODUCT_NAME, root_url=self.root_url, user_str=user_str)
except:
pass
return self.render_error()
def error_404(self, status, message, traceback, version):
"""This method only exists so the web framework's 404 handler has something to call."""
return self.render_page_not_found()
def render_page_not_found(self):
"""Renders the 404 error page."""
try:
error_html_file = os.path.join(self.root_dir, Dirs.HTML_DIR, 'error_404.html')
my_template = Template(filename=error_html_file, module_directory=self.tempmod_dir)
return my_template.render(product=PRODUCT_NAME, root_url=self.root_url)
except:
pass
return self.render_error()
@Perf.statistics
def live_activity(self, activity, activity_user):
"""Renders the map page for the specified (in progress) activity."""
# Sanity check.
if activity is None:
return self.render_error()
if activity_user is None:
return self.render_error()
# Get the logged in user (if any).
logged_in_user_id = None
logged_in_username = self.user_mgr.get_logged_in_username()
if logged_in_username is not None:
logged_in_user_id, _, _ = self.user_mgr.retrieve_user(logged_in_username)
# Is the activity still live? After one day, the activity is no longer considered live.
now = time.time()
diff = now - activity[Keys.ACTIVITY_START_TIME_KEY]
diff_hours = diff / 60 / 60
diff_days = diff_hours / 24
if diff_days >= 1.0:
return self.render_no_live_data_error(activity_user[Keys.REALNAME_KEY])
# Determine if the current user can view the activity.
activity_user_id = activity_user[Keys.DATABASE_ID_KEY]
belongs_to_current_user = str(activity_user_id) == str(logged_in_user_id)
if not (self.data_mgr.is_activity_public(activity) or belongs_to_current_user):
return self.render_error("The requested activity is not public.")
# Determine the activity user's resting heart rate.
activity_user_resting_hr = self.user_mgr.retrieve_user_setting(activity_user_id, Keys.USER_RESTING_HEART_RATE_KEY)
# Determine the activity user's max heart rate.
activity_user_max_hr = self.user_mgr.retrieve_best_max_hr(activity_user_id)
# Render from template.
return self.render_page_for_activity(activity, activity_user[Keys.REALNAME_KEY], activity_user_id, activity_user_resting_hr, activity_user_max_hr, logged_in_user_id, belongs_to_current_user, True)
@Perf.statistics
def live_device(self, device_str):
"""Renders the map page for the current activity from a single device."""
# Sanity check.
if device_str is None:
return self.render_error()
# Determine the ID of the most recent activity logged from the specified device.
activity = self.data_mgr.retrieve_most_recent_activity_for_device(device_str)
if activity is None:
return self.render_error()
# Determine who owns the device.
device_user = self.user_mgr.retrieve_user_from_device(device_str)
# Render the page.
return self.live_activity(activity, device_user)
@Perf.statistics
def live_user(self, user_str):
"""Renders the map page for the current activity for a given user."""
# Sanity check.
if user_str is None:
return self.render_error()
# Look up the user.
user = self.user_mgr.retrieve_user_details(user_str)
# Make sure the user has registered devies.
if not Keys.DEVICES_KEY in user:
return self.render_no_live_data_error(user_str)
# Find the user's most recent activity.
user_devices = user[Keys.DEVICES_KEY]
activity = self.data_mgr.retrieve_most_recent_activity_for_user(user_devices)
if activity is None:
return self.render_no_live_data_error(user_str)
# Render the page.
return self.live_activity(activity, user)
@Perf.statistics
def activity(self, activity_id):
"""Renders the details page for an activity."""
# Sanity check the activity ID.
if not InputChecker.is_uuid(activity_id):
return self.render_error("Invalid activity ID")
# Get the logged in user (if any).
logged_in_user_id = None
logged_in_username = self.user_mgr.get_logged_in_username()
if logged_in_username is not None:
logged_in_user_id, _, _ = self.user_mgr.retrieve_user(logged_in_username)
# Load the activity.
activity = self.data_mgr.retrieve_activity(activity_id)
if activity is None:
return self.render_error("The requested activity does not exist.")
# Determine who owns the device, and hence the activity.
activity_user_id, _, activity_user_realname = self.data_mgr.get_activity_user(activity)
if activity_user_id is None:
return self.render_error("The activity owner cannot be determined.")
belongs_to_current_user = str(activity_user_id) == str(logged_in_user_id)
if activity_user_realname is None:
activity_user_realname = ""
# Determine if the current user can view the activity.
if not (self.data_mgr.is_activity_public(activity) or belongs_to_current_user):
return self.render_error("The requested activity is not public.")
# Determine the activity user's resting heart rate.
activity_user_resting_hr = self.user_mgr.retrieve_user_setting(activity_user_id, Keys.USER_RESTING_HEART_RATE_KEY)
# Determine the activity user's max heart rate.
activity_user_max_hr = self.user_mgr.retrieve_best_max_hr(activity_user_id)
# Render from template.
return self.render_page_for_activity(activity, activity_user_realname, activity_user_id, activity_user_resting_hr, activity_user_max_hr, logged_in_user_id, belongs_to_current_user, False)
@Perf.statistics
def edit_activity(self, activity_id):
"""Renders the edit page for an activity."""
# Sanity check the activity ID.
if not InputChecker.is_uuid(activity_id):
return self.render_error("Invalid activity ID")
# Get the logged in user.
username = self.user_mgr.get_logged_in_username()
if username is None:
raise RedirectException(LOGIN_URL)
# Get the details of the logged in user.
user_id, _, user_realname = self.user_mgr.retrieve_user(username)
if user_id is None:
self.log_error('Unknown user ID')
raise RedirectException(LOGIN_URL)
# Load the activity.
activity = self.data_mgr.retrieve_activity(activity_id)
if activity is None:
return self.render_error("The requested activity does not exist.")
# Determine who owns the device, and hence the activity.
activity_user_id, _, _ = self.data_mgr.get_activity_user(activity)
belongs_to_current_user = str(activity_user_id) == str(user_id)
if not belongs_to_current_user:
return self.render_error("The logged in user does not own the requested activity.")
# Render the activity name.
activity_name_str = ""
if Keys.ACTIVITY_NAME_KEY in activity:
activity_name_str = activity[Keys.ACTIVITY_NAME_KEY]
# Render the activity type.
activity_type_str = ""
if Keys.ACTIVITY_TYPE_KEY in activity:
activity_type_str = activity[Keys.ACTIVITY_TYPE_KEY]
# Render the activity description.
description_str = ""
if Keys.ACTIVITY_DESCRIPTION_KEY in activity:
description_str = activity[Keys.ACTIVITY_DESCRIPTION_KEY]
# Render from template.
html_file = os.path.join(self.root_dir, Dirs.HTML_DIR, 'edit_activity.html')
my_template = Template(filename=html_file, module_directory=self.tempmod_dir)
return my_template.render(nav=self.create_navbar(True), product=PRODUCT_NAME, root_url=self.root_url, email=username, name=user_realname, activity_id=activity_id, activity_name=activity_name_str, activity_type=activity_type_str, description=description_str)
@Perf.statistics
def trim_activity(self, activity_id):
"""Renders the trim page for an activity."""
# Sanity check the activity ID.
if not InputChecker.is_uuid(activity_id):
return self.render_error("Invalid activity ID")
# Get the logged in user.
username = self.user_mgr.get_logged_in_username()
if username is None:
raise RedirectException(LOGIN_URL)
# Get the details of the logged in user.
user_id, _, user_realname = self.user_mgr.retrieve_user(username)
if user_id is None:
self.log_error('Unknown user ID')
raise RedirectException(LOGIN_URL)
# Load the activity.
activity = self.data_mgr.retrieve_activity(activity_id)
if activity is None:
return self.render_error("The requested activity does not exist.")
# Render from template.
html_file = os.path.join(self.root_dir, Dirs.HTML_DIR, 'trim_activity.html')
my_template = Template(filename=html_file, module_directory=self.tempmod_dir)
return my_template.render(nav=self.create_navbar(True), product=PRODUCT_NAME, root_url=self.root_url, email=username, name=user_realname, activity_id=activity_id)
@Perf.statistics
def merge_activity(self, activity_id):
"""Renders the merge page for an activity."""
# Sanity check the activity ID.
if not InputChecker.is_uuid(activity_id):
return self.render_error("Invalid activity ID")
# Get the logged in user.
username = self.user_mgr.get_logged_in_username()
if username is None:
raise RedirectException(LOGIN_URL)
# Get the details of the logged in user.
user_id, _, user_realname = self.user_mgr.retrieve_user(username)
if user_id is None:
self.log_error('Unknown user ID')
raise RedirectException(LOGIN_URL)
# Load the activity.
activity = self.data_mgr.retrieve_activity(activity_id)
if activity is None:
return self.render_error("The requested activity does not exist.")
# Get the activity start and end times.
start_time = 0
end_time = 0
if Keys.ACTIVITY_START_TIME_KEY in activity:
start_time = activity[Keys.ACTIVITY_START_TIME_KEY]
if Keys.ACTIVITY_END_TIME_KEY in activity:
end_time = activity[Keys.ACTIVITY_END_TIME_KEY]
# Render from template.
html_file = os.path.join(self.root_dir, Dirs.HTML_DIR, 'merge_activity.html')
my_template = Template(filename=html_file, module_directory=self.tempmod_dir)
return my_template.render(nav=self.create_navbar(True), product=PRODUCT_NAME, root_url=self.root_url, email=username, name=user_realname, activity_id=activity_id, start_time=start_time, end_time=end_time)
@Perf.statistics
def add_photos(self, activity_id):
"""Renders the edit page for an activity."""
# Sanity check the activity ID.
if not InputChecker.is_uuid(activity_id):
return self.render_error("Invalid activity ID")
# Get the logged in user.
username = self.user_mgr.get_logged_in_username()
if username is None:
raise RedirectException(LOGIN_URL)
# Get the details of the logged in user.
user_id, _, user_realname = self.user_mgr.retrieve_user(username)
if user_id is None:
self.log_error('Unknown user ID')
raise RedirectException(LOGIN_URL)
# Render from template.
html_file = os.path.join(self.root_dir, Dirs.HTML_DIR, 'add_photos.html')
my_template = Template(filename=html_file, module_directory=self.tempmod_dir)
return my_template.render(nav=self.create_navbar(True), product=PRODUCT_NAME, root_url=self.root_url, email=username, name=user_realname, activity_id=activity_id)
@Perf.statistics
def device(self, device_str):
"""Renders the map page for a single device."""
# Get the logged in user (if any).
logged_in_user_id = None
logged_in_username = self.user_mgr.get_logged_in_username()
if logged_in_username is not None:
logged_in_user_id, _, _ = self.user_mgr.retrieve_user(logged_in_username)
# Get the activity ID being requested. If one is not provided then get the latest activity for the device
activity_id = self.data_mgr.retrieve_most_recent_activity_id_for_device(device_str)
if activity_id is None:
return self.render_error()
# Determine who owns the device.
device_user = self.user_mgr.retrieve_user_from_device(device_str)
activity_user_id = device_user[Keys.DATABASE_ID_KEY]
belongs_to_current_user = str(activity_user_id) == str(logged_in_user_id)
# Load the activity.
activity = self.data_mgr.retrieve_activity(activity_id)
if activity is None:
return self.render_error("The requested activity does not exist.")
# Determine if the current user can view the activity.
if not (self.data_mgr.is_activity_public(activity) or belongs_to_current_user):
return self.render_error("The requested activity is not public.")
# Determine the activity user's resting heart rate.
activity_user_resting_hr = self.user_mgr.retrieve_user_setting(activity_user_id, Keys.USER_RESTING_HEART_RATE_KEY)
# Determine the activity user's max heart rate.
activity_user_max_hr = self.user_mgr.retrieve_best_max_hr(activity_user_id)
# Render from template.
return self.render_page_for_activity(activity, device_user[Keys.REALNAME_KEY], activity_user_id, activity_user_resting_hr, activity_user_max_hr, logged_in_user_id, belongs_to_current_user, False)
@Perf.statistics
def my_activities(self):
"""Renders the list of the specified user's activities."""
return self.render_simple_page('my_activities.html')