Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Discord webhook on watchlist connection #33483

Merged
Merged
Show file tree
Hide file tree
Changes from 8 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
using Content.Server.Administration.Notes;
using Content.Server.Database;
using Content.Server.Discord;
using Content.Shared.CCVar;
using Robust.Server;
using Robust.Server.Player;
using Robust.Shared.Enums;
using Robust.Shared.Configuration;
using Robust.Shared.Network;
using Robust.Shared.Player;
using System.Linq;

namespace Content.Server.Administration.Managers;

/// <summary>
/// This manager sends a webhook notification whenever a player with an active
/// watchlist joins the server.
/// </summary>
public interface IWatchlistWebhookManager
{
void Initialize();
void Update();
}
166 changes: 166 additions & 0 deletions Content.Server/Administration/Managers/WatchlistWebhookManager.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,166 @@
using Content.Server.Administration.Notes;
using Content.Server.Database;
using Content.Server.Discord;
using Content.Shared.CCVar;
using Robust.Server;
using Robust.Server.Player;
using Robust.Shared.Enums;
using Robust.Shared.Configuration;
using Robust.Shared.Network;
using Robust.Shared.Player;
using Robust.Shared.Timing;
using System.Linq;

namespace Content.Server.Administration.Managers;

/// <summary>
/// This manager sends a Discord webhook notification whenever a player with an active
/// watchlist joins the server.
/// </summary>
public sealed class WatchlistWebhookManager : IWatchlistWebhookManager
{
[Dependency] private readonly IAdminNotesManager _adminNotes = default!;
[Dependency] private readonly IBaseServer _baseServer = default!;
[Dependency] private readonly IConfigurationManager _cfg = default!;
[Dependency] private readonly DiscordWebhook _discord = default!;
[Dependency] private readonly IPlayerManager _playerManager = default!;

private ISawmill _sawmill = default!;

private WebhookIdentifier? _webhookIdentifier;
private List<WatchlistConnection> watchlistConnections = new();
private TimeSpan _bufferTime;
private RStopwatch? _bufferingStopwatch;

public void Initialize()
{
_sawmill = Logger.GetSawmill("discord");

var bufferTimeSeconds = _cfg.GetCVar(CCVars.DiscordWatchlistConnectionBufferTime);
_bufferTime = TimeSpan.FromSeconds(bufferTimeSeconds);

var webhook = _cfg.GetCVar(CCVars.DiscordWatchlistConnectionWebhook);
if (!string.IsNullOrWhiteSpace(webhook))
{
_discord.GetWebhook(webhook, data => _webhookIdentifier = data.ToIdentifier());
_playerManager.PlayerStatusChanged += OnPlayerStatusChanged;
}
}

private async void OnPlayerStatusChanged(object? sender, SessionStatusEventArgs e)
{
if (e.NewStatus != SessionStatus.Connected)
return;

var watchlists = await _adminNotes.GetActiveWatchlists(e.Session.UserId);

if (watchlists.Count == 0)
return;

watchlistConnections.Add(new WatchlistConnection(e.Session.Name, watchlists));

if (_bufferTime > TimeSpan.Zero)
{
if (_bufferingStopwatch == null)
_bufferingStopwatch = RStopwatch.StartNew();
}
else
{
FlushConnections();
}
}

public void Update()
{
if (_bufferingStopwatch != null && ((RStopwatch)_bufferingStopwatch).Elapsed > _bufferTime)
{
FlushConnections();
_bufferingStopwatch = null;
}
}

private void FlushConnections()
{
SendDiscordMessage();

// Clear the buffered list regardless of whether the message is sent successfully
// This prevents infinitely buffering connections if we fail to send a message
watchlistConnections.Clear();
}

private async void SendDiscordMessage()
{
try
{
if (_webhookIdentifier == null)
return;

var message = Loc.GetString("discord-watchlist-connection-header",
("players", watchlistConnections.Count),
("serverName", _baseServer.ServerName));

foreach (var connection in watchlistConnections)
{
message += '\n';

var watchlist = connection.Watchlists.First();
var expiry = watchlist.ExpirationTime?.ToUnixTimeSeconds();

if (expiry == null)
{
if (connection.Watchlists.Count == 1)
{
message += Loc.GetString("discord-watchlist-connection-entry",
("playerName", connection.PlayerName),
("message", watchlist.Message));
}
else
{
message += Loc.GetString("discord-watchlist-connection-entry-more",
("playerName", connection.PlayerName),
("message", watchlist.Message),
("otherWatchlists", connection.Watchlists.Count - 1));
}
}
else
{
if (connection.Watchlists.Count == 1)
{
message += Loc.GetString("discord-watchlist-connection-entry-expires",
("playerName", connection.PlayerName),
("expiry", expiry),
("message", watchlist.Message));
}
else
{
message += Loc.GetString("discord-watchlist-connection-entry-expires-more",
("playerName", connection.PlayerName),
("expiry", expiry),
("message", watchlist.Message),
("otherWatchlists", connection.Watchlists.Count - 1));
}
}
}

var payload = new WebhookPayload { Content = message };

await _discord.CreateMessage(_webhookIdentifier.Value, payload);
}
catch (Exception e)
{
_sawmill.Error($"Error while sending discord watchlist connection message:\n{e}");
}
}

private sealed class WatchlistConnection
{
public string PlayerName;
public List<AdminWatchlistRecord> Watchlists;

public WatchlistConnection(string playerName, List<AdminWatchlistRecord> watchlists)
{
PlayerName = playerName;
Watchlists = watchlists;
}
}
}
4 changes: 4 additions & 0 deletions Content.Server/Entry/EntryPoint.cs
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ public sealed class EntryPoint : GameServer
private PlayTimeTrackingManager? _playTimeTracking;
private IEntitySystemManager? _sysMan;
private IServerDbManager? _dbManager;
private IWatchlistWebhookManager _watchlistWebhookManager = default!;

/// <inheritdoc />
public override void Init()
Expand Down Expand Up @@ -93,6 +94,7 @@ public override void Init()
_playTimeTracking = IoCManager.Resolve<PlayTimeTrackingManager>();
_sysMan = IoCManager.Resolve<IEntitySystemManager>();
_dbManager = IoCManager.Resolve<IServerDbManager>();
_watchlistWebhookManager = IoCManager.Resolve<IWatchlistWebhookManager>();

logManager.GetSawmill("Storage").Level = LogLevel.Info;
logManager.GetSawmill("db.ef").Level = LogLevel.Info;
Expand All @@ -110,6 +112,7 @@ public override void Init()
_voteManager.Initialize();
_updateManager.Initialize();
_playTimeTracking.Initialize();
_watchlistWebhookManager.Initialize();
IoCManager.Resolve<JobWhitelistManager>().Initialize();
IoCManager.Resolve<PlayerRateLimitManager>().Initialize();
}
Expand Down Expand Up @@ -160,6 +163,7 @@ public override void Update(ModUpdateLevel level, FrameEventArgs frameEventArgs)
{
_euiManager.SendUpdates();
_voteManager.Update();
_watchlistWebhookManager.Update();
break;
}

Expand Down
1 change: 1 addition & 0 deletions Content.Server/IoC/ServerContentIoC.cs
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,7 @@ public static void Register()
IoCManager.Register<PlayerRateLimitManager>();
IoCManager.Register<SharedPlayerRateLimitManager, PlayerRateLimitManager>();
IoCManager.Register<MappingManager>();
IoCManager.Register<IWatchlistWebhookManager, WatchlistWebhookManager>();
}
}
}
16 changes: 15 additions & 1 deletion Content.Shared/CCVar/CCVars.Discord.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
using Robust.Shared.Configuration;
using Robust.Shared.Configuration;

namespace Content.Shared.CCVar;

Expand Down Expand Up @@ -58,4 +58,18 @@ public sealed partial class CCVars
/// </summary>
public static readonly CVarDef<string> DiscordRoundEndRoleWebhook =
CVarDef.Create("discord.round_end_role", string.Empty, CVar.SERVERONLY);

/// <summary>
/// URL of the Discord webhook which will relay watchlist connection notifications. If left empty, disables the webhook.
/// </summary>
public static readonly CVarDef<string> DiscordWatchlistConnectionWebhook =
CVarDef.Create("discord.watchlist_connection_webhook", string.Empty, CVar.SERVERONLY | CVar.CONFIDENTIAL);

/// <summary>
/// How long to buffer watchlist connections for, in seconds.
/// All connections within this amount of time from the first one will be batched and sent as a single
/// Discord notification. If zero, always sends a separate notification for each connection (not recommended).
/// </summary>
public static readonly CVarDef<float> DiscordWatchlistConnectionBufferTime =
CVarDef.Create("discord.watchlist_connection_buffer_time", 5f, CVar.SERVERONLY);
}
16 changes: 16 additions & 0 deletions Resources/Locale/en-US/discord/watchlist-connections.ftl
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
discord-watchlist-connection-header =
{ $players ->
[one] {$players} player on a watchlist has
*[other] {$players} players on a watchlist have
} connected to {$serverName}

discord-watchlist-connection-entry = - {$playerName} with message "{$message}"
discord-watchlist-connection-entry-expires = - {$playerName} with message "{$message}" (expires <t:{$expiry}:R>)
discord-watchlist-connection-entry-more = - {$playerName} with message "{$message}" and { $otherWatchlists ->
[one] {$otherWatchlists} other watchlist
*[other] {$otherWatchlists} other watchlists
}
discord-watchlist-connection-entry-expires-more = - {$playerName} with message "{$message}" (expires <t:{$expiry}:R>) and { $otherWatchlists ->
[one] {$otherWatchlists} other watchlist
*[other] {$otherWatchlists} other watchlists
}
Loading