-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathsockets.py
More file actions
1309 lines (1168 loc) · 49.3 KB
/
Copy pathsockets.py
File metadata and controls
1309 lines (1168 loc) · 49.3 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 urllib.request
from flask_socketio import join_room # type: ignore
from PIL import Image
from typing import Any, Dict, List, Optional, Set
from app import socketio, config, request
from events import (
JoinChatEvent,
ChangeNameEvent,
LeaveChatEvent,
ViewerCountEvent,
SendMessageEvent,
SendDrawingEvent,
SendActionEvent,
SendBroadcastEvent,
ModUserEvent,
DemodUserEvent,
MuteUserEvent,
UnmuteUserEvent,
SetDescriptionEvent,
SetViewerPasswordEvent,
insert_event,
)
from helpers import (
PICTOCHAT_IMAGE_WIDTH,
PICTOCHAT_IMAGE_HEIGHT,
emotes,
first_quality,
get_color,
message_length,
mysql,
now,
stream_live,
)
from presence import (
SocketInfo,
PresenceInfo,
presence_lock,
socket_to_info,
socket_to_presence,
stream_count,
users_in_room,
)
background_thread: Optional[object] = None
def background_thread_proc() -> None:
"""
The background polling thread that manages asynchronous messages from the database.
"""
# Grab the initial list of emoji that are supported so that we can delta it occasionally and
# inform clients of emoji changes on the server. Technically there could be a race where we
# add an emote right after somebody loads the page but before the JS connects to us, but the
# likelihood of that is small, so we will live with the bug.
cursor = mysql().execute(
"SELECT alias, uri FROM emotes",
)
validemotes = {f":{result['alias']}:": result['uri'] for result in cursor}
last_update = now()
# Track our known streamer viewcounts.
viewcounts: Dict[str, int] = {}
while True:
# Just yield to the async system.
socketio.sleep(1.0)
# Our connection for this loop.
data = mysql()
# Look up any pending messages that need to be sent.
streamers = set(s.streamer for s in socket_to_info.values() if s.streamer)
usernames = {s.streamer: s.username for s in socket_to_info.values() if s.admin}
colors = {s.streamer: s.htmlcolor for s in socket_to_info.values() if s.admin}
cursor = data.execute("SELECT id, username, type, message FROM pendingmessages")
for result in cursor:
delid = result['id']
username = result['username']
streamer = username.lower()
msgtype = result['type']
message = result['message']
if streamer not in streamers:
continue
# If they're actually chatting, use the name they're currently set to. Otherwise
# default to their stream username. Also, default to their currently set color or
# use black as the default.
actual_name = usernames.get(streamer, username)
actual_color = colors.get(streamer, '#000000')
if msgtype == "server":
insert_event(
data,
SendBroadcastEvent(
now(),
streamer,
message,
)
)
socketio.emit(
'server',
{'msg': message},
room=streamer,
)
elif msgtype == "action":
insert_event(
data,
SendActionEvent(
now(),
streamer,
actual_name,
emotes(message),
)
)
socketio.emit(
'action received',
{
'username': actual_name,
'type': 'admin',
'color': actual_color,
'message': emotes(message),
},
room=streamer,
)
elif msgtype == "normal":
insert_event(
data,
SendMessageEvent(
now(),
streamer,
actual_name,
emotes(message),
)
)
socketio.emit(
'message received',
{
'username': actual_name,
'type': 'admin',
'color': actual_color,
'message': emotes(message),
},
room=streamer,
)
data.execute("DELETE FROM pendingmessages WHERE id = :id LIMIT 1", {'id': delid})
# Figure out if we need to log an analytics event (viewer count changed).
alltracked = set(streamers)
alltracked.update(viewcounts.keys())
alltracked.update(p.streamer for p in socket_to_presence.values() if p.streamer)
for streamer in alltracked:
cursor = data.execute(
"SELECT `key` FROM streamersettings WHERE username = :username",
{"username": streamer},
)
if cursor.rowcount == 1:
result = cursor.fetchone()
# Figure out if the stream itself is live.
live = stream_live(result['key'], first_quality())
# Grab viewer count, active chatters.
viewers = stream_count(streamer) if live else 0
oldviewers = viewcounts.get(streamer, -1)
if viewers != oldviewers:
viewcounts[streamer] = viewers
insert_event(
data,
ViewerCountEvent(
now(),
streamer,
viewers,
)
)
if now() - last_update >= 5:
# Delta our emojis and send the deltas to clients.
cursor = data.execute(
"SELECT alias, uri FROM emotes",
)
updated: Set[str] = set()
for result in cursor:
key = f":{result['alias']}:"
uri = result['uri']
if key not in validemotes:
# This was an addition.
print(f"Broadcasting new emote {key} to all connected clients.")
validemotes[key] = uri
# Emit to all clients, so don't provide a room.
socketio.emit(
'add emote',
{'key': key, 'uri': uri},
)
updated.add(key)
for existing in list(validemotes.keys()):
if existing not in updated:
# This was a deletion.
print(f"Broadcasting deleted emote {existing} to all connected clients.")
del validemotes[existing]
# Emit to all clients, so don't provide a room.
socketio.emit(
'remove emote',
{'key': existing},
)
last_update = now()
with presence_lock:
# Clean up orphaned watchers.
sids = list(socket_to_presence.keys())
oldest = now() - 30
for sid in sids:
if socket_to_presence[sid].timestamp < oldest:
del socket_to_presence[sid]
# If there's nobody left watching, shut ourselves down to save on DB accesses.
if not socket_to_presence:
print("Shutting down polling thread due to no more client sockets.")
global background_thread
background_thread = None
return
def update_presence(sid: Any, streamer: Optional[str]) -> None:
"""
Given a stream SID and a streamer, update the presence info for the purpose of counting
connected SIDs as well as stream viewers.
"""
with presence_lock:
socket_to_presence[sid] = PresenceInfo(sid, streamer)
global background_thread
if background_thread is None:
print("Starting polling thread due to first client socket connection.")
background_thread = socketio.start_background_task(background_thread_proc)
def delete_presence(sid: Any) -> None:
"""
Given a stream SID, delete the presence info for the purpose of counting connected SIDs.
"""
with presence_lock:
if request.sid in socket_to_presence:
del socket_to_presence[request.sid]
@socketio.on('connect') # type: ignore
def connect() -> None:
if request.sid in socket_to_info:
del socket_to_info[request.sid]
# Make sure we track this client so we don't get a premature hang-up.
update_presence(request.sid, None)
@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]
insert_event(
mysql(),
LeaveChatEvent(
now(),
info.streamer,
info.username,
)
)
socketio.emit('disconnected', {'username': info.username, 'type': info.type, 'color': info.htmlcolor, 'users': users_in_room(info.streamer)}, room=info.streamer)
# Explicitly kill the presence since we know they're gone.
delete_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()
update_presence(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
data = mysql()
if message_length(data, json['username']) > 20:
socketio.emit('error', {'msg': 'Username cannot be that long'}, room=request.sid)
return
streamer = json['streamer'].lower()
username = json['username']
first_to_join = True
for user in users_in_room(streamer):
first_to_join = False
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
update_presence(request.sid, streamer)
cursor = data.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
# If we have any pending API-queued messages for this streamer and this is the first chatter to
# join, blow all those pending messages away. This is so that the first person to join a room
# that was previously empty doesn't get jumpscaped with a ton of stale messages.
if first_to_join:
data.execute("DELETE FROM pendingmessages WHERE username = :streamer", {'streamer': streamer})
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': socket_to_info[request.sid].type, 'color': socket_to_info[request.sid].htmlcolor, 'users': users_in_room(streamer)}, room=streamer)
insert_event(
data,
JoinChatEvent(
now(),
streamer,
json['username']
)
)
if admin:
socketio.emit('server', {'msg': 'You have admin rights.'}, room=request.sid)
@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
# Calculate themes.
themes = config.get('themes', [])
if not themes:
themes = ['default']
if len(themes) == 1:
themes = []
# Update user presence information
update_presence(request.sid, socket_to_info[request.sid].streamer)
# Our data connection for various operations.
data = mysql()
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
insert_event(
data,
SendMessageEvent(
now(),
socket_to_info[request.sid].streamer,
socket_to_info[request.sid].username,
emotes(message),
)
)
socketio.emit(
'message received',
{
'username': socket_to_info[request.sid].username,
'type': socket_to_info[request.sid].type,
'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
insert_event(
data,
SendActionEvent(
now(),
socket_to_info[request.sid].streamer,
socket_to_info[request.sid].username,
emotes(message),
)
)
socketio.emit(
'action received',
{
'username': socket_to_info[request.sid].username,
'type': socket_to_info[request.sid].type,
'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 color is None:
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(
'recolor',
{
'username': socket_to_info[request.sid].username,
'type': socket_to_info[request.sid].type,
'color': socket_to_info[request.sid].htmlcolor,
},
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 message_length(data, name) > 20:
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
insert_event(
data,
ChangeNameEvent(
now(),
socket_to_info[request.sid].streamer,
old,
socket_to_info[request.sid].username,
)
)
socketio.emit(
'rename',
{
'newname': socket_to_info[request.sid].username,
'oldname': old,
'type': socket_to_info[request.sid].type,
'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 <action> - perform an action",
"/color <color> - set the color of your name in chat",
"/name <new 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("/chat enabled/hidden - sets the chat to enabled or hidden for new viewers")
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")
messages.append("/rename <user> <new name> - rename user")
if themes:
messages.append("/theme <theme> - change site theme")
messages.append("/themes - list available site themes")
for message in messages:
socketio.emit(
'server',
{'msg': message},
room=request.sid,
)
elif command in ["/users", "/userlist", "/names"]:
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 = data.execute(
"SELECT `description`, `streampass`, `chat` 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()
if result['streampass']:
socketio.emit(
'server',
{'msg': f"Description: {result['description']}"},
room=request.sid,
)
else:
socketio.emit(
'server',
{'msg': "No stream 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,
)
# We want empty columns to represent the default state of enabled.
chatsetting = result['chat'] or "enabled"
socketio.emit(
'server',
{'msg': f"Chat defaults to {chatsetting}"},
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:
if sinfo.admin:
# Stop admins from softlocking themselves, stop mods from muting admin.
socketio.emit(
'server',
{'msg': f"User '{message}' cannot be muted."},
room=request.sid,
)
elif sinfo.moderator and socket_to_info[request.sid].moderator:
# Stop mods from being able to mute each other, only an admin can mute a mod.
socketio.emit(
'server',
{'msg': f"User '{message}' cannot be muted."},
room=request.sid,
)
else:
# User has permission to mute, reply with the status.
changed = (sinfo.muted is False)
sinfo.muted = True
if changed:
insert_event(
data,
MuteUserEvent(
now(),
socket_to_info[request.sid].streamer,
socket_to_info[request.sid].username,
sinfo.username,
)
)
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,
)
# We found our guy, let's bail.
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:
if sinfo.admin:
# This should never happen, but let's guard against it anyway.
socketio.emit(
'server',
{'msg': f"User '{message}' cannot be unmuted."},
room=request.sid,
)
elif sinfo.moderator and socket_to_info[request.sid].moderator:
# Stop mods from being able to unmute each other, only an admin can unmute a mod.
socketio.emit(
'server',
{'msg': f"User '{message}' cannot be unmuted."},
room=request.sid,
)
else:
# User has permission to unmute, reply with the status.
changed = (sinfo.muted is True)
sinfo.muted = False
if changed:
insert_event(
data,
UnmuteUserEvent(
now(),
socket_to_info[request.sid].streamer,
socket_to_info[request.sid].username,
sinfo.username,
)
)
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,
)
# We found our guy, let's bail.
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:
if sinfo.admin:
# Admins shouldn't be able to set themselves or each other as mods.
socketio.emit(
'server',
{'msg': f"User '{message}' cannot be promoted to moderator."},
room=request.sid,
)
else:
# We're good.
changed = (sinfo.moderator is False)
sinfo.moderator = True
if changed:
insert_event(
data,
ModUserEvent(
now(),
socket_to_info[request.sid].streamer,
socket_to_info[request.sid].username,
sinfo.username,
)
)
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:
if sinfo.admin:
# Admins shouldn't be able to set themselves or each other as mods, so this should never
# happen. But, guard against it anyway.
socketio.emit(
'server',
{'msg': f"User '{message}' cannot be demoted from moderator."},
room=request.sid,
)
else:
# We're good.
changed = (sinfo.moderator is True)
sinfo.moderator = False
if changed:
insert_event(
data,
DemodUserEvent(
now(),
socket_to_info[request.sid].streamer,
socket_to_info[request.sid].username,
sinfo.username,
)
)
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 ["/rename"]:
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()
matcher = message.lower()
for sinfo in socket_to_info.values():
if matcher.startswith(sinfo.username.lower()) and sinfo.streamer == socket_to_info[request.sid].streamer:
new_name = message[len(sinfo.username.lower()):]
if bool(new_name) and new_name[0] != ' ':
# This was a partial match, skip it.
continue
new_name = new_name.strip()
if not new_name:
socketio.emit(
'server',
{'msg': f"Unspecified new username for user '{matcher}'"},
room=request.sid,
)
elif message_length(data, new_name) > 20:
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() == new_name.lower():
socketio.emit(
'server',
{'msg': 'Name has already been taken, try a different name.'},
room=request.sid,
)
break
else:
old = sinfo.username
if sinfo.admin:
# Nobody with admin or mod powers should be able to rename an admin.
socketio.emit(
'server',
{'msg': f"User '{old.lower()}' cannot be renamed."},
room=request.sid,
)
elif sinfo.moderator and socket_to_info[request.sid].moderator:
# Stop mods from being able to rename each other, only an admin can rename a mod.
socketio.emit(
'server',
{'msg': f"User '{old.lower()}' cannot be renamed."},
room=request.sid,
)
else:
# User has permission to rename another user, let's execute it.
sinfo.username = new_name
insert_event(
data,
ChangeNameEvent(
now(),
socket_to_info[request.sid].streamer,
old,
new_name,
)