forked from zoffline/zwift-offline
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathzwift_offline.py
2088 lines (1806 loc) · 82.8 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 platform
import random
import sys
import tempfile
import time
import math
import threading
import re
import smtplib, ssl
import requests
from copy import copy
from functools import wraps
from io import BytesIO
from shutil import copyfile
from logging.handlers import RotatingFileHandler
import jwt
from flask import Flask, request, jsonify, redirect, render_template, url_for, flash, session, abort, 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.descriptor import FieldDescriptor
from protobuf_to_dict import protobuf_to_dict, TYPE_CALLABLE_MAP
from flask_sqlalchemy import sqlalchemy, SQLAlchemy
from werkzeug.security import generate_password_hash, check_password_hash
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import protobuf.udp_node_msgs_pb2 as udp_node_msgs_pb2
import protobuf.activity_pb2 as activity_pb2
import protobuf.goal_pb2 as goal_pb2
import protobuf.login_response_pb2 as login_response_pb2
import protobuf.per_session_info_pb2 as per_session_info_pb2
import protobuf.periodic_info_pb2 as periodic_info_pb2
import protobuf.profile_pb2 as profile_pb2
import protobuf.segment_result_pb2 as segment_result_pb2
import protobuf.world_pb2 as world_pb2
import protobuf.zfiles_pb2 as zfiles_pb2
import protobuf.hash_seeds_pb2 as hash_seeds_pb2
import protobuf.events_pb2 as events_pb2
import protobuf.variants_pb2 as variants_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 os.name == 'nt' and platform.release() == '10' and platform.version() >= '10.0.14393':
# Fix ANSI color in Windows 10 version 10.0.14393 (Windows Anniversary Update)
import ctypes
kernel32 = ctypes.windll.kernel32
kernel32.SetConsoleMode(kernel32.GetStdHandle(-11), 7)
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
try:
# Ensure storage dir exists
if not os.path.isdir(STORAGE_DIR):
os.makedirs(STORAGE_DIR)
except IOError as e:
logger.error("failed to create storage dir (%s): %s", STORAGE_DIR, str(e))
sys.exit(1)
SSL_DIR = "%s/ssl" % SCRIPT_DIR
DATABASE_INIT_SQL = "%s/initialize_db.sql" % SCRIPT_DIR
DATABASE_PATH = "%s/zwift-offline.db" % STORAGE_DIR
DATABASE_CUR_VER = 2
PACE_PARTNERS_DIR = "%s/pace_partners" % SCRIPT_DIR
BOTS_DIR = "%s/bots" % SCRIPT_DIR
# 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:
server_ip = '127.0.0.1'
SECRET_KEY_FILE = "%s/secret-key.txt" % STORAGE_DIR
ENABLEGHOSTS_FILE = "%s/enable_ghosts.txt" % STORAGE_DIR
MULTIPLAYER = False
credentials_key = None
if os.path.exists("%s/multiplayer.txt" % STORAGE_DIR):
MULTIPLAYER = True
try:
if not os.path.isdir(LOGS_DIR):
os.makedirs(LOGS_DIR)
except IOError as e:
logger.error("failed to create logs dir (%s): %s", LOGS_DIR, str(e))
sys.exit(1)
from logging.handlers import RotatingFileHandler
logHandler = RotatingFileHandler('%s/zoffline.log' % LOGS_DIR, maxBytes=1000000, backupCount=10)
logger.addHandler(logHandler)
try:
from cryptography.fernet import Fernet
encrypt = True
except ImportError:
logger.warn("cryptography is not installed. Uploaded garmin_credentials.txt will not be encrypted.")
encrypt = False
if encrypt:
OLD_KEY_FILE = "%s/garmin-key.txt" % STORAGE_DIR
CREDENTIALS_KEY_FILE = "%s/credentials-key.txt" % STORAGE_DIR
if os.path.exists(OLD_KEY_FILE): # check if we need to migrate from the old filename to new
os.rename(OLD_KEY_FILE, CREDENTIALS_KEY_FILE)
if not os.path.exists(CREDENTIALS_KEY_FILE):
with open(CREDENTIALS_KEY_FILE, 'wb') as f:
f.write(Fernet.generate_key())
with open(CREDENTIALS_KEY_FILE, 'rb') as f:
credentials_key = f.read()
try:
with open('%s/strava-client.txt' % STORAGE_DIR, 'r') as f:
client_id = f.readline().rstrip('\r\n')
client_secret = f.readline().rstrip('\r\n')
except:
client_id = '28117'
client_secret = '41b7b7b76d8cfc5dc12ad5f020adfea17da35468'
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'] = 1024 * 1024
db = SQLAlchemy(app)
online = {}
global_pace_partners = {}
global_bots = {}
global_ghosts = {}
ghosts_enabled = {}
player_update_queue = {}
player_partial_profiles = {}
save_ghost = None
restarting = False
restarting_in_minutes = 0
reload_pacer_bots = False
class User(UserMixin, db.Model):
player_id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(100), unique=True, nullable=False)
first_name = db.Column(db.String(100), nullable=False)
last_name = db.Column(db.String(100), nullable=False)
pass_hash = db.Column(db.String(100), 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.utcnow() + 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 User.query.get(id)
return None
class AnonUser(User, AnonymousUserMixin, db.Model):
username = "zoffline"
first_name = "z"
last_name = "offline"
enable_ghosts = True
def is_authenticated(self):
return True
class PartialProfile:
first_name = ''
last_name = ''
country_code = 0
class Online:
total = 0
richmond = 0
watopia = 0
london = 0
makuriislands = 0
newyork = 0
innsbruck = 0
yorkshire = 0
france = 0
paris = 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'
}
def jwt_encode(payload, key, **kwargs):
# For pyjwt >= 2.0.0 compatibility (Issue #108)
if jwt.__version__[0] == '1':
return jwt.encode(payload, key, **kwargs).decode('utf-8')
else:
return jwt.encode(payload, key, **kwargs)
def get_utc_date_time():
return datetime.datetime.utcnow()
def get_utc_seconds_from_date_time(dt):
return (time.mktime(dt.timetuple()) * 1000.0 + dt.microsecond / 1000.0) / 1000
def get_utc_time():
dt = get_utc_date_time()
return get_utc_seconds_from_date_time(dt)
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
online_in_region.total += 1
return online_in_region
def get_partial_profile(player_id):
if not player_id in player_partial_profiles:
#Read from disk
if player_id > 2000000 and player_id < 3000000:
profile_file = '%s/%s/profile.bin' % (PACE_PARTNERS_DIR, player_id)
elif player_id > 3000000 and player_id < 4000000:
profile_file = '%s/%s/profile.bin' % (BOTS_DIR, player_id)
else:
profile_file = '%s/%s/profile.bin' % (STORAGE_DIR, player_id)
if os.path.isfile(profile_file):
try:
with open(profile_file, 'rb') as fd:
profile = profile_pb2.Profile()
profile.ParseFromString(fd.read())
partial_profile = PartialProfile()
partial_profile.first_name = profile.first_name
partial_profile.last_name = profile.last_name
partial_profile.country_code = profile.country_code
player_partial_profiles[player_id] = partial_profile
except:
return None
else: return None
return player_partial_profiles[player_id]
def get_course(state):
return (state.f19 & 0xff0000) >> 16
def is_nearby(player_state1, player_state2, range = 100000):
try:
if player_state1.watchingRiderId == player_state2.id or player_state2.watchingRiderId == player_state1.id:
return True
course1 = get_course(player_state1)
course2 = get_course(player_state2)
if course1 == course2:
x1 = int(player_state1.x)
x2 = int(player_state2.x)
if x1 - range <= x2 and x1 + range >= x2:
y1 = int(player_state1.y)
y2 = int(player_state2.y)
if y1 - range <= y2 and y1 + range >= y2:
a1 = int(player_state1.altitude)
a2 = int(player_state2.altitude)
if a1 - range <= a2 and a1 + range >= a2:
return True
except:
pass
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, 'sha256')
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")
@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 check_password_hash(user.pass_hash, password):
login_user(user, remember=True)
user.remember = remember
db.session.commit()
profile_dir = os.path.join(STORAGE_DIR, str(user.player_id))
try:
if not os.path.isdir(profile_dir):
os.makedirs(profile_dir)
except IOError as e:
logger.error("failed to create profile dir (%s): %s", profile_dir, str(e))
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")
@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:
try:
with open('%s/gmail_credentials.txt' % STORAGE_DIR, 'r') 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, user.get_token())
message.attach(MIMEText(content, 'plain'))
server.sendmail(sender_email, username, message.as_string())
server.close()
flash("E-mail sent.")
except:
flash("Could not send e-mail.")
else:
flash("Invalid username.")
return render_template("forgot.html")
@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, 'sha256')
current_user.pass_hash = hashed_pwd
db.session.commit()
flash("Password changed.")
return render_template("reset.html", username=current_user.username)
@app.route("/strava", methods=['GET'])
@login_required
def strava():
try:
from stravalib.client import Client
except ImportError:
flash("stravalib is not installed. Skipping Strava authorization attempt.")
return redirect('/user/%s/' % current_user.username)
client = Client()
url = client.authorization_url(client_id=client_id,
redirect_uri='https://launcher.zwift.com/authorization',
scope='activity:write')
return redirect(url)
@app.route("/authorization", methods=["GET", "POST"])
@login_required
def authorization():
from stravalib.client import Client
try:
client = Client()
code = request.args.get('code')
token_response = client.exchange_code_for_token(client_id=client_id, client_secret=client_secret, code=code)
with open(os.path.join(STORAGE_DIR, str(current_user.player_id), 'strava_token.txt'), 'w') as f:
f.write(client_id + '\n');
f.write(client_secret + '\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. Go to \"Upload\" to remove authorization.")
except:
flash("Strava canceled.")
flash("Please close this window and return to Zwift Launcher.")
return render_template("strava.html", username=current_user.username)
@app.route("/profile/<username>/", methods=["GET", "POST"])
@login_required
def profile(username):
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)
username = request.form['username']
password = request.form['password']
profile_dir = os.path.join(STORAGE_DIR, str(current_user.player_id))
session = requests.session()
try:
access_token, refresh_token = online_sync.login(session, username, password)
try:
profile = online_sync.query_player_profile(session, access_token)
with open('%s/profile.bin' % SCRIPT_DIR, 'wb') as f:
f.write(profile)
online_sync.logout(session, refresh_token)
os.rename('%s/profile.bin' % SCRIPT_DIR, '%s/profile.bin' % profile_dir)
flash("Zwift profile installed locally.")
except:
flash("Error downloading profile.")
if request.form.get("safe_zwift", None) != None:
try:
file_path = os.path.join(profile_dir, 'zwift_credentials.txt')
with open(file_path, 'w') as f:
f.write(username + '\n');
f.write(password + '\n');
if credentials_key is not None:
with open(file_path, 'rb') as fr:
zwift_credentials = fr.read()
cipher_suite = Fernet(credentials_key)
ciphered_text = cipher_suite.encrypt(zwift_credentials)
with open(file_path, 'wb') as fw:
fw.write(ciphered_text)
flash("Zwift credentials saved.")
except:
flash("Error saving 'zwift_credentiasl.txt' file.")
except:
flash("Invalid username or password.")
return render_template("profile.html", username=current_user.username)
@app.route("/garmin/<username>/", methods=["GET", "POST"])
@login_required
def garmin(username):
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)
username = request.form['username']
password = request.form['password']
try:
file_path = os.path.join(STORAGE_DIR, str(current_user.player_id), 'garmin_credentials.txt')
with open(file_path, 'w') as f:
f.write(username + '\n');
f.write(password + '\n');
if credentials_key is not None:
with open(file_path, 'rb') as fr:
garmin_credentials = fr.read()
cipher_suite = Fernet(credentials_key)
ciphered_text = cipher_suite.encrypt(garmin_credentials)
with open(file_path, 'wb') as fw:
fw.write(ciphered_text)
flash("Garmin credentials saved.")
except:
flash("Error saving 'garmin_credentials.txt' file.")
return render_template("garmin.html", username=current_user.username)
@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),
online=get_online(), is_admin=current_user.is_admin, restarting=restarting, restarting_in_minutes=restarting_in_minutes, server_ip=os.path.exists(SERVER_IP_FILE))
def send_message_to_all_online(message, sender='Server'):
player_update = udp_node_msgs_pb2.PlayerUpdate()
player_update.f2 = 1
player_update.type = 5 #chat message type
player_update.world_time1 = world_time()
player_update.world_time2 = world_time() + 60000
player_update.f12 = 1
player_update.f14 = int(str(int(get_utc_time()*1000000)))
chat_message = udp_node_msgs_pb2.ChatMessage()
chat_message.rider_id = 0
chat_message.to_rider_id = 0
chat_message.f3 = 1
chat_message.firstName = sender
chat_message.lastName = ''
chat_message.message = message
chat_message.countryCode = 0
player_update.payload = chat_message.SerializeToString()
for recieving_player_id in online.keys():
if not recieving_player_id in player_update_queue:
player_update_queue[recieving_player_id] = list()
player_update_queue[recieving_player_id].append(player_update.SerializeToString())
def send_restarting_message():
global restarting
global restarting_in_minutes
while restarting:
send_message_to_all_online('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_to_all_online(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
send_restarting_message_thread = threading.Thread(target=send_restarting_message)
send_restarting_message_thread.start()
discord.send_message('Restarting / Shutting down in %s minutes. Save your progress or continue riding until server is back online' % restarting_in_minutes)
return redirect('/user/%s/' % current_user.username)
@app.route("/cancelrestart")
@login_required
def cancel_restart_server():
global restarting
global restarting_in_minutes
if bool(current_user.is_admin):
restarting = False
restarting_in_minutes = 0
message = 'Restart of the server has been cancelled. Ride on!'
send_message_to_all_online(message)
discord.send_message(message)
return redirect('/user/%s/' % current_user.username)
@app.route("/reloadbots")
@login_required
def reload_bots():
global reload_pacer_bots
if bool(current_user.is_admin):
reload_pacer_bots = True
return redirect('/user/%s/' % current_user.username)
@app.route("/upload/<username>/", methods=["GET", "POST"])
@login_required
def upload(username):
profile_dir = os.path.join(STORAGE_DIR, str(current_user.player_id))
if request.method == 'POST':
uploaded_file = request.files['file']
if uploaded_file.filename in ['profile.bin', 'strava_token.txt', 'garmin_credentials.txt', 'zwift_credentials.txt']:
file_path = os.path.join(profile_dir, uploaded_file.filename)
uploaded_file.save(file_path)
if uploaded_file.filename == 'garmin_credentials.txt' and credentials_key is not None:
with open(file_path, 'rb') as fr:
garmin_credentials = fr.read()
cipher_suite = Fernet(credentials_key)
ciphered_text = cipher_suite.encrypt(garmin_credentials)
with open(file_path, 'wb') as fw:
fw.write(ciphered_text)
if uploaded_file.filename == 'zwift_credentials.txt' and credentials_key is not None:
with open(file_path, 'rb') as fr:
garmin_credentials = fr.read()
cipher_suite = Fernet(credentials_key)
ciphered_text = cipher_suite.encrypt(garmin_credentials)
with open(file_path, 'wb') as fw:
fw.write(ciphered_text)
flash("File %s uploaded." % uploaded_file.filename)
else:
flash("Invalid file name.")
name = ''
profile = None
profile_file = os.path.join(profile_dir, 'profile.bin')
if os.path.isfile(profile_file):
stat = os.stat(profile_file)
profile = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(stat.st_mtime))
with open(profile_file, 'rb') as fd:
p = profile_pb2.Profile()
p.ParseFromString(fd.read())
name = "%s %s" % (p.first_name, p.last_name)
token = None
token_file = os.path.join(profile_dir, 'strava_token.txt')
if os.path.isfile(token_file):
stat = os.stat(token_file)
token = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(stat.st_mtime))
garmin = None
garmin_file = os.path.join(profile_dir, 'garmin_credentials.txt')
if os.path.isfile(garmin_file):
stat = os.stat(garmin_file)
garmin = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(stat.st_mtime))
zwift = None
zwift_file = os.path.join(profile_dir, 'zwift_credentials.txt')
if os.path.isfile(zwift_file):
stat = os.stat(zwift_file)
zwift = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(stat.st_mtime))
return render_template("upload.html", username=current_user.username, profile=profile, name=name, token=token, garmin=garmin, zwift=zwift)
@app.route("/download/profile.bin", methods=["GET"])
@login_required
def download():
player_id = current_user.player_id
profile_dir = os.path.join(STORAGE_DIR, str(player_id))
profile_file = os.path.join(profile_dir, 'profile.bin')
if os.path.isfile(profile_file):
return send_file(profile_file, attachment_filename='profile.bin')
@app.route("/delete/<filename>", methods=["GET"])
@login_required
def delete(filename):
player_id = current_user.player_id
if filename not in ['profile.bin', 'strava_token.txt', 'garmin_credentials.txt', 'zwift_credentials.txt']:
return '', 403
profile_dir = os.path.join(STORAGE_DIR, str(player_id))
delete_file = os.path.join(profile_dir, filename)
if os.path.isfile(delete_file):
os.remove("%s" % delete_file)
return redirect(url_for('upload', username=current_user))
@app.route("/logout/<username>")
@login_required
def logout(username):
logout_user()
flash("Successfully logged out.")
return redirect(url_for('login'))
####
# Set up protobuf_to_dict call map
type_callable_map = copy(TYPE_CALLABLE_MAP)
# Override base64 encoding of byte fields
type_callable_map[FieldDescriptor.TYPE_BYTES] = str
# sqlite doesn't support uint64 so make them strings
type_callable_map[FieldDescriptor.TYPE_UINT64] = str
def insert_protobuf_into_db(table_name, msg):
msg_dict = protobuf_to_dict(msg, type_callable_map=type_callable_map)
columns = ', '.join(list(msg_dict.keys()))
placeholders = ':'+', :'.join(list(msg_dict.keys()))
query = 'INSERT INTO %s (%s) VALUES (%s)' % (table_name, columns, placeholders)
db.session.execute(query, msg_dict)
db.session.commit()
# XXX: can't be used to 'nullify' a column value
def update_protobuf_in_db(table_name, msg, id):
try:
# If protobuf has an id field and it's uint64, make it a string
id_field = msg.DESCRIPTOR.fields_by_name['id']
if id_field.type == id_field.TYPE_UINT64:
id = str(id)
except AttributeError:
pass
msg_dict = protobuf_to_dict(msg, type_callable_map=type_callable_map)
columns = ', '.join(list(msg_dict.keys()))
placeholders = ':'+', :'.join(list(msg_dict.keys()))
setters = ', '.join('{}=:{}'.format(key, key) for key in msg_dict)
query = 'UPDATE %s SET %s WHERE id=%s' % (table_name, setters, id)
db.session.execute(query, msg_dict)
db.session.commit()
def row_to_protobuf(row, msg, exclude_fields=[]):
for key in list(msg.DESCRIPTOR.fields_by_name.keys()):
if key in exclude_fields:
continue
if row[key] is None:
continue
field = msg.DESCRIPTOR.fields_by_name[key]
if field.type == field.TYPE_UINT64:
setattr(msg, key, int(row[key]))
else:
setattr(msg, key, row[key])
return msg
# FIXME: I should really do this properly...
def get_id(table_name):
while True:
# I think activity id is actually only uint32. On the off chance it's
# int32, stick with 31 bits.
ident = int(random.getrandbits(31))
row = db.session.execute(sqlalchemy.text("SELECT id FROM %s WHERE id = %s" % (table_name, ident))).first()
if not row:
break
return ident
def world_time():
return int((get_utc_time()-1414016075)*1000)
@app.route('/api/auth', methods=['GET'])
def api_auth():
return '{"realm":"zwift","launcher":"https://launcher.zwift.com/launcher","url":"https://secure.zwift.com/auth/"}'
@app.route('/api/users/login', methods=['POST'])
def api_users_login():
# Should just return a binary blob rather than build a "proper" response...
response = login_response_pb2.LoginResponse()
response.session_state = 'abc'
response.info.relay_url = "https://us-or-rly101.zwift.com/relay"
response.info.apis.todaysplan_url = "https://whats.todaysplan.com.au"
response.info.apis.trainingpeaks_url = "https://api.trainingpeaks.com"
response.info.time = int(get_utc_time())
udp_node = response.info.nodes.node.add()
if request.remote_addr == '127.0.0.1': # to avoid needing hairpinning
udp_node.ip = "127.0.0.1"
else:
udp_node.ip = server_ip # TCP telemetry server
udp_node.port = 3023
return response.SerializeToString(), 200
def logout_player(player_id):
#Remove player from online when leaving game/world
if player_id in online:
online.pop(player_id)
discord.send_message('%s riders online' % len(online))
if player_id in player_partial_profiles:
player_partial_profiles.pop(player_id)
@app.route('/api/users/logout', methods=['POST'])
@jwt_to_session_cookie
@login_required
def api_users_logout():
logout_player(current_user.player_id)
return '', 204
@app.route('/api/analytics/event', methods=['POST'])
def api_analytics_event():
return '', 200
@app.route('/api/per-session-info', methods=['GET'])
def api_per_session_info():
info = per_session_info_pb2.PerSessionInfo()
info.relay_url = "https://us-or-rly101.zwift.com/relay"
return info.SerializeToString(), 200
@app.route('/api/events/search', methods=['POST'])
def api_events_search():
events = events_pb2.Events()
bologna = events.events.add()
bologna.id = 1000
bologna.title = "Bologna TT"
for cat in range(1,5):
bologna_cat = bologna.category.add()
bologna_cat.id = 1000 + cat
bologna_cat.registrationEnd = int(get_utc_time()) * 1000 + 60000
bologna_cat.registrationEndWT = world_time() + 60000
bologna_cat.route_id = 2843604888
bologna_cat.startLocation = cat
bologna_cat.label = cat
critcw = events.events.add()
critcw.id = 2000
critcw.title = "Crit City CW"
for cat in range(1,5):
critcw_cat = critcw.category.add()
critcw_cat.id = 2000 + cat
critcw_cat.registrationEnd = int(get_utc_time()) * 1000 + 60000
critcw_cat.registrationEndWT = world_time() + 60000
critcw_cat.route_id = 947394567
critcw_cat.startLocation = cat
critcw_cat.label = cat
critccw = events.events.add()
critccw.id = 3000
critccw.title = "Crit City CCW"
for cat in range(1,5):
critccw_cat = critccw.category.add()
critccw_cat.id = 3000 + cat
critccw_cat.registrationEnd = int(get_utc_time()) * 1000 + 60000
critccw_cat.registrationEndWT = world_time() + 60000
critccw_cat.route_id = 2875658892
critccw_cat.startLocation = cat
critccw_cat.label = cat
return events.SerializeToString(), 200
@app.route('/api/events/subgroups/signup/<int:event_id>', methods=['POST'])
def api_events_subgroups_signup_id(event_id):
return '{"signedUp":true}', 200
@app.route('/api/events/subgroups/register/<int:event_id>', methods=['POST'])
def api_events_subgroups_register_id(event_id):
return '{"registered":true}', 200
@app.route('/api/events/subgroups/entrants/<int:event_id>', methods=['GET'])
def api_events_subgroups_entrants_id(event_id):
return '', 200
@app.route('/relay/race/event_starting_line/<int:event_id>', methods=['POST'])
def relay_race_event_starting_line_id(event_id):
return '', 204
@app.route('/api/zfiles', methods=['POST'])
def api_zfiles():
# Don't care about zfiles, but shuts up some errors in Zwift log.
zfile = zfiles_pb2.ZFile()
zfile.id = int(random.getrandbits(31))
zfile.folder = "logfiles"
zfile.filename = "yep_took_good_care_of_that_file.txt"
zfile.timestamp = int(get_utc_time())
return zfile.SerializeToString(), 200
# Custom static data
@app.route('/style/<path:filename>')
def custom_style(filename):
return send_from_directory('%s/cdn/style' % SCRIPT_DIR, filename)
# Launcher files are requested over https on macOS
@app.route('/static/web/launcher/<path:filename>')
def static_web_launcher(filename):
return send_from_directory('%s/cdn/static/web/launcher' % SCRIPT_DIR, filename)
# Probably don't need, haven't investigated
@app.route('/api/zfiles/list', methods=['GET', 'POST'])
def api_zfiles_list():
return '', 200
# Probably don't need, haven't investigated
@app.route('/api/private_event/feed', methods=['GET', 'POST'])
def api_private_event_feed():
return '', 200
# Disable telemetry (shuts up some errors in log)
@app.route('/api/telemetry/config', methods=['GET'])
def api_telemetry_config():
return '{"isEnabled":false}'
@app.route('/api/profiles/me', methods=['GET'])
@jwt_to_session_cookie
@login_required
def api_profiles_me():
profile_id = current_user.player_id
if MULTIPLAYER:
profile_dir = '%s/%s' % (STORAGE_DIR, profile_id)
else:
# Find first profile.bin if one exists and use it. Multi-profile
# support is deprecated and now unsupported for non-multiplayer mode.
profile_dir = None