fish-station/Content.Server/Administration/Systems/BwoinkSystem.cs
Vigers Ray 2da8b9f545 Merge remote-tracking branch 'space-wizards/master'
# Conflicts:
#	.github/CODEOWNERS
#	.github/PULL_REQUEST_TEMPLATE.md
#	Content.Client/Changelog/ChangelogTab.xaml.cs
#	Content.Client/Chemistry/UI/ChemMasterWindow.xaml
#	Content.Client/Entry/EntryPoint.cs
#	Content.Client/GameTicking/Managers/ClientGameTicker.cs
#	Content.Client/Launcher/LauncherConnectingGui.xaml
#	Content.Client/Lobby/LobbyState.cs
#	Content.Client/Lobby/UI/LobbyGui.xaml
#	Content.Client/Paper/UI/PaperWindow.xaml.cs
#	Content.Client/StationRecords/GeneralStationRecordConsoleWindow.xaml.cs
#	Content.Client/Stylesheets/StyleNano.cs
#	Content.Client/UserInterface/Screens/SeparatedChatGameScreen.xaml
#	Content.Client/UserInterface/Systems/Ghost/Widgets/GhostGui.xaml.cs
#	Content.Client/UserInterface/Systems/MenuBar/Widgets/GameTopMenuBar.xaml
#	Content.IntegrationTests/Tests/Destructible/DestructibleDamageGroupTest.cs
#	Content.IntegrationTests/Tests/PostMapInitTest.cs
#	Content.IntegrationTests/Tests/Power/StationPowerTests.cs
#	Content.Packaging/ServerPackaging.cs
#	Content.Server/Administration/Systems/AdminVerbSystem.Smites.cs
#	Content.Server/Administration/Systems/AdminVerbSystem.Tools.cs
#	Content.Server/Atmos/TileAtmosphere.cs
#	Content.Server/Bible/BibleSystem.cs
#	Content.Server/Chat/Systems/ChatSystem.cs
#	Content.Server/Content.Server.csproj
#	Content.Server/Discord/DiscordLink/DiscordLink.cs
#	Content.Server/GameTicking/GameTicker.LobbyBackground.cs
#	Content.Server/GameTicking/GameTicker.Spawning.cs
#	Content.Server/Ghost/GhostSystem.cs
#	Content.Server/Kitchen/Components/MicrowaveComponent.cs
#	Content.Server/Kitchen/EntitySystems/MicrowaveSystem.cs
#	Content.Server/Mech/Systems/MechSystem.cs
#	Content.Server/Medical/CrewMonitoring/CrewMonitoringConsoleSystem.cs
#	Content.Server/Medical/DefibrillatorSystem.cs
#	Content.Server/Medical/HealthAnalyzerSystem.cs
#	Content.Server/Radio/EntitySystems/HeadsetSystem.cs
#	Content.Server/Remotes/DoorRemoteSystem.cs
#	Content.Server/RoundEnd/RoundEndSystem.cs
#	Content.Server/Shuttles/Systems/DockingSystem.Shuttle.cs
#	Content.Server/Silicons/Borgs/BorgSystem.Transponder.cs
#	Content.Server/Tips/TipsSystem.cs
#	Content.Server/Traitor/Uplink/UplinkSystem.cs
#	Content.Server/Weapons/Ranged/Systems/GunSystem.cs
#	Content.Server/Zombies/ZombieSystem.Transform.cs
#	Content.Server/Zombies/ZombieSystem.cs
#	Content.Shared/Bed/BedSystem.cs
#	Content.Shared/Blocking/BlockingSystem.User.cs
#	Content.Shared/Buckle/SharedBuckleSystem.Buckle.cs
#	Content.Shared/Chat/SharedSuicideSystem.cs
#	Content.Shared/Chemistry/Components/HyposprayComponent.cs
#	Content.Shared/Chemistry/EntitySystems/HypospraySystem.cs
#	Content.Shared/Chemistry/EntitySystems/ScoopableSolutionSystem.cs
#	Content.Shared/Chemistry/EntitySystems/SolutionTransferSystem.cs
#	Content.Shared/Chemistry/Events/HyposprayEvents.cs
#	Content.Shared/Content.Shared.csproj
#	Content.Shared/Damage/Systems/DamageableSystem.cs
#	Content.Shared/Friction/TileFrictionController.cs
#	Content.Shared/GameTicking/SharedGameTicker.cs
#	Content.Shared/Interaction/InteractHand.cs
#	Content.Shared/Lock/LockSystem.cs
#	Content.Shared/Medical/Healing/HealingSystem.cs
#	Content.Shared/Mobs/Systems/MobStateSystem.Subscribers.cs
#	Content.Shared/Nutrition/EntitySystems/HungerSystem.cs
#	Content.Shared/Silicons/StationAi/SharedStationAiSystem.Airlock.cs
#	Content.Shared/Throwing/ThrowingSystem.cs
#	Content.Shared/Trigger/Systems/TriggerOnHitscanSystem.cs
#	Content.Shared/Weapons/Hitscan/Systems/HitscanBasicDamageSystem.cs
#	Content.Shared/Weapons/Melee/SharedMeleeWeaponSystem.cs
#	Content.Shared/Weapons/Ranged/Components/BatteryWeaponFireModesComponent.cs
#	Content.Shared/Weapons/Ranged/Components/HitscanBatteryAmmoProviderComponent.cs
#	Content.Shared/Weapons/Ranged/Systems/BatteryWeaponFireModesSystem.cs
#	Content.Shared/Weapons/Ranged/Systems/SharedGunSystem.Ballistic.cs
#	Content.Shared/Weapons/Ranged/Systems/SharedGunSystem.Battery.cs
#	Content.Shared/Zombies/ZombieComponent.cs
#	Content.Shared/_Sunrise/Lobby/LobbyBackgroundPrototype.cs
#	README.md
#	Resources/Locale/en-US/_strings/borg/borg.ftl
#	Resources/Locale/en-US/_strings/chemistry/components/hypospray-component.ftl
#	Resources/Locale/en-US/_strings/chemistry/components/injector-component.ftl
#	Resources/Locale/en-US/_strings/commands/pauseatmos-command.ftl
#	Resources/Locale/en-US/_strings/commands/quick-inspect-command.ftl
#	Resources/Locale/en-US/_strings/commands/show-wallmounts-command.ftl
#	Resources/Locale/en-US/_strings/commands/substepatmos-command.ftl
#	Resources/Locale/en-US/_strings/fluids/components/equip-spray-component.ftl
#	Resources/Locale/en-US/_strings/game-ticking/game-presets/preset-revolutionary.ftl
#	Resources/Locale/en-US/_strings/job/job-names.ftl
#	Resources/Locale/en-US/_strings/lobby/lobby-state-background.ftl
#	Resources/Locale/en-US/_strings/reagents/meta/medicine.ftl
#	Resources/Locale/en-US/_strings/reagents/meta/physical-desc.ftl
#	Resources/Locale/en-US/_strings/silicons/borg-module.ftl
#	Resources/Locale/en-US/_strings/store/changeling-catalog.ftl
#	Resources/Locale/en-US/_strings/store/currency.ftl
#	Resources/Locale/en-US/_strings/store/store.ftl
#	Resources/Locale/en-US/_strings/store/uplink-catalog.ftl
#	Resources/Prototypes/Body/Organs/slime.yml
#	Resources/Prototypes/Catalog/Fills/Backpacks/backpack.yml
#	Resources/Prototypes/Catalog/Fills/Backpacks/duffelbag.yml
#	Resources/Prototypes/Catalog/Fills/Boxes/ammunition.yml
#	Resources/Prototypes/Catalog/Fills/Boxes/emergency.yml
#	Resources/Prototypes/Catalog/Fills/Crates/antag.yml
#	Resources/Prototypes/Catalog/Fills/Crates/armory.yml
#	Resources/Prototypes/Catalog/Fills/Crates/botany.yml
#	Resources/Prototypes/Catalog/Fills/Crates/fun.yml
#	Resources/Prototypes/Catalog/Fills/Crates/medical.yml
#	Resources/Prototypes/Catalog/Fills/Crates/salvage.yml
#	Resources/Prototypes/Catalog/Fills/Crates/security.yml
#	Resources/Prototypes/Catalog/Fills/Crates/service.yml
#	Resources/Prototypes/Catalog/Fills/Crates/syndicate.yml
#	Resources/Prototypes/Catalog/Fills/Items/belt.yml
#	Resources/Prototypes/Catalog/Fills/Items/briefcases.yml
#	Resources/Prototypes/Catalog/Fills/Items/firstaidkits.yml
#	Resources/Prototypes/Catalog/Fills/Items/toolboxes.yml
#	Resources/Prototypes/Catalog/Fills/Lockers/dressers.yml
#	Resources/Prototypes/Catalog/Fills/Lockers/heads.yml
#	Resources/Prototypes/Catalog/Fills/Lockers/security.yml
#	Resources/Prototypes/Catalog/VendingMachines/Inventories/theater.yml
#	Resources/Prototypes/Catalog/uplink_catalog.yml
#	Resources/Prototypes/Entities/Clothing/Back/backpacks.yml
#	Resources/Prototypes/Entities/Clothing/Shoes/magboots.yml
#	Resources/Prototypes/Entities/Debugging/debug_sweps.yml
#	Resources/Prototypes/Entities/Debugging/stress_test.yml
#	Resources/Prototypes/Entities/Markers/Spawners/Random/anomaly.yml
#	Resources/Prototypes/Entities/Markers/Spawners/Random/toy.yml
#	Resources/Prototypes/Entities/Mobs/Cyborgs/base_borg_chassis.yml
#	Resources/Prototypes/Entities/Mobs/Cyborgs/xenoborgs.yml
#	Resources/Prototypes/Entities/Mobs/NPCs/animals.yml
#	Resources/Prototypes/Entities/Mobs/NPCs/carp.yml
#	Resources/Prototypes/Entities/Objects/Devices/base_handheld.yml
#	Resources/Prototypes/Entities/Objects/Fun/Instruments/instruments_misc.yml
#	Resources/Prototypes/Entities/Objects/Fun/dice_bag.yml
#	Resources/Prototypes/Entities/Objects/Fun/snap_pops.yml
#	Resources/Prototypes/Entities/Objects/Materials/Sheets/other.yml
#	Resources/Prototypes/Entities/Objects/Materials/parts.yml
#	Resources/Prototypes/Entities/Objects/Misc/identification_cards.yml
#	Resources/Prototypes/Entities/Objects/Misc/subdermal_implants.yml
#	Resources/Prototypes/Entities/Objects/Shields/shields.yml
#	Resources/Prototypes/Entities/Objects/Specific/Chapel/bibles.yml
#	Resources/Prototypes/Entities/Objects/Specific/Janitorial/janitor.yml
#	Resources/Prototypes/Entities/Objects/Specific/Medical/hypospray.yml
#	Resources/Prototypes/Entities/Objects/Specific/Medical/surgery.yml
#	Resources/Prototypes/Entities/Objects/Specific/Robotics/borg_modules.yml
#	Resources/Prototypes/Entities/Objects/Specific/Robotics/mmi.yml
#	Resources/Prototypes/Entities/Objects/Specific/Service/barber.yml
#	Resources/Prototypes/Entities/Objects/Tools/glowstick.yml
#	Resources/Prototypes/Entities/Objects/Weapons/Guns/Ammunition/Boxes/antimateriel.yml
#	Resources/Prototypes/Entities/Objects/Weapons/Guns/Ammunition/Boxes/magnum.yml
#	Resources/Prototypes/Entities/Objects/Weapons/Guns/Ammunition/Cartridges/heavy_rifle.yml
#	Resources/Prototypes/Entities/Objects/Weapons/Guns/Ammunition/Cartridges/light_rifle.yml
#	Resources/Prototypes/Entities/Objects/Weapons/Guns/Ammunition/Cartridges/magnum.yml
#	Resources/Prototypes/Entities/Objects/Weapons/Guns/Ammunition/Cartridges/pistol.yml
#	Resources/Prototypes/Entities/Objects/Weapons/Guns/Ammunition/Cartridges/rifle.yml
#	Resources/Prototypes/Entities/Objects/Weapons/Guns/Ammunition/Cartridges/shotgun.yml
#	Resources/Prototypes/Entities/Objects/Weapons/Guns/Ammunition/Magazines/light_rifle.yml
#	Resources/Prototypes/Entities/Objects/Weapons/Guns/Ammunition/Magazines/magnum.yml
#	Resources/Prototypes/Entities/Objects/Weapons/Guns/Ammunition/Magazines/pistol.yml
#	Resources/Prototypes/Entities/Objects/Weapons/Guns/Ammunition/Magazines/rifle.yml
#	Resources/Prototypes/Entities/Objects/Weapons/Guns/Ammunition/Projectiles/grenade.yml
#	Resources/Prototypes/Entities/Objects/Weapons/Guns/Ammunition/SpeedLoaders/magnum.yml
#	Resources/Prototypes/Entities/Objects/Weapons/Guns/Ammunition/SpeedLoaders/pistol.yml
#	Resources/Prototypes/Entities/Objects/Weapons/Guns/Ammunition/SpeedLoaders/rifle_light.yml
#	Resources/Prototypes/Entities/Objects/Weapons/Guns/Ammunition/explosives.yml
#	Resources/Prototypes/Entities/Objects/Weapons/Guns/Battery/battery_guns.yml
#	Resources/Prototypes/Entities/Objects/Weapons/Guns/LMGs/lmgs.yml
#	Resources/Prototypes/Entities/Objects/Weapons/Guns/Pistols/pistols.yml
#	Resources/Prototypes/Entities/Objects/Weapons/Guns/Projectiles/hitscan.yml
#	Resources/Prototypes/Entities/Objects/Weapons/Guns/Projectiles/projectiles.yml
#	Resources/Prototypes/Entities/Objects/Weapons/Guns/Rifles/rifles.yml
#	Resources/Prototypes/Entities/Objects/Weapons/Guns/SMGs/smgs.yml
#	Resources/Prototypes/Entities/Objects/Weapons/Melee/knife.yml
#	Resources/Prototypes/Entities/Objects/Weapons/Throwable/grenades.yml
#	Resources/Prototypes/Entities/Structures/Furniture/dresser.yml
#	Resources/Prototypes/Entities/Structures/Machines/lathe.yml
#	Resources/Prototypes/Entities/Structures/Shuttles/cannons.yml
#	Resources/Prototypes/Entities/Structures/Walls/walls.yml
#	Resources/Prototypes/GameRules/roundstart.yml
#	Resources/Prototypes/GameRules/unknown_shuttles.yml
#	Resources/Prototypes/InventoryTemplates/aghost_inventory_template.yml
#	Resources/Prototypes/Loadouts/Jobs/Security/security_officer.yml
#	Resources/Prototypes/Loadouts/loadout_groups.yml
#	Resources/Prototypes/Loadouts/role_loadouts.yml
#	Resources/Prototypes/Maps/Pools/default.yml
#	Resources/Prototypes/Maps/amber.yml
#	Resources/Prototypes/Maps/oasis.yml
#	Resources/Prototypes/Maps/reach.yml
#	Resources/Prototypes/Objectives/objectiveGroups.yml
#	Resources/Prototypes/Reagents/Consumable/Drink/alcohol.yml
#	Resources/Prototypes/Reagents/medicine.yml
#	Resources/Prototypes/Reagents/narcotics.yml
#	Resources/Prototypes/Reagents/toxins.yml
#	Resources/Prototypes/Recipes/Reactions/medicine.yml
#	Resources/Prototypes/Roles/Jobs/Security/head_of_security.yml
#	Resources/Prototypes/Roles/Jobs/Security/security_cadet.yml
#	Resources/Prototypes/Roles/Jobs/Security/security_officer.yml
#	Resources/Prototypes/Roles/Jobs/Security/warden.yml
#	Resources/Prototypes/Roles/Jobs/Wildcards/zookeeper.yml
#	Resources/Prototypes/Roles/play_time_trackers.yml
#	Resources/Prototypes/Shuttles/shuttle_incoming_event.yml
#	Resources/Prototypes/Species/species_weights.yml
#	Resources/Prototypes/Store/presets.yml
#	Resources/Prototypes/ai_factions.yml
#	Resources/Prototypes/borg_types.yml
#	Resources/Prototypes/explosion.yml
#	Resources/Prototypes/game_presets.yml
#	Resources/Prototypes/lobbyscreens.yml
#	Resources/Prototypes/silicon-laws.yml
#	Resources/Textures/Clothing/Back/Duffels/syndicate.rsi/icon-med.png
#	Resources/Textures/Clothing/Back/Duffels/syndicate.rsi/meta.json
#	Resources/Textures/Objects/Specific/Mech/mecha.rsi/meta.json
#	Resources/Textures/Objects/Specific/Mech/mecha.rsi/ripley-broken.png
#	Resources/Textures/Objects/Specific/Mech/mecha.rsi/ripley-empty.png
#	Resources/Textures/Objects/Specific/Mech/mecha.rsi/ripley-open.png
#	Resources/Textures/Objects/Specific/Mech/mecha.rsi/ripley.png
#	Resources/Textures/Objects/Specific/Mech/ripley_construction.rsi/ripley_chassis.png
#	Resources/Textures/Objects/Specific/Mech/ripley_construction.rsi/ripley_harness+o.png
#	Resources/Textures/Objects/Specific/Mech/ripley_construction.rsi/ripley_harness.png
#	Resources/Textures/Objects/Specific/Medical/hypospray.rsi/meta.json
#	Resources/Textures/Objects/Specific/Medical/medical.rsi/meta.json
#	Resources/Textures/Objects/Weapons/Guns/Projectiles/projectiles.rsi/meta.json
#	Resources/Textures/Objects/Weapons/Guns/Projectiles/projectiles2.rsi/meta.json
#	Resources/Textures/Structures/Storage/canister.rsi/meta.json
#	Resources/Textures/Structures/Storage/tanks.rsi/meta.json
#	Resources/migration.yml
#	RobustToolbox
#	SECURITY.md
#	SpaceStation14.sln
2025-12-26 04:19:27 +01:00

1116 lines
45 KiB
C#

using System.Linq;
using System.Net.Http;
using System.Text;
using System.Text.Json;
using System.Text.Json.Nodes;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Content.Server.Administration.Managers;
using Content.Server.Afk;
using Content.Server.Database;
using Content.Server.Discord;
using Content.Server.GameTicking;
using Content.Server.Players.RateLimiting;
using Content.Shared.Administration;
using Content.Shared.CCVar;
using Content.Shared.GameTicking;
using Content.Shared.Mind;
using Content.Shared.Players.RateLimiting;
using JetBrains.Annotations;
using Robust.Server.Player;
using Robust.Shared;
using Robust.Shared.Configuration;
using Robust.Shared.Enums;
using Robust.Shared.Network;
using Robust.Shared.Player;
using Robust.Shared.Timing;
using Robust.Shared.Utility;
using Content.Sunrise.Interfaces.Shared; // Sunrise-Sponsors
using Content.Shared.Database; // Sunrise-Ahelp-Antispam, based on Starlight Build: https://github.com/ss14Starlight/space-station-14/pull/85
namespace Content.Server.Administration.Systems
{
[UsedImplicitly]
public sealed partial class BwoinkSystem : SharedBwoinkSystem
{
private const string RateLimitKey = "AdminHelp";
[Dependency] private readonly IPlayerManager _playerManager = default!;
[Dependency] private readonly IAdminManager _adminManager = default!;
[Dependency] private readonly IConfigurationManager _config = default!;
[Dependency] private readonly IGameTiming _timing = default!;
[Dependency] private readonly IPlayerLocator _playerLocator = default!;
[Dependency] private readonly GameTicker _gameTicker = default!;
[Dependency] private readonly SharedMindSystem _minds = default!;
[Dependency] private readonly IAfkManager _afkManager = default!;
[Dependency] private readonly IServerDbManager _dbManager = default!;
[Dependency] private readonly PlayerRateLimitManager _rateLimit = default!;
private ISharedSponsorsManager? _sponsorsManager; // Sunrise-Sponsors
[Dependency] private readonly IBanManager _banManager = default!; // Sunrise-Ahelp-Antispam, based on Starlight Build: https://github.com/ss14Starlight/space-station-14/pull/85
[Dependency] private readonly DiscordWebhook _discord = default!;
[GeneratedRegex(@"^https://discord\.com/api/webhooks/(\d+)/((?!.*/).*)$")]
private static partial Regex DiscordRegex();
private string _webhookUrl = string.Empty;
private WebhookData? _webhookData;
private string _onCallUrl = string.Empty;
private WebhookData? _onCallData;
private ISawmill _sawmill = default!;
private HttpClient _httpClient = default!;
private string _footerIconUrl = string.Empty;
private string _avatarUrl = string.Empty;
private string _serverName = string.Empty;
private readonly Dictionary<NetUserId, DiscordRelayInteraction> _relayMessages = new();
private Dictionary<NetUserId, string> _oldMessageIds = new();
private readonly Dictionary<NetUserId, Queue<DiscordRelayedData>> _messageQueues = new();
private readonly HashSet<NetUserId> _processingChannels = new();
private readonly Dictionary<NetUserId, (TimeSpan Timestamp, bool Typing)> _typingUpdateTimestamps = new();
private string _overrideClientName = string.Empty;
// Max embed description length is 4096, according to https://discord.com/developers/docs/resources/channel#embed-object-embed-limits
// Keep small margin, just to be safe
private const ushort DescriptionMax = 4000;
// Maximum length a message can be before it is cut off
// Should be shorter than DescriptionMax
private const ushort MessageLengthCap = 3000;
// Sunrise-Ahelp-Antispam-Start
// Based on Starlight Build: https://github.com/ss14Starlight/space-station-14/pull/85
private readonly TimeSpan _messageCooldown = TimeSpan.FromSeconds(2);
private readonly Queue<(NetUserId Channel, string Text, TimeSpan Timestamp)> _recentMessages = new();
private const int MaxRecentMessages = 10;
private const int SpamCheckMessageCount = 3;
// Sunrise-Ahelp-Antispam-End
// Text to be used to cut off messages that are too long. Should be shorter than MessageLengthCap
private const string TooLongText = "... **(too long)**";
private int _maxAdditionalChars;
private readonly Dictionary<NetUserId, DateTime> _activeConversations = new();
public override void Initialize()
{
base.Initialize();
// Sunrise added start
_httpClient = _discord.GetClient();
// Sunrise added end
Subs.CVar(_config, CCVars.DiscordOnCallWebhook, OnCallChanged, true);
Subs.CVar(_config, CCVars.DiscordAHelpWebhook, OnWebhookChanged, true);
Subs.CVar(_config, CCVars.DiscordAHelpFooterIcon, OnFooterIconChanged, true);
Subs.CVar(_config, CCVars.DiscordAHelpAvatar, OnAvatarChanged, true);
Subs.CVar(_config, CVars.GameHostName, OnServerNameChanged, true);
Subs.CVar(_config, CCVars.AdminAhelpOverrideClientName, OnOverrideChanged, true);
_sawmill = IoCManager.Resolve<ILogManager>().GetSawmill("AHELP");
var defaultParams = new AHelpMessageParams(
string.Empty,
string.Empty,
true,
_gameTicker.RoundDuration().ToString("hh\\:mm\\:ss"),
_gameTicker.RunLevel,
playedSound: false
);
_maxAdditionalChars = GenerateAHelpMessage(defaultParams).Message.Length;
_playerManager.PlayerStatusChanged += OnPlayerStatusChanged;
SubscribeLocalEvent<GameRunLevelChangedEvent>(OnGameRunLevelChanged);
SubscribeNetworkEvent<BwoinkClientTypingUpdated>(OnClientTypingUpdated);
SubscribeNetworkEvent<BwoinkRequestDbMessages>(OnRequestDbMessages);
SubscribeLocalEvent<RoundRestartCleanupEvent>(_ => _activeConversations.Clear());
_rateLimit.Register(
RateLimitKey,
new RateLimitRegistration(CCVars.AhelpRateLimitPeriod,
CCVars.AhelpRateLimitCount,
PlayerRateLimitedAction)
);
IoCManager.Instance!.TryResolveType(out _sponsorsManager); // Sunrise-Sponsors
}
private async void OnCallChanged(string url)
{
_onCallUrl = url;
if (url == string.Empty)
return;
var match = DiscordRegex().Match(url);
if (!match.Success)
{
Log.Error("On call URL does not appear to be valid.");
return;
}
if (match.Groups.Count <= 2)
{
Log.Error("Could not get webhook ID or token for on call URL.");
return;
}
var webhookId = match.Groups[1].Value;
var webhookToken = match.Groups[2].Value;
_onCallData = await GetWebhookData(webhookId, webhookToken);
}
private void PlayerRateLimitedAction(ICommonSession obj)
{
RaiseNetworkEvent(
new BwoinkTextMessage(obj.UserId, default, Loc.GetString("bwoink-system-rate-limited"), playSound: false),
obj.Channel);
}
private void OnOverrideChanged(string obj)
{
_overrideClientName = obj;
}
private async void OnPlayerStatusChanged(object? sender, SessionStatusEventArgs e)
{
if (e.NewStatus == SessionStatus.Disconnected)
{
if (_activeConversations.TryGetValue(e.Session.UserId, out var lastMessageTime))
{
var timeSinceLastMessage = DateTime.Now - lastMessageTime;
if (timeSinceLastMessage > TimeSpan.FromMinutes(5))
{
_activeConversations.Remove(e.Session.UserId);
return; // Do not send disconnect message if timeout exceeded
}
}
// Check if the user has been banned
var ban = await _dbManager.GetServerBanAsync(null, e.Session.UserId, null, null);
if (ban != null)
{
var banMessage = Loc.GetString("bwoink-system-player-banned", ("banReason", ban.Reason));
NotifyAdmins(e.Session, banMessage, PlayerStatusType.Banned);
_activeConversations.Remove(e.Session.UserId);
return;
}
}
// Notify all admins if a player disconnects or reconnects
var message = e.NewStatus switch
{
SessionStatus.Connected => Loc.GetString("bwoink-system-player-reconnecting"),
SessionStatus.Disconnected => Loc.GetString("bwoink-system-player-disconnecting"),
_ => null
};
if (message != null)
{
var statusType = e.NewStatus == SessionStatus.Connected
? PlayerStatusType.Connected
: PlayerStatusType.Disconnected;
NotifyAdmins(e.Session, message, statusType);
}
if (e.NewStatus != SessionStatus.InGame)
return;
RaiseNetworkEvent(new BwoinkDiscordRelayUpdated(!string.IsNullOrWhiteSpace(_webhookUrl)), e.Session);
}
private void NotifyAdmins(ICommonSession session, string message, PlayerStatusType statusType)
{
if (!_activeConversations.ContainsKey(session.UserId))
{
// If the user is not part of an active conversation, do not notify admins.
return;
}
// Get the current timestamp
var timestamp = DateTime.Now.ToString("HH:mm:ss");
var roundTime = _gameTicker.RoundDuration().ToString("hh\\:mm\\:ss");
// Determine the icon based on the status type
string icon = statusType switch
{
PlayerStatusType.Connected => ":green_circle:",
PlayerStatusType.Disconnected => ":red_circle:",
PlayerStatusType.Banned => ":no_entry:",
_ => ":question:"
};
// Create the message parameters for Discord
var messageParams = new AHelpMessageParams(
session.Name,
message,
true,
roundTime,
_gameTicker.RunLevel,
playedSound: true,
icon: icon
);
// Create the message for in-game with username
var color = statusType switch
{
PlayerStatusType.Connected => Color.Green.ToHex(),
PlayerStatusType.Disconnected => Color.Yellow.ToHex(),
PlayerStatusType.Banned => Color.Orange.ToHex(),
_ => Color.Gray.ToHex(),
};
var inGameMessage = $"[color={color}]{session.Name} {message}[/color]";
var bwoinkMessage = new BwoinkTextMessage(
userId: session.UserId,
trueSender: SystemUserId,
text: inGameMessage,
sentAt: DateTime.Now,
playSound: false
);
var admins = GetTargetAdmins();
foreach (var admin in admins)
{
RaiseNetworkEvent(bwoinkMessage, admin);
}
// Enqueue the message for Discord relay
if (_webhookUrl != string.Empty)
{
// if (!_messageQueues.ContainsKey(session.UserId))
// _messageQueues[session.UserId] = new Queue<string>();
//
// var escapedText = FormattedMessage.EscapeText(message);
// messageParams.Message = escapedText;
//
// var discordMessage = GenerateAHelpMessage(messageParams);
// _messageQueues[session.UserId].Enqueue(discordMessage);
var queue = _messageQueues.GetOrNew(session.UserId);
var escapedText = FormattedMessage.EscapeText(message);
messageParams.Message = escapedText;
var discordMessage = GenerateAHelpMessage(messageParams);
queue.Enqueue(discordMessage);
}
}
private void OnGameRunLevelChanged(GameRunLevelChangedEvent args)
{
// Don't make a new embed if we
// 1. were in the lobby just now, and
// 2. are not entering the lobby or directly into a new round.
if (args.Old is GameRunLevel.PreRoundLobby ||
args.New is not (GameRunLevel.PreRoundLobby or GameRunLevel.InRound))
{
return;
}
// Store the Discord message IDs of the previous round
_oldMessageIds = new Dictionary<NetUserId, string>();
foreach (var (user, interaction) in _relayMessages)
{
var id = interaction.Id;
if (id == null)
return;
_oldMessageIds[user] = id;
}
_relayMessages.Clear();
}
private void OnClientTypingUpdated(BwoinkClientTypingUpdated msg, EntitySessionEventArgs args)
{
if (_typingUpdateTimestamps.TryGetValue(args.SenderSession.UserId, out var tuple) &&
tuple.Typing == msg.Typing &&
tuple.Timestamp + TimeSpan.FromSeconds(1) > _timing.RealTime)
{
return;
}
_typingUpdateTimestamps[args.SenderSession.UserId] = (_timing.RealTime, msg.Typing);
// Non-admins can only ever type on their own ahelp, guard against fake messages
var isAdmin = _adminManager.GetAdminData(args.SenderSession)?.HasFlag(AdminFlags.Adminhelp) ?? false;
var channel = isAdmin ? msg.Channel : args.SenderSession.UserId;
var update = new BwoinkPlayerTypingUpdated(channel, args.SenderSession.Name, msg.Typing);
foreach (var admin in GetTargetAdmins())
{
if (admin.UserId == args.SenderSession.UserId)
continue;
RaiseNetworkEvent(update, admin);
}
}
// Sunrise-Start
private async void OnRequestDbMessages(BwoinkRequestDbMessages msg, EntitySessionEventArgs args)
{
var isAdmin = _adminManager.IsAdmin(args.SenderSession);
var messages = (await _dbManager.GetAHelpMessagesByReceiverAsync(msg.UserId))
.OrderBy(message => message.SentAt);
var history = new List<BwoinkTextMessage>();
foreach (var aHelpMessage in messages)
{
if (aHelpMessage.AdminOnly && !isAdmin)
continue;
var formatMessage = await FormatDbAhelpMessage(
aHelpMessage.Message,
(NetUserId)aHelpMessage.SenderUserId,
aHelpMessage.PlaySound,
aHelpMessage.AdminOnly);
var bwoinkTextMessage = new BwoinkTextMessage(
(NetUserId)aHelpMessage.ReceiverUserId,
(NetUserId)aHelpMessage.SenderUserId,
formatMessage,
aHelpMessage.SentAt.DateTime.ToLocalTime(),
playSound: aHelpMessage.PlaySound,
adminOnly: aHelpMessage.AdminOnly,
dbLoad: true);
history.Add(bwoinkTextMessage);
}
var historyEvent = new BwoinkTextHistoryMessage(msg.UserId, history);
RaiseNetworkEvent(historyEvent, args.SenderSession.Channel);
}
private async Task<string> FormatDbAhelpMessage(string message, NetUserId senderUserId,
bool playSound = true, bool adminOnly = false)
{
/*
* SUNRISE-TODO: Ахуенная идея, обращаться к БД при каждом форматировании сообщения.
* Очевидно нужно использовать кеширование, но мне впадлу.
*/
var senderAdmin = await _adminManager.LoadAdminData(senderUserId);
var senderData = await _dbManager.GetPlayerRecordByUserId(senderUserId);
var username = "";
if (senderData != null)
{
username = senderData.LastSeenUserName;
}
string bwoinkText;
var adminPrefix = "";
if (_config.GetCVar(CCVars.AhelpAdminPrefix) && senderAdmin is not null && senderAdmin.Value.dat.Title is not null)
{
adminPrefix = $"[bold]\\[{senderAdmin.Value.dat.Title}\\][/bold] ";
}
if (senderAdmin is not null &&
senderAdmin.Value.dat.Flags ==
AdminFlags.Mentor) // Mentor. Not full admin. That's why it's colored differently.
{
bwoinkText = $"[color=purple]{adminPrefix}{username}[/color]";
}
else if (senderAdmin is not null && senderAdmin.Value.dat.Flags.HasFlag(AdminFlags.Adminhelp))
{
bwoinkText = $"[color=red]{adminPrefix}{username}[/color]";
}
else if (_sponsorsManager != null)
{
_sponsorsManager.TryGetOocColor(senderUserId, out var oocColor);
_sponsorsManager.TryGetOocTitle(senderUserId, out var oocTitle);
var sponsorTitle = oocTitle is null ? "" : $"\\[{oocTitle}\\]";
if (oocColor != null)
{
bwoinkText = $"[color={oocColor.Value.ToHex()}]{sponsorTitle} {username}[/color]";
}
else
{
bwoinkText = $"{sponsorTitle} {username}";
}
}
else
{
bwoinkText = $"{username}";
}
var escapedText = FormattedMessage.EscapeText(message);
return $"{(adminOnly ? Loc.GetString("bwoink-message-admin-only") : !playSound ? Loc.GetString("bwoink-message-silent") : "")} {bwoinkText}: {escapedText}";
}
// Sunrise-End
private void OnServerNameChanged(string obj)
{
_serverName = obj;
}
private async void OnWebhookChanged(string url)
{
_webhookUrl = url;
RaiseNetworkEvent(new BwoinkDiscordRelayUpdated(!string.IsNullOrWhiteSpace(url)));
if (url == string.Empty)
return;
// Basic sanity check and capturing webhook ID and token
var match = DiscordRegex().Match(url);
if (!match.Success)
{
// TODO: Ideally, CVar validation during setting should be better integrated
Log.Warning("Webhook URL does not appear to be valid. Using anyways...");
return;
}
if (match.Groups.Count <= 2)
{
Log.Error("Could not get webhook ID or token.");
return;
}
var webhookId = match.Groups[1].Value;
var webhookToken = match.Groups[2].Value;
// Fire and forget
_webhookData = await GetWebhookData(webhookId, webhookToken);
}
private async Task<WebhookData?> GetWebhookData(string id, string token)
{
var response = await _httpClient.GetAsync($"https://discord.com/api/v10/webhooks/{id}/{token}");
var content = await response.Content.ReadAsStringAsync();
if (!response.IsSuccessStatusCode)
{
_sawmill.Log(LogLevel.Error,
$"Discord returned bad status code when trying to get webhook data (perhaps the webhook URL is invalid?): {response.StatusCode}\nResponse: {content}");
return null;
}
return JsonSerializer.Deserialize<WebhookData>(content);
}
private void OnFooterIconChanged(string url)
{
_footerIconUrl = url;
}
private void OnAvatarChanged(string url)
{
_avatarUrl = url;
}
private async void ProcessQueue(NetUserId userId, Queue<DiscordRelayedData> messages)
{
// Whether an embed already exists for this player
var exists = _relayMessages.TryGetValue(userId, out var existingEmbed);
// Whether the message will become too long after adding these new messages
var tooLong = exists && messages.Sum(msg => Math.Min(msg.Message.Length, MessageLengthCap) + "\n".Length)
+ existingEmbed?.Description.Length > DescriptionMax;
// If there is no existing embed, or it is getting too long, we create a new embed
if (!exists || tooLong)
{
var lookup = await _playerLocator.LookupIdAsync(userId);
if (lookup == null)
{
_sawmill.Log(LogLevel.Error,
$"Unable to find player for NetUserId {userId} when sending discord webhook.");
_relayMessages.Remove(userId);
return;
}
var linkToPrevious = string.Empty;
// If we have all the data required, we can link to the embed of the previous round or embed that was too long
if (_webhookData is { GuildId: { } guildId, ChannelId: { } channelId })
{
if (tooLong && existingEmbed?.Id != null)
{
linkToPrevious =
$"**[Go to previous embed of this round](https://discord.com/channels/{guildId}/{channelId}/{existingEmbed.Id})**\n";
}
else if (_oldMessageIds.TryGetValue(userId, out var id) && !string.IsNullOrEmpty(id))
{
linkToPrevious =
$"**[Go to last round's conversation with this player](https://discord.com/channels/{guildId}/{channelId}/{id})**\n";
}
}
var characterName = _minds.GetCharacterName(userId);
existingEmbed = new DiscordRelayInteraction()
{
Id = null,
CharacterName = characterName,
Description = linkToPrevious,
Username = lookup.Username,
LastRunLevel = _gameTicker.RunLevel,
};
_relayMessages[userId] = existingEmbed;
}
// Previous message was in another RunLevel, so show that in the embed
if (existingEmbed!.LastRunLevel != _gameTicker.RunLevel)
{
existingEmbed.Description += _gameTicker.RunLevel switch
{
GameRunLevel.PreRoundLobby => "\n\n:arrow_forward: _**Pre-round lobby started**_\n",
GameRunLevel.InRound => "\n\n:arrow_forward: _**Round started**_\n",
GameRunLevel.PostRound => "\n\n:stop_button: _**Post-round started**_\n",
_ => throw new ArgumentOutOfRangeException(nameof(_gameTicker.RunLevel),
$"{_gameTicker.RunLevel} was not matched."),
};
existingEmbed.LastRunLevel = _gameTicker.RunLevel;
}
// If last message of the new batch is SOS then relay it to on-call.
// ... as long as it hasn't been relayed already.
var discordMention = messages.Last();
var onCallRelay = !discordMention.Receivers && !existingEmbed.OnCall;
// Add available messages to the embed description
while (messages.TryDequeue(out var message))
{
string text;
// In case someone thinks they're funny
if (message.Message.Length > MessageLengthCap)
text = message.Message[..(MessageLengthCap - TooLongText.Length)] + TooLongText;
else
text = message.Message;
existingEmbed.Description += $"\n{text}";
}
var payload = GeneratePayload(existingEmbed.Description,
existingEmbed.Username,
existingEmbed.CharacterName);
// If there is no existing embed, create a new one
// Otherwise patch (edit) it
if (existingEmbed.Id == null)
{
var request = await _httpClient.PostAsync($"{_webhookUrl}?wait=true",
new StringContent(JsonSerializer.Serialize(payload), Encoding.UTF8, "application/json"));
var content = await request.Content.ReadAsStringAsync();
if (!request.IsSuccessStatusCode)
{
_sawmill.Log(LogLevel.Error,
$"Discord returned bad status code when posting message (perhaps the message is too long?): {request.StatusCode}\nResponse: {content}");
_relayMessages.Remove(userId);
return;
}
var id = JsonNode.Parse(content)?["id"];
if (id == null)
{
_sawmill.Log(LogLevel.Error,
$"Could not find id in json-content returned from discord webhook: {content}");
_relayMessages.Remove(userId);
return;
}
existingEmbed.Id = id.ToString();
}
else
{
var request = await _httpClient.PatchAsync($"{_webhookUrl}/messages/{existingEmbed.Id}",
new StringContent(JsonSerializer.Serialize(payload), Encoding.UTF8, "application/json"));
if (!request.IsSuccessStatusCode)
{
var content = await request.Content.ReadAsStringAsync();
_sawmill.Log(LogLevel.Error,
$"Discord returned bad status code when patching message (perhaps the message is too long?): {request.StatusCode}\nResponse: {content}");
_relayMessages.Remove(userId);
return;
}
}
_relayMessages[userId] = existingEmbed;
// Actually do the on call relay last, we just need to grab it before we dequeue every message above.
if (onCallRelay &&
_onCallData != null)
{
existingEmbed.OnCall = true;
var roleMention = _config.GetCVar(CCVars.DiscordAhelpMention);
if (!string.IsNullOrEmpty(roleMention))
{
var message = new StringBuilder();
message.AppendLine($"<@&{roleMention}>");
message.AppendLine("Unanswered SOS");
// Need webhook data to get the correct link for that channel rather than on-call data.
if (_webhookData is { GuildId: { } guildId, ChannelId: { } channelId })
{
message.AppendLine(
$"**[Go to ahelp](https://discord.com/channels/{guildId}/{channelId}/{existingEmbed.Id})**");
}
payload = GeneratePayload(message.ToString(), existingEmbed.Username, existingEmbed.CharacterName);
var request = await _httpClient.PostAsync($"{_onCallUrl}?wait=true",
new StringContent(JsonSerializer.Serialize(payload), Encoding.UTF8, "application/json"));
var content = await request.Content.ReadAsStringAsync();
if (!request.IsSuccessStatusCode)
{
_sawmill.Log(LogLevel.Error, $"Discord returned bad status code when posting relay message (perhaps the message is too long?): {request.StatusCode}\nResponse: {content}");
}
}
}
else
{
existingEmbed.OnCall = false;
}
_processingChannels.Remove(userId);
}
private WebhookPayload GeneratePayload(string messages, string username, string? characterName = null)
{
// Add character name
if (characterName != null)
username += $" ({characterName})";
// If no admins are online, set embed color to red. Otherwise green
var color = GetNonAfkAdmins().Count > 0 ? 0x41F097 : 0xFF0000;
// Limit server name to 1500 characters, in case someone tries to be a little funny
var serverName = _serverName[..Math.Min(_serverName.Length, 1500)];
var round = _gameTicker.RunLevel switch
{
GameRunLevel.PreRoundLobby => _gameTicker.RoundId == 0
? "pre-round lobby after server restart" // first round after server restart has ID == 0
: $"pre-round lobby for round {_gameTicker.RoundId}",
GameRunLevel.InRound => $"round {_gameTicker.RoundId}",
GameRunLevel.PostRound => $"post-round {_gameTicker.RoundId}",
_ => throw new ArgumentOutOfRangeException(nameof(_gameTicker.RunLevel),
$"{_gameTicker.RunLevel} was not matched."),
};
return new WebhookPayload
{
Username = username,
AvatarUrl = string.IsNullOrWhiteSpace(_avatarUrl) ? null : _avatarUrl,
Embeds = new List<WebhookEmbed>
{
new()
{
Description = messages,
Color = color,
Footer = new WebhookEmbedFooter
{
Text = $"{serverName} ({round})",
IconUrl = string.IsNullOrWhiteSpace(_footerIconUrl) ? null : _footerIconUrl
},
},
},
};
}
public override void Update(float frameTime)
{
base.Update(frameTime);
foreach (var userId in _messageQueues.Keys.ToArray())
{
if (_processingChannels.Contains(userId))
continue;
var queue = _messageQueues[userId];
_messageQueues.Remove(userId);
if (queue.Count == 0)
continue;
_processingChannels.Add(userId);
ProcessQueue(userId, queue);
}
}
protected override void OnBwoinkTextMessage(BwoinkTextMessage message, EntitySessionEventArgs eventArgs)
{
base.OnBwoinkTextMessage(message, eventArgs);
_activeConversations[message.UserId] = DateTime.Now;
var senderSession = eventArgs.SenderSession;
// TODO: Sanitize text?
// Confirm that this person is actually allowed to send a message here.
var personalChannel = senderSession.UserId == message.UserId;
var senderAdmin = _adminManager.GetAdminData(senderSession);
var senderAHelpAdmin = senderAdmin?.HasFlag(AdminFlags.Adminhelp) ?? false;
var authorized = personalChannel && !message.AdminOnly || senderAHelpAdmin;
if (!authorized)
{
// Unauthorized bwoink (log?)
return;
}
// Sunrise-Ahelp-Antispam-Start
// Based on Starlight Build: https://github.com/ss14Starlight/space-station-14/pull/85
var currentTime = _timing.RealTime;
if (IsOnCooldown(message.UserId, currentTime, out var remainingCooldown))
{
// Send cooldown feedback to the client
RaiseNetworkEvent(new BwoinkCooldownMessage(remainingCooldown), senderSession.Channel);
return;
}
if (IsSpam(message.UserId, message.Text))
_banManager.CreateServerBan(senderSession.UserId, senderSession.Name, null, null, null, 180, NoteSeverity.High, Loc.GetString("ahelp-antispam-ban-reason"));
AddToRecentMessages(message.UserId, message.Text, currentTime);
// Sunrise-Ahelp-Antispam-End
if (_rateLimit.CountAction(eventArgs.SenderSession, RateLimitKey) != RateLimitStatus.Allowed)
return;
var escapedText = FormattedMessage.EscapeText(message.Text);
// Sunrise-Sponsors-Start
string bwoinkText;
string adminPrefix = "";
//Getting an administrator position
if (_config.GetCVar(CCVars.AhelpAdminPrefix) && senderAdmin is not null && senderAdmin.Title is not null)
{
adminPrefix = $"[bold]\\[{senderAdmin.Title}\\][/bold] ";
}
if (senderAdmin is not null &&
senderAdmin.Flags ==
AdminFlags.Adminhelp) // Mentor. Not full admin. That's why it's colored differently.
{
bwoinkText = $"[color=purple]{adminPrefix}{senderSession.Name}[/color]";
}
else if (senderAdmin is not null && senderAdmin.HasFlag(AdminFlags.Adminhelp))
{
bwoinkText = $"[color=red]{adminPrefix}{senderSession.Name}[/color]";
}
else if (_sponsorsManager != null)
{
_sponsorsManager.TryGetOocColor(message.UserId, out var oocColor);
_sponsorsManager.TryGetOocTitle(message.UserId, out var oocTitle);
var sponsorTitle = oocTitle is null ? "" : $"\\[{oocTitle}\\]";
if (oocColor != null)
{
bwoinkText = $"[color={oocColor.Value.ToHex()}]{sponsorTitle} {senderSession.Name}[/color]";
}
else
{
bwoinkText = $"{sponsorTitle} {senderSession.Name}";
}
}
else
{
bwoinkText = $"{senderSession.Name}";
}
bwoinkText = $"{(message.AdminOnly ? Loc.GetString("bwoink-message-admin-only") : !message.PlaySound ? Loc.GetString("bwoink-message-silent") : "")} {bwoinkText}: {escapedText}";
// If it's not an admin / admin chooses to keep the sound and message is not an admin only message, then play it.
var playSound = (!senderAHelpAdmin || message.PlaySound) && !message.AdminOnly;
var msg = new BwoinkTextMessage(message.UserId, senderSession.UserId, bwoinkText, playSound: playSound, adminOnly: message.AdminOnly);
// Sunrise-Sponsors-End
LogBwoink(msg);
// Sunrise-Start
var sentAt = DateTimeOffset.UtcNow;
_dbManager.AddAHelpMessage(senderSession.UserId, message.UserId, message.Text, sentAt, message.PlaySound, message.AdminOnly);
// Sunrise-End
var admins = GetTargetAdmins();
// Notify all admins
foreach (var channel in admins)
{
RaiseNetworkEvent(msg, channel);
}
string adminPrefixWebhook = "";
if (_config.GetCVar(CCVars.AhelpAdminPrefixWebhook) && senderAdmin is not null && senderAdmin.Title is not null)
{
adminPrefixWebhook = $"[bold]\\[{senderAdmin.Title}\\][/bold] ";
}
// Notify player
if (_playerManager.TryGetSessionById(message.UserId, out var session) && !message.AdminOnly)
{
if (!admins.Contains(session.Channel))
{
// If _overrideClientName is set, we generate a new message with the override name. The admins name will still be the original name for the webhooks.
if (_overrideClientName != string.Empty)
{
string overrideMsgText;
// Doing the same thing as above, but with the override name. Theres probably a better way to do this.
if (senderAdmin is not null &&
senderAdmin.Flags ==
AdminFlags.Adminhelp) // Mentor. Not full admin. That's why it's colored differently.
{
overrideMsgText = $"[color=purple]{adminPrefixWebhook}{_overrideClientName}[/color]";
}
else if (senderAdmin is not null && senderAdmin.HasFlag(AdminFlags.Adminhelp))
{
overrideMsgText = $"[color=red]{adminPrefixWebhook}{_overrideClientName}[/color]";
}
else
{
overrideMsgText = $"{senderSession.Name}"; // Not an admin, name is not overridden.
}
overrideMsgText = $"{(message.PlaySound ? "" : "(S) ")}{overrideMsgText}: {escapedText}";
RaiseNetworkEvent(new BwoinkTextMessage(message.UserId,
senderSession.UserId,
overrideMsgText,
playSound: playSound),
session.Channel);
}
else
RaiseNetworkEvent(msg, session.Channel);
}
}
var sendsWebhook = _webhookUrl != string.Empty;
if (sendsWebhook)
{
if (!_messageQueues.ContainsKey(msg.UserId))
_messageQueues[msg.UserId] = new Queue<DiscordRelayedData>();
var str = message.Text;
var unameLength = senderSession.Name.Length;
if (unameLength + str.Length + _maxAdditionalChars > DescriptionMax)
{
str = str[..(DescriptionMax - _maxAdditionalChars - unameLength)];
}
var nonAfkAdmins = GetNonAfkAdmins();
var messageParams = new AHelpMessageParams(
senderSession.Name,
str,
!personalChannel,
_gameTicker.RoundDuration().ToString("hh\\:mm\\:ss"),
_gameTicker.RunLevel,
playedSound: playSound,
adminOnly: message.AdminOnly,
noReceivers: nonAfkAdmins.Count == 0
);
_messageQueues[msg.UserId].Enqueue(GenerateAHelpMessage(messageParams));
}
if (admins.Count != 0 || sendsWebhook)
return;
// No admin online, let the player know
var systemText = Loc.GetString("bwoink-system-starmute-message-no-other-users");
var starMuteMsg = new BwoinkTextMessage(message.UserId, SystemUserId, systemText);
RaiseNetworkEvent(starMuteMsg, senderSession.Channel);
}
private IList<INetChannel> GetNonAfkAdmins()
{
return _adminManager.ActiveAdmins
.Where(p => (_adminManager.GetAdminData(p)?.HasFlag(AdminFlags.Adminhelp) ?? false) &&
!_afkManager.IsAfk(p))
.Select(p => p.Channel)
.ToList();
}
// Returns all online admins with AHelp access
public IList<INetChannel> GetTargetAdmins()
{
return _adminManager.ActiveAdmins
.Where(p => _adminManager.GetAdminData(p)?.HasFlag(AdminFlags.Adminhelp) ?? false)
.Select(p => p.Channel)
.ToList();
}
private DiscordRelayedData GenerateAHelpMessage(AHelpMessageParams parameters)
{
var stringbuilder = new StringBuilder();
if (parameters.Icon != null)
stringbuilder.Append(parameters.Icon);
else if (parameters.IsAdmin)
stringbuilder.Append(":outbox_tray:");
else if (parameters.NoReceivers)
stringbuilder.Append(":sos:");
else
stringbuilder.Append(":inbox_tray:");
if (parameters.RoundTime != string.Empty && parameters.RoundState == GameRunLevel.InRound)
stringbuilder.Append($" **{parameters.RoundTime}**");
if (!parameters.PlayedSound)
stringbuilder.Append($" **{(parameters.AdminOnly ? Loc.GetString("bwoink-message-admin-only") : Loc.GetString("bwoink-message-silent"))}**");
if (parameters.Icon == null)
stringbuilder.Append($" **{parameters.Username}:** ");
else
stringbuilder.Append($" **{parameters.Username}** ");
stringbuilder.Append(parameters.Message);
return new DiscordRelayedData()
{
Receivers = !parameters.NoReceivers,
Message = stringbuilder.ToString(),
};
}
private record struct DiscordRelayedData
{
/// <summary>
/// Was anyone online to receive it.
/// </summary>
public bool Receivers;
/// <summary>
/// What's the payload to send to discord.
/// </summary>
public string Message;
}
/// <summary>
/// Class specifically for holding information regarding existing Discord embeds
/// </summary>
private sealed class DiscordRelayInteraction
{
public string? Id;
public string Username = String.Empty;
public string? CharacterName;
/// <summary>
/// Contents for the discord message.
/// </summary>
public string Description = string.Empty;
/// <summary>
/// Run level of the last interaction. If different we'll link to the last Id.
/// </summary>
public GameRunLevel LastRunLevel;
/// <summary>
/// Did we relay this interaction to OnCall previously.
/// </summary>
public bool OnCall;
}
// Sunrise-Ahelp-Antispam-Start
// Based on Starlight Build: https://github.com/ss14Starlight/space-station-14/pull/85
private void AddToRecentMessages(NetUserId channelId, string text, TimeSpan timestamp)
{
_recentMessages.Enqueue((channelId, text, timestamp));
if (_recentMessages.Count > MaxRecentMessages)
{
_recentMessages.Dequeue();
}
}
private bool IsOnCooldown(NetUserId channelId, TimeSpan currentTime, out TimeSpan remainingCooldown)
{
remainingCooldown = TimeSpan.Zero;
var lastMessage = _recentMessages
.Where(msg => msg.Channel == channelId)
.OrderByDescending(msg => msg.Timestamp)
.FirstOrDefault();
if (lastMessage == default)
return false;
var timeSinceLastMessage = currentTime - lastMessage.Timestamp;
if (timeSinceLastMessage < _messageCooldown)
{
remainingCooldown = _messageCooldown - timeSinceLastMessage;
return true;
}
return false;
}
private bool IsOnCooldown(NetUserId channelId, TimeSpan currentTime)
{
return IsOnCooldown(channelId, currentTime, out _);
}
private bool IsSpam(NetUserId channelId, string text)
{
var recentMessages = _recentMessages
.Where(msg => msg.Channel == channelId)
.OrderByDescending(msg => msg.Timestamp)
.Take(10);
return recentMessages.All(msg => msg.Text == text) && recentMessages.Count() >= 5;
}
public IEnumerable<(NetUserId Channel, string Text, TimeSpan Timestamp)> GetRecentMessages()
{
return _recentMessages;
}
// Sunrise-Ahelp-Antispam-End
}
public sealed class AHelpMessageParams
{
public string Username { get; set; }
public string Message { get; set; }
public bool IsAdmin { get; set; }
public string RoundTime { get; set; }
public GameRunLevel RoundState { get; set; }
public bool PlayedSound { get; set; }
public readonly bool AdminOnly;
public bool NoReceivers { get; set; }
public string? Icon { get; set; }
public AHelpMessageParams(
string username,
string message,
bool isAdmin,
string roundTime,
GameRunLevel roundState,
bool playedSound,
bool adminOnly = false,
bool noReceivers = false,
string? icon = null)
{
Username = username;
Message = message;
IsAdmin = isAdmin;
RoundTime = roundTime;
RoundState = roundState;
PlayedSound = playedSound;
AdminOnly = adminOnly;
NoReceivers = noReceivers;
Icon = icon;
}
}
public enum PlayerStatusType
{
Connected,
Disconnected,
Banned,
}
}