From 24eb5d3371c2ddb791328aaec2b8517872a75c04 Mon Sep 17 00:00:00 2001 From: linmeideli <2558527373@qq.com> Date: Thu, 9 Jul 2026 13:22:26 +0800 Subject: [PATCH] Update Webhook --- docs/Admin-panel.md | 175 --------- docs/Building-from-source.md | 29 -- docs/Chat-filtering.md | 82 ----- docs/Discord-webhook.md | 55 --- docs/FAQ.md | 23 -- docs/Hello-page.md | 41 --- docs/Http-server.md | 82 ----- docs/Player-statistics.md | 64 ---- docs/Plugin-marketplace.md | 50 --- docs/README.md | 7 - docs/Running-the-server.md | 37 -- docs/Server-configuration.md | 224 ------------ docs/TROUBLESHOOTING.md | 63 ---- docs/Upgrading.md | 12 - docs/Writing-a-plugin.md | 332 ------------------ docs/images/client.jpg | Bin 51524 -> 0 bytes docs/images/logo_100.png | Bin 3847 -> 0 bytes .../Config/DiscordWebhookConfig.cs | 21 +- src/Empostor.Server/Http/AdminController.cs | 53 +-- .../Http/AdminTemplateDefaults.cs | 67 ++-- src/Empostor.Server/Pages/AdminStrings.json | 16 +- .../Service/Api/DiscordWebhookListener.cs | 91 +++-- .../Service/Api/DiscordWebhookStore.cs | 75 ++-- src/Empostor.Server/config.json | 9 +- 24 files changed, 136 insertions(+), 1472 deletions(-) delete mode 100644 docs/Admin-panel.md delete mode 100644 docs/Building-from-source.md delete mode 100644 docs/Chat-filtering.md delete mode 100644 docs/Discord-webhook.md delete mode 100644 docs/FAQ.md delete mode 100644 docs/Hello-page.md delete mode 100644 docs/Http-server.md delete mode 100644 docs/Player-statistics.md delete mode 100644 docs/Plugin-marketplace.md delete mode 100644 docs/README.md delete mode 100644 docs/Running-the-server.md delete mode 100644 docs/Server-configuration.md delete mode 100644 docs/TROUBLESHOOTING.md delete mode 100644 docs/Upgrading.md delete mode 100644 docs/Writing-a-plugin.md delete mode 100644 docs/images/client.jpg delete mode 100644 docs/images/logo_100.png diff --git a/docs/Admin-panel.md b/docs/Admin-panel.md deleted file mode 100644 index c1a662c..0000000 --- a/docs/Admin-panel.md +++ /dev/null @@ -1,175 +0,0 @@ -# Admin Panel - -Empostor includes a built-in web-based admin panel available at `http://your-server:22023/admin`. - -## Authentication - -The panel is protected by a password set in `config.json`: - -```json -"Admin": { - "Password": "your-strong-password-here", - "MarketplaceUrl": "https://raw.githubusercontent.com/your-org/your-repo/main/marketplace/plugins.json" -} -``` - -The password is hashed (SHA256) in memory and in cookies — the plaintext is never stored in the browser or compared directly. On first visit the login page is shown. After a successful login a session cookie (HttpOnly, Secure, SameSite=Strict) valid for 8 hours is set. Clicking **Sign out** clears it immediately. - -After 5 failed login attempts from the same IP, that IP is locked out for 15 minutes. - -All API endpoints under `/api/admin/` return `401 Unauthorized` if the cookie is absent or incorrect. - ---- - -## Overview - -The main dashboard shows at a glance: - -- Total and public game count -- Active games (in progress) -- Connected player count -- Total ban count (IP + friend code) -- Server uptime - -A live game list is displayed below the stat cards, refreshing every 3 seconds. - ---- - -## Games - -Lists all active rooms with: - -- Room code -- State (NotStarted / Starting / Started / Ended) -- Visibility (Public / Private) -- Map name -- Player count vs. max players -- Host name and friend code -- All players in the room (hover for friend code and IP) - ---- - -## Clients - -Lists all connected clients with: - -- Client ID -- Name -- Friend code -- IP address -- Among Us client version -- Platform -- Whether they are in a game, and which room code -- Reactor mod count badge (if the client runs Reactor) - -Clicking **Detail** on any client row opens a side panel showing: - -- Full player identity (name, friend code, PUID, IP, client version, language, platform) -- Current game code -- Reactor protocol version and full mod list (mod ID, version, required flag) - ---- - -## Broadcast - -Sends a chat message to every active game on behalf of the host of that game. The message is prefixed with `[Server]`. - ---- - -## Kick - -Removes a player from the server without banning. The player can reconnect immediately. - -Players can be kicked by entering a Client ID, or by using the **Quick Kick** table which lists all connected clients with a one-click button. - ---- - -## Ban - -### Ban by IP - -Bans an IP address and immediately disconnects all clients connected from that address. The reason is saved to `bans.json` and persists across server restarts. - -### Ban by Friend Code - -Bans a specific friend code and immediately disconnects any client currently connected with it. - -Both ban types can be removed from the **Ban List** tab at any time. - ---- - -## Ban List - -Shows all active IP bans and friend code bans with: - -- Banned value (IP or friend code) -- Reason -- Timestamp - -Each entry has an **Unban** button that takes effect immediately. - ---- - -## Message - -Sends a targeted chat message to a specific game room by code. Useful for communicating with a single room without broadcasting server-wide. - ---- - -## End Game - -Force-terminates a game by kicking all players in it. The room is destroyed immediately. A confirmation dialog is shown before the action is executed. - -The tab also lists all active games with a one-click **End** button per row. - ---- - -## Privacy - -Toggles a game between Public and Private. This affects whether the room appears in the public lobby list. - ---- - -## Plugin Marketplace - -Fetches the plugin list from the URL configured in `Admin.MarketplaceUrl` (a raw GitHub JSON file). For each plugin, the latest version, supported Empostor version, and description are shown. - -Clicking **Install** downloads the `.dll` to the `plugins/` folder. The server must be restarted to load the new plugin. - -If the plugin was built for a different Empostor version, a warning is displayed but installation is not blocked. - ---- - -## Updates - -Queries the GitHub Releases API for the latest Empostor release and compares it with the running version. If a newer version is available, a link to the release page is shown. The server does not update itself automatically. - -The GitHub repository checked is `Empostor/Empostor` by default. If you maintain a fork, this is hardcoded in `MarketplaceController.cs`. - ---- - -## Reports - -Shows the last 200 player reports submitted in-game (via the Among Us report button): - -| Column | Description | -|--------|-------------| -| Time | UTC timestamp of the report | -| Game | Room code | -| Reporter | Name and friend code of the reporting player | -| Reported | Name and friend code of the reported player | -| Reason | `InappropriateName`, `InappropriateChat`, `Cheating_Hacking`, `Harassment_Misconduct` | -| Outcome | `NotReportedUnknown`, `NotReportedNoAccount`, `Reported`, etc. | - -Reports are held in memory and cleared on server restart. Plugins can listen to `IPlayerReportEvent` to persist reports or trigger further actions. - ---- - -## Server Info - -Displays runtime details: - -- Server start time and uptime -- Process ID -- .NET runtime version and OS -- Current ban and auth session counts diff --git a/docs/Building-from-source.md b/docs/Building-from-source.md deleted file mode 100644 index eb4f516..0000000 --- a/docs/Building-from-source.md +++ /dev/null @@ -1,29 +0,0 @@ -# Building from source - -The solution contains the Empostor server and its dependencies, like Hazel and the plugin API. The server is built using [.NET 8](https://dotnet.microsoft.com/download/dotnet/8.0). - -## Cloning Empostor - -You need to clone Empostor using git: - -```bash -git clone https://github.com/Empostor/Empostor.git -``` - -## Building the server - -### Dependencies - -- [.NET 8 SDK](https://dotnet.microsoft.com/download/dotnet/8.0) -- [Rider](https://www.jetbrains.com/rider/) or [Visual Studio](https://visualstudio.microsoft.com/vs/) (Optional, only if you want the full IDE experience) - -### Build using the CLI - -```bash -cd src/Empostor.Server/ -dotnet build -# Or if you want a single file, ready for production: (change linux-x64 to win-x64 if you use Windows) -dotnet publish -c Release -r linux-x64 -p:PublishSingleFile=true -``` - -To setup the server, please look at [Running the server](Running-the-server.md). diff --git a/docs/Chat-filtering.md b/docs/Chat-filtering.md deleted file mode 100644 index cc2864f..0000000 --- a/docs/Chat-filtering.md +++ /dev/null @@ -1,82 +0,0 @@ -# Chat Filtering - -Empostor can filter in-game chat messages by blocking specific words and limiting message spam. This helps server administrators maintain a healthier chat environment. - -This feature is **disabled by default**. Enable it in `config.json` or from the admin panel to activate filtering. - -## Admin Panel - -A **Chat Filter** tab is available in the admin panel under the Monitor section. It allows you to manage all settings at runtime without editing `config.json` or restarting the server: - -- **Enable/Disable** filtering with a checkbox -- **Add/Remove blocked words** — type a word and click Add, or click the × on any tag to remove it -- **Spam settings** — adjust the message threshold and time window -- **Block/log toggle** — choose whether to block messages or only log warnings - -Settings changed via the admin panel take effect immediately but are runtime-only — they are lost on server restart. For permanent settings, edit `config.json`. - -## Configuration - -Add the `ChatFilter` section to your `config.json`: - -```json -{ - "ChatFilter": { - "Enabled": false, - "BlockedWords": [], - "BlockMessage": true, - "SpamThreshold": 5, - "SpamWindowSeconds": 10 - } -} -``` - -| Key | Default | Description | -| :--- | :--- | :--- | -| **Enabled** | `false` | Whether chat filtering is enabled. | -| **BlockedWords** | `[]` | A list of words to block. Matching is **case-insensitive** and uses substring matching (e.g., blocking `"bad"` also blocks `"badword"`). | -| **BlockMessage** | `true` | Whether to actually block filtered messages. When `true`, the message is cancelled and never reaches other players. When `false`, the message is allowed through but a warning is logged. | -| **SpamThreshold** | `5` | Number of messages allowed within the spam window before rate limiting kicks in. | -| **SpamWindowSeconds** | `10` | The sliding time window in seconds for spam detection. | - -## How Filtering Works - -### Word Filter - -When a player sends a chat message, it is checked against the `BlockedWords` list: - -1. The message text is compared against each blocked word (case-insensitive substring match). -2. If a match is found and `BlockMessage` is `true`, the message is blocked — other players will not see it. -3. If `BlockMessage` is `false`, the message goes through but a warning is logged. - -### Spam Filter - -Each player has a per-player sliding window to detect rapid messaging: - -1. Every chat message timestamp is recorded per player. -2. If a player sends `SpamThreshold` or more messages within the last `SpamWindowSeconds` seconds, the message is handled according to `BlockMessage`. -3. Old timestamps outside the window are automatically discarded. - -Both filters run independently — a message can be blocked by either the word filter or the spam filter. - -## Example - -To block profanity and prevent players from sending more than 3 messages in 5 seconds: - -```json -{ - "ChatFilter": { - "Enabled": true, - "BlockedWords": ["badword1", "badword2"], - "BlockMessage": true, - "SpamThreshold": 3, - "SpamWindowSeconds": 5 - } -} -``` - -## Troubleshooting - -- **Messages are not being blocked**: Ensure `Enabled` is `true` and `BlockedWords` contains entries. Remember that matching is substring-based — short words may match unexpectedly. -- **False positives**: Use specific, longer words in your `BlockedWords` list. Substring matching means `"ass"` would match `"pass"` and `"classic"`. -- **Legitimate players get spam-blocked**: Increase `SpamThreshold` or decrease `SpamWindowSeconds`. The defaults (5 messages / 10 seconds) are generous for normal conversation. diff --git a/docs/Discord-webhook.md b/docs/Discord-webhook.md deleted file mode 100644 index 3e5f9f7..0000000 --- a/docs/Discord-webhook.md +++ /dev/null @@ -1,55 +0,0 @@ -# Discord Webhook Integration - -Empostor can send game events to a Discord channel via [webhooks](https://support.discord.com/hc/en-us/articles/228383668-Intro-to-Webhooks). Each event is sent as a rich embed with relevant details. - -This feature is **disabled by default**. Enable it in `config.json` and provide a webhook URL to activate it. - -## Configuration - -Add the `DiscordWebhook` section to your `config.json`: - -```json -{ - "DiscordWebhook": { - "Enabled": false, - "WebhookUrl": "", - "NotifyOnGameCreated": true, - "NotifyOnBan": true, - "NotifyOnReport": true, - "NotifyOnPlayerJoin": false, - "NotifyOnGameEnded": false - } -} -``` - -| Key | Default | Description | -| :--- | :--- | :--- | -| **Enabled** | `false` | Whether the Discord webhook integration is enabled. | -| **WebhookUrl** | `""` | The Discord webhook URL to POST messages to. Create one in Discord under Channel Settings → Integrations → Webhooks. | -| **NotifyOnGameCreated** | `true` | Send a notification when a new game lobby is created. | -| **NotifyOnBan** | `true` | Send a notification when a player is banned from the server. | -| **NotifyOnReport** | `true` | Send a notification when a player reports a dead body in-game. | -| **NotifyOnPlayerJoin** | `false` | Send a notification when a player joins a game lobby. | -| **NotifyOnGameEnded** | `false` | Send a notification when a game ends. | - -## Events - -Each notification is sent as a Discord embed with a colored sidebar: - -| Event | Embed Color | Fields | -| :--- | :--- | :--- | -| Game Created | Green | Game code, host name, host friend code | -| Player Banned | Red | Player name, friend code, game code | -| Player Reported | Yellow | Reporter, reported player, friend codes, game code, reason | -| Player Joined | Green | Player name, friend code, game code, player count | -| Game Ended | Purple | Game code, result, player count | - -## Rate Limiting - -To avoid hitting Discord's rate limits, duplicate events for the same game within 2 seconds are suppressed. - -## Troubleshooting - -- **No messages appear in Discord**: Verify `WebhookUrl` is correct and the webhook is active in your Discord channel. Check the server logs for `[Discord]` warnings. -- **Webhook returns HTTP errors**: Discord may rate-limit or the webhook URL may be invalid. The listener logs the HTTP status code on failure. -- **Events trigger but some fields are blank**: Friendly names and friend codes are read from client data — some fields may be empty (`—`) if the client hasn't fully connected yet. diff --git a/docs/FAQ.md b/docs/FAQ.md deleted file mode 100644 index b175e62..0000000 --- a/docs/FAQ.md +++ /dev/null @@ -1,23 +0,0 @@ -# Frequently Answered Questions - -## What is this? - -The Empostor project is a reverse engineered and open source server for the game Among Us. The game itself is developed by [Innersloth](http://www.innersloth.com/) while this project is maintained by the community. This project was built out of frustration for the lack of server availability in certain regions and the inability for the core developer, [AeonLucid](https://github.com/AeonLucid), to join a public game. As of this time, it has not been officially endorsed by the studio. - -## Can this be used with the mobile version of the game? - -Yes, Empostor can be used with both the Android and iOS versions of the game. You can add a custom server via a link, you can do this using the [site](https://empostor.github.io/Empostor) - -## Can this be used with the console version of the game? - -Sadly not, as these don't allow adding custom servers. - -## Can this be used with Among Us 3D/VR? - -No, it's an entirely different game with a completely different network stack. So we'd need to develop another server completely from scratch. We're currently not interested in doing this. - -## How can I get started? - -See [Setting up your Server](Running-the-server.md) for more information on running the server and [Client Setup](https://empostor.github.io/Empostor/) for helping your friends join in! - -If you're having issues with the server software, check the [Troubleshooting page](TROUBLESHOOTING.md). diff --git a/docs/Hello-page.md b/docs/Hello-page.md deleted file mode 100644 index 0b691b7..0000000 --- a/docs/Hello-page.md +++ /dev/null @@ -1,41 +0,0 @@ -# Hello Page (Home Page) - -Empostor serves a customisable home page at `http://your-server:22023/`. - -## How it works - -On startup, the server checks for a `Pages/` directory next to the executable. If it does not exist it is created automatically, and a default `index.html` is written into it. - -``` -Empostor.Server (binary) -Pages/ - index.html ← served at GET / -``` - -Every request to `/` reads the file from disk at that moment, so edits take effect without restarting the server. - -## Customising the page - -Edit `Pages/index.html` with any HTML content you want. Common uses: - -- Server rules and information -- Discord invite link -- Region file download instructions -- Link to the admin panel - -If the file is deleted, a plain fallback response is returned until the server is restarted and regenerates the default file. - -## Default page - -The generated default page contains: - -- A status indicator showing the server is online -- A link to the admin panel (`/admin`) -- A link to the [region file generator](https://empostor.github.io/Empostor) -- The server start time - -## Notes - -- The page is served as `text/html; charset=utf-8`. -- There is no template engine. The file is served as-is. -- For HTTPS access, configure a reverse proxy. See [Http-server.md](Http-server.md). diff --git a/docs/Http-server.md b/docs/Http-server.md deleted file mode 100644 index e3c1f88..0000000 --- a/docs/Http-server.md +++ /dev/null @@ -1,82 +0,0 @@ -# HTTP Server - -Since Empostor 1.9.0 a HTTP service is included for matchmaking, which is required for clients to connect to the Empostor server. - -Starting from Among Us 16.0.5, you need to set up HTTPS for players to connect to your server. -Unfortunately Empostor doesn't handle SSL certificates, so you need to set up a reverse proxy. - -## Use a reverse proxy - -A reverse proxy allows you to forward HTTP requests from users to multiple services. If you already have one, you should configure it to add Empostor. - -If you have never set up a reverse proxy before, we recommend you to set up [Caddy](https://caddyserver.com/). It is easy to set up and comes with support for requesting SSL certificates out of the box. - -To prevent people from connecting directly to Empostor, we recommend changing the "ListenIp" in the "HttpServer" section to "127.0.0.1". This makes sure people can't connect to your HTTP server other than via your reverse proxy. Keep the "ListenIp" in the "Server" section at "0.0.0.0" though, running the normal game traffic through a proxy is not supported. - -### Caddy - -To install Caddy, follow the [official installation guide](https://caddyserver.com/docs/install). Then use the following lines as your `Caddyfile` configuration file: - -``` -example.com # replace example.com with your domain name - -reverse_proxy :22023 -``` - -Now run `caddy run` in the folder with this Caddyfile and it should set up a server for you with a free SSL certificate. -If this works, you should set up [Caddy to run in the background](https://caddyserver.com/docs/running) - -### Nginx - -Nginx is an alternative to Caddy that is a bit harder to set up. If you already use Nginx, you can use our snippet to add Empostor: - -
Nginx configuration - -```nginx -server { - listen 443 ssl http2; - server_name example.com; # replace example.com with your domain name - - # Assuming you're using Certbot, replace example.com with your domain name - ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem; - ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem; - ssl_trusted_certificate /etc/letsencrypt/live/example.com/fullchain.pem; - - location / { - proxy_pass http://localhost:22023; # Change the port to your HttpServer's ListenPort - proxy_set_header X-Forwarded-For $remote_addr; - proxy_set_header X-Forwarded-Proto $scheme; - } -} - -# Redirect all traffic to HTTPS -server { - listen 80 default_server; - location / { - return 307 https://$host$request_uri; - } -} -``` - -
- -## Stop exposing Empostor's HTTP server to the internet directly - -To only allow connections to Empostor's HTTP servers via the reverse proxy, we recommend to set the ListenIp of the HTTP server to 127.0.0.1: - -```json -{ - // NOTE: merge this snippet into the rest of your configuration - "HttpServer": { - "ListenIp": "127.0.0.1" - } -} -``` - -Or if you're configuring Empostor with environment variables: - -```sh -IMPOSTOR_HttpServer__ListenIp=127.0.0.1 -``` - -For more information on server configuration, see [Server-configuration.md](Server Configuration). diff --git a/docs/Player-statistics.md b/docs/Player-statistics.md deleted file mode 100644 index 8266b12..0000000 --- a/docs/Player-statistics.md +++ /dev/null @@ -1,64 +0,0 @@ -# Player Statistics - -Empostor can track per-player game statistics including wins, kills, tasks completed, and more. Statistics are viewable through the admin panel and via the `/stat` in-game command. - -This feature is **disabled by default**. Enable it in `config.json` to begin tracking. - -## Configuration - -Add the `PlayerStats` section to your `config.json`: - -```json -{ - "PlayerStats": { - "Enabled": false, - "PersistToFile": true - } -} -``` - -| Key | Default | Description | -| :--- | :--- | :--- | -| **Enabled** | `false` | Whether player statistics tracking is enabled. | -| **PersistToFile** | `true` | Whether to save statistics to `player_stats.json` on disk. If disabled, stats are kept in memory only and lost on server restart. | - -## Tracked Statistics - -The following metrics are recorded per player (keyed by Friend Code): - -| Stat | Description | -| :--- | :--- | -| Games Played | Total number of games the player participated in | -| Wins | Number of games won as a crewmate | -| Losses | Number of games lost as a crewmate | -| Impostor Wins | Number of games won as an impostor | -| Kills | Total kills performed | -| Deaths | Total times killed | -| Tasks Completed | Total tasks completed | -| Times Exiled | Total times voted out | - -## Admin Panel - -When enabled, a **Statistics** tab appears in the admin panel under the Monitor section. It displays a ranked table sorted by games played, with columns for all tracked stats. Use the **Refresh** button to reload data and **Reset All** to clear all statistics (requires confirmation). - -## In-Game Command - -Players can check their own stats by typing `/stat` (or `/stats`, `/mystats`) in the in-game chat. The response is sent privately and is localized based on the player's language. - -## Localization - -The `/stat` command response supports all languages configured in Empostor's language system. If no translation exists for the player's language, English is used as a fallback. - -## API Endpoints - -The admin panel uses these API endpoints: - -| Method | Path | Description | -| :--- | :--- | :--- | -| `GET` | `/api/admin/player/stats` | Returns all player statistics sorted by games played. Response: `{"enabled": true, "players": [...]}` | -| `GET` | `/api/admin/player/stats/{friendCode}` | Returns statistics for a single player by Friend Code. | -| `POST` | `/api/admin/player/stats/reset` | Clears all player statistics. Requires admin authentication. | - -## File Persistence - -When `PersistToFile` is enabled, statistics are saved to `player_stats.json` in the server directory. The file is updated after each game ends, following the same pattern as the ban and report stores. diff --git a/docs/Plugin-marketplace.md b/docs/Plugin-marketplace.md deleted file mode 100644 index c6dfa84..0000000 --- a/docs/Plugin-marketplace.md +++ /dev/null @@ -1,50 +0,0 @@ -# Plugin Marketplace Format - -The admin panel plugin marketplace reads `marketplace/plugins.json` at startup. - -## JSON Schema - -```jsonc -[ - { - // Unique plugin identifier (reverse-domain style recommended) - "id": "cn.hayashiume.welcome", - - // Display name shown in the marketplace - "name": "Welcome Messages", - - // Short description (shown as subtitle) - "description": "Sends a localised welcome message when players join a room.", - - // Author attribution - "author": "BunchHanpiDev & HayashiUme", - - // Version history — latest version should be LAST in the array - "versions": [ - { - // Semantic version of this plugin release - "version": "1.0.0", - - // Minimum Empostor / Empostor version required - "empostor_version": "2.0.0", - - // Direct download URL for the .dll file - "download_url": "https://raw.githubusercontent.com/Empostor/Empostor/master/marketplace/Empostor.Plugins.Welcome.dll" - } - ] - } -] -``` - -## Versioning Rules - -- **`versions` array**: Each entry represents one downloadable release. List older versions first; the **last entry** is treated as the latest and is selected by default in the admin panel UI. -- **Single-version plugins**: An array with one entry is valid. The version dropdown is hidden and the sole version is used directly. -- **Multi-version plugins**: When two or more entries exist, the admin panel shows a ` - Enable Discord Webhook - - -
- - -
-

Notifications

-
- - - - - +
+ + +
Game Created, Game Started, Game Ended, Player Joined
+
+
+ + +
Player Banned, Player Reported
+
+
Leave a URL empty to disable its notifications. Leave both empty to disable all webhooks.
@@ -1418,27 +1398,20 @@ internal static class AdminTemplateDefaults async function fDiscordWebhook() { const { data } = await api('GET', '/api/admin/discord'); - document.getElementById('dw-enabled').checked = data.enabled; - const urlEl = document.getElementById('dw-url'); - if (document.activeElement !== urlEl) { - urlEl.value = data.webhookUrl || ''; + const mmUrlEl = document.getElementById('dw-matchmaker-url'); + const adminUrlEl = document.getElementById('dw-admin-url'); + if (document.activeElement !== mmUrlEl) { + mmUrlEl.value = data.matchmakerUrl || ''; + } + if (document.activeElement !== adminUrlEl) { + adminUrlEl.value = data.adminUrl || ''; } - document.getElementById('dw-game-created').checked = data.notifyOnGameCreated; - document.getElementById('dw-ban').checked = data.notifyOnBan; - document.getElementById('dw-report').checked = data.notifyOnReport; - document.getElementById('dw-player-join').checked = data.notifyOnPlayerJoin; - document.getElementById('dw-game-ended').checked = data.notifyOnGameEnded; } async function saveDwSettings() { const { ok, data } = await api('POST', '/api/admin/discord', { - enabled: document.getElementById('dw-enabled').checked, - webhookUrl: document.getElementById('dw-url').value.trim(), - notifyOnGameCreated: document.getElementById('dw-game-created').checked, - notifyOnBan: document.getElementById('dw-ban').checked, - notifyOnReport: document.getElementById('dw-report').checked, - notifyOnPlayerJoin: document.getElementById('dw-player-join').checked, - notifyOnGameEnded: document.getElementById('dw-game-ended').checked + matchmakerUrl: document.getElementById('dw-matchmaker-url').value.trim(), + adminUrl: document.getElementById('dw-admin-url').value.trim() }); if (ok) { msg('dw-r', true, _('discord.saved', 'Discord webhook settings saved.')); diff --git a/src/Empostor.Server/Pages/AdminStrings.json b/src/Empostor.Server/Pages/AdminStrings.json index 55fd290..0d735be 100644 --- a/src/Empostor.Server/Pages/AdminStrings.json +++ b/src/Empostor.Server/Pages/AdminStrings.json @@ -217,14 +217,12 @@ "discord.title": "Discord Webhook", "discord.save": "Save Settings", - "discord.enabled": "Enable Discord Webhook", - "discord.webhook_url": "Webhook URL", - "discord.webhook_url_placeholder": "https://discord.com/api/webhooks/...", - "discord.notifications": "Notifications", - "discord.notify_game_created": "Game Created", - "discord.notify_ban": "Player Banned", - "discord.notify_report": "Player Reported", - "discord.notify_player_join": "Player Joined", - "discord.notify_game_ended": "Game Ended", + "discord.matchmaker_url": "Matchmaker Webhook URL", + "discord.matchmaker_url_placeholder": "https://discord.com/api/webhooks/...", + "discord.matchmaker_desc": "Game Created, Game Started, Game Ended, Player Joined", + "discord.admin_url": "Admin Webhook URL", + "discord.admin_url_placeholder": "https://discord.com/api/webhooks/...", + "discord.admin_desc": "Player Banned, Player Reported", + "discord.hint": "Leave a URL empty to disable its notifications. Leave both empty to disable all webhooks.", "discord.saved": "Discord webhook settings saved." } diff --git a/src/Empostor.Server/Service/Api/DiscordWebhookListener.cs b/src/Empostor.Server/Service/Api/DiscordWebhookListener.cs index 2cdabb4..f8488ae 100644 --- a/src/Empostor.Server/Service/Api/DiscordWebhookListener.cs +++ b/src/Empostor.Server/Service/Api/DiscordWebhookListener.cs @@ -1,5 +1,4 @@ using System; -using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Net.Http; @@ -19,7 +18,6 @@ internal sealed class DiscordWebhookListener : IEventListener private readonly ILogger _logger; private readonly IHttpClientFactory _http; private readonly DiscordWebhookStore _config; - private readonly ConcurrentDictionary _throttle = new(); public DiscordWebhookListener( ILogger logger, @@ -34,12 +32,13 @@ internal sealed class DiscordWebhookListener : IEventListener [EventListener] public ValueTask OnGameCreated(IGameCreatedEvent e) { - if (!_config.Enabled || !_config.NotifyOnGameCreated) + var url = _config.MatchmakerUrl; + if (string.IsNullOrWhiteSpace(url)) { return default; } - return SendAsync("Game Created", 3066993, new() + return SendAsync(url, "Game Created", 3066993, new() { ["Game"] = GameCodeParser.IntToGameName(e.Game.Code), ["Host"] = e.Host?.Name ?? "—", @@ -48,49 +47,33 @@ internal sealed class DiscordWebhookListener : IEventListener } [EventListener] - public ValueTask OnPlayerLeft(IGamePlayerLeftEvent e) + public ValueTask OnGameStarted(IGameStartedEvent e) { - if (!_config.Enabled || !_config.NotifyOnBan || !e.IsBan) + var url = _config.MatchmakerUrl; + if (string.IsNullOrWhiteSpace(url)) { return default; } - return SendAsync("Player Banned", 15158332, new() + return SendAsync(url, "Game Started", 3447003, new() { - ["Player"] = e.Player.Client.Name, - ["Friend Code"] = e.Player.Client.FriendCode ?? "—", ["Game"] = GameCodeParser.IntToGameName(e.Game.Code), - }); - } - - [EventListener] - public ValueTask OnPlayerReport(IPlayerReportEvent e) - { - if (!_config.Enabled || !_config.NotifyOnReport) - { - return default; - } - - return SendAsync("Player Reported", 16776960, new() - { - ["Reporter"] = e.ClientPlayer.Client.Name, - ["Reporter FC"] = e.ClientPlayer.Client.FriendCode ?? "—", - ["Reported"] = e.ReportedClient?.Name ?? "body", - ["Reported FC"] = e.ReportedClient?.FriendCode ?? "—", - ["Game"] = GameCodeParser.IntToGameName(e.Game.Code), - ["Reason"] = e.Reason.ToString(), + ["Map"] = e.Game.Options.Map.ToString(), + ["Players"] = e.Game.PlayerCount.ToString(), + ["Impostors"] = e.Game.Options.NumImpostors.ToString(), }); } [EventListener] public ValueTask OnPlayerJoin(IGamePlayerJoinedEvent e) { - if (!_config.Enabled || !_config.NotifyOnPlayerJoin) + var url = _config.MatchmakerUrl; + if (string.IsNullOrWhiteSpace(url)) { return default; } - return SendAsync("Player Joined", 3066993, new() + return SendAsync(url, "Player Joined", 3066993, new() { ["Player"] = e.Player.Client.Name, ["Friend Code"] = e.Player.Client.FriendCode ?? "—", @@ -102,12 +85,13 @@ internal sealed class DiscordWebhookListener : IEventListener [EventListener] public ValueTask OnGameEnded(IGameEndedEvent e) { - if (!_config.Enabled || !_config.NotifyOnGameEnded) + var url = _config.MatchmakerUrl; + if (string.IsNullOrWhiteSpace(url)) { return default; } - return SendAsync("Game Ended", 10181046, new() + return SendAsync(url, "Game Ended", 10181046, new() { ["Game"] = GameCodeParser.IntToGameName(e.Game.Code), ["Result"] = e.GameOverReason.ToString(), @@ -115,22 +99,51 @@ internal sealed class DiscordWebhookListener : IEventListener }); } - private async ValueTask SendAsync(string title, int color, Dictionary fields) + // ── Admin events ─────────────────────────────────────────────── + [EventListener] + public ValueTask OnPlayerLeft(IGamePlayerLeftEvent e) { - var url = _config.WebhookUrl; + if (!e.IsBan) + { + return default; + } + + var url = _config.AdminUrl; if (string.IsNullOrWhiteSpace(url)) { - return; + return default; } - var key = title + (fields.TryGetValue("Game", out var gc) ? gc : string.Empty); - if (_throttle.TryGetValue(key, out var last) && (DateTime.UtcNow - last).TotalSeconds < 2) + return SendAsync(url, "Player Banned", 15158332, new() { - return; + ["Player"] = e.Player.Client.Name, + ["Friend Code"] = e.Player.Client.FriendCode ?? "—", + ["Game"] = GameCodeParser.IntToGameName(e.Game.Code), + }); + } + + [EventListener] + public ValueTask OnPlayerReport(IPlayerReportEvent e) + { + var url = _config.AdminUrl; + if (string.IsNullOrWhiteSpace(url)) + { + return default; } - _throttle[key] = DateTime.UtcNow; + return SendAsync(url, "Player Reported", 16776960, new() + { + ["Reporter"] = e.ClientPlayer.Client.Name, + ["Reporter FC"] = e.ClientPlayer.Client.FriendCode ?? "—", + ["Reported"] = e.ReportedClient?.Name ?? "body", + ["Reported FC"] = e.ReportedClient?.FriendCode ?? "—", + ["Game"] = GameCodeParser.IntToGameName(e.Game.Code), + ["Reason"] = e.Reason.ToString(), + }); + } + private async ValueTask SendAsync(string url, string title, int color, Dictionary fields) + { try { var embed = new diff --git a/src/Empostor.Server/Service/Api/DiscordWebhookStore.cs b/src/Empostor.Server/Service/Api/DiscordWebhookStore.cs index 00798e1..745a742 100644 --- a/src/Empostor.Server/Service/Api/DiscordWebhookStore.cs +++ b/src/Empostor.Server/Service/Api/DiscordWebhookStore.cs @@ -1,6 +1,7 @@ using System; using System.IO; using System.Text.Json; +using System.Text.Json.Serialization; using System.Threading; using System.Threading.Tasks; using Empostor.Api.Config; @@ -12,7 +13,11 @@ namespace Empostor.Server.Service.Api; public sealed class DiscordWebhookStore { private static readonly string ConfigFile = Path.Combine(Directory.GetCurrentDirectory(), "discord_webhook.json"); - private static readonly JsonSerializerOptions JsonOpts = new() { WriteIndented = true }; + private static readonly JsonSerializerOptions JsonOpts = new() + { + WriteIndented = true, + DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull, + }; private readonly ILogger _logger; private readonly SemaphoreSlim _saveLock = new(1, 1); @@ -21,23 +26,17 @@ public sealed class DiscordWebhookStore { _logger = logger; + DiscordWebhookConfig? cfg = null; + if (File.Exists(ConfigFile)) { try { var json = File.ReadAllText(ConfigFile); - var saved = JsonSerializer.Deserialize(json); - if (saved != null) + cfg = JsonSerializer.Deserialize(json); + if (cfg != null) { - Enabled = saved.Enabled; - WebhookUrl = saved.WebhookUrl; - NotifyOnGameCreated = saved.NotifyOnGameCreated; - NotifyOnBan = saved.NotifyOnBan; - NotifyOnReport = saved.NotifyOnReport; - NotifyOnPlayerJoin = saved.NotifyOnPlayerJoin; - NotifyOnGameEnded = saved.NotifyOnGameEnded; _logger.LogInformation("DiscordWebhookLoaded from {File}", ConfigFile); - return; } } catch (Exception ex) @@ -47,39 +46,23 @@ public sealed class DiscordWebhookStore } // Fall back to config.json values - var cfg = config.Value; - Enabled = cfg.Enabled; - WebhookUrl = cfg.WebhookUrl; - NotifyOnGameCreated = cfg.NotifyOnGameCreated; - NotifyOnBan = cfg.NotifyOnBan; - NotifyOnReport = cfg.NotifyOnReport; - NotifyOnPlayerJoin = cfg.NotifyOnPlayerJoin; - NotifyOnGameEnded = cfg.NotifyOnGameEnded; + cfg ??= config.Value; + + // Migrate legacy WebhookUrl to new fields if present and new fields are empty + MigrateLegacy(cfg); + + MatchmakerUrl = cfg.MatchmakerUrl; + AdminUrl = cfg.AdminUrl; } - public bool Enabled { get; set; } + public string MatchmakerUrl { get; set; } = string.Empty; - public string WebhookUrl { get; set; } = string.Empty; - - public bool NotifyOnGameCreated { get; set; } = true; - - public bool NotifyOnBan { get; set; } = true; - - public bool NotifyOnReport { get; set; } = true; - - public bool NotifyOnPlayerJoin { get; set; } - - public bool NotifyOnGameEnded { get; set; } + public string AdminUrl { get; set; } = string.Empty; public DiscordWebhookConfig Snapshot => new() { - Enabled = Enabled, - WebhookUrl = WebhookUrl, - NotifyOnGameCreated = NotifyOnGameCreated, - NotifyOnBan = NotifyOnBan, - NotifyOnReport = NotifyOnReport, - NotifyOnPlayerJoin = NotifyOnPlayerJoin, - NotifyOnGameEnded = NotifyOnGameEnded, + MatchmakerUrl = MatchmakerUrl, + AdminUrl = AdminUrl, }; public async ValueTask SaveAsync() @@ -104,4 +87,20 @@ public sealed class DiscordWebhookStore _saveLock.Release(); } } + + private static void MigrateLegacy(DiscordWebhookConfig cfg) + { + if (!string.IsNullOrWhiteSpace(cfg.WebhookUrl)) + { + if (string.IsNullOrWhiteSpace(cfg.MatchmakerUrl)) + { + cfg.MatchmakerUrl = cfg.WebhookUrl; + } + + if (string.IsNullOrWhiteSpace(cfg.AdminUrl)) + { + cfg.AdminUrl = cfg.WebhookUrl; + } + } + } } diff --git a/src/Empostor.Server/config.json b/src/Empostor.Server/config.json index 45ceeaf..506a5fe 100644 --- a/src/Empostor.Server/config.json +++ b/src/Empostor.Server/config.json @@ -54,13 +54,8 @@ "MarketplaceUrl": "https://raw.githubusercontent.com/Empostor/Empostor/master/marketplace/plugins.json" }, "DiscordWebhook": { - "Enabled": false, - "WebhookUrl": "", - "NotifyOnGameCreated": true, - "NotifyOnBan": true, - "NotifyOnReport": true, - "NotifyOnPlayerJoin": false, - "NotifyOnGameEnded": false + "MatchmakerUrl": "", + "AdminUrl": "" }, "PlayerStats": { "Enabled": false,