forked from DragonMinded/PyStreaming
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
1135 lines (962 loc) · 39.4 KB
/
Copy pathapp.py
File metadata and controls
1135 lines (962 loc) · 39.4 KB
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 argparse
import calendar
import datetime
import emoji
import os
import random
import webcolors # type: ignore
import yaml
from flask import Flask, Request, Response, abort, jsonify, render_template, request as base_request, redirect, make_response, url_for
from flask_socketio import SocketIO, join_room # type: ignore
from flask_cors import CORS # type: ignore
from typing import Any, Dict, List, Optional, cast
from werkzeug.middleware.proxy_fix import ProxyFix
from data import Data
# Allow cache-busting of entire frontend for stream page and chat updates.
FRONTEND_CACHE_BUST: str = "site.1.0.0"
app = Flask(__name__)
CORS(app)
socketio = SocketIO(app, cors_allowed_origins='*')
config: Dict[str, Any] = {}
# A quick hack to teach mypy about the valid SID parameter.
class StreamingRequest(Request):
sid: Any
request: StreamingRequest = cast(StreamingRequest, base_request)
def mysql() -> Data:
global config
return Data(config)
def now() -> int:
"""
Returns the current unix timestamp in the UTC timezone.
"""
return calendar.timegm(datetime.datetime.utcnow().timetuple())
def modified(fname: str) -> int:
"""
Returns the modification time in the UTC timezone.
"""
return calendar.timegm(datetime.datetime.utcfromtimestamp(os.path.getmtime(fname)).timetuple())
def first_quality() -> Optional[str]:
global config
qualities = config.get('video_qualities', None)
if not qualities:
return None
firstq = qualities[0]
if isinstance(firstq, str):
return firstq
return None
class SocketInfo:
def __init__(self, sid: Any, ip: str, streamer: str, username: str, admin: bool, moderator: bool, muted: bool, color: int) -> None:
self.sid = sid
self.ip = ip
self.streamer = streamer
self.username = username
self.admin = admin
self.moderator = moderator
self.muted = muted
self.color = color
@property
def htmlcolor(self) -> str:
color = hex(self.color)[2:]
if len(color) < 6:
color = ('0' * (6 - len(color))) + color
return '#' + color
class PresenceInfo:
def __init__(self, sid: Any, streamer: str) -> None:
self.sid = sid
self.streamer = streamer
self.timestamp = now()
socket_to_info: Dict[Any, SocketInfo] = {}
socket_to_presence: Dict[Any, PresenceInfo] = {}
def users_in_room(streamer: str) -> List[Dict[str, str]]:
return [{'username': i.username, 'type': get_type(i), 'color': i.htmlcolor} for i in socket_to_info.values() if i.streamer == streamer]
def stream_count(streamer: str) -> int:
oldest = now() - 30
return len([None for x in socket_to_presence.values() if x.streamer == streamer and x.timestamp >= oldest])
def stream_live(streamkey: str, quality: Optional[str] = None) -> bool:
global config
if quality:
filename = f"{streamkey}_{quality}.m3u8"
else:
filename = streamkey + '.m3u8'
m3u8 = os.path.join(config['hls_dir'], filename)
if not os.path.isfile(m3u8):
# There isn't a playlist file, we aren't live.
return False
delta = now() - modified(m3u8)
if delta >= int(config['hls_playlist_length']):
return False
return True
def get_color(color: str) -> Optional[int]:
color = color.strip().lower()
if color == "random":
# Pick a random webcolor.
choices = [k for k in webcolors.CSS3_NAMES_TO_HEX]
color = random.choice(choices)
# Attempt to convert from any color specification to hex.
try:
color = webcolors.name_to_hex(color, spec=webcolors.CSS3)
except ValueError:
pass
try:
color = webcolors.normalize_hex(color)
except ValueError:
pass
if len(color) != 7 or color[0] != '#':
return None
intval = int(color[1:], 16)
if intval < 0 or intval > 0xFFFFFF:
return None
return intval
def get_type(user: SocketInfo) -> str:
if user.admin:
return "admin"
elif user.moderator:
return "moderator"
else:
return "normal"
def fetch_m3u8(streamkey: str, quality: Optional[str] = None) -> Optional[str]:
global config
if quality:
filename = f"{streamkey}_{quality}"
else:
filename = streamkey
m3u8 = os.path.join(config['hls_dir'], filename) + '.m3u8'
if not os.path.isfile(m3u8):
# There isn't a playlist file, we aren't live.
return None
with open(m3u8, "rb") as bfp:
return bfp.read().decode('utf-8')
def fetch_ts(filename: str) -> Optional[bytes]:
global config
ts = os.path.join(config['hls_dir'], filename)
if not os.path.isfile(ts):
# The file doesn't exist
return None
with open(ts, "rb") as bfp:
return bfp.read()
def symlink(oldname: str, newname: str) -> None:
src = os.path.join(config['hls_dir'], oldname)
dst = os.path.join(config['hls_dir'], newname)
try:
os.symlink(src, dst)
except FileExistsError:
pass
def clean_symlinks() -> None:
global config
try:
for name in os.listdir(config['hls_dir']):
if name not in (os.curdir, os.pardir):
full = os.path.join(config['hls_dir'], name)
if os.path.islink(full):
real = os.readlink(full)
if not os.path.isfile(real):
# This symlink points at an old file that nginx has removed.
# So, let's clean up!
os.remove(full)
except Exception:
# We don't want to interrupt playlist fetching due to a failure to
# clean. If this happens the stream will pause.
pass
@app.context_processor
def provide_globals() -> Dict[str, Any]:
return {
"cache_bust": f"v={FRONTEND_CACHE_BUST}",
}
@app.route('/')
def index() -> str:
cursor = mysql().execute(
"SELECT `username`, `key`, `description`, `streampass` FROM streamersettings",
)
streamers = [
{
'username': result['username'],
'live': stream_live(result['key'], first_quality()), 'count': stream_count(result['username'].lower()),
'description': emotes(result['description']) if result['description'] else '',
'locked': result['streampass'] is not None,
}
for result in cursor.fetchall()
]
return render_template('index.html', streamers=streamers)
@app.route('/<streamer>/')
def stream(streamer: str) -> Response:
cursor = mysql().execute(
"SELECT username, streampass FROM streamersettings WHERE username = :username",
{"username": streamer},
)
if cursor.rowcount != 1:
abort(404)
result = cursor.fetchone()
streampass = result['streampass']
if streampass is not None and request.cookies.get('streampass') != streampass:
# This stream is password protected!
return make_response(
render_template(
'password.html',
streamer=result["username"],
),
403
)
# The stream is either not password protected, or the user has already authenticated.
global config
qualities = config.get('video_qualities', None)
if not qualities:
playlists = [{"src": url_for('streamplaylist', streamer=streamer), "label": "live", "type": "application/x-mpegURL"}]
else:
playlists = [{"src": url_for('streamplaylistwithquality', streamer=streamer, quality=quality), "label": quality, "type": "application/x-mpegURL"} for quality in qualities]
emojis = {
**emoji.get_emoji_unicode_dict('en'), # type: ignore
**emoji.get_aliases_unicode_dict(), # type: ignore
}
emojis = {key: emojis[key] for key in emojis if "__" not in key}
cursor = mysql().execute(
"SELECT alias, uri FROM emotes ORDER BY alias",
)
emotes = {f":{result['alias']}:": result['uri'] for result in cursor.fetchall()}
icons = {
'admin': url_for('static', filename='admin.png'),
'moderator': url_for('static', filename='moderator.png'),
}
return make_response(
render_template(
'stream.html',
streamer=result["username"],
playlists=playlists,
emojis=emojis,
emotes=emotes,
icons=icons,
)
)
@app.route('/<streamer>/password', methods=["POST"])
def password(streamer: str) -> Response:
streamer = streamer.lower()
cursor = mysql().execute(
"SELECT `username`, `streampass` FROM streamersettings WHERE username = :username",
{"username": streamer},
)
if cursor.rowcount != 1:
abort(404)
# Verify the password.
result = cursor.fetchone()
streampass = result['streampass']
if request.form.get('streampass') == streampass:
expire_date = datetime.datetime.now()
expire_date = expire_date + datetime.timedelta(days=1)
response = make_response(redirect(url_for("stream", streamer=result["username"])))
response.set_cookie("streampass", streampass, expires=expire_date)
return response
# Wrong password bucko!
return make_response(
render_template(
'password.html',
streamer=result["username"],
password_invalid=True,
),
403
)
@app.route('/<streamer>/info')
def streaminfo(streamer: str) -> Response:
streamer = streamer.lower()
cursor = mysql().execute(
"SELECT `username`, `streampass`, `key`, `description` FROM streamersettings WHERE username = :username",
{"username": streamer},
)
if cursor.rowcount != 1:
abort(404)
# Doesn't cost us much, so let's clean up on the fly.
clean_symlinks()
result = cursor.fetchone()
# First, verify they're even allowed to see this stream.
streampass = result['streampass']
if streampass is not None and request.cookies.get('streampass') != streampass:
# This stream is password protected!
abort(403)
# The stream is either not password protected, or the user has already authenticated.
live = stream_live(result['key'], first_quality())
return make_response(jsonify({
'live': live,
'count': stream_count(streamer) if live else 0,
'description': emotes(result['description']) if result['description'] else '',
}))
@app.route('/<streamer>/playlist.m3u8')
def streamplaylist(streamer: str) -> str:
streamer = streamer.lower()
cursor = mysql().execute(
"SELECT `username`, `streampass`, `key` FROM streamersettings WHERE username = :username",
{"username": streamer},
)
if cursor.rowcount != 1:
abort(404)
result = cursor.fetchone()
# First ensure they're even allowed to see this stream.
streampass = result['streampass']
if streampass is not None and request.cookies.get('streampass') != streampass:
# This stream is password protected!
abort(403)
# The stream is either not password protected, or the user has already authenticated.
key = result['key']
if not stream_live(key):
abort(404)
m3u8 = fetch_m3u8(key)
if m3u8 is None:
abort(404)
lines = m3u8.splitlines()
for i in range(len(lines)):
if lines[i].startswith(key) and lines[i][-3:] == ".ts":
# We need to rewrite this
oldname = lines[i]
newname = f"{streamer}" + lines[i][len(key):]
symlink(oldname, newname)
lines[i] = "/hls/" + newname
if key in lines[i]:
raise Exception("Possible stream key leak!")
# Doesn't cost us much, so let's clean up on the fly.
clean_symlinks()
m3u8 = "\n".join(lines)
return m3u8
@app.route('/<streamer>/playlist/<quality>.m3u8')
def streamplaylistwithquality(streamer: str, quality: str) -> str:
streamer = streamer.lower()
cursor = mysql().execute(
"SELECT `username`, `streampass`, `key` FROM streamersettings WHERE username = :username",
{"username": streamer},
)
if cursor.rowcount != 1:
abort(404)
result = cursor.fetchone()
# First ensure they're even allowed to see this stream.
streampass = result['streampass']
if streampass is not None and request.cookies.get('streampass') != streampass:
# This stream is password protected!
abort(403)
# The stream is either not password protected, or the user has already authenticated.
key = result['key']
if not stream_live(key, quality):
abort(404)
m3u8 = fetch_m3u8(key, quality)
if m3u8 is None:
abort(404)
lines = m3u8.splitlines()
for i in range(len(lines)):
if lines[i].startswith(key + '_' + quality) and lines[i][-3:] == ".ts":
# We need to rewrite this
oldname = lines[i]
newname = f"{streamer}_{quality}" + lines[i][(len(key) + len(quality) + 1):]
symlink(oldname, newname)
lines[i] = "/hls/" + newname
if key in lines[i]:
raise Exception("Possible stream key leak!")
# Doesn't cost us much, so let's clean up on the fly.
clean_symlinks()
m3u8 = "\n".join(lines)
return m3u8
@app.route('/hls/<filename>')
def streamts(filename: str) -> Response:
# This is a debugging endpoint only, your production nginx setup should handle this.
ts = fetch_ts(filename)
if ts is None:
abort(404)
response = make_response(ts)
response.headers.set('Content-Type', 'video/mp2t') # type: ignore
return response
@app.route('/auth/on_publish', methods=["GET", "POST"])
def publishcheck() -> Response:
key = request.values.get('name')
if key is None:
# We don't have a stream key, deny it.
abort(404)
cursor = mysql().execute(
"SELECT `key` FROM streamersettings WHERE `key` = :key",
{"key": key},
)
if cursor.rowcount != 1:
# We didn't find a registered streamer with this key, deny it.
abort(404)
# This is fine, allow it
return make_response("Stream ok!", 200)
@app.route('/auth/on_publish_done', methods=["GET", "POST"])
def donepublishcheck() -> Response:
return make_response("Stream ok!", 200)
@socketio.on('connect') # type: ignore
def connect() -> None:
if request.sid in socket_to_info:
del socket_to_info[request.sid]
@socketio.on('disconnect') # type: ignore
def disconnect() -> None:
if request.sid in socket_to_info:
info = socket_to_info[request.sid]
del socket_to_info[request.sid]
socketio.emit('disconnected', {'username': info.username, 'type': get_type(info), 'color': info.htmlcolor, 'users': users_in_room(info.streamer)}, room=info.streamer)
if request.sid in socket_to_presence:
del socket_to_presence[request.sid]
@socketio.on('presence') # type: ignore
def handle_presence(json: Dict[str, Any], methods: List[str] = ['GET', 'POST']) -> None:
if 'streamer' not in json:
return
# Update user presence information
streamer = json['streamer'].lower()
socket_to_presence[request.sid] = PresenceInfo(request.sid, streamer)
@socketio.on('login') # type: ignore
def handle_login(json: Dict[str, Any], methods: List[str] = ['GET', 'POST']) -> None:
if request.sid in socket_to_info:
socketio.emit('error', {'msg': 'SID already taken?'}, room=request.sid)
return
if 'username' not in json:
socketio.emit('error', {'msg': 'Username mssing from JSON?'}, room=request.sid)
return
if 'streamer' not in json:
socketio.emit('error', {'msg': 'Streamer mssing from JSON?'}, room=request.sid)
return
if len(json['username']) == 0:
socketio.emit('error', {'msg': 'Username cannot be blank'}, room=request.sid)
return
if len(json['username']) >= 30:
socketio.emit('error', {'msg': 'Username cannot be that long'}, room=request.sid)
return
streamer = json['streamer'].lower()
username = json['username']
for user in users_in_room(streamer):
if user['username'].lower() == username.lower():
socketio.emit('error', {'msg': 'Username is already taken'}, room=request.sid)
return
color = get_color(json['color'].strip().lower()) or 0
key = json.get('key', None)
# Update user presence information
socket_to_presence[request.sid] = PresenceInfo(request.sid, streamer)
cursor = mysql().execute(
"SELECT `username`, `key` FROM streamersettings WHERE username = :username",
{"username": streamer},
)
if cursor.rowcount != 1:
socketio.emit('error', {'msg': 'Streamer does not exist'}, room=request.sid)
return
admin = False
if username.lower() == streamer:
result = cursor.fetchone()
if key is None:
socketio.emit('login key required', {'username': result['username']}, room=request.sid)
return
if key != result["key"]:
socketio.emit('error', {'msg': 'Invalid password!'}, room=request.sid)
return
username = result['username']
admin = True
for _, existing in socket_to_info.items():
if existing.streamer != streamer:
# Not the right room
continue
if existing.username.lower() == json['username'].lower():
socketio.emit('error', {'msg': 'Username is taken'}, room=request.sid)
return
socket_to_info[request.sid] = SocketInfo(request.sid, str(request.remote_addr), streamer, json['username'], admin, False, False, color)
join_room(streamer)
socketio.emit('login success', {'username': json['username']}, room=request.sid)
socketio.emit('connected', {'username': json['username'], 'type': get_type(socket_to_info[request.sid]), 'color': socket_to_info[request.sid].htmlcolor, 'users': users_in_room(streamer)}, room=streamer)
if admin:
socketio.emit('server', {'msg': 'You have admin rights.'}, room=request.sid)
def emotes(msg: str) -> str:
return emoji.emojize(emoji.emojize(msg, language="alias"), language="en")
@socketio.on('message') # type: ignore
def handle_message(json: Dict[str, Any], methods: List[str] = ['GET', 'POST']) -> None:
if 'message' not in json:
socketio.emit('error', {'msg': 'Message mssing from JSON?'}, room=request.sid)
return
if len(json['message']) == 0:
socketio.emit('warning', {'msg': 'Message cannot be blank'}, room=request.sid)
return
if request.sid not in socket_to_info:
socketio.emit('error', {'msg': 'User is not authenticated?'}, room=request.sid)
return
# Update user presence information
socket_to_presence[request.sid] = PresenceInfo(request.sid, socket_to_info[request.sid].streamer)
message = json['message'].strip()
if message[0] == "/":
# Command of some sort
if ' ' in message:
command, message = message.split(' ', 1)
else:
command = message
message = ""
if command in ["/say"]:
if socket_to_info[request.sid].muted:
socketio.emit(
'server',
{'msg': "You are muted!"},
room=request.sid,
)
else:
# Just a say message
socketio.emit(
'message received',
{
'username': socket_to_info[request.sid].username,
'type': get_type(socket_to_info[request.sid]),
'color': socket_to_info[request.sid].htmlcolor,
'message': emotes(message),
},
room=socket_to_info[request.sid].streamer,
)
elif command in ["/me", "/action", "/describe"]:
if socket_to_info[request.sid].muted:
socketio.emit(
'server',
{'msg': "You are muted!"},
room=request.sid,
)
else:
# An action message
socketio.emit(
'action received',
{
'username': socket_to_info[request.sid].username,
'type': get_type(socket_to_info[request.sid]),
'color': socket_to_info[request.sid].htmlcolor,
'message': emotes(message),
},
room=socket_to_info[request.sid].streamer,
)
elif command in ["/color", "/setcolor"]:
if socket_to_info[request.sid].muted:
socketio.emit(
'server',
{'msg': "You are muted!"},
room=request.sid,
)
else:
# Set the color of your name
color = get_color(message.strip().lower())
if not color:
socketio.emit(
'server',
{'msg': f'Invalid color {message} specified, try a color name, an HTML color like #ff00ff or "random" for a random color.'},
room=request.sid,
)
else:
socket_to_info[request.sid].color = color
socketio.emit(
'action received',
{
'username': socket_to_info[request.sid].username,
'type': get_type(socket_to_info[request.sid]),
'color': socket_to_info[request.sid].htmlcolor,
'message': 'changed their color!',
},
room=socket_to_info[request.sid].streamer,
)
socketio.emit(
'return color',
{'color': socket_to_info[request.sid].htmlcolor},
room=request.sid,
)
elif command in ["/name", "/nick"]:
if socket_to_info[request.sid].muted:
socketio.emit(
'server',
{'msg': "You are muted!"},
room=request.sid,
)
else:
# Set a new name
name = message.strip()
if len(name) >= 30:
socketio.emit(
'server',
{'msg': 'Too long of a name specified, try a different name.'},
room=request.sid,
)
else:
for user in users_in_room(socket_to_info[request.sid].streamer):
if user['username'].lower() == name.lower():
socketio.emit(
'server',
{'msg': 'Name has already been taken, try a different name.'},
room=request.sid,
)
break
else:
if not name:
socketio.emit(
'server',
{'msg': 'Invalid name specified, try a different name.'},
room=request.sid,
)
else:
old = socket_to_info[request.sid].username
socket_to_info[request.sid].username = name
socketio.emit(
'rename',
{
'newname': socket_to_info[request.sid].username,
'oldname': old,
'type': get_type(socket_to_info[request.sid]),
'color': socket_to_info[request.sid].htmlcolor,
'users': users_in_room(socket_to_info[request.sid].streamer),
},
room=socket_to_info[request.sid].streamer,
)
elif command in ["/help"]:
messages = [
"The following commands are recognized:",
"/help - show this message",
"/users - show the currently chatting users",
"/me - perform an action",
"/color - set the color of your name in chat",
"/name - change your name to a new one",
]
if socket_to_info[request.sid].admin:
messages.append("/settings - display all stream settings")
messages.append("/description <text> - set the stream description")
messages.append("/password [<text>] - set or unset the stream password")
messages.append("/mod <user> - grant moderator privileges to user")
messages.append("/demod <user> - revoke moderator privileges to user")
if socket_to_info[request.sid].admin or socket_to_info[request.sid].moderator:
messages.append("/mute <user> - mute user")
messages.append("/unmute <user> - unmute user")
for message in messages:
socketio.emit(
'server',
{'msg': message},
room=request.sid,
)
elif command in ["/users"]:
socketio.emit(
'userlist',
{'users': users_in_room(socket_to_info[request.sid].streamer)},
room=request.sid,
)
elif command in ["/settings"]:
if not socket_to_info[request.sid].admin:
socketio.emit(
'server',
{'msg': f"Unrecognized command '{command}', use '/help' for info."},
room=request.sid,
)
return
streamer = socket_to_info[request.sid].streamer
cursor = mysql().execute(
"SELECT `description`, `streampass` FROM streamersettings WHERE `username` = :streamer",
{"streamer": streamer}
)
if cursor.rowcount != 1:
socketio.emit(
'server',
{'msg': "Error looking up settings!"},
room=request.sid,
)
else:
result = cursor.fetchone()
socketio.emit(
'server',
{'msg': f"Description: {result['description']}"},
room=request.sid,
)
if result['streampass']:
socketio.emit(
'server',
{'msg': f"Stream password: {result['streampass']}"},
room=request.sid,
)
else:
socketio.emit(
'server',
{'msg': "No stream password"},
room=request.sid,
)
elif command in ["/mute", "/quiet"]:
if not (socket_to_info[request.sid].admin or socket_to_info[request.sid].moderator):
socketio.emit(
'server',
{'msg': f"Unrecognized command '{command}', use '/help' for info."},
room=request.sid,
)
return
message = message.strip().lower()
for sinfo in socket_to_info.values():
if sinfo.username.lower() == message and sinfo.streamer == socket_to_info[request.sid].streamer:
changed = (sinfo.muted is False)
sinfo.muted = True
if changed:
socketio.emit(
'server',
{'msg': f"User '{message}' has been muted."},
room=request.sid,
)
socketio.emit(
'server',
{'msg': "You have been muted."},
room=sinfo.sid,
)
else:
socketio.emit(
'server',
{'msg': f"User '{message}' is already muted."},
room=request.sid,
)
break
else:
socketio.emit(
'server',
{'msg': f"Unrecognized user '{message}'"},
room=request.sid,
)
elif command in ["/unmute", "/unquiet"]:
if not (socket_to_info[request.sid].admin or socket_to_info[request.sid].moderator):
socketio.emit(
'server',
{'msg': f"Unrecognized command '{command}', use '/help' for info."},
room=request.sid,
)
return
message = message.strip().lower()
for sinfo in socket_to_info.values():
if sinfo.username.lower() == message and sinfo.streamer == socket_to_info[request.sid].streamer:
changed = (sinfo.muted is True)
sinfo.muted = False
if changed:
socketio.emit(
'server',
{'msg': f"User '{message}' has been unmuted."},
room=request.sid,
)
socketio.emit(
'server',
{'msg': "You have been unmuted."},
room=sinfo.sid,
)
else:
socketio.emit(
'server',
{'msg': f"User '{message}' is not muted."},
room=request.sid,
)
break
else:
socketio.emit(
'server',
{'msg': f"Unrecognized user '{message}'"},
room=request.sid,
)
elif command in ["/mod"]:
if not socket_to_info[request.sid].admin:
socketio.emit(
'server',
{'msg': f"Unrecognized command '{command}', use '/help' for info."},
room=request.sid,
)
return
message = message.strip().lower()
for sinfo in socket_to_info.values():
if sinfo.username.lower() == message and sinfo.streamer == socket_to_info[request.sid].streamer:
changed = (sinfo.moderator is False)
sinfo.moderator = True
if changed:
socketio.emit(
'server',
{'msg': f"User '{message}' has been promoted to moderator."},
room=request.sid,
)
socketio.emit(
'server',
{'msg': "You have been promoted to moderator."},
room=sinfo.sid,
)
else:
socketio.emit(
'server',
{'msg': f"User '{message}' is already a moderator."},
room=request.sid,
)
break
else:
socketio.emit(
'server',
{'msg': f"Unrecognized user '{message}'"},
room=request.sid,
)
elif command in ["/demod", "/unmod"]:
if not socket_to_info[request.sid].admin:
socketio.emit(
'server',
{'msg': f"Unrecognized command '{command}', use '/help' for info."},
room=request.sid,
)
return
message = message.strip().lower()
for sinfo in socket_to_info.values():
if sinfo.username.lower() == message and sinfo.streamer == socket_to_info[request.sid].streamer:
changed = (sinfo.moderator is True)
sinfo.moderator = False
if changed:
socketio.emit(
'server',
{'msg': f"User '{message}' has been demoted from moderator."},
room=request.sid,
)
socketio.emit(
'server',
{'msg': "You have been demoted from moderator."},
room=sinfo.sid,
)
else:
socketio.emit(
'server',
{'msg': f"User '{message}' is not a moderator."},
room=request.sid,
)
break
else:
socketio.emit(
'server',
{'msg': f"Unrecognized user '{message}'"},
room=request.sid,
)
elif command in ["/desc", "/description"]:
if not socket_to_info[request.sid].admin:
socketio.emit(
'server',
{'msg': f"Unrecognized command '{command}', use '/help' for info."},
room=request.sid,
)
return
streamer = socket_to_info[request.sid].streamer
description = emotes(message.strip())
mysql().execute(
"UPDATE streamersettings SET `description` = :description WHERE `username` = :streamer",
{"streamer": streamer, "description": description}
)
socketio.emit(
'server',
{'msg': "Stream description updated!"},
room=request.sid,
)
elif command in ["/password"]:
if not socket_to_info[request.sid].admin:
socketio.emit(
'server',
{'msg': f"Unrecognized command '{command}', use '/help' for info."},
room=request.sid,
)
return
streamer = socket_to_info[request.sid].streamer
if message: