forked from ss14Starlight/space-station-14
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathChatSystem.cs
More file actions
1193 lines (1026 loc) · 49.9 KB
/
Copy pathChatSystem.cs
File metadata and controls
1193 lines (1026 loc) · 49.9 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
using System.Collections.Immutable;
using System.Globalization;
using System.Linq;
using System.Text;
using Content.Server._Starlight.Language;
using Content.Server.Administration.Logs;
using Content.Server.Administration.Managers;
using Content.Server.Chat.Managers;
using Content.Server.GameTicking;
using Content.Server.Speech.EntitySystems;
using Content.Server.Speech.Prototypes;
using Content.Server.Station.Systems;
using Content.Shared._Starlight.Language;
using Content.Shared._Starlight.Speech;
using Content.Shared.ActionBlocker;
using Content.Shared.Administration;
using Content.Shared.CCVar;
using Content.Shared.Chat;
using Content.Shared.Database;
using Content.Shared.Examine;
using Content.Shared.Ghost;
using Content.Shared.IdentityManagement;
using Content.Shared.Mobs.Systems;
using Content.Shared.Players;
using Content.Shared.Players.RateLimiting;
using Content.Shared.Popups;
using Content.Shared.Radio;
// Starlight Start
using Content.Shared.Speech;
using Content.Shared.Station.Components;
using Content.Shared.Whitelist;
using Npgsql.Replication.PgOutput.Messages;
using Robust.Server.Player;
using Robust.Shared.Audio;
using Robust.Shared.Audio.Systems;
using Robust.Shared.Configuration;
using Robust.Shared.Console;
using Robust.Shared.Network;
using Robust.Shared.Player;
using Robust.Shared.Prototypes;
using Robust.Shared.Random;
using Robust.Shared.Replays;
using Robust.Shared.Utility;
// Starlight Start
using Content.Shared.Speech;
using Content.Server._Starlight.Language;
using Content.Shared._Starlight.Chat;
using Content.Shared._Starlight.Language;
using Content.Shared._Starlight.Language.Systems;
using Content.Shared.Popups;
using Content.Shared._Starlight.Radio;
using Content.Server.Radio.EntitySystems;
using Content.Server._Starlight.TextToSpeech;
// Starlight End
namespace Content.Server.Chat.Systems;
// TODO refactor whatever active warzone this class and chatmanager have become
/// <summary>
/// ChatSystem is responsible for in-simulation chat handling, such as whispering, speaking, emoting, etc.
/// ChatSystem depends on ChatManager to actually send the messages.
/// </summary>
public sealed partial class ChatSystem : SharedChatSystem
{
[Dependency] private IReplayRecordingManager _replay = default!;
[Dependency] private IConfigurationManager _configurationManager = default!;
[Dependency] private IChatManager _chatManager = default!;
[Dependency] private IChatSanitizationManager _sanitizer = default!;
[Dependency] private IAdminManager _adminManager = default!;
[Dependency] private IPlayerManager _playerManager = default!;
[Dependency] private IPrototypeManager _prototypeManager = default!;
[Dependency] private IRobustRandom _random = default!;
[Dependency] private IAdminLogManager _adminLogger = default!;
[Dependency] private ActionBlockerSystem _actionBlocker = default!;
[Dependency] private StationSystem _stationSystem = default!;
[Dependency] private MobStateSystem _mobStateSystem = default!;
[Dependency] private SharedAudioSystem _audio = default!;
[Dependency] private ReplacementAccentSystem _wordreplacement = default!;
[Dependency] private ExamineSystemShared _examineSystem = default!;
[Dependency] private LanguageSystem _language = default!; // Starlight
[Dependency] private SharedPopupSystem _popups = default!; // Starlight
public const float DefaultObfuscationFactor = 0.2f; // Percentage of symbols in a whispered message that can be seen even by "far" listeners - Starlight
public readonly Color DefaultSpeakColor = Color.LightGray; // Starlight
private bool _loocEnabled = true;
private bool _deadLoocEnabled;
private bool _critLoocEnabled;
private readonly bool _adminLoocEnabled = true;
public override void Initialize()
{
base.Initialize();
Subs.CVar(_configurationManager, CCVars.LoocEnabled, OnLoocEnabledChanged, true);
Subs.CVar(_configurationManager, CCVars.DeadLoocEnabled, OnDeadLoocEnabledChanged, true);
Subs.CVar(_configurationManager, CCVars.CritLoocEnabled, OnCritLoocEnabledChanged, true);
SubscribeLocalEvent<GameRunLevelChangedEvent>(OnGameChange);
}
private void OnLoocEnabledChanged(bool val)
{
if (_loocEnabled == val) return;
_loocEnabled = val;
_chatManager.DispatchServerAnnouncement(
Loc.GetString(val ? "chat-manager-looc-chat-enabled-message" : "chat-manager-looc-chat-disabled-message"));
}
private void OnDeadLoocEnabledChanged(bool val)
{
if (_deadLoocEnabled == val) return;
_deadLoocEnabled = val;
_chatManager.DispatchServerAnnouncement(
Loc.GetString(val ? "chat-manager-dead-looc-chat-enabled-message" : "chat-manager-dead-looc-chat-disabled-message"));
}
private void OnCritLoocEnabledChanged(bool val)
{
if (_critLoocEnabled == val)
return;
_critLoocEnabled = val;
_chatManager.DispatchServerAnnouncement(
Loc.GetString(val ? "chat-manager-crit-looc-chat-enabled-message" : "chat-manager-crit-looc-chat-disabled-message"));
}
private void OnGameChange(GameRunLevelChangedEvent ev)
{
switch (ev.New)
{
case GameRunLevel.InRound:
if (!_configurationManager.GetCVar(CCVars.OocEnableDuringRound))
_configurationManager.SetCVar(CCVars.OocEnabled, false);
break;
case GameRunLevel.PostRound:
case GameRunLevel.PreRoundLobby:
if (!_configurationManager.GetCVar(CCVars.OocEnableDuringRound))
_configurationManager.SetCVar(CCVars.OocEnabled, true);
break;
}
}
/// <inheritdoc />
public override void TrySendInGameICMessage(
EntityUid source,
SpeechMessage message, // Starlight
InGameICChatType desiredType,
bool hideChat,
bool hideLog = false,
IConsoleShell? shell = null,
ICommonSession? player = null,
string? nameOverride = null,
bool checkRadioPrefix = true,
bool ignoreActionBlocker = false)
{
TrySendInGameICMessage(source, message, desiredType, hideChat ? ChatTransmitRange.HideChat : ChatTransmitRange.Normal, hideLog, shell, player, nameOverride, checkRadioPrefix, ignoreActionBlocker);
}
/// <inheritdoc />
public override void TrySendInGameICMessage(
EntityUid source,
SpeechMessage message, // Starlight
InGameICChatType desiredType,
ChatTransmitRange range,
bool hideLog = false,
IConsoleShell? shell = null,
ICommonSession? player = null,
string? nameOverride = null,
bool checkRadioPrefix = true,
bool ignoreActionBlocker = false,
LanguagePrototype? languageOverride = null // Starlight
)
{
if (TryComp<GhostComponent>(source, out var ghost) && !ghost.BypassGhostChat) // Starlight-edit: ghost admemes
{
// Ghosts can only send dead chat messages, so we'll forward it to InGame OOC.
TrySendInGameOOCMessage(source, message.Text, InGameOOCChatType.Dead, range == ChatTransmitRange.HideChat, shell, player); // Starlight
return;
}
if (player != null && _chatManager.HandleRateLimit(player) != RateLimitStatus.Allowed)
return;
// Sus
if (player?.AttachedEntity is { Valid: true } entity && source != entity)
{
return;
}
if (!CanSendInGame(message.Text, shell, player)) // Starlight
return;
ignoreActionBlocker = CheckIgnoreSpeechBlocker(source, ignoreActionBlocker);
// this method is a disaster
// every second i have to spend working with this code is fucking agony
// scientists have to wonder how any of this was merged
// coding any game admin feature that involves chat code is pure torture
// changing even 10 lines of code feels like waterboarding myself
// and i dont feel like vibe checking 50 code paths
// so we set this here
// todo free me from chat code
if (player != null)
{
_chatManager.EnsurePlayer(player.UserId).AddEntity(GetNetEntity(source));
}
if (desiredType == InGameICChatType.Speak && message.Text.StartsWith(LocalPrefix)) //Starlight
{
// prevent radios and remove prefix.
checkRadioPrefix = false;
message.Text = message.Text[1..]; //Starlight
}
// Starlight begin
LanguagePrototype language;
if (message.Text.StartsWith(SharedLanguageSystem.ChatPrefixChar))
{
language = _language.GetLanguageFromPrefix(source, ref message.Text, out _, true);
// remove prefix from tts property. luckily this is being done before anything else so i get to just set it directly, yay me!
message.Tts = message.Text;
}
else language = languageOverride ?? _language.GetLanguage(source);
// Starlight end
bool shouldCapitalize = (desiredType != InGameICChatType.Emote);
bool shouldPunctuate = _configurationManager.GetCVar(CCVars.ChatPunctuation);
// Capitalizing the word I only happens in English, so we check language here
bool shouldCapitalizeTheWordI = (!CultureInfo.CurrentCulture.IsNeutralCulture && CultureInfo.CurrentCulture.Parent.Name == "en")
|| (CultureInfo.CurrentCulture.IsNeutralCulture && CultureInfo.CurrentCulture.Name == "en");
message.Text = SanitizeInGameICMessage(source, message.Text, out var emoteStr, shouldCapitalize, shouldPunctuate, shouldCapitalizeTheWordI); //Starlight
message.OriginalText = message.Text; // starlight
// Was there an emote in the message? If so, send it.
if (player != null && emoteStr != message.Text && emoteStr != null) // Starlight
{
SendEntityEmote(source, emoteStr, range, nameOverride, language, ignoreActionBlocker); // Starlight
}
// This can happen if the entire string is sanitized out.
if (string.IsNullOrEmpty(message.Text)) //Starlight
return;
// Starlight being
if (language.Speech.ChatTypeOverride is { } chatTypeOverride)
desiredType = chatTypeOverride;
// This message may have a radio prefix, and should then be whispered to the resolved radio channel
if (checkRadioPrefix)
{
if (TryProcessRadioMessage(source, message.Text, out var modMessage, out var channel, out var customChannel))
{
if (language.Speech.RadioChannel is not null)
_language.SendEntityRadioLanguage(source, modMessage, language.Speech.RadioChannel.Value, language);
if (!language.Speech.BlockSpeech)
SendEntityWhisper(source, modMessage, range, channel, nameOverride, language, hideLog, ignoreActionBlocker, customChannel);
return;
}
}
if (language.Speech.RadioChannel is not null)
_language.SendEntityRadioLanguage(source, message.Text, language.Speech.RadioChannel.Value, language);
if (language.Speech.BlockSpeech)
return;
// Starlight end
// Otherwise, send whatever type.
switch (desiredType)
{
case InGameICChatType.Speak:
SendEntitySpeak(source, message, range, nameOverride, language, hideLog, ignoreActionBlocker); // Starlight
break;
case InGameICChatType.Whisper:
SendEntityWhisper(source, message, range, null, nameOverride, language, hideLog, ignoreActionBlocker); // Starlight
break;
case InGameICChatType.Emote:
SendEntityEmote(source, message.Text, range, nameOverride, language, hideLog: hideLog, ignoreActionBlocker: ignoreActionBlocker); // Starlight
break;
}
}
/// <inheritdoc />
public override void TrySendInGameOOCMessage(
EntityUid source,
string message,
InGameOOCChatType type,
bool hideChat,
IConsoleShell? shell = null,
ICommonSession? player = null
)
{
if (!CanSendInGame(message, shell, player))
return;
if (player != null && _chatManager.HandleRateLimit(player) != RateLimitStatus.Allowed)
return;
// It doesn't make any sense for a non-player to send in-game OOC messages, whereas non-players may be sending
// in-game IC messages.
if (player?.AttachedEntity is not { Valid: true } entity || source != entity)
return;
message = SanitizeInGameOOCMessage(message);
var sendType = type;
// If dead player LOOC is disabled, unless you are an admin with Moderator perms, send dead messages to dead chat
if ((_adminManager.IsAdmin(player) && _adminManager.HasAdminFlag(player, AdminFlags.Moderator)) // Override if admin
|| _deadLoocEnabled
|| (!HasComp<GhostComponent>(source) && !_mobStateSystem.IsDead(source))) // Check that player is not dead
{
}
else
sendType = InGameOOCChatType.Dead;
// If crit player LOOC is disabled, don't send the message at all.
// Starlight edit Start
var critCheckEvent = new LoocCritCheckEvent(source);
RaiseLocalEvent(source, critCheckEvent, true);
if (!_critLoocEnabled && _mobStateSystem.IsCritical(source) && !critCheckEvent.AllowCritLooc)
// Starlight edit End
return;
// Systems can differentiate Looc and DeadChat by type, and cancel the speak attempt if necessary.
var ev = new InGameOocMessageAttemptEvent(player, sendType);
RaiseLocalEvent(source, ref ev, true);
if (ev.Cancelled)
return;
switch (sendType)
{
case InGameOOCChatType.Dead:
SendDeadChat(source, player, message, hideChat);
break;
case InGameOOCChatType.Looc:
SendLOOC(source, player, message, hideChat);
break;
}
}
#region Announcements
/// <inheritdoc />
public override void DispatchGlobalAnnouncement(
SpeechMessage message, // Starlight
string? sender = null,
bool playSound = true,
SoundSpecifier? announcementSound = null,
Color? colorOverride = null,
EntityUid? speaker = null // Starlight
)
{
sender ??= Loc.GetString("chat-manager-sender-announcement");
var wrappedMessage = Loc.GetString("chat-manager-sender-announcement-wrap-message", ("sender", sender), ("message", FormattedMessage.EscapeText(message.Text))); // Starlight
_chatManager.ChatMessageToAll(ChatChannel.Radio, message.Text, wrappedMessage, default, false, true, colorOverride); // Starlight
if (playSound)
{
_audio.PlayGlobal(announcementSound ?? DefaultAnnouncementSound, Filter.Broadcast(), true, AudioParams.Default.WithVolume(-2f));
}
// Starlight start
RaiseLocalEvent(new AnnouncementSpokeEvent
{
Message = message,
Receivers = Filter.Broadcast(),
SpeakerUid = speaker.HasValue ? GetNetEntity(speaker.Value) : null,
AnnouncementSound = announcementSound,
});
// Starlight end
_adminLogger.Add(LogType.Chat, LogImpact.Low, $"Global station announcement from {sender}: {message.Text}");// Starlight
}
/// <inheritdoc />
public override void DispatchFilteredAnnouncement(
Filter filter,
SpeechMessage message, // Starlight
EntityUid? source = null,
string? sender = null,
bool playSound = true,
SoundSpecifier? announcementSound = null,
Color? colorOverride = null,
bool recordToReplay = true) // Starlight
{
sender ??= Loc.GetString("chat-manager-sender-announcement");
var wrappedMessage = Loc.GetString("chat-manager-sender-announcement-wrap-message", ("sender", sender), ("message", FormattedMessage.EscapeText(message.Text))); // Starlight
_chatManager.ChatMessageToManyFiltered(filter, ChatChannel.Radio, message.Text, wrappedMessage, source ?? default, false, recordToReplay, colorOverride); // Starlight
if (playSound)
{
_audio.PlayGlobal(announcementSound ?? DefaultAnnouncementSound, filter, recordToReplay, AudioParams.Default.WithVolume(-2f)); // Starlight-edit
}
// Starlight start
RaiseLocalEvent(new AnnouncementSpokeEvent
{
AnnouncementSound = announcementSound,
Message = message,
Receivers = filter
});
// Starlight end
_adminLogger.Add(LogType.Chat, LogImpact.Low, $"Station Announcement from {sender}: {message.Text}");
}
/// <inheritdoc />
public override void DispatchStationAnnouncement(
EntityUid source,
SpeechMessage message, // Starlight
string? sender = null,
bool playDefaultSound = true,
SoundSpecifier? announcementSound = null,
Color? colorOverride = null)
{
sender ??= Loc.GetString("chat-manager-sender-announcement");
var wrappedMessage = Loc.GetString("chat-manager-sender-announcement-wrap-message", ("sender", sender), ("message", FormattedMessage.EscapeText(message.Text))); // Starlight
var station = _stationSystem.GetOwningStation(source);
if (station == null)
{
// you can't make a station announcement without a station
return;
}
if (!TryComp<StationDataComponent>(station, out var stationDataComp)) return;
var filter = _stationSystem.GetInStation(stationDataComp);
_chatManager.ChatMessageToManyFiltered(filter, ChatChannel.Radio, message.Text, wrappedMessage, source, false, true, colorOverride); // Starlight
if (playDefaultSound)
{
_audio.PlayGlobal(announcementSound ?? DefaultAnnouncementSound, filter, true, AudioParams.Default.WithVolume(-2f));
}
// Starlight start
RaiseLocalEvent(new AnnouncementSpokeEvent
{
AnnouncementSound = announcementSound,
Message = message,
Receivers = filter
});
// Starlight end
_adminLogger.Add(LogType.Chat, LogImpact.Low, $"Station Announcement on {station} from {sender}: {message.Text}"); // Starlight
}
/// Starlight Start:
/// <summary>
/// Dispatches an announcement from the Communications Console, replacing the default announcement.
/// </summary>
/// <param name="source">The entity making the announcement (Communications Console entity)</param>
/// <param name="message">The contents of the message</param>
/// <param name="sender">The sender name</param>
/// <param name="playSound">Play the announcement sound</param>
/// <param name="announcementSound">Sound to play</param>
/// <param name="colorOverride">Optional color for the announcement message</param>
public void DispatchCommunicationsConsoleAnnouncement(
EntityUid source,
string message,
string? sender = null,
bool playSound = true,
SoundSpecifier? announcementSound = null,
EntityUid? speaker = null, // Starlight
Color? colorOverride = null)
{
sender ??= Loc.GetString("chat-manager-sender-announcement");
var wrappedMessage = Loc.GetString("chat-manager-sender-announcement-wrap-message", ("sender", sender), ("message", FormattedMessage.EscapeText(message)));
var station = _stationSystem.GetOwningStation(source);
if (station == null)
{
// you can't make a communications console announcement without a station
return;
}
if (!EntityManager.TryGetComponent<StationDataComponent>(station, out var stationDataComp)) return;
var filter = _stationSystem.GetInStation(stationDataComp);
// Custom behavior: For example, change the chat channel or message formatting here if needed
_chatManager.ChatMessageToManyFiltered(filter, ChatChannel.Radio, message, wrappedMessage, source, false, true, colorOverride);
if (playSound)
{
var commsConsoleSound = announcementSound ?? new SoundPathSpecifier("/Audio/_Starlight/Announcements/announce2.ogg");
var resolvedSound = _audio.ResolveSound(commsConsoleSound);
_audio.PlayGlobal(resolvedSound, filter, true, AudioParams.Default.WithVolume(-2f));
}
RaiseLocalEvent(new AnnouncementSpokeEvent
{
AnnouncementSound = announcementSound,
Message = message,
SpeakerUid = speaker.HasValue ? GetNetEntity(speaker.Value) : null,
Receivers = filter
});
_adminLogger.Add(LogType.Chat, LogImpact.Low, $"Communications Console Announcement on {station} from {sender}: {message}");
}
// Starlight End
#endregion
#region Private API
private void SendEntitySpeak(
EntityUid source,
SpeechMessage message, // Starlight
ChatTransmitRange range,
string? nameOverride,
LanguagePrototype language, // Starlight
bool hideLog = false,
bool ignoreActionBlocker = false
)
{
if (!_actionBlocker.CanSpeak(source) && !ignoreActionBlocker)
return;
message = TransformSpeech(source, message, language); // Starlight-edit: Languages, tts v5.0
if (message.Text.Length == 0) // Starlight
return;
var original = message.Text; // Starlight
var speech = GetSpeechVerb(source, message.Text); // Starlight
// get the entity's apparent name (if no override provided).
string name;
if (nameOverride != null)
{
name = nameOverride;
}
else
{
var nameEv = new TransformSpeakerNameEvent(source, Name(source));
RaiseLocalEvent(source, nameEv);
name = nameEv.VoiceName;
// Check for a speech verb override
if (nameEv.SpeechVerb != null && _prototypeManager.Resolve(nameEv.SpeechVerb, out var proto))
speech = proto;
}
name = FormattedMessage.EscapeText(name);
// Starlight - Start
var wrappedMessage = WrapPublicMessage(source, name, message.Text, language: language); // Starlight
// The chat message obfuscated via language obfuscation.
var obfuscated = SanitizeInGameICMessage(source, _language.ObfuscateSpeech(message.Text, language), out var emoteStr, true, _configurationManager.GetCVar(CCVars.ChatPunctuation), // Starlight
(!CultureInfo.CurrentCulture.IsNeutralCulture && CultureInfo.CurrentCulture.Parent.Name == "en")
|| (CultureInfo.CurrentCulture.IsNeutralCulture && CultureInfo.CurrentCulture.Name == "en"));
// The language-obfuscated message wrapped in a "x says y" string.
var wrappedObfuscated = WrapPublicMessage(source, name, obfuscated, language: language, obfuscated: true);
// Starlight End
SendInVoiceRange(ChatChannel.Local, name, message.Text, wrappedMessage, obfuscated, wrappedObfuscated, source, range, languageOverride: language); // Starlight-edit: Languages
var ev = new EntitySpokeEvent(source, message, null, null, false, language); // Starlight-edit: Languages
RaiseLocalEvent(source, ev, true);
// To avoid logging any messages sent by entities that are not players, like vendors, cloning, etc.
// Also doesn't log if hideLog is true.
if (!HasComp<ActorComponent>(source) || hideLog)
return;
if (original == message.Text) // Starlight
{
if (name != Name(source))
_adminLogger.Add(LogType.Chat, LogImpact.Low, $"Say from {source} as {name}: {original}."); // Starlight
else
_adminLogger.Add(LogType.Chat, LogImpact.Low, $"Say from {source}: {original}."); // Starlight
}
else
{
if (name != Name(source))
_adminLogger.Add(LogType.Chat, LogImpact.Low,
$"Say from {source} as {name}, original: {original}, transformed: {message}."); // Starlight
else
_adminLogger.Add(LogType.Chat, LogImpact.Low,
$"Say from {source}, original: {original}, transformed: {message}."); // Starlight
}
}
private void SendEntityWhisper(
EntityUid source,
SpeechMessage message, // Starlight
ChatTransmitRange range,
RadioChannelPrototype? channel,
string? nameOverride,
LanguagePrototype language, // Starlight
bool hideLog = false,
bool ignoreActionBlocker = false,
CustomRadioChannelData? customChannel = null // Starlight
)
{
if (!_actionBlocker.CanSpeak(source) && !ignoreActionBlocker)
return;
var original = message.Text; // Starlight
message.Text = FormattedMessage.RemoveMarkupOrThrow(message.Text);
message = TransformSpeech(source, message, language); // Starlight-edit: Languages, tts v5.0
if (message.Text.Length == 0) // Starlight
return;
// get the entity's name by visual identity (if no override provided).
string nameIdentity = FormattedMessage.EscapeText(nameOverride ?? Identity.Name(source, EntityManager));
// get the entity's name by voice (if no override provided).
string name;
if (nameOverride != null)
{
name = nameOverride;
}
else
{
var nameEv = new TransformSpeakerNameEvent(source, Name(source));
RaiseLocalEvent(source, nameEv);
name = nameEv.VoiceName;
}
name = FormattedMessage.EscapeText(name);
var languageObfuscatedMessage = SanitizeInGameICMessage(source, _language.ObfuscateSpeech(message.Text, language), out var emoteStr, true, _configurationManager.GetCVar(CCVars.ChatPunctuation),
(!CultureInfo.CurrentCulture.IsNeutralCulture && CultureInfo.CurrentCulture.Parent.Name == "en")
|| (CultureInfo.CurrentCulture.IsNeutralCulture && CultureInfo.CurrentCulture.Name == "en")); // Starlight
foreach (var (session, data) in GetRecipients(source, WhisperMuffledRange, true)) // Starlight-edit
{
if (session.AttachedEntity is not { Valid: true } listener) // Starlight-edit: Languages
continue;
// Moffstation - Start - Radio Host, hide chat messages from station radio
var rangeCheck = MessageRangeCheck(session, data, range);
if (rangeCheck == MessageRangeCheckResult.Disallowed)
// Moffstation - End
continue; // Won't get logged to chat, and ghosts are too far away to see the pop-up, so we just won't send it to them.
// Starlight - Start
var canUnderstandLanguage = _language.CanUnderstand(listener, language.ID);
// How the entity perceives the message depends on whether it can understand its language
var perceivedMessage = canUnderstandLanguage ? message.Text : languageObfuscatedMessage; // Starlight
var obfuscated = canUnderstandLanguage != true;
var whisperClearRange = WhisperClearRange;
var whisperMuffledRange = WhisperMuffledRange;
if (TryComp<ChatListenerRangeComponent>(listener, out var rangeComp))
{
whisperClearRange = rangeComp.WhisperClearRange;
whisperMuffledRange = rangeComp.WhisperMuffledRange;
}
// Result is the intermediate message derived from the perceived one via obfuscation
// Wrapped message is the result wrapped in an "x says y" string
string result, wrappedMessage;
if (data.Range <= whisperClearRange || data.Observer)
{
// Scenario 1: the listener can clearly understand the message
result = perceivedMessage;
wrappedMessage = WrapWhisperMessage(source, "chat-manager-entity-whisper-wrap-message", name, result, language, obfuscated);
}
else if (_examineSystem.InRangeUnOccluded(source, listener, whisperMuffledRange))
{
// Scenario 2: if the listener is too far, they only hear fragments of the message
result = ObfuscateMessageReadability(perceivedMessage);
wrappedMessage = WrapWhisperMessage(source, "chat-manager-entity-whisper-wrap-message", nameIdentity, result, language, obfuscated);
}
else
{
// Scenario 3: If listener is too far and has no line of sight, they can't identify the whisperer's identity
result = ObfuscateMessageReadability(perceivedMessage);
wrappedMessage = WrapWhisperMessage(source, "chat-manager-entity-whisper-unknown-wrap-message", string.Empty, result, language, obfuscated);
}
_chatManager.ChatMessageToOne(ChatChannel.Whisper, result, wrappedMessage, source, rangeCheck == MessageRangeCheckResult.HideChat, session.Channel); // Moffstation - Radio Host, hide chat messages from station radio
// Starlight - End
}
var replayWrap = WrapWhisperMessage(source, "chat-manager-entity-whisper-wrap-message", name, message.Text, language); // Starlight-edit: Languages
_replay.RecordServerMessage(new ChatMessage(ChatChannel.Whisper, message.Text, replayWrap, GetNetEntity(source), null, MessageRangeHideChatForReplay(range))); // Starlight-edit: Languages
//Starlight begin
var ev = customChannel is not null
? new EntitySpokeEvent(source, message, languageObfuscatedMessage, true, language, customChannel)
: new EntitySpokeEvent(source, message, channel, languageObfuscatedMessage, true, language);
//Starlight end
RaiseLocalEvent(source, ev, true);
if (!hideLog)
if (original == message.Text) // Starlight
{
if (name != Name(source))
_adminLogger.Add(LogType.Chat, LogImpact.Low, $"Whisper from {source} as {name}: {original}.");
else
_adminLogger.Add(LogType.Chat, LogImpact.Low, $"Whisper from {source}: {original}.");
}
else
{
if (name != Name(source))
_adminLogger.Add(LogType.Chat, LogImpact.Low,
$"Whisper from {source} as {name}, original: {original}, transformed: {message}.");
else
_adminLogger.Add(LogType.Chat, LogImpact.Low,
$"Whisper from {source}, original: {original}, transformed: {message}.");
}
}
protected override void SendEntityEmote(
EntityUid source,
string action,
ChatTransmitRange range,
string? nameOverride,
LanguagePrototype language, // Starlight-edit: Languages
bool hideLog = false,
bool checkEmote = true,
bool ignoreActionBlocker = false,
NetUserId? author = null
)
{
if (!_actionBlocker.CanEmote(source) && !ignoreActionBlocker)
return;
// get the entity's apparent name (if no override provided).
var ent = Identity.Entity(source, EntityManager);
string name = FormattedMessage.EscapeText(nameOverride ?? Name(ent));
// Emotes use Identity.Name, since it doesn't actually involve your voice at all.
var wrappedMessage = Loc.GetString("chat-manager-entity-me-wrap-message",
("entityName", name),
("entity", ent),
("message", FormattedMessage.RemoveMarkupOrThrow(action)));
if (checkEmote &&
!TryEmoteChatInput(source, action))
return;
SendInVoiceRange(ChatChannel.Emotes, name, action, wrappedMessage, obfuscated: "", obfuscatedWrappedMessage: "", source, range, author); // Starlight
if (!hideLog)
if (name != Name(source))
_adminLogger.Add(LogType.Chat, LogImpact.Low, $"Emote from {source} as {name}: {action}");
else
_adminLogger.Add(LogType.Chat, LogImpact.Low, $"Emote from {source}: {action}");
}
// ReSharper disable once InconsistentNaming
private void SendLOOC(EntityUid source, ICommonSession player, string message, bool hideChat)
{
var name = FormattedMessage.EscapeText(Identity.Name(source, EntityManager));
if (_adminManager.IsAdmin(player))
{
if (!_adminLoocEnabled) return;
}
else if (!_loocEnabled) return;
// If crit player LOOC is disabled, don't send the message at all.
// Starlight edit Start
var critCheckEvent = new LoocCritCheckEvent(source);
RaiseLocalEvent(source, critCheckEvent, true);
if (!_critLoocEnabled && _mobStateSystem.IsCritical(source) && !critCheckEvent.AllowCritLooc)
// Starlight edit End
return;
var wrappedMessage = Loc.GetString("chat-manager-entity-looc-wrap-message",
("entityName", name),
("message", FormattedMessage.EscapeText(message)));
SendInVoiceRange(ChatChannel.LOOC, name, message, wrappedMessage,
obfuscated: string.Empty,
obfuscatedWrappedMessage: string.Empty, // will be skipped anyway
source,
hideChat ? ChatTransmitRange.HideChat : ChatTransmitRange.Normal,
player.UserId,
languageOverride: LanguageSystem.Universal); // Starlight
// Starlight Start: Telephone Looc
var loocEv = new EntityLoocEvent(source, message);
RaiseLocalEvent(source, loocEv, true);
// Starlight End
_adminLogger.Add(LogType.Chat, LogImpact.Low, $"LOOC from {player:Player}: {message}");
}
private void SendDeadChat(EntityUid source, ICommonSession player, string message, bool hideChat)
{
var clients = GetDeadChatClients();
var playerName = Name(source);
string wrappedMessage;
if (_adminManager.IsAdmin(player))
{
wrappedMessage = Loc.GetString("chat-manager-send-admin-dead-chat-wrap-message",
("adminChannelName", Loc.GetString("chat-manager-admin-channel-name")),
("userName", player.Channel.UserName),
("message", FormattedMessage.EscapeText(message)));
_adminLogger.Add(LogType.Chat, LogImpact.Low, $"Admin dead chat from {source}: {message}");
}
else
{
wrappedMessage = Loc.GetString("chat-manager-send-dead-chat-wrap-message",
("deadChannelName", Loc.GetString("chat-manager-dead-channel-name")),
("playerName", (playerName)),
("message", FormattedMessage.EscapeText(message)));
_adminLogger.Add(LogType.Chat, LogImpact.Low, $"Dead chat from {source}: {message}");
}
_chatManager.ChatMessageToMany(ChatChannel.Dead, message, wrappedMessage, source, hideChat, true, clients.ToList(), author: player.UserId);
}
#endregion
#region Utility
private enum MessageRangeCheckResult
{
Disallowed,
HideChat,
Full
}
/// <summary>
/// If hideChat should be set as far as replays are concerned.
/// </summary>
private bool MessageRangeHideChatForReplay(ChatTransmitRange range)
{
return range == ChatTransmitRange.HideChat;
}
/// <summary>
/// Checks if a target as returned from GetRecipients should receive the message.
/// Keep in mind data.Range is -1 for out of range observers.
/// </summary>
private MessageRangeCheckResult MessageRangeCheck(ICommonSession session, ICChatRecipientData data, ChatTransmitRange range)
{
var initialResult = MessageRangeCheckResult.Full;
switch (range)
{
case ChatTransmitRange.Normal:
initialResult = MessageRangeCheckResult.Full;
break;
case ChatTransmitRange.GhostRangeLimit:
initialResult = (data.Observer && data.Range < 0 && !_adminManager.IsAdmin(session)) ? MessageRangeCheckResult.HideChat : MessageRangeCheckResult.Full;
break;
case ChatTransmitRange.HideChat:
initialResult = MessageRangeCheckResult.HideChat;
break;
case ChatTransmitRange.NoGhosts:
initialResult = (data.Observer && !_adminManager.IsAdmin(session)) ? MessageRangeCheckResult.Disallowed : MessageRangeCheckResult.Full;
break;
}
var insistHideChat = data.HideChatOverride ?? false;
var insistNoHideChat = !(data.HideChatOverride ?? true);
if (insistHideChat && initialResult == MessageRangeCheckResult.Full)
return MessageRangeCheckResult.HideChat;
if (insistNoHideChat && initialResult == MessageRangeCheckResult.HideChat)
return MessageRangeCheckResult.Full;
return initialResult;
}
/// <summary>
/// Sends a chat message to the given players in range of the source entity.
/// </summary>
private void SendInVoiceRange(ChatChannel channel, string name, string message, string wrappedMessage, string obfuscated, string obfuscatedWrappedMessage, EntityUid source, ChatTransmitRange range, NetUserId? author = null, LanguagePrototype? languageOverride = null) // Starlight
{
// Starlight - Start
var ignoreLanguage = channel.IsExemptFromLanguages();
var language = languageOverride ?? _language.GetLanguage(source);
if (!ignoreLanguage && language.Speech.RequireHands && !_actionBlocker.CanInteract(source, null))
{
_popups.PopupEntity(Loc.GetString("chat-manager-language-requires-hands"), source, PopupType.Medium);
return;
}
// Starlight - End
foreach (var (session, data) in GetRecipients(source, VoiceRange))
{
var entRange = MessageRangeCheck(session, data, range);
if (entRange == MessageRangeCheckResult.Disallowed)
continue;
var entHideChat = entRange == MessageRangeCheckResult.HideChat;
// Starlight - start
if (session.AttachedEntity is not { Valid: true } playerEntity)
continue;
EntityUid listener = session.AttachedEntity.Value;
// If the channel does not support languages, or the entity can understand the message, send the original message, otherwise send the obfuscated version
if (ignoreLanguage || _language.CanUnderstand(listener, language.ID))
_chatManager.ChatMessageToOne(channel, message, wrappedMessage, source, entHideChat, session.Channel, author: author);
else
_chatManager.ChatMessageToOne(channel, obfuscated, obfuscatedWrappedMessage, source, entHideChat, session.Channel, author: author);
// Starlight - end
}
_replay.RecordServerMessage(new ChatMessage(channel, message, wrappedMessage, GetNetEntity(source), null, MessageRangeHideChatForReplay(range)));
}
/// <summary>
/// Returns true if the given player is 'allowed' to send the given message, false otherwise.
/// </summary>
private bool CanSendInGame(string message, IConsoleShell? shell = null, ICommonSession? player = null)
{
// Non-players don't have to worry about these restrictions.
if (player == null)
return true;
var mindContainerComponent = player.ContentData()?.Mind;
if (mindContainerComponent == null)
{
shell?.WriteError("You don't have a mind!");
return false;
}
if (player.AttachedEntity is not { Valid: true } _)
{
shell?.WriteError("You don't have an entity!");
return false;
}
return !_chatManager.MessageCharacterLimit(player, message);
}
// ReSharper disable once InconsistentNaming
private string SanitizeInGameICMessage(EntityUid source, string message, out string? emoteStr, bool capitalize = true, bool punctuate = false, bool capitalizeTheWordI = true, bool noDisallowedCharacters = true) // Starlight
{
var newMessage = SanitizeMessageReplaceWords(message.Trim()).Text; // Starlight
GetRadioKeycodePrefix(source, newMessage, out newMessage, out var prefix);
// Sanitize it first as it might change the word order
_sanitizer.TrySanitizeEmoteShorthands(newMessage, source, out newMessage, out emoteStr);
if (capitalize)
newMessage = SanitizeMessageCapital(newMessage);
if (capitalizeTheWordI)
newMessage = SanitizeMessageCapitalizeTheWordI(newMessage, "i");
if (punctuate)
newMessage = SanitizeMessagePeriod(newMessage);
if (noDisallowedCharacters) // Starlight
newMessage = SanitizeMessageOfEvilCharacters(newMessage); // Starlight
return prefix + newMessage;
}
private string SanitizeInGameOOCMessage(string message)
{
var newMessage = message.Trim();
newMessage = FormattedMessage.EscapeText(newMessage);
return newMessage;
}
public SpeechMessage TransformSpeech(EntityUid sender, SpeechMessage message, LanguagePrototype language) // Starlight
{
if (!language.Speech.RequireSpeech) // Starlight
return message; // Do not apply speech accents if there's no speech involved.
var ev = new TransformSpeechEvent(sender, message);
RaiseLocalEvent(sender, ev, true);
return ev.Message;// Starlight
}
public bool CheckIgnoreSpeechBlocker(EntityUid sender, bool ignoreBlocker)
{
if (ignoreBlocker)
return ignoreBlocker;
var ev = new CheckIgnoreSpeechBlockerEvent(sender, ignoreBlocker);
RaiseLocalEvent(sender, ev, true);
return ev.IgnoreBlocker;
}
private IEnumerable<INetChannel> GetDeadChatClients()
{
return Filter.Empty()
.AddWhereAttachedEntity(HasComp<GhostComponent>)
.Recipients
.Union(_adminManager.ActiveAdmins)
.Select(p => p.Channel);
}
private string SanitizeMessagePeriod(string message)
{
if (string.IsNullOrEmpty(message))
return message;
// Adds a period if the last character is a letter.
if (char.IsLetter(message[^1]))
message += ".";
return message;
}
public static readonly ProtoId<ReplacementAccentPrototype> ChatSanitize_Accent = "chatsanitize";
public SpeechMessage SanitizeMessageReplaceWords(SpeechMessage message) //Starlight
{
if (string.IsNullOrEmpty(message.Text)) return message;
var msg = _wordreplacement.ApplyReplacements(message, ChatSanitize_Accent); //Starlight