-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathapplication.py
1869 lines (1471 loc) · 60.7 KB
/
application.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
import json
import os
import uuid
import random
import io
import threading
from flask import Flask, render_template, send_from_directory, request, abort, session, redirect, url_for, send_file, jsonify
from flask_caching import Cache
from flask_babel import Babel, _
import firebase_admin
from firebase_admin import credentials, auth, db, exceptions
from firebase_admin.exceptions import FirebaseError
from urllib.parse import urlparse
from datetime import datetime, timedelta
from utils.emailProvider import EmailProvider
import utils.helpers
import utils.js_helpers
import utils.zone_helpers
import utils.MadBoulderDatabase
import utils.channel
import utils.drive
import dashboard
import dashboard_videos
import re
import time
from slugify import slugify
from functools import wraps
from dotenv import load_dotenv
import traceback
import requests
import utils.searchManager
from types import SimpleNamespace
from bokeh.embed import components
from bokeh.resources import INLINE
import mailerlite as MailerLite
from google.oauth2 import service_account
from google.cloud import recaptchaenterprise_v1
from google.cloud.recaptchaenterprise_v1 import Assessment
from utils.ai_helper import GenerativeAI
EXTENSION = '.html'
EMAIL_SUBJECT_FIELDS = ['name', 'zone', 'climber']
REMOVE_FIRST = slice(1, None, 1)
load_dotenv() # Take environment variables from .env.
# create and configure the application object
app = Flask(__name__, static_folder='static')
app.config.from_pyfile('config.py')
if os.environ.get('FLASK_ENV') == 'production':
app.config.update(
SESSION_COOKIE_SECURE=True,
SESSION_COOKIE_HTTPONLY=True,
SESSION_COOKIE_SAMESITE='Lax',
)
app.secret_key = bytes.fromhex(os.environ.get('SECRET_KEY'))
app.jinja_env.filters['format_views'] = utils.helpers.format_views
babel = Babel(app)
cache = Cache(app, config={'CACHE_TYPE': 'simple'})
cred = credentials.Certificate('madboulder.json')
firebase_admin.initialize_app(cred, {
'databaseURL': 'https://madboulder.firebaseio.com'
})
mailerlite = MailerLite.Client({
'api_key': os.environ['MAILERLITE_API_KEY']
})
SERVICE_ACCOUNT_FILE = 'madboulder-f1887f0310ec.env'
credentials = service_account.Credentials.from_service_account_file(SERVICE_ACCOUNT_FILE)
recaptcha_client = recaptchaenterprise_v1.RecaptchaEnterpriseServiceClient(credentials=credentials)
current_progress = 0
mail = EmailProvider(app)
search_manager = utils.searchManager.SearchManager()
# Initialize AI helper
ai = GenerativeAI()
def _get_seconds_to_next_time(hour, minute, second):
"""Get seconds until next occurrence of the specified time"""
now = datetime.now()
next_time = now.replace(hour=hour, minute=minute, second=second)
if next_time <= now:
next_time += timedelta(days=1)
return (next_time - now).total_seconds()
@cache.cached(
timeout=_get_seconds_to_next_time(hour=11, minute=10, second=00),
key_prefix='mad_zones'
)
def get_zone_data():
return utils.MadBoulderDatabase.getAreasData()
def get_playlist_data():
return utils.MadBoulderDatabase.getPlaylistsData()
# Set language
@app.route('/language/<language>')
def set_language(language=None):
print("set_language")
session['language'] = language
referrer_url = request.referrer
print("referrer_url: " + referrer_url)
if referrer_url:
parsed_url = urlparse(referrer_url)
print("parsed_url.path: " + parsed_url.path)
path_without_language = parsed_url.path.replace('/es/', '/').replace('/en/', '/')
return redirect(path_without_language)
else:
return redirect('')
#@babel.localeselector
def get_locale():
# if the user has set up the language manually it will be stored in the session,
# so we use the locale from the user settings
try:
language = session['language']
except KeyError:
language = request.accept_languages.best_match(app.config['LANGUAGES'])
if language is not None:
return language
return 'en'
babel.init_app(app, locale_selector=get_locale)
@app.context_processor
def inject_language():
language = get_locale()
return dict(current_lang=language)
# Load favicon
@app.route('/favicon.ico')
def favicon():
return send_from_directory(os.path.join(app.root_path, 'static/images/logo'),
'favicon.ico', mimetype='image/vnd.microsoft.icon')
# robots
@app.route('/robots.txt')
def static_from_root():
return send_from_directory(app.static_folder, request.path[1:])
@app.route('/ads.txt')
def ads():
return send_file('ads.txt')
# cache keys for zones
def zone_cache_key():
return request.url
@app.route('/home.html')
@app.route('/home')
@app.route('/')
def home():
language_extension = ''
if get_locale() == 'es':
language_extension = 'es/'
home_path = '/' + language_extension + 'home' + EXTENSION
return render_template(home_path)
@app.route('/es/home.html')
@app.route('/es/home')
@app.route('/es')
def home_es():
return render_template('/es/home.html')
@app.route('/bouldering-areas-list', methods=['GET'])
def zones():
return render_template('bouldering-areas-list.html')
@app.route('/area-problem-finder', methods=['GET', 'POST'])
def search():
query = ""
if request.method == 'POST':
query = request.form.get('searchterm', '')
if not query:
query = request.form.get('searchterm-small', '')
return redirect(url_for('search', search_query=query))
elif request.method == 'GET':
query = request.args.get('search_query', '')
print(f"Search request: {query}")
if query:
session_id = session.get('session_id')
if not session_id:
session_id = session['session_id'] = str(uuid.uuid4().hex)
max_score = 0.01
results = search_manager.search(session_id, query, max_score)
return render_template(
'area-problem-finder.html',
areas=results.get('areas', []),
problems=results.get('problems', []),
search_term=query,
)
return render_template(
'area-problem-finder.html', areas=[], videos=[], search_term='')
@app.route('/search-api', methods=['GET'])
def search_api():
query = request.args.get('query', '')
print(f"Search API request: {query}")
if query:
session_id = session.get('session_id')
if not session_id:
session_id = session['session_id'] = str(uuid.uuid4().hex)
max_score = 0.01
results = search_manager.search(session_id, query, max_score)
if results:
return jsonify({
'areas': results.get('areas', []),
'problems': results.get('problems', [])
})
return jsonify({'areas': [], 'problems': []})
@app.route('/video-uploader-not-working', methods=['GET', 'POST'])
def video_uploader_not_working():
return render_template('video-uploader-not-working.html')
@app.route('/upload', methods=['GET', 'POST'])
@app.route('/video-uploader', methods=['GET', 'POST'])
def video_uploader():
user_uid = session.get('uid')
user_data = getUserData(user_uid)
contributors = utils.MadBoulderDatabase.getContributorsList()
climbers = [data["name"] for data in contributors.values()]
playlists = utils.MadBoulderDatabase.getPlaylistsData()
areas = {
playlist["zone_code"]: {
"name": playlist["title"],
"sectors": [
{"name": sector["name"], "sector_code": sector_code}
for sector_code, sector in playlist.get("sectors", {}).items()
],
}
for playlist in playlists.values()
}
return render_template('video-uploader.html', user_data=user_data, climbers=sorted(climbers), areas=areas)
@app.route('/video-uploader-test', methods=['GET', 'POST'])
def video_uploader_test():
return render_template('video-uploader.html')
@app.route('/upload-file', methods=['GET', 'POST'])
def upload_file():
print("upload_file")
uploaded_file = request.files['file']
if uploaded_file:
try:
properties_dict = {
'name': request.form.get('name', ''),
'email': request.form.get('email', ''),
'grade': request.form.get('grade', ''),
'zone': request.form.get('area', ''),
'climber': request.form.get('climber', ''),
'sector': request.form.get('sector', ''),
'notes': request.form.get('notes', '')
}
properties = SimpleNamespace(**properties_dict)
renamed_file = rename_file(uploaded_file.filename, properties.name, properties.grade, properties.zone)
file_id = utils.drive.upload(uploaded_file, renamed_file, vars(properties))
permissionNewsletter = request.form.get('permission-newsletter')
if permissionNewsletter and properties.email:
register_new_subscriber(properties.email)
mail.sendNewVideoBeta(properties, renamed_file, file_id)
return jsonify({"message": "File uploaded, renamed, and notification sent successfully"}), 200
except Exception as e:
print(f"Upload failed: {str(e)}")
return jsonify({"error": "Internal server error occurred"}), 500
else:
return jsonify({"error": "File upload failed. Please check your request."}), 400
def rename_file(original_filename, name, grade, zone):
# name format: "Name, Grade. Zone.mp4"
extension = original_filename.split('.')[-1]
renamed_filename = f"{name}, {grade}. {zone}.{extension}"
print(f"Renamed file to: {renamed_filename}")
return renamed_filename
@app.route('/progress', methods=['GET'])
def get_progress():
return jsonify({'progress': current_progress})
@app.route('/upload-completed', methods=['GET'])
def upload_completed():
return render_template('thanks-for-uploading.html')
@app.route('/upload-hub')
def upload_hub():
try:
file_id = request.args.get('file_id')
if file_id:
session['file_id'] = file_id # Save file_id in session for redirection
else:
file_id = session.get('file_id') # Use stored file_id if available
if not file_id:
return "Error: No file ID provided.", 400
isAuthenticated = utils.channel.is_authenticated()
if not isAuthenticated:
return render_template('upload-hub.html', authenticated=False, file_id=file_id)
metadata = utils.drive.getFileMetadata(file_id)
if not metadata:
return "Error fetching metadata from Google Drive.", 500
filename = metadata.get('name', 'Unknown File')
title = os.path.splitext(filename)[0]
thumbnail = metadata.get('thumbnailLink')
properties = metadata.get('properties', {})
climber = properties.get('climber', 'Unknown Climber')
name = properties.get('name', 'Unknown Problem')
grade = properties.get('grade', '')
zone = properties.get('zone', 'Unknown Zone')
zone_code = slugify(zone)
sector = properties.get('sector', '')
sector_code = slugify(sector)
schedule_info = suggest_upload_time(file_id, name, climber, grade, zone)
# Generate description and tags
description = utils.helpers.generateDescription(name, climber, grade, zone, properties.get('sector'))
tags = utils.helpers.generateTags(name, zone, grade)
context = {
"authenticated": isAuthenticated,
"file_id": file_id,
"title": title,
"description": description,
"tags": ", ".join(tags),
"thumbnail": thumbnail,
"zone_code": zone_code,
"sector_code": sector_code,
"schedule_info": schedule_info
}
return render_template('upload-hub.html', **context)
except Exception as e:
print(f"Error in upload_hub: {e}")
return str(e), 500
@app.route('/test-schedule')
def test_schedule():
"""Test endpoint to check scheduling recommendation without uploading"""
try:
file_id = request.args.get('file_id')
if file_id:
session['file_id'] = file_id # Save file_id in session for redirection
else:
file_id = session.get('file_id') # Use stored file_id if available
if not file_id:
return "Error: No file ID provided.", 400
isAuthenticated = utils.channel.is_authenticated()
if not isAuthenticated:
return render_template('upload-hub.html', authenticated=False, file_id=file_id)
metadata = utils.drive.getFileMetadata(file_id)
if not metadata:
return "Error fetching metadata from Google Drive.", 500
properties = metadata.get('properties', {})
climber = properties.get('climber', 'Unknown Climber')
name = properties.get('name', 'Unknown Problem')
grade = properties.get('grade', '')
zone = properties.get('zone', 'Unknown Zone')
# Get AI recommendation
schedule_info = suggest_upload_time(file_id, name, climber, grade, zone)
if schedule_info and schedule_info.get('success'):
publish_time = datetime.strptime(schedule_info['scheduled_time'], "%Y-%m-%d %H:%M:%S")
return jsonify({
'success': True,
'scheduled_time': schedule_info['scheduled_time'],
'hour': publish_time.hour,
'reasoning': schedule_info.get('reasoning', '')
})
else:
return jsonify({
'success': False,
'message': 'Could not determine scheduling time'
})
except Exception as e:
print(f"Error testing schedule: {e}")
return jsonify({
'success': False,
'error': str(e)
}), 500
@app.route('/authenticate')
def authenticate():
local=request.host.startswith('localhost') or request.host.startswith('127.0.0.1')
return utils.channel.authenticate(local)
@app.route('/oauth2callback')
def oauth2callback():
authorization_response=request.url
utils.channel.oauth2callback(authorization_response)
return redirect(url_for('upload_hub'))
@app.route('/process-upload-youtube-from-drive', methods=['POST'])
def process_upload_youtube_from_drive():
print("process_upload_youtube_from_drive")
try:
if not utils.channel.is_authenticated():
return redirect(url_for('authenticate'))
file_id = session.get('file_id')
if not file_id:
return "Error: No file ID available.", 400
title = request.form['title']
description = request.form['description']
tags = request.form.getlist('tags')
zone_code = request.form['zone_code']
sector_code = request.form['sector_code']
# Get publish time from form
publish_time = None
if request.form.get('scheduled_time'):
try:
# The time from the form is already in UTC
publish_time = datetime.strptime(
request.form['scheduled_time'],
'%Y-%m-%d %H:%M:%S'
)
except ValueError as e:
print(f"Error parsing scheduled time: {e}")
print(f"Raw scheduled_time value: {request.form.get('scheduled_time')}")
print("process_upload_youtube_from_drive 2")
video_stream = utils.drive.getVideoStream(file_id)
print("video stream from Drive ready")
# Upload video with private status initially
response = utils.channel.uploadVideo(
video_stream,
title,
description,
tags,
'private',
publish_time=publish_time # Will be None if AI scheduling failed
)
uploadedVideoId = response['id']
print("video uploaded to Youtube")
print(f"adding video to playlist {zone_code}")
playlists = utils.MadBoulderDatabase.getPlaylistData(zone_code)
zonePlaylistId = playlists.get("id")
sectorPlaylists = playlists.get("sectors", {})
if zonePlaylistId:
utils.channel.addVideoToPlaylist(uploadedVideoId, zonePlaylistId)
if sector_code in sectorPlaylists:
print("adding video to sector playlist")
sectorPlaylistId = sectorPlaylists[sector_code]["id"]
utils.channel.addVideoToPlaylist(uploadedVideoId, sectorPlaylistId)
print("enabling video monetization")
utils.channel.enableMonetization(uploadedVideoId)
# Generate success page with scheduling info if available
return generate_success_page(uploadedVideoId, title, publish_time)
except Exception as e:
return jsonify({'error': str(e)}), 500
def generate_success_page(video_id, title, publish_time=None):
"""Generate success page HTML with video details"""
try:
youtube_url = f"https://studio.youtube.com/video/{video_id}/edit"
success_html = f"""
<h2>Video Upload Successful!</h2>
<p>Your video "{title}" has been uploaded to YouTube.</p>
"""
if publish_time:
# Format datetime to ISO format for JavaScript
utc_time = publish_time.strftime('%Y-%m-%dT%H:%M:%S')
success_html += f"""
<script>
function formatMadridTime(utcString) {{
const utcDate = new Date(utcString + 'Z');
return new Intl.DateTimeFormat('en-GB', {{
timeZone: 'Europe/Madrid',
year: 'numeric',
month: '2-digit',
day: '2-digit',
hour: '2-digit',
minute: '2-digit',
second: '2-digit',
hour12: false
}}).format(utcDate);
}}
document.write(`
<p>The video will be published at: ${{formatMadridTime("{utc_time}")}} (Madrid time)</p>
`);
</script>
<noscript>
<p>The video will be published at: {publish_time} (UTC)</p>
</noscript>
"""
success_html += f"""
<p>Continue the edition in Youtube Studio:</p>
<a href="{youtube_url}">{title}</a>
"""
return success_html
except Exception as e:
print(f"Error generating success page: {e}")
return "<h2>Upload completed, but there was an error generating the success page.</h2>"
@app.route('/login', methods=['GET'])
def login():
caller_url = request.args.get('caller_url', None)
if caller_url:
session['nextUrl'] = caller_url
return render_template('login.html')
@app.route('/signup', methods=['GET'])
def signup():
return render_template('signup.html')
@app.route('/logout', methods=['POST'])
def logout():
session.clear()
return jsonify({"message": "Session cleared on server."}), 200
@app.route('/verify-token', methods=['POST'])
def verify_token():
auth_header = request.headers.get('Authorization')
if not auth_header or not auth_header.startswith('Bearer '):
return jsonify({'error': 'Authorization token is missing or invalid.'}), 401
id_token = auth_header.split(' ')[1]
try:
uid = get_user_uid(id_token)
session['uid'] = uid
session['is_admin'] = check_admin_privileges(uid)
return jsonify({"message": "Token verified", "uid": uid}), 200
except Exception as e:
print(f"Error verifying token: {e}")
return jsonify({"error": str(e)}), 401
@app.route('/register-subscriber', methods=['POST'])
def register_subscriber():
try:
data = request.get_json()
email = data.get('email')
if email:
register_new_subscriber(email)
return jsonify({"message": "New Subscriber registered successfully"}), 200
else:
return jsonify({"error": "No email provided"}), 400
except Exception as e:
print(f"Registration failed: {str(e)}")
return jsonify({"error": "Internal server error occurred"}), 500
def register_new_subscriber(email):
print("register_new_subscriber")
subscriber_exists = False
try:
existing_subscriber = mailerlite.subscribers.get(email)
if existing_subscriber.get('data') or ('message' not in existing_subscriber):
subscriber_exists = True
except Exception as e:
print(f"Error checking for existing subscriber: {str(e)}")
if not subscriber_exists:
mailerlite.subscribers.create(email=email)
def login_required(f):
@wraps(f)
def decorated_function(*args, **kwargs):
print(f"login_required: Checking login for access to {f.__name__}")
if 'uid' not in session:
print("login_required: No user ID in session, redirecting to login")
session['nextUrl'] = request.url
return redirect(url_for('login'))
print(f"login_required: User ID found in session")
return f(*args, **kwargs)
return decorated_function
def admin_required(f):
@wraps(f)
def decorated_function(*args, **kwargs):
@login_required
def inner(*args, **kwargs):
print(f"admin_required: Checking admin privileges")
if not session.get('is_admin', False):
return jsonify({'error': 'Access denied. Admin privileges required.'}), 403
# For web pages maybe use a redirect:
# return redirect(url_for('some_route_name'))
return f(*args, **kwargs)
return inner(*args, **kwargs)
return decorated_function
def check_admin_privileges(uid):
user = auth.get_user(uid)
if user.custom_claims:
return user.custom_claims.get('admin', False)
else:
return False
@app.route('/reset-next-url')
def reset_next_url():
session.pop('nextUrl', None)
return ('', 204)
@app.route('/check-profile-completion', methods=['POST'])
@login_required
def check_profile_completion():
try:
user_uid = session.get('uid')
user_record = auth.get_user(user_uid)
try:
existing_subscriber = mailerlite.subscribers.get(user_record.email)
is_in_database = bool(existing_subscriber and existing_subscriber.get('data'))
except Exception as e:
print(f"Error fetching subscriber information: {str(e)}")
is_in_database = False
user_details_ref = db.reference(f'users/{user_uid}')
user_details = user_details_ref.get()
required_fields = ['contributor_status']
is_complete = user_details and all(field in user_details for field in required_fields) and is_in_database
return jsonify({'isComplete': is_complete}), 200
except Exception as e:
print(f"Error checking profile completion: {str(e)}")
return jsonify({'error': 'Could not check profile completion'}), 500
@app.route('/complete-profile', methods=['GET'])
@login_required
def complete_profile():
return render_template('complete-profile.html')
@app.route('/settings/profile', methods=['GET', 'POST'])
@login_required
def settings_profile():
user_uid = session.get('uid')
user_data = getUserData(user_uid)
return render_template('settings/settings-profile.html', user_data=user_data)
def getUserData(user_uid):
user_data = {}
if user_uid:
user_record = auth.get_user(user_uid)
user_data['uid'] = user_uid
user_data['displayName'] = user_record.display_name
user_data['email'] = user_record.email
user_details_ref = db.reference(f'users/{user_uid}')
user_details = user_details_ref.get()
if(user_details):
user_data.update(user_details)
return user_data
@app.route('/settings/account', methods=['GET', 'POST'])
@login_required
def settings_account():
user_uid = session.get('uid')
user_data = {}
if user_uid:
user_record = auth.get_user(user_uid)
user_data['uid'] = user_uid
user_data['email'] = user_record.email
user_data['displayName'] = user_record.display_name
return render_template('settings/settings-account.html', user_data=user_data)
@app.route('/settings/my-videos', methods=['GET'])
@login_required
def settings_my_videos():
user_uid = session.get('uid')
user_data = {}
if user_uid:
user_record = auth.get_user(user_uid)
user_data['uid'] = user_uid
user_data['email'] = user_record.email
user_data['displayName'] = user_record.display_name
user_details_ref = db.reference(f'users/{user_uid}')
user_details = user_details_ref.get()
user_data.update(user_details)
climber_id = user_data.get('climber_id')
if(climber_id):
url = "/contributors/" + slugify(climber_id)
return redirect(url)
else:
print("Error loading my videos: No climber_id found")
return redirect("/settings/profile")
@app.route('/settings/stats', methods=['GET'])
@login_required
def settings_stats():
user_uid = session.get('uid')
user_data = {}
if user_uid:
user_record = auth.get_user(user_uid)
user_data['uid'] = user_uid
user_data['email'] = user_record.email
user_data['displayName'] = user_record.display_name
account_creation_timestamp = user_record.user_metadata.creation_timestamp / 1000 # Convert from milliseconds to seconds
account_creation_date = datetime.fromtimestamp(account_creation_timestamp)
user_data['dateCreated'] = account_creation_date.strftime('%Y-%m-%d')
time_since_creation = datetime.now() - account_creation_date
user_data['timeSinceCreation'] = str(time_since_creation.days) + " days"
user_details_ref = db.reference(f'users/{user_uid}')
user_details = user_details_ref.get()
user_data.update(user_details)
contributor_stats = utils.zone_helpers.calculate_contributor_stats(user_data['climber_id'])
user_data['contributor_stats'] = contributor_stats
user_data['total_contributors'] = utils.MadBoulderDatabase.getContributorsCount()
return render_template("/settings/settings-stats.html", user_data=user_data)
@app.route('/settings/projects', methods=['GET'])
@login_required
def settings_projects():
user_uid = session.get('uid')
projectIds = utils.MadBoulderDatabase.getProjects(user_uid)
projectsList = []
print(projectIds)
if projectIds:
for problemId in projectIds:
videoData = utils.MadBoulderDatabase.getVideoDataWithSlug(problemId)
if videoData:
projectsList.append(videoData)
else:
print(f"Data for problem ID {problemId} not found.")
print(projectsList)
return render_template("/settings/settings-projects.html", projects=projectsList)
@app.route('/settings/admin/users', methods=['GET'])
@admin_required
def settings_admin_users():
users_list, admins_list = get_all_users()
contributors = utils.MadBoulderDatabase.getContributorsList()
return render_template('settings/settings-admin-users.html', users_list=users_list, contributors=contributors)
@app.route('/settings/admin/admins', methods=['GET'])
@admin_required
def settings_admin_admins():
users_list, admins_list = get_all_users()
return render_template('settings/settings-admin-admins.html', users_list=users_list, admins_list=admins_list)
def get_all_users():
users_list = []
admins_list = []
page = auth.list_users()
while page:
for user_record in page.users:
uid = user_record.uid
user_info = {
'uid': uid,
'email': user_record.email,
'displayName': user_record.display_name,
'contributor_status': 'N/A', # Default value
'climber_id': 'N/A', # Default value
'profile_completed': False
}
user_details_ref = db.reference(f'users/{uid}')
user_details = user_details_ref.get()
if user_details:
user_info['contributor_status'] = user_details.get('contributor_status', 'N/A')
user_info['climber_id'] = user_details.get('climber_id', 'N/A')
user_info['profile_completed'] = True
users_list.append(user_info)
if check_admin_privileges(uid):
admins_list.append(user_info)
page = page.get_next_page()
return users_list, admins_list
@app.route('/settings/admin/urls', methods=['GET'])
@admin_required
def settings_admin_urls():
print("settings_admin_urls")
urlMappings = utils.MadBoulderDatabase.getUrlMappings()
return render_template('settings/settings-admin-urls.html', urlMappings=urlMappings)
@app.route('/settings/admin/missing-areas', methods=['GET'])
@admin_required
def settings_admin_missing_areas():
print("settings_admin_missing_areas")
sortedMissingAreasCount = utils.helpers.getMissingAreasCount()
return render_template('settings/settings-admin-missing-areas.html', sortedMissingAreasCount=sortedMissingAreasCount)
@app.route('/update-slug', methods=['POST'])
@admin_required
def update_slug():
print(request)
data = request.get_json()
print(data)
oldSlug = data.get('oldSlug')
newSlug = data.get('newSlug')
try:
utils.MadBoulderDatabase.addSlug(oldSlug, newSlug)
return jsonify({'status': 'success', 'message': 'Slug updated successfully.'})
except Exception as e:
return jsonify({'status': 'error', 'message': str(e)}), 500
@app.route('/delete-slug', methods=['POST'])
@admin_required
def delete_slug():
data = request.get_json()
oldSlug = data.get('oldSlug')
utils.MadBoulderDatabase.deleteSlug(oldSlug)
return jsonify({'status': 'success', 'message': 'Slug deleted successfully'})
def get_user_uid(id_token):
decoded_token = auth.verify_id_token(id_token)
uid = decoded_token['uid']
return uid
@app.route('/set-admin-claim/<userid>', methods=['POST'])
@admin_required
def add_admin_privileges(userid):
try:
auth.set_custom_user_claims(userid, {'admin': True})
return jsonify({'status': 'success', 'message': 'Admin privileges added successfully.'})
except Exception as e:
return jsonify({'status': 'error', 'message': str(e)}), 500
@app.route('/revoke-admin-claim/<userid>', methods=['POST'])
@admin_required
def revoke_admin_privileges(userid):
try:
auth.set_custom_user_claims(userid, None)
return jsonify({'status': 'success', 'message': 'Admin privileges revoked successfully.'})
except Exception as e:
return jsonify({'status': 'error', 'message': str(e)}), 500
@app.route('/update_user', methods=['POST'])
@login_required
def update_user():
if request.is_json:
data = request.get_json()
else:
data = request.form
user_uid = session.get('uid')
try:
if 'displayName' in data:
auth.update_user(user_uid, display_name=data['displayName'])
except FirebaseError as e:
return jsonify({'status': 'error', 'message': str(e)}), 500
if request.is_json:
return jsonify({'status': 'success', 'message': 'User updated successfully'})
@app.route('/update_user_details', methods=['POST'])
@login_required
def update_user_details():
if request.is_json:
data = request.get_json()
else:
data = request.form
user_uid = session.get('uid')
updates = {}
if 'contributor_status' in data and data['contributor_status'] != 'approved':
updates['contributor_status'] = data['contributor_status']
if data['contributor_status'] == 'pending':
user_record = auth.get_user(user_uid)
mail.sendPendingContributor(user_record.email)
if updates:
user_details_ref = db.reference(f'users/{user_uid}')
user_details_ref.update(updates)
if request.is_json:
return jsonify({'status': 'success', 'message': 'User updated successfully'})
@app.route('/update_user_details_protected', methods=['POST'])
@admin_required
def update_user_details_protected():
if request.is_json:
data = request.get_json()
else:
data = request.form
uid = data.get('uid')
updates = {}
if 'contributor_status' in data:
updates['contributor_status'] = data['contributor_status']
if 'climber_id' in data:
updates['climber_id'] = data['climber_id']
if updates:
user_details_ref = db.reference(f'users/{uid}')
user_details_ref.update(updates)