Skip to content
Closed
Show file tree
Hide file tree
Changes from all 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
2 changes: 1 addition & 1 deletion mods.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
"mods": [
{ "id": "backpack", "name": "Extra Backpack", "description": "An optional native 20-slot extra backpack for every character class.", "author": "zj1022", "version": "1.0.3", "compatibleClientVersions": ["0.5.1-beta", "0.5.2-beta"], "kind": "feature", "type": "script", "path": "mods/backpack", "depends": [], "settings": false },
{ "id": "fastcampaign", "name": "Fast Campaign", "description": "A faster campaign: 5x kill experience, +50% movement speed, and /fast lists the commands that skip ahead.", "author": "LocalExile", "version": "1.1.4", "compatibleClientVersions": ["0.4.3-beta", "0.5.0-beta", "0.5.1-beta", "0.5.2-beta"], "kind": "feature", "type": "project", "path": "mods/fastcampaign", "depends": [], "settings": true },
{ "id": "globalchat", "name": "Global Chat", "description": "Talk to other LocalExile players: global, trade and whisper chat go through the LocalExile global chat server.", "author": "JetStream", "version": "1.1.4", "compatibleClientVersions": ["0.4.3-beta", "0.5.0-beta", "0.5.1-beta", "0.5.2-beta"], "kind": "feature", "type": "project", "path": "mods/globalchat", "depends": [], "settings": true },
{ "id": "globalchat", "name": "Global Chat", "description": "Talk to other LocalExile players through a shared chat server, with optional Discord and simulated chat routes.", "author": "JetStream", "version": "1.2.16", "compatibleClientVersions": ["0.5.2-beta"], "kind": "feature", "type": "project", "path": "mods/globalchat", "depends": [], "settings": true },
{ "id": "gm-commands", "name": "GM Commands", "description": "The development and testing chat commands: teleport, items, monsters, experience, quest flags, test hits and protocol probes.", "author": "LocalExile", "version": "1.5.0", "compatibleClientVersions": ["0.5.2-beta"], "kind": "feature", "type": "project", "path": "mods/gm-commands", "depends": ["Game"], "settings": false },
{ "id": "itemquantity", "name": "Item Quantity", "description": "10 times as many item drops from every kill.", "author": "LocalExile", "version": "1.1.4", "compatibleClientVersions": ["0.4.3-beta", "0.5.0-beta", "0.5.1-beta", "0.5.2-beta"], "kind": "feature", "type": "project", "path": "mods/itemquantity", "depends": [], "settings": true },
{ "id": "itemrarity", "name": "Item Rarity", "description": "10 times the chance of magic, rare and unique equipment.", "author": "LocalExile", "version": "1.1.4", "compatibleClientVersions": ["0.4.3-beta", "0.5.0-beta", "0.5.1-beta", "0.5.2-beta"], "kind": "feature", "type": "project", "path": "mods/itemrarity", "depends": [], "settings": true },
Expand Down
139 changes: 139 additions & 0 deletions mods/globalchat/ChatChannelRouting.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,139 @@
using System.Globalization;
using System.Text.Json.Nodes;
using GameServer.Core.Protocol.Instance;

namespace GlobalChat;

enum ChatChannelRouteType { Blank, Server, Discord, Fake }

sealed record ChannelChoice(JsonNode? Type, JsonNode? DiscordChannelId, JsonNode? Address, JsonNode? Port, JsonNode? SendToDiscord = null);
sealed record ChatChoices(Dictionary<string, ChannelChoice>? GlobalChannels, Dictionary<string, ChannelChoice>? TradeChannels,
ChannelChoice? FallbackRoute = null, string? DiscordBotToken = null);

readonly record struct ChatRoom(ChatChannelKind Kind, ushort Channel, byte Language)
{
internal TypedChannel TypedChannel => Kind == ChatChannelKind.Trade ? TypedChannel.Trade : TypedChannel.Global;
internal static ChatRoom? Of(ClientState conn, ChatChannelKind kind) =>
ChatRoutes.Membership(Program.CharacterName(conn), kind) is { } channel
? new(kind, channel.Channel, channel.Language) : null;
internal static bool IsListener(ClientState conn) =>
conn is { Controlled: false, Closed: false, LeavingArea: false, PlayerSent: true, Outbox: not null };
public override string ToString() => $"{Kind} {Channel}";
}

sealed record DiscordRoute(ushort Channel, string ChannelId, bool SendToDiscord, ChatChannelKind Kind, bool IsFallback = false);

sealed class ChatChannelRouting
{
internal sealed record Route(ChatChannelRouteType Type, string DiscordId = "", (string Host, int Port)? Server = null, bool SendToDiscord = true);

readonly Dictionary<(ChatChannelKind Kind, ushort Channel), Route> routes = [];
readonly Route fallback;

internal ChatChannelRouting(ChatChoices settings, Action<string> log)
{
Apply(ChatChannelKind.Global, settings.GlobalChannels, log);
Apply(ChatChannelKind.Trade, settings.TradeChannels, log);
fallback = settings.FallbackRoute is { } choice ? ParseRoute(choice, "Fallback route", log, defaultForward: false)
: new(ChatChannelRouteType.Blank);
HasFakeChat = fallback.Type == ChatChannelRouteType.Fake || routes.Values.Any(route => route.Type == ChatChannelRouteType.Fake);
}

internal Dictionary<(ChatChannelKind Kind, ushort Channel), (string Host, int Port)?> ChannelServers() =>
routes.OrderBy(pair => pair.Key.Kind).ThenBy(pair => pair.Key.Channel)
.ToDictionary(pair => pair.Key, pair => pair.Value.Server);

internal (string Host, int Port)? FallbackServer => fallback.Server;

static bool ValidServer(string? host, int port) =>
!string.IsNullOrWhiteSpace(host) && Uri.CheckHostName(host) != UriHostNameType.Unknown && port is >= 1 and <= 65535;

internal bool HasFakeChat { get; }
internal bool IsDefined(ChatChannelKind kind, ushort channel) => routes.ContainsKey((kind, channel));
internal Route? Find(ChatChannelKind kind, ushort channel) => routes.GetValueOrDefault((kind, channel))
?? (fallback.Type == ChatChannelRouteType.Blank ? null : fallback);

void Apply(ChatChannelKind kind, Dictionary<string, ChannelChoice>? choices, Action<string> log)
{
if (choices is null) return;
foreach (var (number, choice) in choices)
{
if (!ushort.TryParse(number, NumberStyles.None, CultureInfo.InvariantCulture, out ushort channel)
|| channel is 0 or InstanceChat.AnyChannel || number != channel.ToString(CultureInfo.InvariantCulture))
{
log($"Ignoring {kind} chat route '{number}'. Use a channel number from 1 to 65534.");
continue;
}
routes[(kind, channel)] = ParseRoute(choice, $"{kind} {channel}", log, defaultForward: true);
}
}

static Route ParseRoute(ChannelChoice choice, string label, Action<string> log, bool defaultForward)
{
string? routeType = choice.Type is JsonValue value && value.TryGetValue<string>(out string? name)
? name : choice.Type is null ? "blank" : null;
var type = routeType?.Trim().ToLowerInvariant() switch
{
"server" => ChatChannelRouteType.Server,
"discord" => ChatChannelRouteType.Discord,
"fake" => ChatChannelRouteType.Fake,
"blank" or "none" or "" => ChatChannelRouteType.Blank,
_ => (ChatChannelRouteType?)null
};
if (type is null) log($"Unknown route type for {label}. Using local chat.");

string? discordId = null;
if (type == ChatChannelRouteType.Discord && choice.DiscordChannelId is { } configuredId
&& (configuredId is not JsonValue text || !text.TryGetValue<string>(out discordId)))
{
log($"{label}: discordChannelId must be quoted. Skipping this mapping.");
type = ChatChannelRouteType.Blank;
}

(string Host, int Port)? server = null;
if (type == ChatChannelRouteType.Server)
{
string? host = choice.Address is JsonValue address && address.TryGetValue<string>(out string? textAddress)
? textAddress?.Trim() : null;
int port = choice.Port is JsonValue portValue && portValue.TryGetValue<int>(out int numberPort) ? numberPort
: choice.Port is null ? 0 : -1;
if (port == 0) port = 6113;
if (ValidServer(host, port)) server = (host!.ToLowerInvariant(), port);
else
{
log($"{label}: invalid server address or port. Using local chat.");
type = ChatChannelRouteType.Blank;
}
}

bool sendToDiscord = choice.SendToDiscord is null ? defaultForward
: choice.SendToDiscord is JsonValue outbound && outbound.TryGetValue<bool>(out bool send) && send;
return new(type ?? ChatChannelRouteType.Blank, discordId ?? "", server, sendToDiscord);
}

internal IEnumerable<DiscordRoute> DiscordRoutes(Action<string> log)
{
var used = new HashSet<ulong>();
foreach (var ((kind, channel), route) in routes.OrderBy(pair => pair.Key.Kind).ThenBy(pair => pair.Key.Channel))
if (RegisterDiscordId(route, $"Discord {kind} {channel}") is { } id)
yield return new(channel, id, route.SendToDiscord, kind);
if (RegisterDiscordId(fallback, "Discord fallback") is { } fallbackId)
yield return new(0, fallbackId, fallback.SendToDiscord, ChatChannelKind.Global, IsFallback: true);

string? RegisterDiscordId(Route route, string label)
{
if (route.Type != ChatChannelRouteType.Discord || string.IsNullOrWhiteSpace(route.DiscordId)) return null;
if (!ulong.TryParse(route.DiscordId.Trim(), NumberStyles.None, CultureInfo.InvariantCulture, out ulong id) || id == 0)
{
log($"{label}: discordChannelId must be a quoted numeric channel ID; skipping this mapping.");
return null;
}
if (!used.Add(id))
{
log($"{label}: discordChannelId repeats an earlier channel ID; skipping this mapping.");
return null;
}
return id.ToString(CultureInfo.InvariantCulture);
}
}
}
65 changes: 65 additions & 0 deletions mods/globalchat/DiscordApi.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
using System.Globalization;
using System.Net;
using System.Net.Http.Headers;
using System.Text;
using System.Text.Json;

namespace GlobalChat;

sealed class DiscordApiException(int status) : Exception($"Discord HTTP {status}")
{
internal int Status => status;
}

/// <summary>One worker uses the client serially, sharing Discord's rate-limit cooldown across both directions.</summary>
sealed class DiscordApi
{
readonly HttpClient http;
readonly Func<TimeSpan, CancellationToken, Task> wait;
readonly TimeProvider time;
DateTimeOffset nextRequest;

internal DiscordApi(HttpClient http, string token, Func<TimeSpan, CancellationToken, Task>? wait = null, TimeProvider? time = null)
{
this.http = http;
this.wait = wait ?? ((delay, cancel) => Task.Delay(delay, cancel));
this.time = time ?? TimeProvider.System;
http.BaseAddress ??= new Uri("https://discord.com/api/v10/");
http.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bot", token);
http.DefaultRequestHeaders.UserAgent.ParseAdd("DiscordBot (https://github.com/LocalExile/LocalExile-Mods, 1.2.16)");
}

internal async Task<JsonElement> Request(HttpMethod method, string path, string? body, CancellationToken cancel)
{
for (int attempt = 0; ; attempt++)
{
var cooldown = nextRequest - time.GetUtcNow();
if (cooldown > TimeSpan.Zero) await wait(cooldown, cancel).ConfigureAwait(false);
using var request = new HttpRequestMessage(method, path);
if (body is not null) request.Content = new StringContent(body, Encoding.UTF8, "application/json");
using var response = await http.SendAsync(request, cancel).ConfigureAwait(false);
string content = await response.Content.ReadAsStringAsync(cancel).ConfigureAwait(false);
if (response.StatusCode == HttpStatusCode.TooManyRequests)
{
using var limited = JsonDocument.Parse(content);
double seconds = limited.RootElement.GetProperty("retry_after").GetDouble();
if (!double.IsFinite(seconds) || seconds < 0 || seconds > 86400) throw new InvalidDataException("Invalid Discord cooldown.");
nextRequest = time.GetUtcNow().AddSeconds(Math.Max(.1, seconds));
if (attempt < 3) continue;
}
if ((int)response.StatusCode >= 500 && attempt < 3)
{
nextRequest = time.GetUtcNow().AddSeconds(1 << attempt);
continue;
}
if (!response.IsSuccessStatusCode) throw new DiscordApiException((int)response.StatusCode);
if (response.Headers.TryGetValues("X-RateLimit-Remaining", out var remaining) && remaining.FirstOrDefault() == "0"
&& response.Headers.TryGetValues("X-RateLimit-Reset-After", out var reset)
&& double.TryParse(reset.FirstOrDefault(), CultureInfo.InvariantCulture, out double delay)
&& double.IsFinite(delay) && delay is >= 0 and <= 86400)
nextRequest = time.GetUtcNow().AddSeconds(delay);
using var document = JsonDocument.Parse(content);
return document.RootElement.Clone();
}
}
}
Loading