Add exp_discord_sync to give linked players Discord roles

New controller plugin that maps clusterio roles to Discord roles and gives them to players linked through exp_discord_auth. The mapping is edited in a Discord Roles section on the role page, which needs the new exp_discord_sync.mapping.update permission. The guild's roles fill a dropdown, and typing a role ID still works when the bot can't list them.

Discord is reached with Node's fetch and WebSocket, no library. REST requests go one at a time and wait out 429 and exhausted rate limits. A minimal gateway connection with the Server Members intent gives roles on guild join. It identifies again instead of resuming, and every READY syncs all linked accounts, which covers startup and joins missed while disconnected. Without the intent the gateway is dropped and syncing carries on over REST.

Syncs run on link, unlink, clusterio role change, guild join, mapping change and connect. Only mapped Discord roles are ever added or removed.

exp_discord_auth may load after this plugin, so it is looked up and its hooks attached when the first sync runs.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
bbassieandClaude Opus 5.5 committed 2026-11-23 16:25:53 +00:00
1 parent c1490c0709
commit 2c55cb796e
18 files changed
+1494

No files matched your search

+1
View File
@@ -51,6 +51,7 @@ Each plugin has a readme in its folder with its config, permissions and API.
| [Reports (@expcluster/reports)](exp_reports/README.md) | Lets players report each other in game or from the web interface, with optional Discord and JSON webhooks. |
| [Server List (@expcluster/server-list)](exp_server_list/README.md) | Shares the details of every instance with the others, for the server list in game. |
| [Discord Auth (@expcluster/discord-auth)](exp_discord_auth/README.md) | Log in to the web interface with Discord, and link Factorio accounts to a Discord account. |
| [Discord Sync (@expcluster/discord-sync)](exp_discord_sync/README.md) | Gives linked players the Discord roles mapped to their clusterio roles. |
| [Auto Restart (@expcluster/auto-restart)](exp_auto_restart/README.md) | Restarts hosts, and optionally the controller, that need a restart once nobody is playing on them. |
| [Server UPS (@expcluster/server-ups)](exp_server_ups/README.md) | Shows the UPS the server is running at, toggled with `/server-ups`. |
| [Commands (@expcluster/lib_commands)](exp_commands/README.md) | Lua library for commands with typed arguments, aliases and permission checks. |
+1
View File
@@ -0,0 +1 @@
# Without an .npmignore pnpm packs using the repository .gitignore, which leaves out dist/
+47
View File
@@ -0,0 +1,47 @@
# ExpGaming - Discord Sync
Gives players the Discord roles that match their clusterio roles. Only players who linked their Factorio account with [Discord Auth](../exp_discord_auth/README.md) get roles, and only the Discord roles picked on a role page are ever added or removed.
## Setup
1. In the [Discord developer portal](https://discord.com/developers/applications), open the application (the one used by Discord Auth is fine) and go to Bot. Reset the token to get one, and turn on Server Members Intent.
2. Invite the bot to the server with the Manage Roles permission: `https://discord.com/oauth2/authorize?client_id=<client id>&scope=bot&permissions=268435456`.
3. In the server settings, drag the bot's role above every role it should give. Discord refuses changes to roles above the bot's highest role.
4. Turn on Developer Mode in Discord, right click the server and Copy Server ID.
5. Set the config on the controller:
```
npx clusterioctl controller config set exp_discord_sync.bot_token <bot token>
npx clusterioctl controller config set exp_discord_sync.guild_id <server id>
```
Without Server Members Intent the bot still syncs roles, but a player who joins the Discord server after linking only gets their roles at the next sync instead of straight away.
## Config
All fields are on the controller.
| Field | Default | Description |
|---|---|---|
| `exp_discord_sync.bot_token` | | Token of the Discord bot. Only readable on the controller. |
| `exp_discord_sync.guild_id` | | ID of the Discord server to give roles in. |
## Role mapping
Each role page has a Discord Roles section. Pick roles from the list, which comes from the bot, or type a role ID. Changing it needs the `exp_discord_sync.mapping.update` permission, which nobody has by default. The plugin doesn't compare the editor's own roles against the ones they map, so only give this permission to cluster admins.
A linked player gets every Discord role mapped to any clusterio role held by any of the Factorio accounts linked to their Discord account. A mapped Discord role the player shouldn't have is removed. Roles which are not mapped are never touched, and neither are members who haven't linked.
Removing a role from the mapping, or deleting the clusterio role, leaves that Discord role on the members who have it.
Mappings are stored in `database/exp_discord_sync/role_mappings.json` on the controller.
## When roles are synced
- A player links or unlinks their Discord account.
- A user's clusterio roles change.
- A linked player joins the Discord server (needs Server Members Intent).
- A role mapping changes, which syncs every linked player.
- The bot connects to Discord, which syncs every linked player. This happens on startup and whenever the connection to Discord drops and comes back, so joins missed while disconnected are caught up.
Requests go to Discord one at a time and wait when Discord answers with a rate limit.
+332
View File
@@ -0,0 +1,332 @@
import type { Controller, ControllerPluginContext } from "@clusterio/controller";
import * as lib from "@clusterio/lib";
import * as path from "node:path";
import { ControllerPlugin as DiscordAuth } from "@expcluster/discord-auth/dist/node/controller.js";
import * as messages from "./messages.js";
import {
DiscordApiError, DiscordGateway, DiscordRest, GuildMember, discordApi, discordGateway, gatewayIntents,
} from "./discord.js";
const snowflake = /^\d{17,20}$/;
function roleKey(roleIds: Iterable<number>) {
return [...roleIds].sort((a, b) => a - b).join(",");
}
export class ControllerPlugin {
/** Overridden by tests to point at a fake Discord */
apiBase = discordApi;
gatewayUrl = discordGateway;
rest?: DiscordRest;
gateway?: DiscordGateway;
guildId?: string;
/** Discord accounts waiting to be synced */
pending = new Set<string>();
syncAll = false;
/** Resolves once the queue is empty */
draining?: Promise<void>;
/** Roles of each user as last seen, so updates which don't touch roles are ignored */
userRoles = new Map<string, string>();
authAttached = false;
private constructor(
public controller: Controller,
public logger: lib.Logger,
public name: string,
public mappings: lib.SubscribableDatastore<messages.RoleMappingRecord>,
) {}
static async fromContext(context: ControllerPluginContext) {
const controller = context.controller;
const databaseDirectory = controller.config.get("controller.database_directory");
const mappings = await lib.SubscribableDatastore.fromProvider(new lib.JsonIdDatastoreProvider(
path.join(databaseDirectory, "exp_discord_sync", "role_mappings.json"),
messages.RoleMappingRecord.fromJSON.bind(messages.RoleMappingRecord),
));
const plugin = new ControllerPlugin(controller, context.logger, context.plugin.name, mappings);
plugin.sweepMappings();
for (const user of controller.users.values()) {
plugin.userRoles.set(user.id, roleKey(user.roleIds));
}
controller.subscriptions.handle(
messages.RoleMappingUpdatedEvent, plugin.handleMappingSubscription.bind(plugin)
);
controller.handle(messages.RoleMappingUpdateRequest, plugin.handleMappingUpdateRequest.bind(plugin));
controller.handle(messages.GuildRoleListRequest, plugin.handleGuildRoleListRequest.bind(plugin));
mappings.on("update", plugin.mappingsUpdated.bind(plugin));
controller.roles.on("update", () => plugin.sweepMappings());
controller.users.records.on("update", plugin.usersUpdated.bind(plugin));
const hooks = controller.hooks;
hooks.save.attach(plugin.name, plugin.onSave.bind(plugin));
hooks.shutdown.attach(plugin.name, plugin.onShutdown.bind(plugin));
hooks.controllerConfigFieldChanged.attach(plugin.name, plugin.onControllerConfigFieldChanged.bind(plugin));
plugin.connect();
return plugin;
}
async onSave() {
await this.mappings.save();
}
async onShutdown() {
this.disconnect();
await this.mappings.save();
}
async onControllerConfigFieldChanged(field: string) {
if (field === "exp_discord_sync.bot_token" || field === "exp_discord_sync.guild_id") {
this.disconnect();
this.connect();
}
}
/*
Discord connection
*/
connect() {
const token = this.controller.config.get("exp_discord_sync.bot_token");
const guildId = this.controller.config.get("exp_discord_sync.guild_id");
if (!token || !guildId) {
return;
}
this.guildId = guildId;
this.rest = new DiscordRest(token, this.apiBase);
this.gateway = new DiscordGateway(token, gatewayIntents.GUILD_MEMBERS, this.logger, {
// Joins are missed while disconnected, so every (re)connect syncs everyone
onReady: () => this.queueAll(),
onDispatch: (type, data) => {
if (type === "GUILD_MEMBER_ADD" && data.guild_id === this.guildId) {
this.queue(data.user.id);
}
},
onFatalClose: (code, reason) => {
if (code === 4014) {
this.logger.warn(
"The Discord bot is missing the Server Members intent, joining the server does not give roles"
);
this.queueAll();
} else {
this.logger.error(`Discord gateway refused the bot with ${code}: ${reason}`);
}
},
}, this.gatewayUrl);
this.gateway.start();
}
disconnect() {
this.gateway?.stop();
this.gateway = undefined;
this.rest = undefined;
this.guildId = undefined;
this.pending.clear();
this.syncAll = false;
}
/*
Syncing
*/
/** exp_discord_auth may load after this plugin, so it is looked up when first needed. */
getDiscordAuth() {
const discordAuth = DiscordAuth.get(this.controller);
if (discordAuth && !this.authAttached) {
this.authAttached = true;
discordAuth.hooks.linked.attach(this.name, (_playerName, discordUser) => this.queue(discordUser.id));
discordAuth.hooks.unlinked.attach(this.name, (_playerName, discordUser) => this.queue(discordUser.id));
}
return discordAuth;
}
queue(discordId: string) {
if (!this.rest) {
return;
}
this.pending.add(discordId);
this.drain();
}
queueAll() {
if (!this.rest) {
return;
}
this.syncAll = true;
this.drain();
}
drain() {
this.draining ??= this.processQueue().finally(() => { this.draining = undefined; });
return this.draining;
}
private async processQueue() {
while (this.syncAll || this.pending.size) {
const discordAuth = this.getDiscordAuth();
if (!discordAuth) {
this.logger.error("exp_discord_auth is not loaded, Discord roles can not be synced");
this.pending.clear();
this.syncAll = false;
return;
}
if (this.syncAll) {
this.syncAll = false;
for (const account of discordAuth.getAccounts()) {
this.pending.add(account.id);
}
}
const [discordId] = this.pending;
if (discordId === undefined) {
continue;
}
this.pending.delete(discordId);
try {
await this.syncAccount(discordId);
} catch (err: any) {
if (err instanceof DiscordApiError && err.status === 403) {
this.logger.warn(
`Discord refused to change roles of ${discordId}, the bot needs Manage Roles `
+ "and a role above every mapped role"
);
} else {
this.logger.warn(`Failed to sync Discord roles of ${discordId}: ${err.message}`);
}
}
}
}
/** Every Discord role this plugin gives, any other role is left alone. */
managedRoleIds() {
const managed = new Set<string>();
for (const mapping of this.mappings.values()) {
for (const id of mapping.discordRoleIds) {
managed.add(id);
}
}
return managed;
}
/** The mapped Discord roles for the clusterio roles of every player linked to the account. */
wantedRoleIds(discordId: string) {
const wanted = new Set<string>();
const account = this.getDiscordAuth()?.getAccount(discordId);
for (const playerName of account?.playerNames ?? []) {
const user = this.controller.users.getByName(playerName);
for (const roleId of user?.roleIds ?? []) {
for (const id of this.mappings.get(roleId)?.discordRoleIds ?? []) {
wanted.add(id);
}
}
}
return wanted;
}
async syncAccount(discordId: string) {
const managed = this.managedRoleIds();
if (!this.rest || !this.guildId || !managed.size) {
return;
}
const rest = this.rest;
const guildId = this.guildId;
const member: GuildMember | undefined = await rest.getGuildMember(guildId, discordId);
if (!member) {
return;
}
const wanted = this.wantedRoleIds(discordId);
const current = new Set(member.roles);
for (const id of wanted) {
if (!current.has(id)) {
await rest.addMemberRole(guildId, discordId, id);
}
}
for (const id of current) {
if (managed.has(id) && !wanted.has(id)) {
await rest.removeMemberRole(guildId, discordId, id);
}
}
}
usersUpdated(users: lib.UserDetails[]) {
for (const user of users) {
const key = user.isDeleted ? "" : roleKey(user.roleIds);
if (this.userRoles.get(user.id) === key) {
continue;
}
if (user.isDeleted) {
this.userRoles.delete(user.id);
} else {
this.userRoles.set(user.id, key);
}
const link = this.rest ? this.getDiscordAuth()?.getLink(user.name) : undefined;
if (link) {
this.queue(link.id);
}
}
}
/*
Role mappings
*/
/** Mappings of deleted roles, the Discord roles they gave stay on members. */
sweepMappings() {
const orphaned = [...this.mappings.valuesMutable()].filter(mapping => !this.controller.roles.has(mapping.id));
if (orphaned.length) {
this.mappings.deleteMany(orphaned);
}
}
mappingsUpdated(updates: messages.RoleMappingRecord[]) {
this.controller.subscriptions.broadcast(new messages.RoleMappingUpdatedEvent(updates));
}
async handleMappingSubscription(request: lib.SubscriptionRequest) {
const updates = [...this.mappings.values()].filter(mapping => mapping.updatedAtMs > request.lastRequestTimeMs);
return updates.length ? new messages.RoleMappingUpdatedEvent(updates) : null;
}
async handleMappingUpdateRequest(request: messages.RoleMappingUpdateRequest) {
if (!this.controller.roles.has(request.roleId)) {
throw new lib.NotFoundError(`Role with ID ${request.roleId} does not exist`);
}
const discordRoleIds = [...new Set(request.discordRoleIds)];
const invalid = discordRoleIds.filter(id => !snowflake.test(id));
if (invalid.length) {
throw new lib.ValidationError(`Not a Discord role ID: ${invalid.join(", ")}`);
}
const existing = this.mappings.getMutable(request.roleId);
if (!discordRoleIds.length) {
if (existing) {
this.mappings.delete(existing);
}
} else {
this.mappings.set(new messages.RoleMappingRecord(request.roleId, discordRoleIds));
}
this.queueAll();
}
async handleGuildRoleListRequest() {
if (!this.rest || !this.guildId) {
throw new lib.UnavailableError("The Discord bot is not configured");
}
const guildId = this.guildId;
const roles = await this.rest.getGuildRoles(guildId);
return roles
// @everyone has the guild id, and integration roles can't be given by bots
.filter(role => role.id !== guildId && !role.managed)
.sort((a, b) => b.position - a.position)
.map(role => ({ id: role.id, name: role.name, color: role.color }));
}
}
export default ControllerPlugin.fromContext.bind(ControllerPlugin);
+223
View File
@@ -0,0 +1,223 @@
import * as lib from "@clusterio/lib";
import { setTimeout as sleep } from "node:timers/promises";
export const discordApi = "https://discord.com/api/v10";
export const discordGateway = "wss://gateway.discord.gg/?v=10&encoding=json";
const userAgent = "DiscordBot (https://github.com/explosivegaming/ExpCluster, 7)";
const maxRetries = 5;
export type GuildRole = { id: string, name: string, color: number, position: number, managed: boolean };
export type GuildMember = { user: { id: string }, roles: string[] };
export class DiscordApiError extends Error {
constructor(
public status: number,
message: string,
) {
super(message);
}
}
/** Bot requests to the Discord REST API, sent one at a time and waiting out rate limits. */
export class DiscordRest {
/** Requests wait until this time when Discord says a rate limit is used up */
waitUntilMs = 0;
private queue: Promise<unknown> = Promise.resolve();
constructor(
private token: string,
public baseUrl = discordApi,
) {}
request(method: string, route: string): Promise<unknown> {
const result = this.queue.then(() => this.send(method, route));
this.queue = result.catch(() => {});
return result;
}
private async send(method: string, route: string) {
for (let attempt = 0; ; attempt++) {
const waitMs = this.waitUntilMs - Date.now();
if (waitMs > 0) {
await sleep(waitMs);
}
const response = await fetch(`${this.baseUrl}${route}`, {
method,
headers: { "Authorization": `Bot ${this.token}`, "User-Agent": userAgent },
});
if (response.headers.get("x-ratelimit-remaining") === "0") {
const resetAfter = Number(response.headers.get("x-ratelimit-reset-after")) || 0;
this.waitUntilMs = Date.now() + resetAfter * 1e3;
}
if (response.status === 429 && attempt < maxRetries) {
const body = await response.json().catch(() => ({})) as { retry_after?: number };
const retryAfter = body.retry_after ?? (Number(response.headers.get("retry-after")) || 1);
this.waitUntilMs = Date.now() + retryAfter * 1e3;
continue;
}
if (!response.ok) {
throw new DiscordApiError(
response.status, `${method} ${route} responded with ${response.status}: ${await response.text()}`
);
}
return response.status === 204 ? undefined : response.json();
}
}
async getGuildRoles(guildId: string) {
return await this.request("GET", `/guilds/${guildId}/roles`) as GuildRole[];
}
/** Undefined when the user is not in the guild. */
async getGuildMember(guildId: string, userId: string) {
try {
return await this.request("GET", `/guilds/${guildId}/members/${userId}`) as GuildMember;
} catch (err) {
if (err instanceof DiscordApiError && err.status === 404) {
return undefined;
}
throw err;
}
}
async addMemberRole(guildId: string, userId: string, roleId: string) {
await this.request("PUT", `/guilds/${guildId}/members/${userId}/roles/${roleId}`);
}
async removeMemberRole(guildId: string, userId: string, roleId: string) {
await this.request("DELETE", `/guilds/${guildId}/members/${userId}/roles/${roleId}`);
}
}
export const gatewayIntents = { GUILD_MEMBERS: 1 << 1 };
/** Close codes after which reconnecting would fail the same way, such as a bad token or missing intent. */
export const fatalCloseCodes = new Set([4004, 4010, 4011, 4012, 4013, 4014]);
type GatewayPayload = { op: number, d: any, s: number | null, t: string | null };
/**
* Minimal Discord gateway connection which only receives dispatch events.
*
* It identifies again on every reconnect instead of resuming, so events sent
* while disconnected are missed. onReady is the place to catch up on them.
*/
export class DiscordGateway {
ws?: WebSocket;
private heartbeatTimer?: ReturnType<typeof setTimeout>;
private reconnectTimer?: ReturnType<typeof setTimeout>;
private sequence: number | null = null;
private acked = true;
private stopped = false;
backoff = new lib.ExponentialBackoff({ base: 2, max: 60 });
constructor(
private token: string,
private intents: number,
private logger: lib.Logger,
public handlers: {
onReady?: () => void,
onDispatch?: (type: string, data: any) => void,
onFatalClose?: (code: number, reason: string) => void,
},
public url = discordGateway,
) {}
start() {
this.stopped = false;
this.connect();
}
stop() {
this.stopped = true;
clearTimeout(this.reconnectTimer);
this.close(1000);
}
private connect() {
const ws = new WebSocket(this.url);
this.ws = ws;
this.acked = true;
ws.addEventListener("message", event => this.receive(JSON.parse(String(event.data))));
ws.addEventListener("close", event => this.closed(ws, event.code, event.reason));
ws.addEventListener("error", () => {});
}
private close(code: number) {
clearTimeout(this.heartbeatTimer);
if (this.ws && this.ws.readyState <= WebSocket.OPEN) {
this.ws.close(code);
}
}
private send(op: number, d: unknown) {
this.ws?.send(JSON.stringify({ op, d }));
}
private heartbeat(intervalMs: number) {
if (!this.acked) {
this.logger.warn("Discord gateway stopped answering heartbeats, reconnecting");
this.close(4000);
return;
}
this.acked = false;
this.send(1, this.sequence);
this.heartbeatTimer = setTimeout(() => this.heartbeat(intervalMs), intervalMs);
}
private receive(payload: GatewayPayload) {
if (payload.s !== null && payload.s !== undefined) {
this.sequence = payload.s;
}
switch (payload.op) {
case 10: { // Hello
const intervalMs = payload.d.heartbeat_interval;
this.heartbeatTimer = setTimeout(() => this.heartbeat(intervalMs), intervalMs * Math.random());
this.send(2, {
token: this.token,
intents: this.intents,
properties: { os: process.platform, browser: "exp_discord_sync", device: "exp_discord_sync" },
});
break;
}
case 11: // Heartbeat ACK
this.acked = true;
break;
case 1: // Heartbeat request
this.send(1, this.sequence);
break;
case 7: // Reconnect
case 9: // Invalid session
this.close(4000);
break;
case 0: // Dispatch
if (payload.t === "READY") {
this.handlers.onReady?.();
} else {
this.handlers.onDispatch?.(payload.t!, payload.d);
}
break;
default:
}
}
private closed(ws: WebSocket, code: number, reason: string) {
if (ws !== this.ws) {
return;
}
clearTimeout(this.heartbeatTimer);
this.sequence = null;
if (this.stopped) {
return;
}
if (fatalCloseCodes.has(code)) {
this.stopped = true;
this.handlers.onFatalClose?.(code, reason);
return;
}
const delayMs = this.backoff.delay();
this.logger.verbose(`Discord gateway closed with ${code}, reconnecting in ${Math.round(delayMs / 1e3)}s`);
this.reconnectTimer = setTimeout(() => this.connect(), delayMs);
}
}
+52
View File
@@ -0,0 +1,52 @@
import * as lib from "@clusterio/lib";
import * as messages from "./messages.js";
declare module "@clusterio/lib" {
export interface ControllerConfigFields {
"exp_discord_sync.bot_token": string | null;
"exp_discord_sync.guild_id": string | null;
}
export interface Permissions {
"exp_discord_sync.mapping.update": never;
}
}
export const plugin: lib.PluginDeclaration = {
name: "exp_discord_sync",
title: "ExpGaming - Discord Sync",
description: "Clusterio plugin giving players linked with exp_discord_auth the Discord roles mapped to their clusterio roles",
messages: [
messages.RoleMappingUpdatedEvent,
messages.RoleMappingUpdateRequest,
messages.GuildRoleListRequest,
],
permissions: [
{
name: "exp_discord_sync.mapping.update",
title: "Update Discord Roles",
description: "Change which Discord roles are given to players holding a role.",
grantByDefault: false,
},
],
controllerEntrypoint: "./dist/node/controller.js",
controllerConfigFields: {
"exp_discord_sync.bot_token": {
title: "Bot Token",
description: "Token of the Discord bot which gives the roles.",
type: "string",
credential: ["controller"],
optional: true,
},
"exp_discord_sync.guild_id": {
title: "Guild ID",
description: "ID of the Discord server to give roles in.",
type: "string",
optional: true,
},
},
webEntrypoint: "./web",
};
+115
View File
@@ -0,0 +1,115 @@
import * as lib from "@clusterio/lib";
import { Type, Static } from "@sinclair/typebox";
/*
Data records
*/
/** The Discord roles given to linked players holding a clusterio role. */
export class RoleMappingRecord {
constructor(
/** Clusterio role id */
public id: number,
public discordRoleIds: string[],
public updatedAtMs: number = 0,
public isDeleted: boolean = false,
) {}
static jsonSchema = Type.Object({
id: Type.Integer(),
discord_role_ids: Type.Array(Type.String()),
updated_at_ms: Type.Optional(Type.Number()),
is_deleted: Type.Optional(Type.Boolean()),
});
toJSON() {
const json: Static<typeof RoleMappingRecord.jsonSchema> = {
id: this.id,
discord_role_ids: this.discordRoleIds,
};
if (this.updatedAtMs) {
json.updated_at_ms = this.updatedAtMs;
}
if (this.isDeleted) {
json.is_deleted = true;
}
return json;
}
static fromJSON(json: Static<typeof this.jsonSchema>) {
return new this(json.id, json.discord_role_ids, json.updated_at_ms ?? 0, json.is_deleted ?? false);
}
}
export class RoleMappingUpdatedEvent {
declare ["constructor"]: typeof RoleMappingUpdatedEvent;
static plugin = "exp_discord_sync" as const;
static type = "event" as const;
static src = "controller" as const;
static dst = "control" as const;
static permission = "core.role.subscribe" as const;
constructor(
public updates: RoleMappingRecord[],
) {}
static jsonSchema = Type.Object({
updates: Type.Array(RoleMappingRecord.jsonSchema),
});
toJSON() {
return { updates: this.updates.map(mapping => mapping.toJSON()) };
}
static fromJSON(json: Static<typeof this.jsonSchema>) {
return new this(json.updates.map(mapping => RoleMappingRecord.fromJSON(mapping)));
}
}
/** Set the Discord roles of a clusterio role, an empty list removes the mapping. */
export class RoleMappingUpdateRequest {
declare ["constructor"]: typeof RoleMappingUpdateRequest;
static plugin = "exp_discord_sync" as const;
static type = "request" as const;
static src = "control" as const;
static dst = "controller" as const;
static permission = "exp_discord_sync.mapping.update" as const;
constructor(
public roleId: number,
public discordRoleIds: string[],
) {}
static jsonSchema = Type.Object({
role_id: Type.Integer(),
discord_role_ids: Type.Array(Type.String()),
});
toJSON() {
return { role_id: this.roleId, discord_role_ids: this.discordRoleIds };
}
static fromJSON(json: Static<typeof this.jsonSchema>) {
return new this(json.role_id, json.discord_role_ids);
}
}
const GuildRole = Type.Object({
id: Type.String(),
name: Type.String(),
color: Type.Integer(),
});
/** The roles of the configured guild which the bot can give, highest first. */
export class GuildRoleListRequest {
declare ["constructor"]: typeof GuildRoleListRequest;
static plugin = "exp_discord_sync" as const;
static type = "request" as const;
static src = "control" as const;
static dst = "controller" as const;
static permission = "core.role.list" as const;
static Response = lib.plainJson(Type.Array(GuildRole));
}
+54
View File
@@ -0,0 +1,54 @@
{
"name": "@expcluster/discord-sync",
"version": "7.0.5",
"description": "Clusterio plugin giving players linked with exp_discord_auth the Discord roles mapped to their clusterio roles",
"author": "Cooldude2606 <https://github.com/Cooldude2606>",
"license": "MIT",
"repository": "explosivegaming/ExpCluster",
"type": "module",
"main": "dist/node/index.js",
"scripts": {
"prepare": "tsc --build && vite build",
"test": "tap --type-strip-only --disable-coverage --allow-empty-coverage test/*.test.js",
"coverage": "tap --coverage-report=text test/*.test.js"
},
"engines": {
"node": ">=22"
},
"peerDependencies": {
"@clusterio/controller": "workspace:^",
"@clusterio/lib": "workspace:^"
},
"peerDependenciesMeta": {
"@clusterio/controller": {
"optional": true
}
},
"devDependencies": {
"@clusterio/controller": "workspace:^",
"@clusterio/lib": "workspace:^",
"@clusterio/web_ui": "workspace:^",
"@types/node": "catalog:",
"@types/react": "catalog:",
"antd": "catalog:",
"react": "catalog:",
"react-dom": "catalog:",
"react-router-dom": "catalog:",
"tap": "^21.1.0",
"typescript": "catalog:",
"vite": "catalog:",
"ws": "catalog:"
},
"dependencies": {
"@sinclair/typebox": "catalog:",
"@expcluster/discord-auth": "workspace:^"
},
"publishConfig": {
"access": "public"
},
"keywords": [
"clusterio",
"clusterio-plugin",
"factorio"
]
}
+284
View File
@@ -0,0 +1,284 @@
import t from "tap";
import * as lib from "@clusterio/lib";
import { Controller } from "@clusterio/controller";
import { ControllerPlugin as DiscordAuth } from "@expcluster/discord-auth/dist/node/controller.js";
import { plugin as discordAuthDeclaration } from "@expcluster/discord-auth/dist/node/index.js";
import entrypoint, { ControllerPlugin } from "../dist/node/controller.js";
import * as messages from "../dist/node/messages.js";
import { plugin as pluginDeclaration } from "../dist/node/index.js";
import { guildId, startFakeDiscord, until } from "./fake_discord.js";
for (const Message of [...pluginDeclaration.messages, ...discordAuthDeclaration.messages]) {
lib.Link.register(Message);
}
lib.addPluginConfigFields([pluginDeclaration, discordAuthDeclaration]);
const warnings = [];
const logger = {
child: () => logger, info: () => {}, error: msg => warnings.push(msg), verbose: () => {},
warn: msg => warnings.push(msg),
};
lib.logger.silent = true;
t.after(() => {
lib.logger.silent = false;
});
const discordRoles = { moderator: "200000000000000001", trusted: "200000000000000002", other: "200000000000000003" };
const alice = { id: "300000000000000001", name: "Alice" };
const bob = { id: "300000000000000002", name: "Bob" };
const role = (id, name) => new lib.Role(id, name, "", new Set());
/**
* exp_discord_sync and exp_discord_auth on a real controller, talking to a fake Discord.
*
* Sync loads before auth to cover auth being looked up late.
*/
const defaultMappings = { 5: [discordRoles.moderator], 6: [discordRoles.trusted] };
async function startPlugin(t2, { fakeOptions, mappings = defaultMappings } = {}) {
const fake = await startFakeDiscord(fakeOptions);
t2.teardown(fake.close);
fake.roles.push(
{ id: discordRoles.moderator, name: "Moderator", color: 0xff0000, position: 3, managed: false },
{ id: discordRoles.trusted, name: "Trusted", color: 0, position: 2, managed: false },
{ id: discordRoles.other, name: "Other", color: 0, position: 1, managed: false },
{ id: "200000000000000004", name: "Some Bot", color: 0, position: 4, managed: true },
);
const controllerConfig = new lib.ControllerConfig("controller", {
"controller.database_directory": t2.testdir(),
"controller.auth_secret": Buffer.from("test secret").toString("base64"),
});
const controller = new Controller(logger, [], controllerConfig);
controller.roles.set(role(5, "Moderator"));
controller.roles.set(role(6, "Trusted"));
controller.roles.set(role(7, "Regular"));
for (const name of ["Player1", "Player2", "Player3"]) {
controller.users.createUser(name);
}
const plugin = await ControllerPlugin.fromContext({ plugin: { name: "exp_discord_sync" }, controller, logger });
t2.teardown(() => plugin.disconnect());
const auth = await DiscordAuth.fromContext({ plugin: { name: "exp_discord_auth" }, controller, logger });
t2.teardown(() => clearInterval(auth.cleanupInterval));
for (const [roleId, ids] of Object.entries(mappings)) {
plugin.mappings.set(new messages.RoleMappingRecord(Number(roleId), ids));
}
plugin.apiBase = fake.apiBase;
plugin.gatewayUrl = fake.gatewayUrl;
controller.config.set("exp_discord_sync.bot_token", "token");
controller.config.set("exp_discord_sync.guild_id", guildId);
if (!plugin.gateway) {
plugin.connect();
}
return { plugin, auth, controller, fake };
}
function setRoles(controller, name, roleIds) {
controller.users.getByNameMutable(name).set("roleIds", new Set(roleIds));
}
const rolesOf = (fake, id) => [...fake.members.get(id)].sort();
async function settled(plugin) {
await until(() => !plugin.draining && !plugin.pending.size);
}
t.test("entrypoint", async t2 => {
const controllerConfig = new lib.ControllerConfig("controller", { "controller.database_directory": t2.testdir() });
const controller = new Controller(logger, [], controllerConfig);
await entrypoint({ controller, logger, plugin: { name: "exp_discord_sync" }, metrics: undefined });
for (const hook of ["save", "shutdown", "controllerConfigFieldChanged"]) {
t2.ok([...controller.hooks[hook].attached].includes("exp_discord_sync"), `attached to ${hook}`);
}
await controller.hooks.shutdown.invoke();
});
t.test("syncing", t2 => {
t2.test("connecting syncs every linked account and only touches mapped roles", async t3 => {
const { fake, auth, controller, plugin } = await startPlugin(t3);
await plugin.drain();
fake.members.set(alice.id, new Set([discordRoles.trusted, discordRoles.other]));
fake.members.set(bob.id, new Set([discordRoles.trusted]));
setRoles(controller, "Player1", [5]);
auth.linkAccount(alice, "Player1");
await settled(plugin);
plugin.disconnect();
fake.members.set(alice.id, new Set([discordRoles.trusted, discordRoles.other]));
plugin.connect();
await until(() => fake.identifies.length === 2);
await until(() => rolesOf(fake, alice.id).join() === [discordRoles.moderator, discordRoles.other].join());
t3.same(rolesOf(fake, bob.id), [discordRoles.trusted], "unlinked member is left alone");
});
t2.test("roles come from every player linked to the account", async t3 => {
const { fake, auth, controller, plugin } = await startPlugin(t3);
fake.members.set(alice.id, new Set());
setRoles(controller, "Player1", [5]);
setRoles(controller, "Player2", [6, 7]);
auth.linkAccount(alice, "Player1");
auth.linkAccount(alice, "Player2");
await until(() => rolesOf(fake, alice.id).length === 2);
t3.same(rolesOf(fake, alice.id), [discordRoles.moderator, discordRoles.trusted]);
});
t2.test("unlinking takes the roles away", async t3 => {
const { fake, auth, controller, plugin } = await startPlugin(t3);
fake.members.set(alice.id, new Set([discordRoles.other]));
setRoles(controller, "Player1", [5]);
auth.linkAccount(alice, "Player1");
await until(() => rolesOf(fake, alice.id).length === 2);
auth.removeLink("Player1");
await until(() => rolesOf(fake, alice.id).length === 1);
t3.same(rolesOf(fake, alice.id), [discordRoles.other]);
await settled(plugin);
});
t2.test("role changes in clusterio are passed on, other user updates are not", async t3 => {
const { fake, auth, controller, plugin } = await startPlugin(t3);
fake.members.set(alice.id, new Set());
auth.linkAccount(alice, "Player1");
await settled(plugin);
setRoles(controller, "Player1", [6]);
await until(() => rolesOf(fake, alice.id).length === 1);
t3.same(rolesOf(fake, alice.id), [discordRoles.trusted]);
setRoles(controller, "Player1", [5]);
await until(() => rolesOf(fake, alice.id)[0] === discordRoles.moderator);
t3.same(rolesOf(fake, alice.id), [discordRoles.moderator]);
await settled(plugin);
fake.requests.length = 0;
controller.users.getByNameMutable("Player1").set("isAdmin", true);
setRoles(controller, "Player2", [5]);
await settled(plugin);
t3.same(fake.requests, [], "no requests for unlinked users or other fields");
});
t2.test("a member joining the guild gets their roles", async t3 => {
const { fake, auth, controller, plugin } = await startPlugin(t3);
setRoles(controller, "Player1", [5]);
auth.linkAccount(alice, "Player1");
await settled(plugin);
fake.members.set(alice.id, new Set());
fake.dispatch("GUILD_MEMBER_ADD", { guild_id: guildId, user: { id: alice.id }, roles: [] });
await until(() => rolesOf(fake, alice.id).length === 1);
t3.same(rolesOf(fake, alice.id), [discordRoles.moderator]);
});
t2.test("roles Discord refuses are logged and the rest carry on", async t3 => {
const { fake, auth, controller, plugin } = await startPlugin(t3);
fake.roles.find(r => r.id === discordRoles.moderator).name = "Above bot";
fake.members.set(alice.id, new Set());
fake.members.set(bob.id, new Set());
setRoles(controller, "Player1", [5]);
setRoles(controller, "Player2", [6]);
warnings.length = 0;
auth.linkAccount(alice, "Player1");
auth.linkAccount(bob, "Player2");
await until(() => rolesOf(fake, bob.id).length === 1);
t3.ok(warnings.some(msg => /Discord refused to change roles of 300000000000000001/.test(msg)));
await settled(plugin);
});
t2.test("a bot without the members intent still syncs", async t3 => {
const { fake, auth, controller, plugin } = await startPlugin(t3, { fakeOptions: { closeCode: 4014 } });
await until(() => fake.identifies.length === 1);
await settled(plugin);
fake.members.set(alice.id, new Set());
setRoles(controller, "Player1", [5]);
auth.linkAccount(alice, "Player1");
await until(() => rolesOf(fake, alice.id).length === 1);
t3.ok(plugin.rest, "rest is kept");
t3.ok(warnings.some(msg => /missing the Server Members intent/.test(msg)));
});
t2.test("nothing is sent while the bot is not configured", async t3 => {
const { fake, auth, controller, plugin } = await startPlugin(t3);
await settled(plugin);
controller.config.set("exp_discord_sync.bot_token", null);
plugin.disconnect();
plugin.connect();
fake.requests.length = 0;
fake.members.set(alice.id, new Set());
setRoles(controller, "Player1", [5]);
auth.linkAccount(alice, "Player1");
await settled(plugin);
t3.same(fake.requests, []);
t3.ok(await plugin.handleGuildRoleListRequest().catch(err => err) instanceof lib.UnavailableError);
});
t2.end();
});
t.test("role mappings", t2 => {
t2.test("RoleMappingUpdateRequest sets, validates and removes mappings", async t3 => {
const { fake, auth, controller, plugin } = await startPlugin(t3, { mappings: {} });
fake.members.set(alice.id, new Set());
setRoles(controller, "Player1", [7]);
auth.linkAccount(alice, "Player1");
await settled(plugin);
const update = (roleId, ids) => plugin.handleMappingUpdateRequest(
new messages.RoleMappingUpdateRequest(roleId, ids)
);
await update(7, [discordRoles.other, discordRoles.other]);
t3.same(plugin.mappings.get(7).discordRoleIds, [discordRoles.other], "duplicates are dropped");
await until(() => rolesOf(fake, alice.id).length === 1);
t3.ok(await update(7, ["abc"]).catch(err => err) instanceof lib.ValidationError);
t3.ok(await update(99, [discordRoles.other]).catch(err => err) instanceof lib.NotFoundError);
await update(7, []);
t3.notOk(plugin.mappings.has(7), "empty list removes the mapping");
await settled(plugin);
t3.same(rolesOf(fake, alice.id), [discordRoles.other], "roles no longer mapped are left on members");
});
t2.test("mapping changes are broadcast", async t3 => {
const { controller, plugin } = await startPlugin(t3, { mappings: {} });
const sent = [];
controller.subscriptions.broadcast = event => sent.push(event);
await plugin.handleMappingUpdateRequest(new messages.RoleMappingUpdateRequest(5, [discordRoles.moderator]));
t3.equal(sent.length, 1);
t3.same(sent[0].updates.map(m => [m.id, m.discordRoleIds]), [[5, [discordRoles.moderator]]]);
const event = await plugin.handleMappingSubscription({ lastRequestTimeMs: 0 });
t3.same(event.updates.map(m => m.id), [5]);
await settled(plugin);
});
t2.test("mappings of deleted roles are removed", async t3 => {
const { controller, plugin } = await startPlugin(t3);
controller.roles.delete(controller.roles.get(6));
t3.same([...plugin.mappings.values()].map(m => m.id), [5]);
await settled(plugin);
});
t2.test("mappings are saved and loaded", async t3 => {
const { controller, plugin } = await startPlugin(t3);
await plugin.onShutdown();
const restarted = new Controller(logger, [], new lib.ControllerConfig("controller", {
"controller.database_directory": controller.config.get("controller.database_directory"),
}));
restarted.roles.set(role(5, "Moderator"));
restarted.roles.set(role(6, "Trusted"));
const reloaded = await ControllerPlugin.fromContext({
plugin: { name: "exp_discord_sync" }, controller: restarted, logger,
});
t3.same([...reloaded.mappings.values()].map(m => [m.id, m.discordRoleIds]), [
[5, [discordRoles.moderator]],
[6, [discordRoles.trusted]],
]);
});
t2.test("GuildRoleListRequest lists roles the bot can give, highest first", async t3 => {
const { plugin } = await startPlugin(t3);
t3.same(await plugin.handleGuildRoleListRequest(), [
{ id: discordRoles.moderator, name: "Moderator", color: 0xff0000 },
{ id: discordRoles.trusted, name: "Trusted", color: 0 },
{ id: discordRoles.other, name: "Other", color: 0 },
]);
await settled(plugin);
});
t2.end();
});
+129
View File
@@ -0,0 +1,129 @@
import t from "tap";
import * as lib from "@clusterio/lib";
import { DiscordApiError, DiscordGateway, DiscordRest, gatewayIntents } from "../dist/node/discord.js";
import { guildId, startFakeDiscord, until } from "./fake_discord.js";
const logger = { child: () => logger, info: () => {}, warn: () => {}, error: () => {}, verbose: () => {} };
const memberId = "300000000000000000";
const roleId = "200000000000000001";
t.test("class DiscordRest", async t2 => {
const fake = await startFakeDiscord();
t2.teardown(fake.close);
fake.members.set(memberId, new Set());
t2.test(".getGuildMember() returns the member, or undefined when not in the guild", async t3 => {
const rest = new DiscordRest("token", fake.apiBase);
t3.same(await rest.getGuildMember(guildId, memberId), { user: { id: memberId }, roles: [] });
t3.equal(await rest.getGuildMember(guildId, "1"), undefined);
});
t2.test(".addMemberRole() and .removeMemberRole() change roles", async t3 => {
const rest = new DiscordRest("token", fake.apiBase);
await rest.addMemberRole(guildId, memberId, roleId);
t3.same([...fake.members.get(memberId)], [roleId]);
await rest.removeMemberRole(guildId, memberId, roleId);
t3.same([...fake.members.get(memberId)], []);
});
t2.test("waits out 429 responses and retries", async t3 => {
const rest = new DiscordRest("token", fake.apiBase);
fake.requests.length = 0;
fake.rateLimit = 2;
const start = Date.now();
await rest.getGuildRoles(guildId);
t3.equal(fake.requests.length, 3);
t3.ok(Date.now() - start >= 90, "waited retry_after twice");
});
t2.test("gives up after repeated 429 responses", async t3 => {
const rest = new DiscordRest("token", fake.apiBase);
fake.rateLimit = 6;
await t3.rejects(rest.getGuildRoles(guildId), { status: 429 });
fake.rateLimit = 0;
});
t2.test("throws DiscordApiError with the status", async t3 => {
const rest = new DiscordRest("wrong", fake.apiBase);
const err = await rest.getGuildRoles(guildId).catch(e => e);
t3.ok(err instanceof DiscordApiError);
t3.equal(err.status, 401);
});
t2.test("sends one request at a time", async t3 => {
const rest = new DiscordRest("token", fake.apiBase);
fake.requests.length = 0;
fake.rateLimit = 1;
await Promise.all([rest.getGuildRoles(guildId), rest.getGuildMember(guildId, memberId)]);
t3.same(fake.requests, [
`GET /guilds/${guildId}/roles`,
`GET /guilds/${guildId}/roles`,
`GET /guilds/${guildId}/members/${memberId}`,
]);
});
});
t.test("class DiscordGateway", async t2 => {
t2.test("identifies with the intents and passes on dispatches", async t3 => {
const fake = await startFakeDiscord();
t3.teardown(fake.close);
const events = [];
const gateway = new DiscordGateway("token", gatewayIntents.GUILD_MEMBERS, logger, {
onReady: () => events.push("ready"),
onDispatch: (type, data) => events.push([type, data]),
}, fake.gatewayUrl);
t3.teardown(() => gateway.stop());
gateway.start();
await until(() => events.length);
t3.equal(fake.identifies[0].token, "token");
t3.equal(fake.identifies[0].intents, gatewayIntents.GUILD_MEMBERS);
fake.dispatch("GUILD_MEMBER_ADD", { guild_id: guildId, user: { id: memberId } });
await until(() => events.length === 2);
t3.same(events, ["ready", ["GUILD_MEMBER_ADD", { guild_id: guildId, user: { id: memberId } }]]);
});
t2.test("reconnects when the connection drops", async t3 => {
const fake = await startFakeDiscord();
t3.teardown(fake.close);
let ready = 0;
const gateway = new DiscordGateway("token", 0, logger, { onReady: () => { ready += 1; } }, fake.gatewayUrl);
gateway.backoff = new lib.ExponentialBackoff({ base: 0.01, max: 0.02 });
t3.teardown(() => gateway.stop());
gateway.start();
await until(() => ready === 1);
for (const ws of fake.sockets) {
ws.terminate();
}
await until(() => ready === 2);
t3.equal(fake.identifies.length, 2);
});
t2.test("stops on a fatal close code", async t3 => {
const fake = await startFakeDiscord({ closeCode: 4014 });
t3.teardown(fake.close);
let closed;
const gateway = new DiscordGateway("token", 0, logger, {
onFatalClose: (code, reason) => { closed = { code, reason }; },
}, fake.gatewayUrl);
gateway.backoff = new lib.ExponentialBackoff({ base: 0.01, max: 0.02 });
gateway.start();
await until(() => closed);
t3.same(closed, { code: 4014, reason: "closed by fake" });
await new Promise(resolve => setTimeout(resolve, 100));
t3.equal(fake.identifies.length, 1, "did not reconnect");
});
t2.test(".stop() closes without reconnecting", async t3 => {
const fake = await startFakeDiscord();
t3.teardown(fake.close);
let ready = 0;
const gateway = new DiscordGateway("token", 0, logger, { onReady: () => { ready += 1; } }, fake.gatewayUrl);
gateway.backoff = new lib.ExponentialBackoff({ base: 0.01, max: 0.02 });
gateway.start();
await until(() => ready === 1);
gateway.stop();
await until(() => fake.sockets.size === 0);
await new Promise(resolve => setTimeout(resolve, 100));
t3.equal(fake.identifies.length, 1);
});
});
+118
View File
@@ -0,0 +1,118 @@
import * as http from "node:http";
import { WebSocketServer } from "ws";
export const guildId = "100000000000000000";
/**
* Discord REST and gateway for one guild on a local port.
*
* members maps user id to a Set of role ids. rateLimit makes the next n
* requests answer 429. The gateway sends READY after identify, more events
* go through dispatch().
*/
export async function startFakeDiscord({ token = "token", closeCode } = {}) {
const fake = {
roles: [
{ id: guildId, name: "@everyone", color: 0, position: 0, managed: false },
],
members: new Map(),
requests: [],
rateLimit: 0,
identifies: [],
sockets: new Set(),
dispatch(t, d) {
for (const ws of fake.sockets) {
ws.send(JSON.stringify({ op: 0, s: 2, t, d }));
}
},
};
const server = http.createServer((req, res) => {
const route = `${req.method} ${req.url.replace(/^\/api\/v10/, "")}`;
fake.requests.push(route);
const reply = (status, body) => {
res.writeHead(status, { "Content-Type": "application/json" });
res.end(body === undefined ? undefined : JSON.stringify(body));
};
if (req.headers.authorization !== `Bot ${token}`) {
reply(401, { message: "401: Unauthorized" });
return;
}
if (fake.rateLimit > 0) {
fake.rateLimit -= 1;
reply(429, { message: "You are being rate limited.", retry_after: 0.05, global: false });
return;
}
let match;
if (route === `GET /guilds/${guildId}/roles`) {
reply(200, fake.roles);
} else if ((match = route.match(new RegExp(`^GET /guilds/${guildId}/members/(\\d+)$`)))) {
const roles = fake.members.get(match[1]);
if (roles) {
reply(200, { user: { id: match[1] }, roles: [...roles] });
} else {
reply(404, { message: "Unknown Member", code: 10007 });
}
} else if ((match = route.match(new RegExp(`^(PUT|DELETE) /guilds/${guildId}/members/(\\d+)/roles/(\\d+)$`)))) {
const roles = fake.members.get(match[2]);
if (!roles) {
reply(404, { message: "Unknown Member", code: 10007 });
} else if (fake.roles.find(role => role.id === match[3])?.name === "Above bot") {
reply(403, { message: "Missing Permissions", code: 50013 });
} else {
roles[match[1] === "PUT" ? "add" : "delete"](match[3]);
reply(204);
}
} else {
reply(404, { message: "404: Not Found" });
}
});
const wss = new WebSocketServer({ server });
wss.on("connection", ws => {
fake.sockets.add(ws);
ws.on("close", () => fake.sockets.delete(ws));
ws.send(JSON.stringify({ op: 10, s: null, t: null, d: { heartbeat_interval: 45000 } }));
ws.on("message", data => {
const payload = JSON.parse(String(data));
if (payload.op === 1) {
ws.send(JSON.stringify({ op: 11, s: null, t: null, d: null }));
} else if (payload.op === 2) {
fake.identifies.push(payload.d);
if (closeCode) {
ws.close(closeCode, "closed by fake");
} else if (payload.d.token !== token) {
ws.close(4004, "Authentication failed.");
} else {
ws.send(JSON.stringify({ op: 0, s: 1, t: "READY", d: { session_id: "s" } }));
}
}
});
});
await new Promise(resolve => server.listen(0, "127.0.0.1", resolve));
const port = server.address().port;
fake.apiBase = `http://127.0.0.1:${port}/api/v10`;
fake.gatewayUrl = `ws://127.0.0.1:${port}/?v=10&encoding=json`;
fake.close = async () => {
for (const ws of wss.clients) {
ws.terminate();
}
wss.close();
server.closeAllConnections();
await new Promise(resolve => server.close(resolve));
};
return fake;
}
/** Wait until check() is truthy, failing after a second. */
export async function until(check) {
for (let i = 0; i < 100; i++) {
if (check()) {
return;
}
await new Promise(resolve => setTimeout(resolve, 10));
}
throw new Error("timed out waiting");
}
+4
View File
@@ -0,0 +1,4 @@
{
"extends": "../tsconfig.browser.json",
"include": [ "web/**/*.tsx", "web/**/*.ts", "index.ts", "messages.ts", "package.json" ],
}
+7
View File
@@ -0,0 +1,7 @@
{
"files": [],
"references": [
{ "path": "./tsconfig.node.json" },
{ "path": "./tsconfig.browser.json" }
]
}
+8
View File
@@ -0,0 +1,8 @@
{
"extends": "../tsconfig.node.json",
"references": [
{ "path": "../exp_discord_auth/tsconfig.node.json" },
],
"include": ["./**/*.ts"],
"exclude": ["test/*", "./dist/*"],
}
+6
View File
@@ -0,0 +1,6 @@
import { defineConfig } from "vite";
import { clusterioPlugin } from "@clusterio/web_ui/vite.mjs";
export default defineConfig({
plugins: [clusterioPlugin()],
});
@@ -0,0 +1,90 @@
import React, { useContext, useEffect, useState } from "react";
import { Alert, Button, Select, Typography } from "antd";
import { ControlContext, PluginExtensionProps, SectionHeader, notifyErrorHandler, useAccount } from "@clusterio/web_ui";
import { GuildRoleListRequest, RoleMappingUpdateRequest } from "../../messages.js";
import { useRoleMappings } from "..";
type GuildRole = { id: string, name: string, color: number };
function roleColor(color: number) {
return color ? `#${color.toString(16).padStart(6, "0")}` : undefined;
}
/** The Discord roles given to linked players holding this role. */
export default function RoleDiscordRoles(props: PluginExtensionProps<"RoleViewPageBeforePermissions">) {
const control = useContext(ControlContext);
const account = useAccount();
const [mappings, synced] = useRoleMappings();
const [guildRoles, setGuildRoles] = useState<GuildRole[]>([]);
const [guildError, setGuildError] = useState<string>();
const [selected, setSelected] = useState<string[]>();
const [applying, setApplying] = useState(false);
const canUpdate = account.hasPermission("exp_discord_sync.mapping.update");
const saved = (props.role ? mappings.get(props.role.id)?.discordRoleIds : undefined) ?? [];
const value = selected ?? saved;
const changed = selected !== undefined && selected.join() !== saved.join();
useEffect(() => {
control.send(new GuildRoleListRequest())
.then(roles => { setGuildRoles(roles); setGuildError(undefined); })
.catch(err => setGuildError(err.message));
}, []);
useEffect(() => setSelected(undefined), [props.role?.id, saved.join()]);
if (!props.role || !synced) {
return null;
}
async function apply() {
await control.send(new RoleMappingUpdateRequest(props.role!.id, value));
setSelected(undefined);
}
const options = guildRoles.map(role => ({
value: role.id,
label: <span style={{ color: roleColor(role.color) }}>{role.name}</span>,
search: role.name,
}));
return <>
<SectionHeader
title="Discord Roles"
extra={canUpdate ? <Button
type="primary"
disabled={!changed}
loading={applying}
onClick={() => {
setApplying(true);
apply()
.catch(notifyErrorHandler("Error updating Discord roles"))
.finally(() => setApplying(false));
}}
>Apply Discord roles</Button> : undefined}
/>
{guildError && <Alert
type="warning"
showIcon
message={`Could not list the Discord roles: ${guildError}`}
description={canUpdate ? "Role IDs can still be typed in." : undefined}
style={{ marginBottom: 8 }}
/>}
<Select
mode="tags"
style={{ width: "100%" }}
placeholder={canUpdate ? "Select Discord roles or type a role ID" : "None"}
disabled={!canUpdate}
value={value}
options={options}
optionFilterProp="search"
tokenSeparators={[",", " "]}
onChange={setSelected}
/>
<Typography.Paragraph type="secondary" style={{ marginTop: 8 }}>
Players linked to Discord get these roles while they hold this role.
</Typography.Paragraph>
</>;
}
+22
View File
@@ -0,0 +1,22 @@
import { useCallback, useSyncExternalStore } from "react";
import { WebPluginContext } from "@clusterio/web_ui";
import * as lib from "@clusterio/lib";
import * as messages from "../messages.js";
import RoleDiscordRoles from "./components/RoleDiscordRoles";
let mappings: lib.MapSubscriber<messages.RoleMappingUpdatedEvent> | undefined;
export function useRoleMappings() {
const subscribe = useCallback((cb: () => void) => mappings!.subscribe(cb), []);
return useSyncExternalStore(subscribe, () => mappings!.getSnapshot());
}
export default function registerPlugin(context: WebPluginContext) {
context.control.hooks.extensionComponents.attach("exp_discord_sync", () => ({
RoleViewPageBeforePermissions: RoleDiscordRoles,
}));
mappings = new lib.MapSubscriber(messages.RoleMappingUpdatedEvent, context.control);
}
+1
View File
@@ -4,6 +4,7 @@
{ "path": "./exp_auto_restart/" },
{ "path": "./exp_commands/" },
{ "path": "./exp_discord_auth/" },
{ "path": "./exp_discord_sync/" },
{ "path": "./exp_groups/" },
{ "path": "./exp_gui/" },
{ "path": "./exp_reports/" },