-
Notifications
You must be signed in to change notification settings - Fork 2
/
flaskapp.py
1509 lines (1210 loc) · 64.1 KB
/
flaskapp.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 os
from classes.data_classes import WebData, Guild, ReturnData
from classes.discord_classes import DiscordUser
from classes.typed_dictionaries import WebSearchResult
from commands.autocomplete import query_autocomplete_def
from utils.convert import convert_duration
from utils.log import log, collect_data
from utils.files import get_readable_byte_size, get_icon_class_for_filename, get_log_files, sort_files_by_name
from utils.translate import txtf
from utils.video_time import video_time_from_start
from utils.checks import check_isdigit
from utils.web import *
from web_func.utils import *
import classes.data_classes
from flask import Flask, render_template, request, url_for, redirect, send_file, abort, send_from_directory
from flask import session as flask_session, jsonify
from werkzeug.utils import safe_join
from pathlib import Path
from typing import List
import json
import math
import asyncio
from oauth import Oauth
import config
authorized_users = config.AUTHORIZED_USERS
my_id = config.OWNER_ID
bot_id = config.CLIENT_ID
prefix = config.PREFIX
vlc_logo = config.VLC_LOGO
default_discord_avatar = config.DEFAULT_DISCORD_AVATAR
d_id = 349164237605568513
# -------------------------------------------- Database -------------------------------------------- #
from database.guild import *
from database.main import *
# --------------------------------------------- LOAD DATA --------------------------------------------- #
from utils.global_vars import radio_dict, languages_dict, sound_effects, languages_shortcuts_dict, languages_list_dict
authorized_users += [my_id, 349164237605568513]
# --------------------------------------------- FUNCTIONS --------------------------------------------- #
def check_admin(session_data, _db) -> list:
if session_data is None:
raise ValueError('Session data is None')
if 'discord_user' not in session_data.keys():
if 'allowed_guilds' not in session_data.keys():
return []
return session_data['allowed_guilds']
user_id = int(session_data['discord_user']['id'])
if user_id in authorized_users:
with app.app_context():
return [_tuple[0] for _tuple in _db.session.query(classes.data_classes.Guild).with_entities(classes.data_classes.Guild.id).all()]
return session_data['allowed_guilds']
def is_admin(user) -> bool:
if user is None:
return False
user_id = user.get('id', None)
if user_id is None:
return False
try:
user_id = int(user_id)
except ValueError:
return False
if user_id in authorized_users:
return True
return False
async def simulate():
try:
await asyncio.sleep(float(os.environ.get('SIMULATE', 0)))
except (ValueError, TypeError):
pass
# Global vars
badge_dict_new = {
'active_developer': '/static/discord/svg/active_developer.svg',
'bot_http_interactions': '/static/discord/svg/bot_http_interactions.svg',
'bug_hunter': '/static/discord/svg/bug_hunter.svg',
'bug_hunter_level_2': '/static/discord/svg/bug_hunter_level_2.svg',
'discord_certified_moderator': '/static/discord/svg/discord_certified_moderator.svg',
'early_supporter': '/static/discord/svg/early_supporter.svg',
'hypesquad': '/static/discord/svg/hypesquad.svg',
'hypesquad_balance': '/static/discord/svg/hypesquad_balance.svg',
'hypesquad_bravery': '/static/discord/svg/hypesquad_bravery.svg',
'hypesquad_brilliance': '/static/discord/svg/hypesquad_brilliance.svg',
'partner': '/static/discord/svg/partner.svg',
'spammer': '/static/discord/svg/spammer.svg',
'staff': '/static/discord/svg/staff.svg',
'system': '/static/discord/svg/system.svg',
'team_user': '/static/discord/svg/team_user.svg',
'value': '/static/discord/svg/value.svg',
'verified_bot': '/static/discord/svg/verified_bot.svg',
'verified_bot_developer': '/static/discord/svg/verified_bot_developer.svg'
}
# --------------------------------------------- WEB SERVER -------------------------------------------------------------
app = Flask(__name__, static_folder='static', template_folder='templates')
app.config['SECRET_KEY'] = config.WEB_SECRET_KEY
file_path = os.path.join(os.path.abspath(os.getcwd()), 'db', 'database.db')
app.config['SQLALCHEMY_DATABASE_URI'] = f'sqlite:///{file_path}'
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy(app, model_class=Base)
with app.app_context():
for guild_obj in db.session.query(Guild).all():
guild_obj.keep_alive = False
db.session.commit()
@app.route('/favicon.ico')
def favicon():
return send_from_directory(app.static_folder, 'favicon/favicon.ico', mimetype='image/vnd.microsoft.icon')
@app.route('/robots.txt')
def robots():
return send_from_directory(app.static_folder, 'robots.txt', mimetype='text/plain')
@app.context_processor
def inject_data():
return dict(lang='en',
auth=authorized_users,
int=int,
str=str,
range=range,
len=len,
vars=vars,
dict=dict,
enumerate=enumerate,
txt=txtf,
get_username=get_username,
struct_to_time=struct_to_time,
convert_duration=convert_duration,
video_time_from_start=video_time_from_start,
check_isdigit=check_isdigit,
ceil=math.ceil,
lang_list=languages_list_dict,
)
@app.before_request
def make_session_permanent():
if not flask_session.get('lang', None):
flask_session['lang'] = 'en'
flask_session.permanent = True
# @app.teardown_appcontext
# def shutdown_session(exception=None):
# ses.remove()
# -------------------------------------------------- Index page --------------------------------------------------------
@app.route('/')
async def index_page():
log(request.remote_addr, request.full_path, log_type='ip')
await simulate()
user = flask_session.get('discord_user', {})
# flask_session['lang'] = 'cs'
try:
return render_template('nav/index.html', user=user)
except Exception as e:
return f'index = {str(e)}'
@app.route('/about')
async def about_page():
log(request.remote_addr, '/about', log_type='ip')
await simulate()
user = flask_session.get('discord_user', {})
return render_template('nav/about.html', user=user)
# -------------------------------------------------- Guild pages -------------------------------------------------------
@app.route('/guild')
async def guilds_page():
log(request.remote_addr, request.full_path, log_type='ip')
await simulate()
user = flask_session.get('discord_user', {})
allowed_guilds = check_admin(flask_session, db)
_guilds = sort_guilds(db.session.query(classes.data_classes.Guild).all(), allowed_guilds)
return render_template('nav/guild_list.html', guilds=_guilds, allowed_guilds=allowed_guilds, user=user)
@app.route('/guild/<int:guild_id>', methods=['GET', 'POST'])
async def guild_page(guild_id):
log(request.remote_addr, request.full_path, log_type='ip')
await simulate()
# Get data from session
user = flask_session.get('discord_user', {})
user_name = user.get('username', 'WEB Guest')
user_id = user.get('id', 'Remote Address')
key = request.args.get('key')
admin = is_admin(user)
allowed_guilds = check_admin(flask_session, db)
guild_object = guild(db, int(guild_id))
if guild_object is None:
return render_template('base/message.html', guild_id=guild_id, user=user,
message="That Server doesn't exist or the bot is not in it", errors=None, title='Error')
if key != guild_object.data.key:
if guild_object.id in allowed_guilds:
return redirect(f'/guild/{guild_id}?key={guild_object.data.key}')
if user:
if int(user['id']) in authorized_users:
return redirect(f'/guild/{guild_id}?key={guild_object.data.key}')
if request.method == 'POST':
key = request.form['key'] if 'key' in request.form.keys() else None
if key == guild_object.data.key:
if 'allowed_guilds' not in flask_session.keys():
flask_session['allowed_guilds'] = []
flask_session['allowed_guilds'] = flask_session['allowed_guilds'] + [guild_object.id]
# mutual_guild_ids = flask_session['mutual_guild_ids']
return redirect(f'/guild/{guild_id}?key={guild_object.data.key}')
return render_template('main/get_key.html', guild_id=guild_id,
errors=[f'Invalid code: {request.form["key"]} -> do /key in the server'],
url=Oauth.discord_login_url, user=user)
return render_template('main/get_key.html', guild_id=guild_id, errors=None, url=Oauth.discord_login_url, user=user)
if guild_object.id not in allowed_guilds:
allowed_guilds.append(guild_object.id)
flask_session['allowed_guilds'] = allowed_guilds
flask_session['guild_id'] = guild_id
errors = []
messages = []
if request.method == 'POST':
web_data = WebData(int(guild_id), {'id': user_id, 'name': user_name})
response = None
keys = request.form.keys()
if 'edit_btn' in keys:
log(web_data, 'web_video_edit', {'form': request.form}, log_type='web', author=web_data.author)
response = execute_function('web_video_edit', web_data=web_data, form=request.form)
if 'options_btn' in keys:
log(web_data, 'web_options', {'form': request.form}, log_type='web', author=web_data.author)
response = execute_function('web_user_options_edit', web_data=web_data, form=request.form)
if response:
if not response.response:
errors = [response.message]
nppd = guild_object.now_playing.played_duration if guild_object.now_playing else [{'start': None, 'end': None}] # played duration
npd = (guild_object.now_playing.duration if check_isdigit(guild_object.now_playing.duration) else 'null') if guild_object.now_playing else 'null' # now playing duration
npc = 'null' # now playing captions
nps = 'null' # now playing subtitles
nph = None
if guild_object.now_playing:
await guild_object.now_playing.renew(None)
if guild_object.now_playing.heatmap:
nph = heatmap_to_svg(guild_object.now_playing.heatmap, guild_object.now_playing.duration)
if guild_object.now_playing.captions:
npc = json.dumps(guild_object.now_playing.captions)
if guild_object.now_playing.subtitles:
nps = json.dumps(guild_object.now_playing.subtitles)
return render_template('main/guild.html',
guild=guild(db, guild_id),
gi=int(guild_id),
key=key,
user=user,
errors=errors,
messages=messages,
volume=round(guild_object.options.volume * 100),
saves=guild_save_names(db, guild_object.id),
nppd=json.dumps(nppd),
npd=npd,
nph=nph,
npc=npc,
nps=nps,
bot_status=get_guild_bot_status(int(guild_id)),
last_updated=int(guild_object.last_updated['queue']),
# radios=sort_radios(radio_dict),
admin=admin,
socket_host=os.environ.get('SOCKET_HOST', '127.0.0.1:5001'),
)
# ---------------------------------------------------- HTMX ------------------------------------------------------------
@app.route('/guild/<int:guild_id>/queue')
async def htmx_queue(guild_id):
await simulate()
user = flask_session.get('discord_user', {})
user_name = user.get('username', 'WEB Guest')
user_id = user.get('id', 'Remote Address')
admin = is_admin(user)
response = ReturnData(True, 'No action')
# await asyncio.sleep(5)
# Queue API for HTMX
#
# attributes:
# key: guild key - used to verify user
# render: json, html, none
# act: action - actions (below)
# var: variable - usually a number
# resp: (true, false, only) - if true renders response in html,
# only renders response in html, false does not render response
key = request.args.get('key')
render = request.args.get('render')
act = request.args.get('act')
var = request.args.get('var')
resp = request.args.get('resp')
guild_object = guild(db, guild_id)
if guild_object is None:
return {'success': False, 'message': 'Guild not found'}, 404, {'ContentType': 'application/json'}
if key != guild_object.data.key:
return {'success': False, 'message': 'Invalid key'}, 403, {'ContentType': 'application/json'}
if render and render not in ['json', 'html', 'none']:
render = 'html'
if act:
web_data = WebData(int(guild_id), {'id': user_id, 'name': user_name})
if 'now_video' == act:
track = guild_object.now_playing
if not track:
return {'success': False, 'message': 'No video playing'}, 404, {'ContentType': 'application/json'}
if render == 'json':
return jsonify(guild_object.now_playing.to_json())
return render_template('main/htmx/now_playing.html', gi=int(guild_id), guild=guild_object, key=key, admin=admin)
if 'queue_video' == act:
if not var.isdigit() or int(var) >= len(guild_object.queue):
return {'success': False, 'message': 'Invalid var'}, 400, {'ContentType': 'application/json'}
track = guild_object.queue[int(var)]
await track.renew(None)
if render == 'json':
_return = {
'success': True,
'message': 'Video found',
'video': track.to_json()
}
return _return, 200, {'ContentType': 'application/json'}
return render_template('main/htmx/queue_video.html', gi=int(guild_id), guild=guild_object,
struct_to_time=struct_to_time, convert_duration=convert_duration,
get_username=get_username, key=key, admin=admin, track=track)
if 'del_btn' == act:
log(web_data, 'remove', {'var': var}, log_type='web', author=web_data.author)
response = execute_function('remove_def', web_data=web_data, number=int(var), list_type='queue')
if 'up_btn' == act:
log(web_data, 'up', {'var': var}, log_type='web', author=web_data.author)
response = execute_function('web_up', web_data=web_data, number=int(var))
if 'down_btn' == act:
log(web_data, 'down', {'var': var}, log_type='web', author=web_data.author)
response = execute_function('web_down', web_data=web_data, number=int(var))
if 'top_btn' == act:
log(web_data, 'top', {'var': var}, log_type='web', author=web_data.author)
response = execute_function('web_top', web_data=web_data, number=int(var))
if 'bottom_btn' == act:
log(web_data, 'bottom', {'var': var}, log_type='web', author=web_data.author)
response = execute_function('web_bottom', web_data=web_data, number=int(var))
if 'duplicate_btn' == act:
log(web_data, 'duplicate', {'var': var}, log_type='web', author=web_data.author)
response = execute_function('web_duplicate', web_data=web_data, number=int(var))
# Buttons
if 'loop_btn' == act:
log(web_data, 'loop', {}, log_type='web', author=web_data.author)
execute_function('loop_command_def', web_data=web_data)
return render_template('main/htmx/single/loop.html', gi=guild_id, guild=guild_object, key=key)
if 'shuffle_btn' == act:
log(web_data, 'shuffle', {}, log_type='web', author=web_data.author)
response = execute_function('shuffle_def', web_data=web_data)
if 'clear_btn' == act:
log(web_data, 'clear', {}, log_type='web', author=web_data.author)
response = execute_function('clear_def', web_data=web_data)
# History Video
if 'queue_btn' == act:
log(web_data, 'queue', {'var': var}, log_type='web', author=web_data.author)
response = execute_function('web_queue', web_data=web_data, video_type=var, position=None)
if 'nextup_btn' == act:
log(web_data, 'nextup', {'var': var, 'position': 0}, log_type='web', author=web_data.author)
response = execute_function('web_queue', web_data=web_data, video_type=var, position=0)
if 'add' == act:
log(web_data, 'queue_command_def', {'var': var}, log_type='web', author=web_data.author)
response = execute_function('queue_command_def', web_data=web_data, url=var)
# Save
if 'loadName' == act:
log(web_data, 'web_load_queue', {'load_name': var}, log_type='web', author=web_data.author)
response = execute_function('load_queue_save', web_data=web_data, save_name=var)
if 'saveName' == act:
log(web_data, 'web_save_queue', {'save_name': var}, log_type='web', author=web_data.author)
response = execute_function('new_queue_save', web_data=web_data, save_name=var, author={'id': user_id, 'name': user_name})
if response is None:
return {'success': False, 'message': 'Unknown error'}, 500, {'ContentType': 'application/json'}
if render == 'json':
_return = {
'success': response.response,
'message': response.message,
'queue': [],
}
if resp == 'only':
return jsonify(_return)
for video in guild_object.queue:
await video.renew(None)
_return['queue'].append(video.to_json())
return jsonify(_return)
if resp == 'only':
return render_template('main/htmx/single/response.html', response=response)
guild_object = guild(db, guild_id)
for video in guild_object.queue:
await video.renew(None)
return render_template('main/htmx/queue.html', gi=int(guild_id), guild=guild_object, key=key,
admin=admin, response=response, resp=resp)
@app.route('/guild/<int:guild_id>/history')
async def htmx_history(guild_id):
await simulate()
user = flask_session.get('discord_user', {})
user_name = user.get('username', 'WEB Guest')
user_id = user.get('id', 'Remote Address')
admin = is_admin(user)
guild_object = guild(db, guild_id)
if guild_object is None:
return abort(404, 'Guild not found')
key = request.args.get('key')
if key != guild_object.data.key:
return abort(403, 'Invalid key')
act = request.args.get('act')
if act:
if not admin:
return abort(403, 'User is not admin')
web_data = WebData(int(guild_id), {'id': user_id, 'name': user_name})
if 'hdel_btn' == act:
var = request.args.get('var')
log(web_data, 'history remove', {'var': var}, log_type='web', author=web_data.author)
execute_function('remove_def', web_data=web_data, number=int(var), list_type='history')
return render_template('main/htmx/history.html', gi=int(guild_id), guild=guild_object,
struct_to_time=struct_to_time, convert_duration=convert_duration, get_username=get_username,
key=key, admin=admin)
@app.route('/guild/<int:guild_id>/modals')
async def htmx_modal(guild_id):
await simulate()
user = flask_session.get('discord_user', {})
# user_name = user.get('username', 'WEB Guest')
# user_id = user.get('id', 'Remote Address')
admin = is_admin(user)
guild_object = guild(db, int(guild_id))
if guild_object is None:
return abort(404, 'Guild not found')
key = request.args.get('key')
if key != guild_object.data.key:
return abort(403, 'Invalid key')
modal_type = request.args.get('type')
if modal_type == 'queue0Modal':
return render_template('main/htmx/modals/queue/queue0Modal.html', gi=int(guild_id), key=key)
if modal_type == 'queue1Modal':
return render_template('main/htmx/modals/queue/queue1Modal.html', gi=int(guild_id), key=key)
if modal_type == 'queue2Modal':
return render_template('main/htmx/modals/queue/queue2Modal.html', gi=int(guild_id), key=key)
if modal_type == 'queue3Modal':
return render_template('main/htmx/modals/queue/queue3Modal.html', gi=int(guild_id), key=key)
if modal_type == 'queue4Modal': # local radio
return render_template('main/htmx/modals/queue/queue4Modal.html', gi=int(guild_id), key=key, radios=sort_radios(radio_dict))
if modal_type == 'queue5Modal': # local files
return render_template('main/htmx/modals/queue/queue5Modal.html', gi=int(guild_id), key=key, files=sound_effects, logo=vlc_logo)
if modal_type == 'joinModal':
return render_template('main/htmx/modals/joinModal.html', gi=int(guild_id), guild=guild_object, key=key)
if modal_type == 'loadModal':
return render_template('main/htmx/modals/loadModal.html', gi=int(guild_id), saves=guild_saves(db, guild_object.id), key=key)
if modal_type == 'optionsModal':
return render_template('main/htmx/modals/optionsModal.html', gi=int(guild_id), guild=guild_object, languages_dict=languages_dict, int=int, key=key)
if modal_type == 'saveModal':
return render_template('main/htmx/modals/saveModal.html', gi=int(guild_id), key=key)
if modal_type == 'timeModal':
return render_template('main/htmx/modals/timeModal.html', gi=int(guild_id), guild=guild_object, key=key)
if modal_type == 'volumeModal':
return render_template('main/htmx/modals/volumeModal.html', gi=int(guild_id), guild=guild_object, key=key)
if modal_type == 'subtitlesModal':
return render_template('main/htmx/modals/subtitlesModal.html', gi=int(guild_id), guild=guild_object, key=key)
if modal_type == 'queue':
track_id = request.args.get('var')
track = guild_object.queue[int(track_id)]
return render_template('main/htmx/modals/video/queue.html', gi=int(guild_id), guild=guild_object, track=track, key=key)
if modal_type == 'history':
track_id = request.args.get('var')
track = guild_object.history[int(track_id)]
return render_template('main/htmx/modals/video/history.html', gi=int(guild_id), guild=guild_object, track=track, key=key)
if modal_type == 'now_playing':
return render_template('main/htmx/modals/video/now_playing.html', gi=int(guild_id), guild=guild_object, key=key)
if modal_type == 'queue_edit' and admin:
track_id = request.args.get('var')
track = guild_object.queue[int(track_id)]
return render_template('main/htmx/modals/video/queue_edit.html', gi=int(guild_id), guild=guild_object, track=track, key=key)
if modal_type == 'history_edit' and admin:
track_id = request.args.get('var')
track = guild_object.history[int(track_id)]
return render_template('main/htmx/modals/video/history_edit.html', gi=int(guild_id), guild=guild_object, track=track, key=key)
if modal_type == 'now_playing_edit' and admin:
return render_template('main/htmx/modals/video/now_playing_edit.html', gi=int(guild_id), guild=guild_object, key=key)
return abort(404, 'Modal not found')
@app.route('/guild/<int:guild_id>/search')
async def htmx_search(guild_id):
await simulate()
db_key = guild_data_key(db, guild_id)
key = request.args.get('key')
if key != db_key:
return abort(403, 'Invalid key')
act = request.args.get('act')
if act == 'youtube':
sp = request.args.get('sp', 'videos')
results: List[WebSearchResult] = await query_autocomplete_def(None, query=request.args.get('var'), include_youtube=True, raw=True, youtube_search_type=sp, title_max_length=None)
elif act == 'tunein':
results: List[WebSearchResult] = await query_autocomplete_def(None, query=request.args.get('var'), include_tunein=True, raw=True, title_max_length=None)
elif act == 'radio':
results: List[WebSearchResult] = await query_autocomplete_def(None, query=request.args.get('var'), include_radio=True, raw=True, title_max_length=None)
elif act == 'garden':
results: List[WebSearchResult] = await query_autocomplete_def(None, query=request.args.get('var'), include_garden=True, raw=True, title_max_length=None)
elif act == 'local':
results: List[WebSearchResult] = await query_autocomplete_def(None, query=request.args.get('var'), include_local=True, raw=True, title_max_length=None)
else:
return abort(404, 'Unknown search type')
return render_template('main/htmx/search.html', gi=int(guild_id), key=key, results=results)
@app.route('/guild/<int:guild_id>/action')
async def htmx_action(guild_id):
await simulate()
user = flask_session.get('discord_user', {})
user_name = user.get('username', 'WEB Guest')
user_id = user.get('id', 'Remote Address')
key = request.args.get('key')
act = request.args.get('act')
var = request.args.get('var')
resp = request.args.get('resp')
refresh = request.args.get('refresh')
guild_object = guild(db, guild_id)
if guild_object is None:
return {'success': False, 'message': 'Guild not found'}, 404, {'ContentType': 'application/json'}
if key != guild_object.data.key:
return {'success': False, 'message': 'Invalid key'}, 403, {'ContentType': 'application/json'}
resp = True if resp in ['true', 'True'] else False
refresh = False if refresh in ['false', 'False'] else True
if not act:
return {'success': False, 'message': 'No action'}, 400, {'ContentType': 'application/json'}
web_data = WebData(int(guild_id), {'id': user_id, 'name': user_name})
if 'play' == act:
log(web_data, 'play', {}, log_type='web', author=web_data.author)
response = execute_function('play_def', web_data=web_data)
elif 'skip' == act:
log(web_data, 'skip', {}, log_type='web', author=web_data.author)
response = execute_function('skip_def', web_data=web_data)
elif 'stop' == act:
log(web_data, 'stop', {}, log_type='web', author=web_data.author)
response = execute_function('stop_def', web_data=web_data)
elif 'pause' == act:
log(web_data, 'pause', {}, log_type='web', author=web_data.author)
response = execute_function('pause_def', web_data=web_data)
elif 'join' == act:
log(web_data, 'join', {'var': var}, log_type='web', author=web_data.author)
response = execute_function('web_join', web_data=web_data, channel_id=var)
elif 'disconnect' == act:
log(web_data, 'disconnect', {}, log_type='web', author=web_data.author)
response = execute_function('web_disconnect', web_data=web_data)
elif 'jump' == act:
log(web_data, 'set_video_time', {'var': var}, log_type='web', author=web_data.author)
response = execute_function('set_video_time', web_data=web_data, time_stamp=var)
elif 'time' == act:
log(web_data, 'set_video_time', {'var': var}, log_type='web', author=web_data.author)
response = execute_function('set_video_time', web_data=web_data, time_stamp=var)
elif 'volume' == act:
log(web_data, 'volume_command_def', {'var': var}, log_type='web', author=web_data.author)
response = execute_function('volume_command_def', web_data=web_data, volume=var)
elif 'subtitles' == act:
log(web_data, 'subtitles_command_def', {'var': var}, log_type='web', author=web_data.author)
response = execute_function('subtitles_command_def', web_data=web_data, subtitles=var)
elif 'edit' == act:
log(web_data, 'web_video_edit', {}, log_type='web', author=web_data.author)
response = execute_function('web_video_edit', web_data=web_data, form=request.form) # TODO
elif 'options' == act:
log(web_data, 'web_options', {}, log_type='web', author=web_data.author)
response = execute_function('web_user_options_edit', web_data=web_data, form=request.form) # TODO
elif 'loop' == act:
log(web_data, 'loop', {}, log_type='web', author=web_data.author)
execute_function('loop_command_def', web_data=web_data)
return render_template('main/htmx/single/loop.html', gi=guild_id, guild=guild_object, key=key)
else:
return {'success': False, 'message': 'Unknown action'}, 400, {'ContentType': 'application/json'}
if response is None:
return {'success': False, 'message': 'No response'}, 500, {'ContentType': 'application/json'}
if resp is False and refresh is False:
return {'success': response.response, 'message': response.message, 'refresh': refresh}, 200, {'ContentType': 'application/json'}
return render_template('main/htmx/single/response.html', response=response, refresh=refresh, resp=resp)
# -------------------------------------------------- SocketIO ----------------------------------------------------------
# @app.route('/push')
# def push_endpoint():
# guild_id = request.args.get('id')
# if guild_id:
# socketio.emit('update', int(time()), to=str(guild_id))
#
# return json.dumps({'success': True}), 200, {'ContentType': 'application/json'}
#
# return abort(403)
#
# @socketio.on('connect')
# def connect():
# if 'guild_id' in flask_session.keys():
# join_room(flask_session['guild_id'])
#
# @socketio.on('disconnect')
# def disconnect():
# if 'guild_id' in flask_session.keys():
# leave_room(flask_session['guild_id'])
#
# @socketio.on('getUpdates')
# def get_update(guild_id):
# join_room(guild_id)
# ------------------------------------------------- User Login ---------------------------------------------------------
@app.route('/login')
async def login_page():
log(request.remote_addr, request.full_path, log_type='web')
await simulate()
update, admin = False, False
if 'discord_user' not in flask_session.keys():
code = request.args.get('code')
if code is None:
return redirect(Oauth.discord_login_url)
response = Oauth.get_access_token(code)
flask_session['access_token'] = response['access_token']
log(request.remote_addr, 'Got access token', log_type='text')
if 'discord_user' in flask_session.keys():
update = True
# Get API data
user = Oauth.get_user(flask_session['access_token'])
allowed_guilds = Oauth.get_user_guilds(flask_session['access_token']) # user guilds
# Collect data
collect_data(user)
collect_data(f'{user["username"]} -> {user_guilds}')
# Store data in session
flask_session['discord_user'] = {
'avatar': user['avatar'],
'discriminator': user['discriminator'],
'global_name': user['global_name'],
'id': user['id'],
'locale': user['locale'],
'username': user['username'],
}
user_lang = user['locale'][:2]
flask_session['lang'] = user_lang if user_lang in languages_dict.keys() else 'en'
# Check if user is admin and set allowed guilds to user+bot guilds
if int(user['id']) in authorized_users:
allowed_guilds += Oauth.get_bot_guilds()
# Store allowed guilds in session as list of guild IDs
flask_session['allowed_guilds'] = [int(g_dict['id']) for g_dict in allowed_guilds]
# Customize message
msg_type = "updated session for" if update else "logged in as"
message = f"Success, {msg_type} {user['username']}#{user['discriminator']}{' -> ADMIN' if admin else ''}"
return render_template('base/message.html', message=message, errors=None, user=user, title='Login Success')
@app.route('/logout')
async def logout_page():
log(request.remote_addr, request.full_path, log_type='ip')
await simulate()
if 'discord_user' in flask_session.keys():
user = flask_session['discord_user']
username = user['username']
discriminator = user['discriminator']
flask_session.clear()
return render_template('base/message.html', message=f"Logged out {username}#{discriminator}", errors=None,
user=None, title='Logout Success')
return redirect(url_for('index_page'))
# ------------------------------------------------------- Session ------------------------------------------------------
@app.route('/reset')
async def reset_page():
log(request.remote_addr, request.full_path, log_type='ip')
await simulate()
flask_session.clear()
return redirect(url_for('index_page'))
# -------------------------------------------------------- Invite ------------------------------------------------------
@app.route('/invite')
async def invite_page():
log(request.remote_addr, request.full_path, log_type='ip')
await simulate()
return redirect(config.INVITE_URL)
# ------------------------------------------------------- Action -------------------------------------------------------
@app.route('/action')
async def action_page():
log(request.remote_addr, request.full_path, log_type='ip')
await simulate()
act = request.args.get('act')
var = request.args.get('var')
resp = request.args.get('resp')
refresh = request.args.get('refresh')
resp = True if resp in ['true', 'True'] else False
refresh = False if refresh in ['false', 'False'] else True
if not act:
return {'success': False, 'message': 'No action'}, 400, {'ContentType': 'application/json'}
if 'user_lang' == act:
if var not in languages_dict.keys() or len(var) != 2 or not var:
return {'success': False, 'message': 'Invalid language'}, 400, {'ContentType': 'application/json'}
flask_session['lang'] = var
response = ReturnData(True, 'Language changed to ' + languages_list_dict[var]['name'])
else:
return {'success': False, 'message': 'Unknown action'}, 400, {'ContentType': 'application/json'}
if response is None:
return {'success': False, 'message': 'No response'}, 500, {'ContentType': 'application/json'}
if resp is False:
return {'success': response.response, 'message': response.message, 'refresh': refresh}, 200, {
'ContentType': 'application/json'}
return render_template('main/htmx/single/response.html', response=response, refresh=refresh, resp=resp)
# -------------------------------------------------------- Admin -------------------------------------------------------
@app.route('/admin', methods=['GET', 'POST'])
async def admin_page():
log(request.remote_addr, request.full_path, log_type='ip')
await simulate()
user = flask_session.get('discord_user', {})
if user is None:
return render_template('base/message.html', message="403 Forbidden", message4='You have to be logged in.',
errors=None, user=None, title='403 Forbidden'), 403
if int(user.get('id', 0)) not in authorized_users:
return abort(403, 'User not authorized')
guild_list = sort_guilds(guilds(db), flask_session.get('allowed_guilds', []))
bot_status = get_guilds_bot_status()
hash_map = {
'Playing': 0,
'Paused': 0,
'Connected': 0,
'Not connected': 0,
'Unknown': 0
}
for status in bot_status.values():
hash_map[status] += 1
return render_template('admin/admin.html', user=user, guild=guild_list,
bot_status=bot_status, hash_map=hash_map, last_played=guilds_last_played(db))
# Admin Files ---------------------------------------------------
@app.route('/admin/log')
async def admin_log_tree():
log(request.remote_addr, request.full_path, log_type='ip')
await simulate()
user = flask_session.get('discord_user', {})
if user is None:
return render_template('base/message.html', message="403 Forbidden", message4='You have to be logged in.',
errors=None, user=None, title='403 Forbidden'), 403
if not is_admin(user):
return abort(403, 'User not authorized')
log_files = get_log_files()
return render_template('admin/text_file/logs.html', user=user, title='Log', log_files=log_files)
# Files
@app.route('/admin/log/<path:file_name>')
async def admin_log_page(file_name):
log(request.remote_addr, request.full_path, log_type='ip')
await simulate()
user = flask_session.get('discord_user', {})
if user is None:
return render_template('base/message.html', message="403 Forbidden", message4='You have to be logged in.',
errors=None, user=None, title='403 Forbidden'), 403
if not is_admin(user):
return abort(403, 'User not authorized')
file_names = get_log_files()
if file_name not in file_names:
return abort(404, 'File not found')
try:
with open(f'logs/{file_name}', 'r', encoding='utf-8') as f:
lines = list(reversed([(value, index) for index, value in enumerate(f.readlines())]))
chunks = math.ceil(len(lines) / 100)
except Exception as e:
log(request.remote_addr, [str(e)], log_type='error', author=user['username'])
return abort(500, f'Error reading file {e}')
separate_lines = True if request.args.get('separate_lines') is not None else False
return render_template('admin/text_file/iscroll.html', user=user, chunks=chunks, lines=lines, title='Log', log_type=file_name, separate_lines=separate_lines)
# @app.route('/admin/json/<path:file_name>')
# async def admin_json_page(file_name):
# log(request.remote_addr, request.full_path, log_type='ip')
# if 'discord_user' in flask_session.keys():
# user = flask_session['discord_user']
# else:
# return render_template('base/message.html', message="403 Forbidden", message4='You have to be logged in.',
# errors=None, user=None, title='403 Forbidden'), 403
#
# if int(user['id']) not in authorized_users:
# return abort(403)
#
# file_names = ['radio', 'languages']
# if file_name not in file_names:
# return abort(404)
#
# try:
# with open(f'json/{file_name}.json', 'r', encoding='utf-8') as f:
# lines = list(reversed(f.readlines()))
# chunks = math.ceil(len(lines) / 100)
# except Exception as e:
# log(request.remote_addr, [str(e)], log_type='error', author=user['username'])
# return abort(500)
#
# return render_template('admin/text_file/iscroll.html', user=user, chunks=chunks, lines=lines, title='Log', range=range, log_type=file_name)
# Admin Data Data
# @app.route('/admin/data', methods=['GET', 'POST'])
# async def admin_data_page():
# log(request.remote_addr, request.full_path, log_type='ip')
# if 'discord_user' in flask_session.keys():
# user = flask_session['discord_user']
# else:
# return render_template('base/message.html', message="403 Forbidden", message4='You have to be logged in.',
# errors=None, user=None, title='403 Forbidden'), 403
#
# if int(user['id']) not in authorized_users:
# return abort(403)
#
# with open(f'logs/data.log', 'r', encoding='utf-8') as f:
# data_data = f.readlines()
#
# return render_template('admin/text_file/data.html', user=user, data_data=data_data, title='Log')
# Admin Files HTMX ---------------------------------------------------
@app.route('/admin/inflog', methods=['GET'])
async def admin_inflog_page():
await simulate()
user = flask_session.get('discord_user', {})
if user is None:
return render_template('base/message.html', message="403 Forbidden", message4='You have to be logged in.',
errors=None, user=None, title='403 Forbidden'), 403
if not is_admin(user):
return abort(403, 'User not authorized')
log_type = request.args.get('type')
if log_type not in get_log_files():
return abort(404, 'File not found')
try:
with open(f'logs/{log_type}', 'r', encoding='utf-8') as f:
lines = list(reversed([(value, index) for index, value in enumerate(f.readlines())]))
except Exception as e:
log(request.remote_addr, [str(e)], log_type='error', author=user['username'])
return abort(500, f'Error reading file {e}')
index_num = request.args.get('index')
if index_num:
index_num = int(index_num)
else:
return abort(400, 'No index provided')
if index_num > math.ceil(len(lines)/100):
return "<p>Index out of range</p>"
if index_num == 0:
lines = lines[:100]
else:
if index_num == math.ceil(len(lines)/100):
lines = lines[index_num*100:]
else:
lines = lines[index_num*100:(index_num+1)*100]
separate_lines = True if request.args.get('separate_lines') is not None else False
return render_template('admin/text_file/chunk.html', lines=lines, separate_lines=separate_lines)
# Admin user data ----------------------------------------------------
@app.route('/admin/user/<int:user_id>', methods=['GET', 'POST'])
async def admin_user_page(user_id):
log(request.remote_addr, request.full_path, log_type='ip')
await simulate()
user = flask_session.get('discord_user', {})
if user is None:
return render_template('base/message.html', message="403 Forbidden", message4='You have to be logged in.',
errors=None, user=None, title='403 Forbidden'), 403
if int(user.get('id', 0)) not in authorized_users:
return abort(403, 'User not authorized')