-
Notifications
You must be signed in to change notification settings - Fork 129
/
zwift_offline.py
4085 lines (3679 loc) · 178 KB
/
zwift_offline.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
#!/usr/bin/env python
import calendar
import datetime
import logging
import os
import signal
import random
import sys
import tempfile
import time
import math
import threading
import re
import smtplib
import ssl
import requests
import json
import base64
import uuid
import jwt
import sqlalchemy
import fitdecode
import xml.etree.ElementTree as ET
from copy import deepcopy
from functools import wraps
from io import BytesIO
from shutil import copyfile
from urllib.parse import quote
from flask import Flask, request, jsonify, redirect, render_template, url_for, flash, session, make_response, send_file, send_from_directory
from flask_login import UserMixin, AnonymousUserMixin, LoginManager, login_user, current_user, login_required, logout_user
from gevent.pywsgi import WSGIServer
from google.protobuf.json_format import MessageToDict, Parse
from flask_sqlalchemy import SQLAlchemy
from werkzeug.security import generate_password_hash, check_password_hash
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from Crypto.Cipher import AES
from Crypto.Random import get_random_bytes
from collections import deque
from itertools import islice
sys.path.append(os.path.join(sys.path[0], 'protobuf')) # otherwise import in .proto does not work
import udp_node_msgs_pb2
import tcp_node_msgs_pb2
import activity_pb2
import goal_pb2
import login_pb2
import per_session_info_pb2
import profile_pb2
import segment_result_pb2
import route_result_pb2
import world_pb2
import zfiles_pb2
import hash_seeds_pb2
import events_pb2
import variants_pb2
import playback_pb2
import user_storage_pb2
import online_sync
logging.basicConfig(level=os.environ.get("LOGLEVEL", "INFO"))
logger = logging.getLogger('zoffline')
logger.setLevel(logging.DEBUG)
logging.getLogger('sqlalchemy.engine').setLevel(logging.WARN)
if getattr(sys, 'frozen', False):
# If we're running as a pyinstaller bundle
SCRIPT_DIR = sys._MEIPASS
STORAGE_DIR = "%s/storage" % os.path.dirname(sys.executable)
LOGS_DIR = "%s/logs" % os.path.dirname(sys.executable)
else:
SCRIPT_DIR = os.path.dirname(os.path.realpath(__file__))
STORAGE_DIR = "%s/storage" % SCRIPT_DIR
LOGS_DIR = "%s/logs" % SCRIPT_DIR
def make_dir(name):
try:
if not os.path.isdir(name):
os.makedirs(name)
except IOError as e:
logger.error("failed to create dir (%s): %s", name, str(e))
return False
return True
# Ensure storage dir exists
if not make_dir(STORAGE_DIR):
sys.exit(1)
SSL_DIR = "%s/ssl" % SCRIPT_DIR
DATABASE_PATH = "%s/zwift-offline.db" % STORAGE_DIR
DATABASE_CUR_VER = 3
ZWIFT_VER_CUR = ET.parse('%s/cdn/gameassets/Zwift_Updates_Root/Zwift_ver_cur.xml' % SCRIPT_DIR).getroot().get('sversion')
# For auth server
AUTOLAUNCH_FILE = "%s/auto_launch.txt" % STORAGE_DIR
SERVER_IP_FILE = "%s/server-ip.txt" % STORAGE_DIR
if os.path.exists(SERVER_IP_FILE):
with open(SERVER_IP_FILE, 'r') as f:
server_ip = f.read().rstrip('\r\n')
else:
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
try:
s.connect(('10.254.254.254', 1))
server_ip = s.getsockname()[0]
except:
server_ip = '127.0.0.1'
finally:
s.close()
logger.info("server-ip.txt not found, using %s", server_ip)
SECRET_KEY_FILE = "%s/secret-key.txt" % STORAGE_DIR
ENABLEGHOSTS_FILE = "%s/enable_ghosts.txt" % STORAGE_DIR
GHOST_PROFILE = None
GHOST_PROFILE_FILE = "%s/ghost_profile.txt" % STORAGE_DIR
if os.path.exists(GHOST_PROFILE_FILE):
with open(GHOST_PROFILE_FILE) as f:
GHOST_PROFILE = json.load(f)
ALL_TIME_LEADERBOARDS = os.path.exists("%s/all_time_leaderboards.txt" % STORAGE_DIR)
MULTIPLAYER = os.path.exists("%s/multiplayer.txt" % STORAGE_DIR)
if MULTIPLAYER:
if not make_dir(LOGS_DIR):
sys.exit(1)
from logging.handlers import RotatingFileHandler
logHandler = RotatingFileHandler('%s/zoffline.log' % LOGS_DIR, maxBytes=1000000, backupCount=10)
logger.addHandler(logHandler)
CREDENTIALS_KEY_FILE = "%s/credentials-key.bin" % STORAGE_DIR
if not os.path.exists(CREDENTIALS_KEY_FILE):
with open(CREDENTIALS_KEY_FILE, 'wb') as f:
f.write(get_random_bytes(32))
with open(CREDENTIALS_KEY_FILE, 'rb') as f:
credentials_key = f.read()
GARMIN_DOMAIN = 'garmin.com'
GARMIN_DOMAIN_FILE = '%s/garmin_domain.txt' % STORAGE_DIR
if os.path.exists(GARMIN_DOMAIN_FILE):
with open(GARMIN_DOMAIN_FILE) as f:
GARMIN_DOMAIN = f.readline().rstrip('\r\n')
import warnings
with warnings.catch_warnings():
from stravalib.client import Client
from tokens import *
# Android uses https for cdn
app = Flask(__name__, static_folder='%s/cdn/gameassets' % SCRIPT_DIR, static_url_path='/gameassets', template_folder='%s/cdn/static/web/launcher' % SCRIPT_DIR)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///{db}'.format(db=DATABASE_PATH)
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
if not os.path.exists(SECRET_KEY_FILE):
with open(SECRET_KEY_FILE, 'wb') as f:
f.write(os.urandom(16))
with open(SECRET_KEY_FILE, 'rb') as f:
app.config['SECRET_KEY'] = f.read()
app.config['MAX_CONTENT_LENGTH'] = 4 * 1024 * 1024 # A typical .fit file with power, cadence, and heartrate data recorded in December 2024 is approximately 1.3 MB / 4 hours.
db = SQLAlchemy()
db.init_app(app)
online = {}
ghosts_enabled = {}
player_update_queue = {}
zc_connect_queue = {}
player_partial_profiles = {}
map_override = {}
climb_override = {}
global_bookmarks = {}
restarting = False
restarting_in_minutes = 0
reload_pacer_bots = False
with open(os.path.join(SCRIPT_DIR, "data", "climbs.txt")) as f:
CLIMBS = json.load(f)
with open(os.path.join(SCRIPT_DIR, "data", "game_dictionary.txt")) as f:
GD = json.load(f, object_hook=lambda d: {int(k) if k.lstrip('-').isdigit() else k: v for k, v in d.items()})
class User(UserMixin, db.Model):
player_id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.Text, unique=True, nullable=False)
first_name = db.Column(db.Text, nullable=False)
last_name = db.Column(db.Text, nullable=False)
pass_hash = db.Column(db.Text, nullable=False)
enable_ghosts = db.Column(db.Integer, nullable=False, default=1)
is_admin = db.Column(db.Integer, nullable=False, default=0)
remember = db.Column(db.Integer, nullable=False, default=0)
def __repr__(self):
return self.username
def get_id(self):
return self.player_id
def get_token(self):
dt = datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta(minutes=30)
return jwt.encode({'user': self.player_id, 'exp': dt}, app.config['SECRET_KEY'], algorithm='HS256')
@staticmethod
def verify_token(token):
try:
data = jwt.decode(token, app.config['SECRET_KEY'], algorithms='HS256')
except:
return None
id = data.get('user')
if id:
return db.session.get(User, id)
return None
class AnonUser(User, AnonymousUserMixin, db.Model):
username = "zoffline"
first_name = "z"
last_name = "offline"
enable_ghosts = os.path.isfile(ENABLEGHOSTS_FILE)
def is_authenticated(self):
return True
class Activity(db.Model):
id = db.Column(db.Integer, primary_key=True)
player_id = db.Column(db.Integer)
course_id = db.Column(db.Integer)
name = db.Column(db.Text)
f5 = db.Column(db.Integer)
privateActivity = db.Column(db.Integer)
start_date = db.Column(db.Text)
end_date = db.Column(db.Text)
distanceInMeters = db.Column(db.Float)
avg_heart_rate = db.Column(db.Float)
max_heart_rate = db.Column(db.Float)
avg_watts = db.Column(db.Float)
max_watts = db.Column(db.Float)
avg_cadence = db.Column(db.Float)
max_cadence = db.Column(db.Float)
avg_speed = db.Column(db.Float)
max_speed = db.Column(db.Float)
calories = db.Column(db.Float)
total_elevation = db.Column(db.Float)
strava_upload_id = db.Column(db.Integer)
strava_activity_id = db.Column(db.Integer)
f22 = db.Column(db.Text)
f23 = db.Column(db.Integer)
fit = db.Column(db.LargeBinary)
fit_filename = db.Column(db.Text)
subgroupId = db.Column(db.Integer)
workoutHash = db.Column(db.Integer)
progressPercentage = db.Column(db.Float)
sport = db.Column(db.Integer)
date = db.Column(db.Text)
act_f32 = db.Column(db.Float)
act_f33 = db.Column(db.Text)
act_f34 = db.Column(db.Text)
privacy = db.Column(db.Integer)
fitness_privacy = db.Column(db.Integer)
club_name = db.Column(db.Text)
movingTimeInMs = db.Column(db.Integer)
class SegmentResult(db.Model):
id = db.Column(db.Integer, primary_key=True)
player_id = db.Column(db.Integer)
server_realm = db.Column(db.Integer)
course_id = db.Column(db.Integer)
segment_id = db.Column(db.Integer)
event_subgroup_id = db.Column(db.Integer)
first_name = db.Column(db.Text)
last_name = db.Column(db.Text)
world_time = db.Column(db.Integer)
finish_time_str = db.Column(db.Text)
elapsed_ms = db.Column(db.Integer)
power_source_model = db.Column(db.Integer)
weight_in_grams = db.Column(db.Integer)
f14 = db.Column(db.Integer)
avg_power = db.Column(db.Integer)
is_male = db.Column(db.Integer)
time = db.Column(db.Text)
player_type = db.Column(db.Integer)
avg_hr = db.Column(db.Integer)
sport = db.Column(db.Integer)
activity_id = db.Column(db.Integer)
f22 = db.Column(db.Integer)
f23 = db.Column(db.Text)
class RouteResult(db.Model):
id = db.Column(db.Integer, primary_key=True)
player_id = db.Column(db.Integer)
server_realm = db.Column(db.Integer)
map_id = db.Column(db.Integer)
route_hash = db.Column(db.Integer)
event_id = db.Column(db.Integer)
world_time = db.Column(db.Integer)
elapsed_ms = db.Column(db.Integer)
power_type = db.Column(db.Integer)
weight_in_grams = db.Column(db.Integer)
height_in_centimeters = db.Column(db.Integer)
ftp = db.Column(db.Integer)
avg_power = db.Column(db.Integer)
max_power = db.Column(db.Integer)
avg_hr = db.Column(db.Integer)
max_hr = db.Column(db.Integer)
calories = db.Column(db.Integer)
gender = db.Column(db.Integer)
player_type = db.Column(db.Integer)
sport = db.Column(db.Integer)
activity_id = db.Column(db.Integer)
steering = db.Column(db.Integer)
hr_monitor = db.Column(db.Text)
power_meter = db.Column(db.Text)
controllable = db.Column(db.Text)
cadence_sensor = db.Column(db.Text)
class Goal(db.Model):
id = db.Column(db.Integer, primary_key=True)
player_id = db.Column(db.Integer)
sport = db.Column(db.Integer)
name = db.Column(db.Text)
type = db.Column(db.Integer)
periodicity = db.Column(db.Integer)
target_distance = db.Column(db.Float)
target_duration = db.Column(db.Float)
actual_distance = db.Column(db.Float)
actual_duration = db.Column(db.Float)
created_on = db.Column(db.Integer)
period_end_date = db.Column(db.Integer)
status = db.Column(db.Integer)
timezone = db.Column(db.Text)
class Playback(db.Model):
id = db.Column(db.Integer, primary_key=True)
player_id = db.Column(db.Integer, nullable=False)
uuid = db.Column(db.Text, nullable=False)
segment_id = db.Column(db.Integer, nullable=False)
time = db.Column(db.Float, nullable=False)
world_time = db.Column(db.Integer, nullable=False)
type = db.Column(db.Integer)
class Zfile(db.Model):
id = db.Column(db.Integer, primary_key=True)
folder = db.Column(db.Text, nullable=False)
filename = db.Column(db.Text, nullable=False)
timestamp = db.Column(db.Integer, nullable=False)
player_id = db.Column(db.Integer, nullable=False)
class PrivateEvent(db.Model): # cached in glb_private_events
id = db.Column(db.Integer, primary_key=True)
json = db.Column(db.Text, nullable=False)
class Notification(db.Model):
id = db.Column(db.Integer, primary_key=True)
event_id = db.Column(db.Integer, nullable=False)
player_id = db.Column(db.Integer, nullable=False)
json = db.Column(db.Text, nullable=False)
class ActivityFile(db.Model):
id = db.Column(db.Integer, primary_key=True)
activity_id = db.Column(db.Integer, nullable=False)
full = db.Column(db.Integer, nullable=False)
class ActivityImage(db.Model):
id = db.Column(db.Integer, primary_key=True)
player_id = db.Column(db.Integer, nullable=False)
activity_id = db.Column(db.Integer, nullable=False)
class PowerCurve(db.Model):
id = db.Column(db.Integer, primary_key=True)
player_id = db.Column(db.Integer, nullable=False)
time = db.Column(db.Text, nullable=False)
power = db.Column(db.Integer, nullable=False)
power_wkg = db.Column(db.Float, nullable=False)
timestamp = db.Column(db.Integer, nullable=False)
class Version(db.Model):
version = db.Column(db.Integer, primary_key=True)
class Relay:
def __init__(self, key = b''):
self.ri = 0
self.tcp_ci = 0
self.udp_ci = 0
self.tcp_r_sn = 0
self.tcp_t_sn = 0
self.udp_r_sn = 0
self.udp_t_sn = 0
self.key = key
class PartialProfile:
player_id = 0
first_name = ''
last_name = ''
country_code = 0
route = 0
player_type = 'NORMAL'
male = True
weight_in_grams = 0
imageSrc = ''
def to_json(self):
return {"countryCode": self.country_code,
"enrolledZwiftAcademy": False, #don't need
"firstName": self.first_name,
"id": self.player_id,
"imageSrc": self.imageSrc,
"lastName": self.last_name,
"male": self.male,
"playerType": self.player_type }
class Bookmark:
name = ''
state = None
class Online:
total = 0
richmond = 0
watopia = 0
london = 0
makuriislands = 0
newyork = 0
innsbruck = 0
yorkshire = 0
france = 0
paris = 0
scotland = 0
courses_lookup = {
2: 'Richmond',
4: 'Unknown', # event specific?
6: 'Watopia',
7: 'London',
8: 'New York',
9: 'Innsbruck',
10: 'Bologna', # event specific
11: 'Yorkshire',
12: 'Crit City', # event specific
13: 'Makuri Islands',
14: 'France',
15: 'Paris',
16: 'Gravel Mountain', # event specific
17: 'Scotland'
}
def get_online():
online_in_region = Online()
for p_id in online:
player_state = online[p_id]
course = get_course(player_state)
course_name = courses_lookup[course]
if course_name == 'Richmond':
online_in_region.richmond += 1
elif course_name == 'Watopia':
online_in_region.watopia += 1
elif course_name == 'London':
online_in_region.london += 1
elif course_name == 'Makuri Islands':
online_in_region.makuriislands += 1
elif course_name == 'New York':
online_in_region.newyork += 1
elif course_name == 'Innsbruck':
online_in_region.innsbruck += 1
elif course_name == 'Yorkshire':
online_in_region.yorkshire += 1
elif course_name == 'France':
online_in_region.france += 1
elif course_name == 'Paris':
online_in_region.paris += 1
elif course_name == 'Scotland':
online_in_region.scotland += 1
online_in_region.total += 1
return online_in_region
def toSigned(n, byte_count):
return int.from_bytes(n.to_bytes(byte_count, 'little'), 'little', signed=True)
def imageSrc(player_id):
if os.path.isfile(os.path.join(STORAGE_DIR, str(player_id), 'avatarLarge.jpg')):
return "https://us-or-rly101.zwift.com/download/%s/avatarLarge.jpg" % player_id
else:
return None
def get_partial_profile(player_id):
if not player_id in player_partial_profiles:
partial_profile = PartialProfile()
partial_profile.player_id = player_id
if player_id in global_pace_partners.keys():
profile = global_pace_partners[player_id].profile
elif player_id in global_bots.keys():
profile = global_bots[player_id].profile
elif player_id > 10000000:
g_id = math.floor(player_id / 10000000)
p_id = player_id - g_id * 10000000
partial_profile.first_name = ''
partial_profile.last_name = time_since(global_ghosts[p_id].play[g_id-1].date)
return partial_profile
else:
profile = profile_pb2.PlayerProfile()
#Read from disk
profile_file = '%s/%s/profile.bin' % (STORAGE_DIR, player_id)
if os.path.isfile(profile_file):
with open(profile_file, 'rb') as fd:
profile.ParseFromString(fd.read())
else:
user = User.query.filter_by(player_id=player_id).first()
if user:
partial_profile.first_name = user.first_name
partial_profile.last_name = user.last_name
return partial_profile
partial_profile.imageSrc = imageSrc(player_id)
partial_profile.first_name = profile.first_name
partial_profile.last_name = profile.last_name
partial_profile.country_code = profile.country_code
partial_profile.player_type = profile_pb2.PlayerType.Name(jsf(profile, 'player_type', 1))
partial_profile.male = profile.is_male
partial_profile.weight_in_grams = profile.weight_in_grams
for f in profile.public_attributes:
#0x69520F20=1766985504 - crc32 of "PACE PARTNER - ROUTE"
if f.id == 1766985504:
if f.number_value >= 0:
partial_profile.route = toSigned(f.number_value, 4)
else:
partial_profile.route = -toSigned(-f.number_value, 4)
break
player_partial_profiles[player_id] = partial_profile
return player_partial_profiles[player_id]
def get_course(state):
return (state.f19 & 0xff0000) >> 16
def road_id(state):
return (state.aux3 & 0xff00) >> 8
def is_forward(state):
return (state.f19 & 4) != 0
def is_nearby(s1, s2):
if s1 is None or s2 is None:
return False
if s1.watchingRiderId == s2.id or s2.watchingRiderId == s1.id:
return True
if get_course(s1) == get_course(s2):
dist = math.sqrt((s2.x - s1.x)**2 + (s2.z - s1.z)**2 + (s2.y_altitude - s1.y_altitude)**2)
if dist <= 100000 or road_id(s1) == road_id(s2):
return True
return False
# We store flask-login's cookie in the "fake" JWT that we give Zwift.
# Make it a cookie again to reuse flask-login on API calls.
def jwt_to_session_cookie(f):
@wraps(f)
def wrapper(*args, **kwargs):
if not MULTIPLAYER:
return f(*args, **kwargs)
token = request.headers.get('Authorization')
if token and not session.get('_user_id'):
token = jwt.decode(token.split()[1], options=({'verify_signature': False, 'verify_aud': False}))
request.cookies = request.cookies.copy() # request.cookies is an immutable dict
request.cookies['remember_token'] = token['session_cookie']
login_manager._load_user()
return f(*args, **kwargs)
return wrapper
@app.route("/signup/", methods=["GET", "POST"])
def signup():
if request.method == "POST":
username = request.form['username']
password = request.form['password']
confirm_password = request.form['confirm_password']
first_name = request.form['first_name']
last_name = request.form['last_name']
if not (username and password and confirm_password and first_name and last_name):
flash("All fields are required.")
return redirect(url_for('signup'))
if not re.match(r"[^@]+@[^@]+\.[^@]+", username):
flash("Username is not a valid e-mail address.")
return redirect(url_for('signup'))
if password != confirm_password:
flash("Passwords did not match.")
return redirect(url_for('signup'))
hashed_pwd = generate_password_hash(password, 'scrypt')
new_user = User(username=username, pass_hash=hashed_pwd, first_name=first_name, last_name=last_name)
db.session.add(new_user)
try:
db.session.commit()
except sqlalchemy.exc.IntegrityError:
flash("Username {u} is not available.".format(u=username))
return redirect(url_for('signup'))
flash("User account has been created.")
return redirect(url_for("login"))
return render_template("signup.html")
def check_sha256_hash(pwhash, password):
import hmac
try:
method, salt, hashval = pwhash.split("$", 2)
except ValueError:
return False
return hmac.compare_digest(hmac.new(salt.encode("utf-8"), password.encode("utf-8"), method).hexdigest(), hashval)
def make_profile_dir(player_id):
return make_dir(os.path.join(STORAGE_DIR, str(player_id)))
@app.route("/login/", methods=["GET", "POST"])
def login():
if request.method == "POST":
username = request.form['username']
password = request.form['password']
remember = bool(request.form.get('remember'))
if not (username and password):
flash("Username and password cannot be empty.")
return redirect(url_for('login'))
user = User.query.filter_by(username=username).first()
if user and user.pass_hash.startswith('sha256'): # sha256 is deprecated in werkzeug 3
if check_sha256_hash(user.pass_hash, password):
user.pass_hash = generate_password_hash(password, 'scrypt')
db.session.commit()
else:
flash("Invalid username or password.")
return redirect(url_for('login'))
if user and check_password_hash(user.pass_hash, password):
login_user(user, remember=True)
user.remember = remember
db.session.commit()
if not make_profile_dir(user.player_id):
return '', 500
return redirect(url_for("user_home", username=username, enable_ghosts=bool(user.enable_ghosts), online=get_online()))
else:
flash("Invalid username or password.")
if current_user.is_authenticated and current_user.remember:
return redirect(url_for("user_home", username=current_user.username, enable_ghosts=bool(current_user.enable_ghosts), online=get_online()))
user = User.verify_token(request.args.get('token'))
if user:
login_user(user, remember=False)
return redirect(url_for("reset", username=user.username))
return render_template("login_form.html")
def send_mail(username, token):
try:
with open('%s/gmail_credentials.txt' % STORAGE_DIR) as f:
sender_email = f.readline().rstrip('\r\n')
password = f.readline().rstrip('\r\n')
with smtplib.SMTP_SSL("smtp.gmail.com", 465, context=ssl.create_default_context()) as server:
server.login(sender_email, password)
message = MIMEMultipart()
message['From'] = sender_email
message['To'] = username
message['Subject'] = "Password reset"
content = "https://%s/login/?token=%s" % (server_ip, token)
message.attach(MIMEText(content, 'plain'))
server.sendmail(sender_email, username, message.as_string())
server.close()
except Exception as exc:
logger.warning('send e-mail: %s' % repr(exc))
return False
return True
@app.route("/forgot/", methods=["GET", "POST"])
def forgot():
if request.method == "POST":
username = request.form['username']
if not username:
flash("Username cannot be empty.")
return redirect(url_for('forgot'))
if not re.match(r"[^@]+@[^@]+\.[^@]+", username):
flash("Username is not a valid e-mail address.")
return redirect(url_for('forgot'))
user = User.query.filter_by(username=username).first()
if user:
if send_mail(username, user.get_token()):
flash("E-mail sent.")
else:
flash("Could not send e-mail.")
else:
flash("Invalid username.")
return render_template("forgot.html")
@app.route("/api/push/fcm/<type>/<token>", methods=["POST", "DELETE"])
@app.route("/api/push/fcm/<type>/<token>/enables", methods=["PUT"])
def api_push_fcm_production(type, token):
return '', 500
@app.route("/api/users", methods=["POST"]) # Android user registration
def api_users():
first_name = request.json['profile']['firstName']
last_name = request.json['profile']['lastName']
if MULTIPLAYER:
username = request.json['email']
if not re.match(r"[^@]+@[^@]+\.[^@]+", username):
return '', 400
pass_hash = generate_password_hash(request.json['password'], 'scrypt')
user = User(username=username, pass_hash=pass_hash, first_name=first_name, last_name=last_name)
db.session.add(user)
try:
db.session.commit()
except sqlalchemy.exc.IntegrityError:
return '', 400
login_user(user, remember=True)
if not make_profile_dir(user.player_id):
return '', 500
else:
AnonUser.first_name = first_name
AnonUser.last_name = last_name
return '', 200
@app.route("/api/users/reset-password-email", methods=["PUT"]) # Android password reset
def api_users_reset_password_email():
username = request.form['username']
if re.match(r"[^@]+@[^@]+\.[^@]+", username):
user = User.query.filter_by(username=username).first()
if user:
send_mail(username, user.get_token())
return '', 200
@app.route("/api/users/password-reset/", methods=["POST"])
@jwt_to_session_cookie
@login_required
def api_users_password_reset():
password = request.form.get("password-new")
confirm_password = request.form.get("password-confirm")
if password != confirm_password:
return 'passwords not match', 500
hashed_pwd = generate_password_hash(password, 'scrypt')
current_user.pass_hash = hashed_pwd
db.session.commit()
return '', 200
@app.route("/reset/<username>/", methods=["GET", "POST"])
@login_required
def reset(username):
if request.method == "POST":
password = request.form['password']
confirm_password = request.form['confirm_password']
if not (password and confirm_password):
flash("All fields are required.")
return redirect(url_for('reset', username=current_user.username))
if password != confirm_password:
flash("Passwords did not match.")
return redirect(url_for('reset', username=current_user.username))
hashed_pwd = generate_password_hash(password, 'scrypt')
current_user.pass_hash = hashed_pwd
db.session.commit()
flash("Password changed.")
return redirect(url_for('settings', username=current_user.username))
return render_template("reset.html", username=current_user.username)
@app.route("/strava/<username>/", methods=["GET", "POST"])
@login_required
def strava(username):
profile_dir = '%s/%s' % (STORAGE_DIR, current_user.player_id)
api = '%s/strava_api.bin' % profile_dir
token = os.path.isfile('%s/strava_token.txt' % profile_dir)
if request.method == "POST":
if request.form['client_id'] == "" or request.form['client_secret'] == "":
flash("Client ID and secret can't be empty.")
return render_template("strava.html", username=current_user.username, token=token)
encrypt_credentials(api, (request.form['client_id'], request.form['client_secret']))
cred = decrypt_credentials(api)
return render_template("strava.html", username=current_user.username, cid=cred[0], cs=cred[1], token=token)
@app.route("/strava_auth", methods=['GET'])
@login_required
def strava_auth():
cred = decrypt_credentials('%s/%s/strava_api.bin' % (STORAGE_DIR, current_user.player_id))
client = Client()
url = client.authorization_url(client_id=cred[0],
redirect_uri='https://launcher.zwift.com/authorization',
scope=['activity:write'])
return redirect(url)
@app.route("/authorization", methods=["GET", "POST"])
@login_required
def authorization():
try:
cred = decrypt_credentials('%s/%s/strava_api.bin' % (STORAGE_DIR, current_user.player_id))
client = Client()
code = request.args.get('code')
token_response = client.exchange_code_for_token(client_id=int(cred[0]), client_secret=cred[1], code=code)
with open(os.path.join(STORAGE_DIR, str(current_user.player_id), 'strava_token.txt'), 'w') as f:
f.write(cred[0] + '\n')
f.write(cred[1] + '\n')
f.write(token_response['access_token'] + '\n')
f.write(token_response['refresh_token'] + '\n')
f.write(str(token_response['expires_at']) + '\n')
flash("Strava authorized.")
except Exception as exc:
logger.warning('Strava: %s' % repr(exc))
flash("Strava authorization canceled.")
return redirect(url_for('strava', username=current_user.username))
def encrypt_credentials(file, cred):
try:
cipher_suite = AES.new(credentials_key, AES.MODE_CFB)
with open(file, 'wb') as f:
f.write(cipher_suite.iv)
f.write(cipher_suite.encrypt((cred[0] + '\n' + cred[1]).encode('UTF-8')))
flash("Credentials saved.")
except Exception as exc:
logger.warning('encrypt_credentials: %s' % repr(exc))
flash("Error saving %s" % file)
def decrypt_credentials(file):
cred = ('', '')
if os.path.isfile(file):
try:
with open(file, 'rb') as f:
cipher_suite = AES.new(credentials_key, AES.MODE_CFB, iv=f.read(16))
lines = cipher_suite.decrypt(f.read()).decode('UTF-8').splitlines()
cred = (lines[0], lines[1])
except Exception as exc:
logger.warning('decrypt_credentials: %s' % repr(exc))
return cred
def backup_file(file):
if os.path.isfile(file):
copyfile(file, "%s-%s.bak" % (file, datetime.datetime.now(datetime.timezone.utc).strftime("%Y-%m-%d-%H-%M-%S")))
@app.route("/profile/<username>/", methods=["GET", "POST"])
@login_required
def profile(username):
profile_dir = os.path.join(STORAGE_DIR, str(current_user.player_id))
file = os.path.join(profile_dir, 'zwift_credentials.bin')
cred = decrypt_credentials(file)
if request.method == "POST":
if request.form['username'] == "" or request.form['password'] == "":
flash("Zwift credentials can't be empty.")
return render_template("profile.html", username=current_user.username)
if not request.form.get("zwift_profile") and not request.form.get("achievements") and not request.form.get("save_zwift"):
flash("Select at least one option.")
return render_template("profile.html", username=current_user.username, uname=cred[0], passw=cred[1])
username = request.form['username']
password = request.form['password']
session = requests.session()
try:
access_token, refresh_token = online_sync.login(session, username, password)
try:
if request.form.get("zwift_profile"):
profile = online_sync.query(session, access_token, "api/profiles/me")
profile_file = '%s/profile.bin' % profile_dir
backup_file(profile_file)
with open(profile_file, 'wb') as f:
f.write(profile)
login_request = login_pb2.LoginRequest()
login_request.key = random.randbytes(16)
login_response = login_pb2.LoginResponse()
login_response.ParseFromString(online_sync.api_login(session, access_token, login_request))
login_response_dict = MessageToDict(login_response, preserving_proto_field_name=True)
if 'economy_config' in login_response_dict:
economy_config_file = '%s/economy_config.txt' % profile_dir
backup_file(economy_config_file)
with open(economy_config_file, 'w') as f:
json.dump(login_response_dict['economy_config'], f, indent=2)
if request.form.get("achievements"):
achievements = online_sync.query(session, access_token, "achievement/loadPlayerAchievements")
achievements_file = '%s/achievements.bin' % profile_dir
backup_file(achievements_file)
with open(achievements_file, 'wb') as f:
f.write(achievements)
online_sync.logout(session, refresh_token)
if request.form.get("save_zwift"):
encrypt_credentials(file, (username, password))
except Exception as exc:
logger.warning('Zwift profile: %s' % repr(exc))
flash("Error downloading profile.")
return render_template("profile.html", username=current_user.username, uname=cred[0], passw=cred[1])
except Exception as exc:
logger.warning('online_sync.login: %s' % repr(exc))
flash("Invalid username or password.")
return render_template("profile.html", username=current_user.username)
return redirect(url_for('settings', username=current_user.username))
return render_template("profile.html", username=current_user.username, uname=cred[0], passw=cred[1])
@app.route("/garmin/<username>/", methods=["GET", "POST"])
@login_required
def garmin(username):
file = '%s/%s/garmin_credentials.bin' % (STORAGE_DIR, current_user.player_id)
token = os.path.isfile('%s/%s/garth/oauth1_token.json' % (STORAGE_DIR, current_user.player_id))
if request.method == "POST":
if request.form['username'] == "" or request.form['password'] == "":
flash("Garmin credentials can't be empty.")
return render_template("garmin.html", username=current_user.username, token=token)
encrypt_credentials(file, (request.form['username'], request.form['password']))
cred = decrypt_credentials(file)
return render_template("garmin.html", username=current_user.username, uname=cred[0], passw=cred[1], token=token)
@app.route("/garmin_auth", methods=['GET'])
@login_required
def garmin_auth():
try:
import garth
garth.configure(domain=GARMIN_DOMAIN)
username, password = decrypt_credentials('%s/%s/garmin_credentials.bin' % (STORAGE_DIR, current_user.player_id))
garth.login(username, password)
garth.save('%s/%s/garth' % (STORAGE_DIR, current_user.player_id))
flash("Garmin authorized.")
except Exception as exc:
logger.warning('garmin_auth: %s' % repr(exc))
flash("Garmin authorization failed.")
return redirect(url_for('garmin', username=current_user.username))
@app.route("/intervals/<username>/", methods=["GET", "POST"])
@login_required
def intervals(username):
file = '%s/%s/intervals_credentials.bin' % (STORAGE_DIR, current_user.player_id)
if request.method == "POST":
if request.form['athlete_id'] == "" or request.form['api_key'] == "":
flash("Intervals.icu credentials can't be empty.")
return render_template("intervals.html", username=current_user.username)
encrypt_credentials(file, (request.form['athlete_id'], request.form['api_key']))
return redirect(url_for('settings', username=current_user.username))
cred = decrypt_credentials(file)
return render_template("intervals.html", username=current_user.username, aid=cred[0], akey=cred[1])
@app.route("/user/<username>/")
@login_required
def user_home(username):
return render_template("user_home.html", username=current_user.username, enable_ghosts=bool(current_user.enable_ghosts), climbs=CLIMBS,
online=get_online(), is_admin=current_user.is_admin, restarting=restarting, restarting_in_minutes=restarting_in_minutes)
def enqueue_player_update(player_id, wa_bytes):
if not player_id in player_update_queue:
player_update_queue[player_id] = list()
player_update_queue[player_id].append(wa_bytes)
def send_message(message, sender='Server', recipients=None):
player_update = udp_node_msgs_pb2.WorldAttribute()
player_update.server_realm = udp_node_msgs_pb2.ZofflineConstants.RealmID
player_update.wa_type = udp_node_msgs_pb2.WA_TYPE.WAT_SPA
player_update.world_time_born = world_time()
player_update.world_time_expire = world_time() + 60000
player_update.wa_f12 = 1
player_update.timestamp = int(time.time()*1000000)
chat_message = tcp_node_msgs_pb2.SocialPlayerAction()
chat_message.player_id = 0
chat_message.to_player_id = 0
chat_message.spa_type = tcp_node_msgs_pb2.SocialPlayerActionType.SOCIAL_TEXT_MESSAGE
chat_message.firstName = sender
chat_message.lastName = ''
chat_message.message = message
chat_message.countryCode = 0
player_update.payload = chat_message.SerializeToString()
player_update_s = player_update.SerializeToString()
if not recipients:
recipients = online.keys()
for receiving_player_id in recipients:
enqueue_player_update(receiving_player_id, player_update_s)
def send_restarting_message():
global restarting
global restarting_in_minutes
while restarting:
send_message('Restarting / Shutting down in %s minutes. Save your progress or continue riding until server is back online' % restarting_in_minutes)
time.sleep(60)
restarting_in_minutes -= 1
if restarting and restarting_in_minutes == 0:
message = 'See you later! Look for the back online message.'
send_message(message)
discord.send_message(message)
time.sleep(6)
os.kill(os.getpid(), signal.SIGINT)
@app.route("/restart")
@login_required
def restart_server():
global restarting
global restarting_in_minutes
if bool(current_user.is_admin):
restarting = True
restarting_in_minutes = 10