mirror of
https://github.com/PHIDIAS0303/ExpCluster.git
synced 2026-11-21 23:33:12 +09:00
Add the exp_reports plugin and move the scenario onto it
Reports were the last legacy control module, kept in the lua state of each instance. They are now an exp_reports plugin which stores them on the controller: a report is immutable and holds the reported player, who made it, the reason, the instance name and when it was made, and the only operations are get, list, create and delete. In game nothing is stored. The lua module sends each request over ipc, the instance plugin asks the controller and hands the answer back with rcon, and the module prints it to whoever asked if they are still online. Answers are dropped if the instance stopped meanwhile. The module raises on_player_reported with the count and reporters of every report against the player, which report_jail and discord_alerts use, and the commands and player list button call into it. The web ui gets a /reports page: a table with search on the player, reporter and reason, a filter on the instance, delete per row and a create form which reports in the name of the web user. New reports are posted to two optional webhooks configured on the controller, a Discord channel hook as an embed and a generic JSON hook. Failures are logged rather than failing the report. Tests cover the messages, the controller against a real Controller, the instance plugin against a real Instance, and the lua module through the shared harness.
This commit is contained in:
1 parent
142d296a02
commit
bad98c5013
35 files changed
+1707
-350
No files matched your search
@@ -0,0 +1,143 @@
|
||||
import { BaseControllerPlugin } from "@clusterio/controller";
|
||||
import * as lib from "@clusterio/lib";
|
||||
import * as messages from "./messages";
|
||||
import * as path from "node:path";
|
||||
|
||||
export class ControllerPlugin extends BaseControllerPlugin {
|
||||
reports!: lib.SubscribableDatastore<messages.ReportRecord>;
|
||||
|
||||
async init() {
|
||||
const databaseDirectory = this.controller.config.get("controller.database_directory");
|
||||
|
||||
this.reports = new lib.SubscribableDatastore(
|
||||
...await new lib.JsonIdDatastoreProvider(
|
||||
path.join(databaseDirectory, "exp_reports", "reports.json"),
|
||||
messages.ReportRecord.fromJSON.bind(messages.ReportRecord),
|
||||
).bootstrap()
|
||||
);
|
||||
|
||||
this.controller.subscriptions.handle(messages.ReportUpdatedEvent, this.handleReportSubscription.bind(this));
|
||||
this.reports.on("update", this.reportsUpdated.bind(this));
|
||||
|
||||
this.controller.handle(messages.ReportListRequest, this.handleReportListRequest.bind(this));
|
||||
this.controller.handle(messages.ReportGetRequest, this.handleReportGetRequest.bind(this));
|
||||
this.controller.handle(messages.ReportCreateRequest, this.handleReportCreateRequest.bind(this));
|
||||
this.controller.handle(messages.ReportDeleteRequest, this.handleReportDeleteRequest.bind(this));
|
||||
}
|
||||
|
||||
async onShutdown() {
|
||||
await this.reports.save();
|
||||
}
|
||||
|
||||
/** Reports are immutable, so any update which is not a deletion is a new report. */
|
||||
reportsUpdated(reports: messages.ReportRecord[]) {
|
||||
this.controller.subscriptions.broadcast(new messages.ReportUpdatedEvent(reports));
|
||||
|
||||
for (const report of reports) {
|
||||
if (!report.isDeleted) {
|
||||
this.sendWebhooks(report);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async handleReportSubscription(request: lib.SubscriptionRequest) {
|
||||
const reports = [...this.reports.values()].filter(report => report.updatedAtMs > request.lastRequestTimeMs);
|
||||
return reports.length ? new messages.ReportUpdatedEvent(reports) : null;
|
||||
}
|
||||
|
||||
/** Every report, or only those against one player. */
|
||||
listReports(playerName?: string) {
|
||||
const reports = [...this.reports.values()];
|
||||
return playerName === undefined ? reports : reports.filter(report => report.playerName === playerName);
|
||||
}
|
||||
|
||||
async handleReportListRequest(request: messages.ReportListRequest) {
|
||||
return this.listReports(request.playerName);
|
||||
}
|
||||
|
||||
async handleReportGetRequest(request: messages.ReportGetRequest) {
|
||||
const report = this.reports.get(request.id);
|
||||
if (!report) {
|
||||
throw new lib.RequestError(`Report with ID ${request.id} does not exist`);
|
||||
}
|
||||
return report;
|
||||
}
|
||||
|
||||
async handleReportCreateRequest(request: messages.ReportCreateRequest, src: lib.Address) {
|
||||
let byPlayerName = request.byPlayerName;
|
||||
let instanceName = "";
|
||||
if (src.type === lib.Address.control) {
|
||||
byPlayerName = this.controller.wsServer.controlConnections.get(src.id)!.user.name;
|
||||
} else {
|
||||
const instance = this.controller.instances.get(src.id);
|
||||
instanceName = instance ? instance.config.get("instance.name") : String(src.id);
|
||||
}
|
||||
|
||||
if (!byPlayerName) {
|
||||
throw new lib.RequestError("A report needs the name of the player making it");
|
||||
}
|
||||
if (!request.reason.trim()) {
|
||||
throw new lib.RequestError("A report needs a reason");
|
||||
}
|
||||
if (this.listReports(request.playerName).some(report => report.byPlayerName === byPlayerName)) {
|
||||
throw new lib.RequestError(`${byPlayerName} has already reported ${request.playerName}`);
|
||||
}
|
||||
|
||||
let id = Math.random() * 2 ** 31 | 0;
|
||||
while (this.reports.has(id)) {
|
||||
id = Math.random() * 2 ** 31 | 0;
|
||||
}
|
||||
|
||||
const report = new messages.ReportRecord(id, request.playerName, byPlayerName, request.reason.trim(), instanceName);
|
||||
this.reports.set(report);
|
||||
return report;
|
||||
}
|
||||
|
||||
async handleReportDeleteRequest(request: messages.ReportDeleteRequest) {
|
||||
const report = this.reports.getMutable(request.id);
|
||||
if (!report) {
|
||||
throw new lib.RequestError(`Report with ID ${request.id} does not exist`);
|
||||
}
|
||||
this.reports.delete(report);
|
||||
}
|
||||
|
||||
/** Post a new report to the configured webhooks, failures are logged rather than failing the report. */
|
||||
sendWebhooks(report: messages.ReportRecord) {
|
||||
const discordUrl = this.controller.config.get("exp_reports.discord_webhook_url");
|
||||
if (discordUrl) {
|
||||
this.postWebhook(discordUrl, {
|
||||
embeds: [{
|
||||
title: "Player reported",
|
||||
color: 0xffcc00,
|
||||
timestamp: new Date(report.updatedAtMs).toISOString(),
|
||||
fields: [
|
||||
{ name: "Player", value: report.playerName, inline: true },
|
||||
{ name: "By", value: report.byPlayerName, inline: true },
|
||||
{ name: "Instance", value: report.instanceName || "Web UI", inline: true },
|
||||
{ name: "Reason", value: report.reason },
|
||||
],
|
||||
}],
|
||||
});
|
||||
}
|
||||
|
||||
const jsonUrl = this.controller.config.get("exp_reports.json_webhook_url");
|
||||
if (jsonUrl) {
|
||||
this.postWebhook(jsonUrl, { type: "report_created", report: report.toJSON() });
|
||||
}
|
||||
}
|
||||
|
||||
async postWebhook(url: string, body: unknown) {
|
||||
try {
|
||||
const response = await fetch(url, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify(body),
|
||||
});
|
||||
if (!response.ok) {
|
||||
this.logger.warn(`Webhook ${url} responded with ${response.status}`);
|
||||
}
|
||||
} catch (err: any) {
|
||||
this.logger.warn(`Webhook ${url} failed: ${err.message}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
import * as lib from "@clusterio/lib";
|
||||
import * as messages from "./messages";
|
||||
|
||||
declare module "@clusterio/lib" {
|
||||
export interface ControllerConfigFields {
|
||||
"exp_reports.discord_webhook_url": string | null;
|
||||
"exp_reports.json_webhook_url": string | null;
|
||||
}
|
||||
}
|
||||
|
||||
lib.definePermission({
|
||||
name: "exp_reports.report.get",
|
||||
title: "Get Reports",
|
||||
description: "Retrieve a specific report by id.",
|
||||
grantByDefault: true,
|
||||
});
|
||||
lib.definePermission({
|
||||
name: "exp_reports.report.list",
|
||||
title: "List Reports",
|
||||
description: "List the reports against every player, or against one player.",
|
||||
grantByDefault: true,
|
||||
});
|
||||
lib.definePermission({
|
||||
name: "exp_reports.report.subscribe",
|
||||
title: "Subscribe to Report Updates",
|
||||
description: "Receive updates when reports are made or deleted.",
|
||||
grantByDefault: true,
|
||||
});
|
||||
lib.definePermission({
|
||||
name: "exp_reports.report.create",
|
||||
title: "Create Reports",
|
||||
description: "Report a player.",
|
||||
grantByDefault: false,
|
||||
});
|
||||
lib.definePermission({
|
||||
name: "exp_reports.report.delete",
|
||||
title: "Delete Reports",
|
||||
description: "Delete reports made against a player.",
|
||||
grantByDefault: false,
|
||||
});
|
||||
|
||||
export const plugin: lib.PluginDeclaration = {
|
||||
name: "exp_reports",
|
||||
title: "ExpGaming - Reports",
|
||||
description: "Clusterio plugin storing player reports on the controller",
|
||||
|
||||
features: [
|
||||
"SavePatching",
|
||||
"ScriptCommands",
|
||||
],
|
||||
|
||||
messages: [
|
||||
messages.ReportUpdatedEvent,
|
||||
|
||||
messages.ReportListRequest,
|
||||
messages.ReportGetRequest,
|
||||
messages.ReportCreateRequest,
|
||||
messages.ReportDeleteRequest,
|
||||
],
|
||||
|
||||
instanceEntrypoint: "./dist/node/instance",
|
||||
|
||||
controllerEntrypoint: "./dist/node/controller",
|
||||
controllerConfigFields: {
|
||||
"exp_reports.discord_webhook_url": {
|
||||
title: "Discord Webhook URL",
|
||||
description: "Discord channel webhook which new reports are posted to as an embed.",
|
||||
type: "string",
|
||||
optional: true,
|
||||
},
|
||||
"exp_reports.json_webhook_url": {
|
||||
title: "JSON Webhook URL",
|
||||
description: "URL which new reports are posted to as JSON.",
|
||||
type: "string",
|
||||
optional: true,
|
||||
},
|
||||
},
|
||||
|
||||
webEntrypoint: "./web",
|
||||
routes: [
|
||||
"/reports",
|
||||
],
|
||||
};
|
||||
@@ -0,0 +1,95 @@
|
||||
import { BaseInstancePlugin } from "@clusterio/host";
|
||||
import * as messages from "./messages";
|
||||
|
||||
/** Sent by the lua side when a player reports another. */
|
||||
export type IpcReportCreate = {
|
||||
player_name: string,
|
||||
by_player_name: string,
|
||||
reason: string,
|
||||
};
|
||||
|
||||
/** Sent by the lua side to list the reports for a player, or for everyone. */
|
||||
export type IpcReportList = {
|
||||
caller: string,
|
||||
player_name: string | undefined,
|
||||
};
|
||||
|
||||
/** Sent by the lua side to delete the reports against a player, optionally only those from one player. */
|
||||
export type IpcReportDelete = {
|
||||
caller: string,
|
||||
player_name: string,
|
||||
by_player_name: string | undefined,
|
||||
};
|
||||
|
||||
/**
|
||||
* Bridges the lua side and the controller.
|
||||
*
|
||||
* Nothing is kept in the lua state, every request goes to the controller and
|
||||
* the answer is handed back to lua once it arrives. The instance may have
|
||||
* stopped by then, in which case the answer is dropped.
|
||||
*/
|
||||
export class InstancePlugin extends BaseInstancePlugin {
|
||||
async init() {
|
||||
this.instance.server.handle("exp_reports:create", this.handleCreateIPC.bind(this));
|
||||
this.instance.server.handle("exp_reports:list", this.handleListIPC.bind(this));
|
||||
this.instance.server.handle("exp_reports:delete", this.handleDeleteIPC.bind(this));
|
||||
}
|
||||
|
||||
async handleCreateIPC(event: IpcReportCreate) {
|
||||
try {
|
||||
const report = await this.instance.sendTo("controller", new messages.ReportCreateRequest(
|
||||
event.player_name, event.reason, event.by_player_name,
|
||||
));
|
||||
const reports = await this.instance.sendTo("controller", new messages.ReportListRequest(event.player_name));
|
||||
await this.luaSend("receive_created", {
|
||||
report: report.toJSON(),
|
||||
reports: reports.map(other => other.toJSON()),
|
||||
});
|
||||
} catch (err: any) {
|
||||
await this.luaSend("receive_error", { caller: event.by_player_name, message: err.message });
|
||||
}
|
||||
}
|
||||
|
||||
async handleListIPC(event: IpcReportList) {
|
||||
try {
|
||||
const reports = await this.instance.sendTo("controller", new messages.ReportListRequest(event.player_name));
|
||||
await this.luaSend("receive_list", {
|
||||
caller: event.caller,
|
||||
player_name: event.player_name,
|
||||
reports: reports.map(report => report.toJSON()),
|
||||
});
|
||||
} catch (err: any) {
|
||||
await this.luaSend("receive_error", { caller: event.caller, message: err.message });
|
||||
}
|
||||
}
|
||||
|
||||
async handleDeleteIPC(event: IpcReportDelete) {
|
||||
try {
|
||||
let reports = await this.instance.sendTo("controller", new messages.ReportListRequest(event.player_name));
|
||||
if (event.by_player_name !== undefined) {
|
||||
reports = reports.filter(report => report.byPlayerName === event.by_player_name);
|
||||
}
|
||||
for (const report of reports) {
|
||||
await this.instance.sendTo("controller", new messages.ReportDeleteRequest(report.id));
|
||||
}
|
||||
await this.luaSend("receive_deleted", {
|
||||
caller: event.caller,
|
||||
player_name: event.player_name,
|
||||
by_player_name: event.by_player_name,
|
||||
count: reports.length,
|
||||
});
|
||||
} catch (err: any) {
|
||||
await this.luaSend("receive_error", { caller: event.caller, message: err.message });
|
||||
}
|
||||
}
|
||||
|
||||
/** Hand an answer to lua, unless the instance stopped while it was being fetched. */
|
||||
async luaSend(receiver: string, json: any) {
|
||||
if (this.instance.status !== "running") {
|
||||
return;
|
||||
}
|
||||
await this.instance.sendRcon(
|
||||
`/sc exp_reports.${receiver}(helpers.json_to_table[=[${JSON.stringify(json)}]=])`, true
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,222 @@
|
||||
import * as lib from "@clusterio/lib";
|
||||
import { Type, Static } from "@sinclair/typebox";
|
||||
|
||||
/*
|
||||
Data records
|
||||
*/
|
||||
|
||||
/**
|
||||
* A report made against a player.
|
||||
*
|
||||
* Reports are immutable, so until it is deleted updatedAtMs is when the
|
||||
* report was made.
|
||||
*/
|
||||
export class ReportRecord {
|
||||
constructor(
|
||||
public id: number,
|
||||
public playerName: string,
|
||||
public byPlayerName: string,
|
||||
public reason: string,
|
||||
/** Name of the instance the report was made on, empty when made from the web ui. */
|
||||
public instanceName: string,
|
||||
public updatedAtMs: number = 0,
|
||||
public isDeleted: boolean = false,
|
||||
) {}
|
||||
|
||||
static jsonSchema = Type.Object({
|
||||
id: Type.Integer(),
|
||||
player_name: Type.String(),
|
||||
by_player_name: Type.String(),
|
||||
reason: Type.String(),
|
||||
instance_name: Type.String(),
|
||||
updated_at_ms: Type.Optional(Type.Number()),
|
||||
is_deleted: Type.Optional(Type.Boolean()),
|
||||
});
|
||||
|
||||
toJSON() {
|
||||
const json: Static<typeof ReportRecord.jsonSchema> = {
|
||||
id: this.id,
|
||||
player_name: this.playerName,
|
||||
by_player_name: this.byPlayerName,
|
||||
reason: this.reason,
|
||||
instance_name: this.instanceName,
|
||||
};
|
||||
|
||||
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.player_name,
|
||||
json.by_player_name,
|
||||
json.reason,
|
||||
json.instance_name,
|
||||
json.updated_at_ms ?? 0,
|
||||
json.is_deleted ?? false,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
Update events
|
||||
*/
|
||||
|
||||
export class ReportUpdatedEvent {
|
||||
declare ["constructor"]: typeof ReportUpdatedEvent;
|
||||
static plugin = "exp_reports" as const;
|
||||
static type = "event" as const;
|
||||
static src = "controller" as const;
|
||||
static dst = "control" as const;
|
||||
static permission = "exp_reports.report.subscribe" as const;
|
||||
|
||||
constructor(
|
||||
public updates: ReportRecord[],
|
||||
) {}
|
||||
|
||||
static jsonSchema = Type.Object({
|
||||
updates: Type.Array(ReportRecord.jsonSchema),
|
||||
});
|
||||
|
||||
toJSON() {
|
||||
return { updates: this.updates.map(report => report.toJSON()) };
|
||||
}
|
||||
|
||||
static fromJSON(json: Static<typeof this.jsonSchema>) {
|
||||
return new this(json.updates.map(report => ReportRecord.fromJSON(report)));
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
Report requests
|
||||
*/
|
||||
|
||||
/** List every report, or only those against one player. */
|
||||
export class ReportListRequest {
|
||||
declare ["constructor"]: typeof ReportListRequest;
|
||||
static plugin = "exp_reports" as const;
|
||||
static type = "request" as const;
|
||||
static src = ["control", "instance"] as const;
|
||||
static dst = "controller" as const;
|
||||
static permission = "exp_reports.report.list" as const;
|
||||
static Response = lib.jsonArray(ReportRecord);
|
||||
|
||||
constructor(
|
||||
public playerName?: string,
|
||||
) {}
|
||||
|
||||
static jsonSchema = Type.Object({
|
||||
player_name: Type.Optional(Type.String()),
|
||||
});
|
||||
|
||||
toJSON() {
|
||||
const json: Static<typeof ReportListRequest.jsonSchema> = {};
|
||||
if (this.playerName !== undefined) {
|
||||
json.player_name = this.playerName;
|
||||
}
|
||||
return json;
|
||||
}
|
||||
|
||||
static fromJSON(json: Static<typeof this.jsonSchema>) {
|
||||
return new this(json.player_name);
|
||||
}
|
||||
}
|
||||
|
||||
export class ReportGetRequest {
|
||||
declare ["constructor"]: typeof ReportGetRequest;
|
||||
static plugin = "exp_reports" as const;
|
||||
static type = "request" as const;
|
||||
static src = ["control", "instance"] as const;
|
||||
static dst = "controller" as const;
|
||||
static permission = "exp_reports.report.get" as const;
|
||||
static Response = ReportRecord;
|
||||
|
||||
constructor(
|
||||
public id: number,
|
||||
) {}
|
||||
|
||||
static jsonSchema = Type.Object({
|
||||
id: Type.Integer(),
|
||||
});
|
||||
|
||||
toJSON() {
|
||||
return { id: this.id };
|
||||
}
|
||||
|
||||
static fromJSON(json: Static<typeof this.jsonSchema>) {
|
||||
return new this(json.id);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Report a player.
|
||||
*
|
||||
* From an instance byPlayerName is the player who made the report. From the
|
||||
* web ui it is ignored and the report is made by the user of the connection.
|
||||
*/
|
||||
export class ReportCreateRequest {
|
||||
declare ["constructor"]: typeof ReportCreateRequest;
|
||||
static plugin = "exp_reports" as const;
|
||||
static type = "request" as const;
|
||||
static src = ["control", "instance"] as const;
|
||||
static dst = "controller" as const;
|
||||
static permission = "exp_reports.report.create" as const;
|
||||
static Response = ReportRecord;
|
||||
|
||||
constructor(
|
||||
public playerName: string,
|
||||
public reason: string,
|
||||
public byPlayerName: string = "",
|
||||
) {}
|
||||
|
||||
static jsonSchema = Type.Object({
|
||||
player_name: Type.String(),
|
||||
reason: Type.String(),
|
||||
by_player_name: Type.String(),
|
||||
});
|
||||
|
||||
toJSON() {
|
||||
return {
|
||||
player_name: this.playerName,
|
||||
reason: this.reason,
|
||||
by_player_name: this.byPlayerName,
|
||||
};
|
||||
}
|
||||
|
||||
static fromJSON(json: Static<typeof this.jsonSchema>) {
|
||||
return new this(json.player_name, json.reason, json.by_player_name);
|
||||
}
|
||||
}
|
||||
|
||||
export class ReportDeleteRequest {
|
||||
declare ["constructor"]: typeof ReportDeleteRequest;
|
||||
static plugin = "exp_reports" as const;
|
||||
static type = "request" as const;
|
||||
static src = ["control", "instance"] as const;
|
||||
static dst = "controller" as const;
|
||||
static permission = "exp_reports.report.delete" as const;
|
||||
|
||||
constructor(
|
||||
public id: number,
|
||||
) {}
|
||||
|
||||
static jsonSchema = Type.Object({
|
||||
id: Type.Integer(),
|
||||
});
|
||||
|
||||
toJSON() {
|
||||
return { id: this.id };
|
||||
}
|
||||
|
||||
static fromJSON(json: Static<typeof this.jsonSchema>) {
|
||||
return new this(json.id);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,194 @@
|
||||
--[[-- ExpReports
|
||||
Lets players report each other, with the reports kept on the controller.
|
||||
|
||||
Nothing is stored in the lua state. Each call sends a request to the
|
||||
controller through the instance plugin, and the answer is printed to the
|
||||
player who asked once it arrives, if they are still online.
|
||||
]]
|
||||
|
||||
local clusterio_api = require("modules/clusterio/api")
|
||||
local ExpUtil = require("modules/exp_util")
|
||||
|
||||
local format_player_name = ExpUtil.format_player_name_locale
|
||||
|
||||
--- @class ExpReports
|
||||
local ExpReports = {
|
||||
--- Raised once the controller has accepted a report, the reported player is online
|
||||
--- @type EventData.ExpReports.on_player_reported
|
||||
on_player_reported = script.generate_event_name(),
|
||||
--- Raised once the controller has deleted reports, the reported player is online
|
||||
--- @type EventData.ExpReports.on_reports_deleted
|
||||
on_reports_deleted = script.generate_event_name(),
|
||||
}
|
||||
|
||||
--- @class EventData.ExpReports.on_player_reported : EventData
|
||||
--- @field player_index uint
|
||||
--- @field by_player_name string
|
||||
--- @field reason string
|
||||
--- @field report_count number Reports against the player including this one
|
||||
--- @field by_player_names string[] Who made each of those reports
|
||||
|
||||
--- @class EventData.ExpReports.on_reports_deleted : EventData
|
||||
--- @field player_index uint
|
||||
--- @field by_player_name string Who deleted the reports
|
||||
--- @field count number
|
||||
|
||||
--- @class ExpReports.Report
|
||||
--- @field id number
|
||||
--- @field player_name string
|
||||
--- @field by_player_name string
|
||||
--- @field reason string
|
||||
--- @field instance_name string
|
||||
--- @field updated_at_ms number
|
||||
|
||||
local error_settings = { color = ExpUtil.color.orange_red, sound_path = "utility/wire_pickup" }
|
||||
|
||||
--- Report a player, the outcome is printed once the controller answers
|
||||
--- @param player LuaPlayer
|
||||
--- @param reported_player LuaPlayer
|
||||
--- @param reason string
|
||||
function ExpReports.create_report(player, reported_player, reason)
|
||||
clusterio_api.send_json("exp_reports:create", {
|
||||
player_name = reported_player.name,
|
||||
by_player_name = player.name,
|
||||
reason = reason,
|
||||
})
|
||||
end
|
||||
|
||||
--- List the reports against a player, or against everyone, printed to the player once the controller answers
|
||||
--- @param player LuaPlayer
|
||||
--- @param reported_player LuaPlayer?
|
||||
function ExpReports.list_reports(player, reported_player)
|
||||
clusterio_api.send_json("exp_reports:list", {
|
||||
caller = player.name,
|
||||
player_name = reported_player and reported_player.name or nil,
|
||||
})
|
||||
end
|
||||
|
||||
--- Delete the reports against a player, or only those from one player
|
||||
--- @param player LuaPlayer
|
||||
--- @param reported_player LuaPlayer
|
||||
--- @param by_player_name string?
|
||||
function ExpReports.delete_reports(player, reported_player, by_player_name)
|
||||
clusterio_api.send_json("exp_reports:delete", {
|
||||
caller = player.name,
|
||||
player_name = reported_player.name,
|
||||
by_player_name = by_player_name,
|
||||
})
|
||||
end
|
||||
|
||||
--- A player who can still be printed to, nil once they have left
|
||||
--- @param name string
|
||||
--- @return LuaPlayer?
|
||||
local function get_online_player(name)
|
||||
local player = game.get_player(name)
|
||||
if player and player.valid and player.connected then
|
||||
return player
|
||||
end
|
||||
return nil
|
||||
end
|
||||
|
||||
--- The controller accepted a report
|
||||
--- @param payload { report: ExpReports.Report, reports: ExpReports.Report[] }
|
||||
function ExpReports.receive_created(payload)
|
||||
local report = payload.report
|
||||
local player_name = format_player_name(report.player_name)
|
||||
local by_player_name = format_player_name(report.by_player_name)
|
||||
for _, player in pairs(game.connected_players) do
|
||||
if player.admin then
|
||||
player.print{ "exp-reports.created-admin", player_name, by_player_name, report.reason }
|
||||
else
|
||||
player.print{ "exp-reports.created", player_name, report.reason }
|
||||
end
|
||||
end
|
||||
|
||||
local player = get_online_player(report.player_name)
|
||||
if not player then return end
|
||||
|
||||
local by_player_names = {}
|
||||
for index, other in ipairs(payload.reports) do
|
||||
by_player_names[index] = other.by_player_name
|
||||
end
|
||||
|
||||
script.raise_event(ExpReports.on_player_reported, {
|
||||
name = ExpReports.on_player_reported,
|
||||
tick = game.tick,
|
||||
player_index = player.index,
|
||||
by_player_name = report.by_player_name,
|
||||
reason = report.reason,
|
||||
report_count = #payload.reports,
|
||||
by_player_names = by_player_names,
|
||||
})
|
||||
end
|
||||
|
||||
--- The controller answered a list request
|
||||
--- @param payload { caller: string, player_name: string?, reports: ExpReports.Report[] }
|
||||
function ExpReports.receive_list(payload)
|
||||
local caller = get_online_player(payload.caller)
|
||||
if not caller then return end
|
||||
|
||||
if payload.player_name then
|
||||
caller.print{ "exp-reports.list-title", format_player_name(payload.player_name), #payload.reports }
|
||||
for _, report in ipairs(payload.reports) do
|
||||
caller.print{ "exp-reports.list-entry", format_player_name(report.by_player_name), report.reason }
|
||||
end
|
||||
return
|
||||
end
|
||||
|
||||
local counts = {} --- @type table<string, number>
|
||||
local names = {} --- @type string[]
|
||||
for _, report in ipairs(payload.reports) do
|
||||
if not counts[report.player_name] then
|
||||
names[#names + 1] = report.player_name
|
||||
counts[report.player_name] = 0
|
||||
end
|
||||
counts[report.player_name] = counts[report.player_name] + 1
|
||||
end
|
||||
|
||||
if #names == 0 then
|
||||
caller.print{ "exp-reports.list-all-none" }
|
||||
return
|
||||
end
|
||||
|
||||
table.sort(names)
|
||||
caller.print{ "exp-reports.list-all-title" }
|
||||
for _, name in ipairs(names) do
|
||||
caller.print{ "exp-reports.list-all-entry", format_player_name(name), counts[name] }
|
||||
end
|
||||
end
|
||||
|
||||
--- The controller deleted reports
|
||||
--- @param payload { caller: string, player_name: string, by_player_name: string?, count: number }
|
||||
function ExpReports.receive_deleted(payload)
|
||||
if payload.count == 0 then
|
||||
local caller = get_online_player(payload.caller)
|
||||
if caller then
|
||||
caller.print({ "exp-reports.deleted-none", format_player_name(payload.player_name) }, error_settings)
|
||||
end
|
||||
return
|
||||
end
|
||||
|
||||
game.print{ "exp-reports.deleted", format_player_name(payload.player_name), payload.count, format_player_name(payload.caller) }
|
||||
|
||||
local player = get_online_player(payload.player_name)
|
||||
if not player then return end
|
||||
|
||||
script.raise_event(ExpReports.on_reports_deleted, {
|
||||
name = ExpReports.on_reports_deleted,
|
||||
tick = game.tick,
|
||||
player_index = player.index,
|
||||
by_player_name = payload.caller,
|
||||
count = payload.count,
|
||||
})
|
||||
end
|
||||
|
||||
--- The controller refused a request, the message is printed to whoever asked
|
||||
--- @param payload { caller: string, message: string }
|
||||
function ExpReports.receive_error(payload)
|
||||
local caller = get_online_player(payload.caller)
|
||||
if caller then
|
||||
caller.print(payload.message, error_settings)
|
||||
end
|
||||
end
|
||||
|
||||
return ExpReports
|
||||
@@ -0,0 +1,10 @@
|
||||
--[[
|
||||
It is best practice to not expose any globals because all modules share a global environment
|
||||
However, sometimes you need globals, for example to access functions within rcon commands
|
||||
Therefore, we advise that this should be the only file in your module to expose globals
|
||||
]]
|
||||
|
||||
--- @diagnostic disable: global-in-non-module
|
||||
|
||||
-- Access using `/sc exp_reports.foo()`
|
||||
exp_reports = require("modules/exp_reports/control")
|
||||
@@ -0,0 +1,10 @@
|
||||
[exp-reports]
|
||||
created=__1__ was reported for __2__.
|
||||
created-admin=__1__ was reported by __2__ for __3__.
|
||||
list-title=__1__ has __2__ __plural_for_parameter__2__{1=report|rest=reports}__ against them:
|
||||
list-entry=__1__: __2__
|
||||
list-all-title=The following players have reports against them:
|
||||
list-all-entry=__1__: __2__ __plural_for_parameter__2__{1=report|rest=reports}__
|
||||
list-all-none=No players have reports against them.
|
||||
deleted=__1__ had __2__ __plural_for_parameter__2__{1=report|rest=reports}__ removed by __3__.
|
||||
deleted-none=__1__ has no reports against them.
|
||||
@@ -0,0 +1,10 @@
|
||||
[exp-reports]
|
||||
created=__1__ 因 __2__ 被舉報了。
|
||||
created-admin=__1__ 因 __3__ 被 __2__ 舉報了。
|
||||
list-title=__1__ 有 __2__ 項被舉報的紀錄:
|
||||
list-entry=__1__: __2__
|
||||
list-all-title=該用戶現在的被舉報紀錄:
|
||||
list-all-entry=__1__: __2__
|
||||
list-all-none=沒有用戶被舉報。
|
||||
deleted=__1__ 被舉報的 __2__ 個紀錄已被 __3__ 清除。
|
||||
deleted-none=__1__ 沒有被舉報的紀錄。
|
||||
@@ -0,0 +1,10 @@
|
||||
[exp-reports]
|
||||
created=__1__ 因 __2__ 被舉報了。
|
||||
created-admin=__1__ 因 __3__ 被 __2__ 舉報了。
|
||||
list-title=__1__ 有 __2__ 項被舉報的紀錄:
|
||||
list-entry=__1__: __2__
|
||||
list-all-title=該用戶現在的被舉報紀錄:
|
||||
list-all-entry=__1__: __2__
|
||||
list-all-none=沒有用戶被舉報。
|
||||
deleted=__1__ 被舉報的 __2__ 個紀錄已被 __3__ 清除。
|
||||
deleted-none=__1__ 沒有被舉報的紀錄。
|
||||
@@ -0,0 +1,12 @@
|
||||
{
|
||||
"name": "exp_reports",
|
||||
"load": [
|
||||
],
|
||||
"require": [
|
||||
"globals.lua"
|
||||
],
|
||||
"dependencies": {
|
||||
"clusterio": "*",
|
||||
"exp_util": "*"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
|
||||
-- Access the exports from other modules using require("modules/exp_reports")
|
||||
return require("modules/exp_reports/control")
|
||||
@@ -0,0 +1,53 @@
|
||||
{
|
||||
"name": "@expcluster/reports",
|
||||
"version": "7.0.1",
|
||||
"description": "Clusterio plugin storing player reports on the controller",
|
||||
"author": "Cooldude2606 <https://github.com/Cooldude2606>",
|
||||
"license": "MIT",
|
||||
"repository": "explosivegaming/ExpCluster",
|
||||
"main": "dist/node/index.js",
|
||||
"scripts": {
|
||||
"prepare": "tsc --build && webpack-cli --env production",
|
||||
"test": "tap --disable-coverage --allow-empty-coverage test/*.test.js",
|
||||
"coverage": "tap --coverage-report=text test/*.test.js"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@clusterio/controller": "workspace:^",
|
||||
"@clusterio/host": "workspace:^",
|
||||
"@clusterio/lib": "workspace:^",
|
||||
"@clusterio/web_ui": "workspace:^"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@ant-design/icons": "^6.2.3",
|
||||
"@clusterio/controller": "workspace:^",
|
||||
"@clusterio/host": "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:",
|
||||
"typescript": "catalog:",
|
||||
"webpack": "catalog:",
|
||||
"fengari": "^0.1.5",
|
||||
"tap": "^21.1.0",
|
||||
"webpack-cli": "catalog:",
|
||||
"webpack-merge": "catalog:"
|
||||
},
|
||||
"dependencies": {
|
||||
"@sinclair/typebox": "catalog:"
|
||||
},
|
||||
"publishConfig": {
|
||||
"access": "public"
|
||||
},
|
||||
"keywords": [
|
||||
"clusterio",
|
||||
"clusterio-plugin",
|
||||
"factorio"
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,193 @@
|
||||
"use strict";
|
||||
const t = require("tap");
|
||||
const lib = require("@clusterio/lib");
|
||||
const { Controller, InstanceRecord } = require("@clusterio/controller");
|
||||
const { ControllerPlugin } = require("../dist/node/controller");
|
||||
const messages = require("../dist/node/messages");
|
||||
const { plugin: pluginDeclaration } = require("../dist/node/index");
|
||||
|
||||
// The controller validates message classes against the link registry, and the
|
||||
// plugin's config fields must be defined before a ControllerConfig can set them
|
||||
for (const Message of pluginDeclaration.messages) {
|
||||
lib.Link.register(Message);
|
||||
}
|
||||
lib.addPluginConfigFields([pluginDeclaration]);
|
||||
|
||||
const logger = { child: () => logger, info: () => {}, warn: () => {}, error: () => {}, verbose: () => {} };
|
||||
|
||||
// Silence the singleton logger to avoid polluting the test output
|
||||
lib.logger.silent = true;
|
||||
t.after(() => {
|
||||
lib.logger.silent = false;
|
||||
});
|
||||
|
||||
const fromInstance = lib.Address.fromShorthand({ instanceId: 1 });
|
||||
const fromUnknownInstance = lib.Address.fromShorthand({ instanceId: 9 });
|
||||
const fromControl = lib.Address.fromShorthand({ controlId: 7 });
|
||||
|
||||
/** Build the plugin around a real controller, which is side effect free while not started. */
|
||||
async function startPlugin(t2, { config = {} } = {}) {
|
||||
const controllerConfig = new lib.ControllerConfig("controller", {
|
||||
"controller.database_directory": t2.testdir(),
|
||||
...config,
|
||||
});
|
||||
const controller = new Controller(logger, [], controllerConfig);
|
||||
|
||||
const instanceConfig = new lib.InstanceConfig("controller");
|
||||
instanceConfig.set("instance.id", 1);
|
||||
instanceConfig.set("instance.name", "EXP");
|
||||
controller.instances.records.set(new InstanceRecord(instanceConfig, "running"));
|
||||
controller.wsServer.controlConnections.set(7, { user: { name: "admin" } });
|
||||
|
||||
// Spies which record and then defer to the real behaviour
|
||||
const state = { broadcasts: [], posts: [], warnings: [] };
|
||||
const broadcast = controller.subscriptions.broadcast.bind(controller.subscriptions);
|
||||
controller.subscriptions.broadcast = event => {
|
||||
state.broadcasts.push(event);
|
||||
broadcast(event);
|
||||
};
|
||||
|
||||
const plugin = new ControllerPlugin({ name: "exp_reports" }, controller, undefined, logger);
|
||||
plugin.logger = { ...logger, warn: message => state.warnings.push(message) };
|
||||
plugin.postWebhook = async (url, body) => { state.posts.push({ url, body }); };
|
||||
await plugin.init();
|
||||
return { plugin, controller, state };
|
||||
}
|
||||
|
||||
t.test("class ControllerPlugin", t2 => {
|
||||
t2.test(".handleReportCreateRequest() from an instance records the instance and the reporter", async t3 => {
|
||||
const { plugin } = await startPlugin(t3);
|
||||
const report = await plugin.handleReportCreateRequest(
|
||||
new messages.ReportCreateRequest("bob", " griefing ", "alice"), fromInstance,
|
||||
);
|
||||
|
||||
t3.strictSame(report.playerName, "bob");
|
||||
t3.strictSame(report.byPlayerName, "alice", "the reporter comes from the request");
|
||||
t3.strictSame(report.reason, "griefing", "the reason is trimmed");
|
||||
t3.strictSame(report.instanceName, "EXP", "the instance is named");
|
||||
t3.ok(report.updatedAtMs > 0, "the report is timestamped");
|
||||
t3.strictSame(plugin.listReports(), [report], "the report is stored");
|
||||
|
||||
const unknown = await plugin.handleReportCreateRequest(
|
||||
new messages.ReportCreateRequest("carol", "spam", "alice"), fromUnknownInstance,
|
||||
);
|
||||
t3.strictSame(unknown.instanceName, "9", "an unknown instance is named by its id");
|
||||
});
|
||||
|
||||
t2.test(".handleReportCreateRequest() from the web ui uses the user of the connection", async t3 => {
|
||||
const { plugin } = await startPlugin(t3);
|
||||
const report = await plugin.handleReportCreateRequest(
|
||||
new messages.ReportCreateRequest("bob", "griefing", "someone-else"), fromControl,
|
||||
);
|
||||
|
||||
t3.strictSame(report.byPlayerName, "admin", "the reporter is the connected user");
|
||||
t3.strictSame(report.instanceName, "", "there is no instance");
|
||||
});
|
||||
|
||||
t2.test(".handleReportCreateRequest() rejects reports which can not be stored", async t3 => {
|
||||
const { plugin } = await startPlugin(t3);
|
||||
await plugin.handleReportCreateRequest(new messages.ReportCreateRequest("bob", "griefing", "alice"), fromInstance);
|
||||
|
||||
await t3.rejects(
|
||||
plugin.handleReportCreateRequest(new messages.ReportCreateRequest("bob", "again", "alice"), fromInstance),
|
||||
{ message: "alice has already reported bob" },
|
||||
"a player can only report another once",
|
||||
);
|
||||
await t3.rejects(
|
||||
plugin.handleReportCreateRequest(new messages.ReportCreateRequest("bob", " ", "carol"), fromInstance),
|
||||
{ message: "A report needs a reason" },
|
||||
"a reason is required",
|
||||
);
|
||||
await t3.rejects(
|
||||
plugin.handleReportCreateRequest(new messages.ReportCreateRequest("bob", "spam", ""), fromInstance),
|
||||
{ message: "A report needs the name of the player making it" },
|
||||
"an instance must name the reporter",
|
||||
);
|
||||
t3.strictSame(plugin.listReports().length, 1, "nothing else was stored");
|
||||
});
|
||||
|
||||
t2.test(".handleReportListRequest() and .handleReportGetRequest() find reports", async t3 => {
|
||||
const { plugin } = await startPlugin(t3);
|
||||
const first = await plugin.handleReportCreateRequest(new messages.ReportCreateRequest("bob", "griefing", "alice"), fromInstance);
|
||||
await plugin.handleReportCreateRequest(new messages.ReportCreateRequest("carol", "spam", "alice"), fromInstance);
|
||||
|
||||
t3.strictSame((await plugin.handleReportListRequest(new messages.ReportListRequest())).length, 2, "everything is listed");
|
||||
t3.strictSame(
|
||||
await plugin.handleReportListRequest(new messages.ReportListRequest("bob")), [first],
|
||||
"a player's reports are listed",
|
||||
);
|
||||
t3.strictSame(await plugin.handleReportGetRequest(new messages.ReportGetRequest(first.id)), first);
|
||||
await t3.rejects(
|
||||
plugin.handleReportGetRequest(new messages.ReportGetRequest(123)),
|
||||
{ message: "Report with ID 123 does not exist" },
|
||||
);
|
||||
});
|
||||
|
||||
t2.test(".handleReportDeleteRequest() removes the report and broadcasts the deletion", async t3 => {
|
||||
const { plugin, state } = await startPlugin(t3);
|
||||
const report = await plugin.handleReportCreateRequest(new messages.ReportCreateRequest("bob", "griefing", "alice"), fromInstance);
|
||||
|
||||
state.broadcasts.length = 0;
|
||||
await plugin.handleReportDeleteRequest(new messages.ReportDeleteRequest(report.id));
|
||||
t3.strictSame(plugin.listReports(), [], "the report is gone");
|
||||
t3.ok(
|
||||
state.broadcasts.some(event => event instanceof messages.ReportUpdatedEvent && event.updates[0].isDeleted),
|
||||
"subscribers are told it was deleted",
|
||||
);
|
||||
await t3.rejects(
|
||||
plugin.handleReportDeleteRequest(new messages.ReportDeleteRequest(report.id)),
|
||||
{ message: `Report with ID ${report.id} does not exist` },
|
||||
);
|
||||
});
|
||||
|
||||
t2.test(".handleReportSubscription() replays only newer records", async t3 => {
|
||||
const { plugin } = await startPlugin(t3);
|
||||
const report = await plugin.handleReportCreateRequest(new messages.ReportCreateRequest("bob", "griefing", "alice"), fromInstance);
|
||||
|
||||
const all = await plugin.handleReportSubscription({ lastRequestTimeMs: 0 });
|
||||
t3.strictSame(all.updates, [report], "everything is replayed from the start");
|
||||
const none = await plugin.handleReportSubscription({ lastRequestTimeMs: report.updatedAtMs });
|
||||
t3.strictSame(none, null, "nothing is replayed when up to date");
|
||||
});
|
||||
|
||||
t2.test(".sendWebhooks() posts new reports to the configured hooks", async t3 => {
|
||||
const { plugin, state } = await startPlugin(t3, { config: {
|
||||
"exp_reports.discord_webhook_url": "https://discord.example/hook",
|
||||
"exp_reports.json_webhook_url": "https://json.example/hook",
|
||||
} });
|
||||
const report = await plugin.handleReportCreateRequest(new messages.ReportCreateRequest("bob", "griefing", "alice"), fromInstance);
|
||||
|
||||
t3.strictSame(state.posts.map(post => post.url), ["https://discord.example/hook", "https://json.example/hook"]);
|
||||
const embed = state.posts[0].body.embeds[0];
|
||||
t3.strictSame(embed.fields.map(field => field.value), ["bob", "alice", "EXP", "griefing"], "the embed names the report");
|
||||
t3.strictSame(state.posts[1].body, { type: "report_created", report: report.toJSON() }, "the json hook gets the record");
|
||||
|
||||
state.posts.length = 0;
|
||||
await plugin.handleReportDeleteRequest(new messages.ReportDeleteRequest(report.id));
|
||||
t3.strictSame(state.posts, [], "deletions are not posted");
|
||||
});
|
||||
|
||||
t2.test(".sendWebhooks() does nothing without hooks", async t3 => {
|
||||
const { plugin, state } = await startPlugin(t3);
|
||||
await plugin.handleReportCreateRequest(new messages.ReportCreateRequest("bob", "griefing", "alice"), fromInstance);
|
||||
t3.strictSame(state.posts, []);
|
||||
});
|
||||
|
||||
t2.test(".postWebhook() logs rather than throws when the hook fails", async t3 => {
|
||||
const { plugin, state } = await startPlugin(t3);
|
||||
plugin.postWebhook = ControllerPlugin.prototype.postWebhook;
|
||||
|
||||
const realFetch = globalThis.fetch;
|
||||
globalThis.fetch = async () => { throw new Error("connection refused"); };
|
||||
t3.teardown(() => { globalThis.fetch = realFetch; });
|
||||
|
||||
await plugin.postWebhook("https://down.example/hook", {});
|
||||
t3.strictSame(state.warnings, ["Webhook https://down.example/hook failed: connection refused"]);
|
||||
|
||||
globalThis.fetch = async () => ({ ok: false, status: 404 });
|
||||
await plugin.postWebhook("https://down.example/hook", {});
|
||||
t3.strictSame(state.warnings[1], "Webhook https://down.example/hook responded with 404");
|
||||
});
|
||||
|
||||
t2.end();
|
||||
});
|
||||
@@ -0,0 +1,142 @@
|
||||
"use strict";
|
||||
const t = require("tap");
|
||||
const lib = require("@clusterio/lib");
|
||||
const { Instance } = require("@clusterio/host");
|
||||
const { InstancePlugin } = require("../dist/node/instance");
|
||||
const { plugin: pluginDeclaration } = require("../dist/node/index");
|
||||
const messages = require("../dist/node/messages");
|
||||
|
||||
// The instance validates message classes against the link registry
|
||||
for (const Message of pluginDeclaration.messages) {
|
||||
lib.Link.register(Message);
|
||||
}
|
||||
|
||||
class TestConnector extends lib.BaseConnector {
|
||||
constructor() {
|
||||
super(lib.Address.fromShorthand({ instanceId: 1 }), lib.Address.fromShorthand({ hostId: 1 }));
|
||||
this.valid = true;
|
||||
this.connected = true;
|
||||
this.hasSession = true;
|
||||
}
|
||||
|
||||
send() {}
|
||||
}
|
||||
|
||||
const report = (id, playerName, byPlayerName) => new messages.ReportRecord(id, playerName, byPlayerName, "griefing", "EXP", 1000);
|
||||
|
||||
/** Build a plugin around a real running instance with spies on what leaves it. */
|
||||
async function startPlugin(t2, { reports = [report(1, "bob", "alice"), report(2, "bob", "carol")] } = {}) {
|
||||
const instanceConfig = new lib.InstanceConfig("host");
|
||||
instanceConfig.set("instance.id", 1);
|
||||
instanceConfig.set("instance.name", "test");
|
||||
|
||||
const instance = new Instance(
|
||||
{ assignGamePort: () => 1 }, new TestConnector(), t2.testdir(), "factorioDir", instanceConfig
|
||||
);
|
||||
|
||||
// Spies which record the messages and commands leaving the instance
|
||||
const state = { sent: [], rcons: [], failNext: null };
|
||||
instance.server = {
|
||||
handle: () => {},
|
||||
sendRcon: async command => {
|
||||
state.rcons.push(command);
|
||||
return "";
|
||||
},
|
||||
};
|
||||
instance.sendTo = async (dst, request) => {
|
||||
state.sent.push(request);
|
||||
if (state.failNext) {
|
||||
const error = state.failNext;
|
||||
state.failNext = null;
|
||||
throw error;
|
||||
}
|
||||
if (request instanceof messages.ReportCreateRequest) {
|
||||
return report(3, request.playerName, request.byPlayerName);
|
||||
}
|
||||
if (request instanceof messages.ReportListRequest) {
|
||||
return reports.filter(other => request.playerName === undefined || other.playerName === request.playerName);
|
||||
}
|
||||
return undefined;
|
||||
};
|
||||
|
||||
instance.notifyStatus("running");
|
||||
state.sent.length = 0;
|
||||
|
||||
const plugin = new InstancePlugin({ name: "exp_reports" }, instance, {});
|
||||
await plugin.init();
|
||||
return { plugin, instance, state };
|
||||
}
|
||||
|
||||
/** The lua receiver and payload of a recorded rcon command. */
|
||||
function decodeRcon(command) {
|
||||
const match = command.match(/^\/sc exp_reports\.(\w+)\(helpers\.json_to_table\[=\[(.*)\]=\]\)$/s);
|
||||
return { receiver: match[1], payload: JSON.parse(match[2]) };
|
||||
}
|
||||
|
||||
t.test("class InstancePlugin", t2 => {
|
||||
t2.test(".handleCreateIPC() creates the report and hands it to lua with the others against the player", async t3 => {
|
||||
const { plugin, state } = await startPlugin(t3);
|
||||
await plugin.handleCreateIPC({ player_name: "bob", by_player_name: "dave", reason: "griefing" });
|
||||
|
||||
const create = state.sent.find(request => request instanceof messages.ReportCreateRequest);
|
||||
t3.strictSame([create.playerName, create.byPlayerName, create.reason], ["bob", "dave", "griefing"]);
|
||||
t3.ok(state.sent.some(request => request instanceof messages.ReportListRequest && request.playerName === "bob"),
|
||||
"the reports against the player are requested");
|
||||
|
||||
const { receiver, payload } = decodeRcon(state.rcons[0]);
|
||||
t3.strictSame(receiver, "receive_created");
|
||||
t3.strictSame(payload.report.by_player_name, "dave", "the new report is sent");
|
||||
t3.strictSame(payload.reports.map(other => other.by_player_name), ["alice", "carol"], "along with the existing ones");
|
||||
});
|
||||
|
||||
t2.test(".handleCreateIPC() prints a refusal to the reporter", async t3 => {
|
||||
const { plugin, state } = await startPlugin(t3);
|
||||
state.failNext = new lib.RequestError("dave has already reported bob");
|
||||
await plugin.handleCreateIPC({ player_name: "bob", by_player_name: "dave", reason: "griefing" });
|
||||
|
||||
const { receiver, payload } = decodeRcon(state.rcons[0]);
|
||||
t3.strictSame(receiver, "receive_error");
|
||||
t3.strictSame(payload, { caller: "dave", message: "dave has already reported bob" });
|
||||
});
|
||||
|
||||
t2.test(".handleListIPC() lists the reports for the caller", async t3 => {
|
||||
const { plugin, state } = await startPlugin(t3);
|
||||
await plugin.handleListIPC({ caller: "admin", player_name: "bob" });
|
||||
await plugin.handleListIPC({ caller: "admin", player_name: undefined });
|
||||
|
||||
const forPlayer = decodeRcon(state.rcons[0]);
|
||||
t3.strictSame(forPlayer.receiver, "receive_list");
|
||||
t3.strictSame([forPlayer.payload.caller, forPlayer.payload.player_name], ["admin", "bob"]);
|
||||
t3.strictSame(forPlayer.payload.reports.length, 2);
|
||||
|
||||
const forAll = decodeRcon(state.rcons[1]);
|
||||
t3.strictSame(forAll.payload.player_name, undefined, "no player when listing everyone");
|
||||
});
|
||||
|
||||
t2.test(".handleDeleteIPC() deletes only the matching reports", async t3 => {
|
||||
const { plugin, state } = await startPlugin(t3);
|
||||
await plugin.handleDeleteIPC({ caller: "admin", player_name: "bob", by_player_name: "carol" });
|
||||
|
||||
const deletes = state.sent.filter(request => request instanceof messages.ReportDeleteRequest);
|
||||
t3.strictSame(deletes.map(request => request.id), [2], "only carol's report is deleted");
|
||||
const { receiver, payload } = decodeRcon(state.rcons[0]);
|
||||
t3.strictSame(receiver, "receive_deleted");
|
||||
t3.strictSame(payload, { caller: "admin", player_name: "bob", by_player_name: "carol", count: 1 });
|
||||
|
||||
state.sent.length = 0;
|
||||
await plugin.handleDeleteIPC({ caller: "admin", player_name: "bob", by_player_name: undefined });
|
||||
t3.strictSame(
|
||||
state.sent.filter(request => request instanceof messages.ReportDeleteRequest).length, 2,
|
||||
"every report is deleted without a reporter",
|
||||
);
|
||||
});
|
||||
|
||||
t2.test(".luaSend() drops answers once the instance has stopped", async t3 => {
|
||||
const { plugin, instance, state } = await startPlugin(t3);
|
||||
instance.notifyStatus("stopped");
|
||||
await plugin.handleListIPC({ caller: "admin", player_name: undefined });
|
||||
t3.strictSame(state.rcons, [], "nothing is sent to a stopped instance");
|
||||
});
|
||||
|
||||
t2.end();
|
||||
});
|
||||
@@ -0,0 +1,62 @@
|
||||
"use strict";
|
||||
const t = require("tap");
|
||||
const messages = require("../dist/node/messages");
|
||||
const { testMatrix, testRoundTripJsonSerialisable } = require("../../test/common");
|
||||
|
||||
const sampleReport = new messages.ReportRecord(7, "bob", "alice", "griefing", "EXP", 12345);
|
||||
|
||||
t.test("class ReportRecord", t2 => {
|
||||
testRoundTripJsonSerialisable(t2, messages.ReportRecord, testMatrix(
|
||||
[7], // id
|
||||
["bob"], // playerName
|
||||
["alice"], // byPlayerName
|
||||
["griefing"], // reason
|
||||
["", "EXP"], // instanceName
|
||||
[0, 12345], // updatedAtMs
|
||||
[false, true], // isDeleted
|
||||
));
|
||||
|
||||
t2.end();
|
||||
});
|
||||
|
||||
t.test("class ReportUpdatedEvent", t2 => {
|
||||
testRoundTripJsonSerialisable(t2, messages.ReportUpdatedEvent, testMatrix(
|
||||
[[], [sampleReport]], // updates
|
||||
));
|
||||
|
||||
t2.end();
|
||||
});
|
||||
|
||||
t.test("class ReportListRequest", t2 => {
|
||||
testRoundTripJsonSerialisable(t2, messages.ReportListRequest, testMatrix(
|
||||
[undefined, "bob"], // playerName
|
||||
));
|
||||
|
||||
t2.end();
|
||||
});
|
||||
|
||||
t.test("class ReportGetRequest", t2 => {
|
||||
testRoundTripJsonSerialisable(t2, messages.ReportGetRequest, testMatrix(
|
||||
[7], // id
|
||||
));
|
||||
|
||||
t2.end();
|
||||
});
|
||||
|
||||
t.test("class ReportCreateRequest", t2 => {
|
||||
testRoundTripJsonSerialisable(t2, messages.ReportCreateRequest, testMatrix(
|
||||
["bob"], // playerName
|
||||
["griefing"], // reason
|
||||
["", "alice"], // byPlayerName
|
||||
));
|
||||
|
||||
t2.end();
|
||||
});
|
||||
|
||||
t.test("class ReportDeleteRequest", t2 => {
|
||||
testRoundTripJsonSerialisable(t2, messages.ReportDeleteRequest, testMatrix(
|
||||
[7], // id
|
||||
));
|
||||
|
||||
t2.end();
|
||||
});
|
||||
@@ -0,0 +1,14 @@
|
||||
"use strict";
|
||||
const path = require("node:path");
|
||||
const t = require("tap");
|
||||
const { reportLuaTests } = require("../../test/lua/runner");
|
||||
|
||||
const envFile = path.join(__dirname, "module", "env.lua");
|
||||
|
||||
// Each file runs in its own lua state, and each test in a fresh environment
|
||||
t.test("control.lua", t2 => {
|
||||
for (const file of ["requests.lua", "receivers.lua"]) {
|
||||
t2.test(file, t3 => reportLuaTests(t3, envFile, path.join(__dirname, "module", file)));
|
||||
}
|
||||
t2.end();
|
||||
});
|
||||
@@ -0,0 +1,59 @@
|
||||
--[[-- Test environment for module/control.lua
|
||||
Extends the shared stubs with a fresh copy of the reports module, a stub of
|
||||
the exp_util functions it uses, and helpers to build the payloads the
|
||||
instance plugin sends.
|
||||
|
||||
Run as a chunk by test/lua/runner.js, receiving the shared folder. The suite
|
||||
returned here becomes `...` in each test file.
|
||||
]]
|
||||
|
||||
local shared_root = ... --- @type string
|
||||
local source = assert(debug.getinfo(1, "S")).source:gsub("\\", "/")
|
||||
local plugin_root = assert(source:match("^@(.*)/test/module/env%.lua$"))
|
||||
|
||||
local Framework = assert(loadfile(shared_root .. "/framework.lua"))() --- @type Framework
|
||||
|
||||
--- A stubbed player which also carries the admin flag the module reads
|
||||
--- @class ExpReports.TestPlayer : Stubs.Player
|
||||
--- @field admin boolean
|
||||
|
||||
--- The environment given to each test: the stubs extended with a fresh copy
|
||||
--- of the reports module and the fixture helpers
|
||||
--- @class ExpReports.TestEnv : Stubs
|
||||
--- @field Reports ExpReports A fresh copy of the reports module
|
||||
--- @field add_player fun(name: string, is_connected: boolean?, is_admin: boolean?): ExpReports.TestPlayer
|
||||
--- @field report fun(player_name: string, by_player_name: string, reason: string?): ExpReports.Report A report as the controller sends it
|
||||
|
||||
return Framework.suite(function(env)
|
||||
--- @cast env ExpReports.TestEnv
|
||||
env.extend_requires{
|
||||
["modules/exp_util"] = {
|
||||
format_player_name_locale = function(name) return name end,
|
||||
color = { orange_red = "orange_red" },
|
||||
},
|
||||
}
|
||||
env.Reports = assert(loadfile(plugin_root .. "/module/control.lua"))() --- @type ExpReports
|
||||
|
||||
-- The module reads player.admin, which the strict stub raises on unless it is set
|
||||
local add_player = env.add_player
|
||||
function env.add_player(name, is_connected, is_admin)
|
||||
local player = add_player(name, is_connected) --[[@as ExpReports.TestPlayer]]
|
||||
player.admin = is_admin == true
|
||||
return player
|
||||
end
|
||||
|
||||
local next_id = 0
|
||||
function env.report(player_name, by_player_name, reason)
|
||||
next_id = next_id + 1
|
||||
return {
|
||||
id = next_id,
|
||||
player_name = player_name,
|
||||
by_player_name = by_player_name,
|
||||
reason = reason or "griefing",
|
||||
instance_name = "test",
|
||||
updated_at_ms = 1000,
|
||||
}
|
||||
end
|
||||
|
||||
return env
|
||||
end)
|
||||
@@ -0,0 +1,102 @@
|
||||
local Suite = ... --- @type Suite<ExpReports.TestEnv>
|
||||
|
||||
Suite.test("receive_created() tells everyone and raises on_player_reported", function(env)
|
||||
env.add_player("alice", true, true)
|
||||
local bob = env.add_player("bob")
|
||||
env.add_player("carol")
|
||||
local report = env.report("bob", "alice")
|
||||
env.Reports.receive_created{ report = report, reports = { report, env.report("bob", "carol") } }
|
||||
|
||||
Suite.eq(env.printed, {
|
||||
{ to = "alice", { "exp-reports.created-admin", "bob", "alice", "griefing" } },
|
||||
{ to = "bob", { "exp-reports.created", "bob", "griefing" } },
|
||||
{ to = "carol", { "exp-reports.created", "bob", "griefing" } },
|
||||
}, "admins see who reported, everyone else only the reason")
|
||||
Suite.eq(env.events, {
|
||||
{
|
||||
name = env.Reports.on_player_reported,
|
||||
tick = 1,
|
||||
player_index = bob.index,
|
||||
by_player_name = "alice",
|
||||
reason = "griefing",
|
||||
report_count = 2,
|
||||
by_player_names = { "alice", "carol" },
|
||||
},
|
||||
}, "the event carries every report against the player")
|
||||
end)
|
||||
|
||||
Suite.test("receive_created() raises nothing when the reported player has left", function(env)
|
||||
env.add_player("alice")
|
||||
env.add_player("bob", false)
|
||||
local report = env.report("bob", "alice")
|
||||
env.Reports.receive_created{ report = report, reports = { report } }
|
||||
Suite.eq(env.printed, { { to = "alice", { "exp-reports.created", "bob", "griefing" } } }, "the report is still announced")
|
||||
Suite.empty(env.events, "there is nobody to act on")
|
||||
end)
|
||||
|
||||
Suite.test("receive_list() prints the reports against a player to the caller", function(env)
|
||||
env.add_player("alice")
|
||||
env.Reports.receive_list{
|
||||
caller = "alice",
|
||||
player_name = "bob",
|
||||
reports = { env.report("bob", "carol", "spam"), env.report("bob", "dave", "griefing") },
|
||||
}
|
||||
Suite.eq(env.printed, {
|
||||
{ to = "alice", { "exp-reports.list-title", "bob", 2 } },
|
||||
{ to = "alice", { "exp-reports.list-entry", "carol", "spam" } },
|
||||
{ to = "alice", { "exp-reports.list-entry", "dave", "griefing" } },
|
||||
}, "the title is followed by one line per report")
|
||||
end)
|
||||
|
||||
Suite.test("receive_list() prints how many reports each player has", function(env)
|
||||
env.add_player("alice")
|
||||
env.Reports.receive_list{
|
||||
caller = "alice",
|
||||
reports = { env.report("dave", "alice"), env.report("bob", "carol"), env.report("dave", "carol") },
|
||||
}
|
||||
Suite.eq(env.printed, {
|
||||
{ to = "alice", { "exp-reports.list-all-title" } },
|
||||
{ to = "alice", { "exp-reports.list-all-entry", "bob", 1 } },
|
||||
{ to = "alice", { "exp-reports.list-all-entry", "dave", 2 } },
|
||||
}, "players are listed by name with their count")
|
||||
end)
|
||||
|
||||
Suite.test("receive_list() says when nobody is reported", function(env)
|
||||
env.add_player("alice")
|
||||
env.Reports.receive_list{ caller = "alice", reports = {} }
|
||||
Suite.eq(env.printed, { { to = "alice", { "exp-reports.list-all-none" } } }, "the caller is told there are none")
|
||||
end)
|
||||
|
||||
Suite.test("receive_list() prints nothing once the caller has left", function(env)
|
||||
env.add_player("alice", false)
|
||||
env.Reports.receive_list{ caller = "alice", reports = { env.report("bob", "carol") } }
|
||||
Suite.empty(env.printed, "nothing is printed")
|
||||
end)
|
||||
|
||||
Suite.test("receive_deleted() announces the deletion and raises on_reports_deleted", function(env)
|
||||
env.add_player("alice")
|
||||
local bob = env.add_player("bob")
|
||||
env.Reports.receive_deleted{ caller = "alice", player_name = "bob", count = 2 }
|
||||
Suite.eq(env.printed, { { "exp-reports.deleted", "bob", 2, "alice" } }, "everyone is told")
|
||||
Suite.eq(env.events, {
|
||||
{ name = env.Reports.on_reports_deleted, tick = 1, player_index = bob.index, by_player_name = "alice", count = 2 },
|
||||
}, "the event names who deleted how many")
|
||||
end)
|
||||
|
||||
Suite.test("receive_deleted() tells the caller when there was nothing to delete", function(env)
|
||||
env.add_player("alice")
|
||||
env.add_player("bob")
|
||||
env.Reports.receive_deleted{ caller = "alice", player_name = "bob", count = 0 }
|
||||
Suite.eq(env.printed, { { to = "alice", { "exp-reports.deleted-none", "bob" } } }, "only the caller is told")
|
||||
Suite.empty(env.events, "nothing was deleted")
|
||||
end)
|
||||
|
||||
Suite.test("receive_error() prints the refusal to the caller while they are online", function(env)
|
||||
env.add_player("alice")
|
||||
env.add_player("bob", false)
|
||||
env.Reports.receive_error{ caller = "alice", message = "alice has already reported bob" }
|
||||
env.Reports.receive_error{ caller = "bob", message = "gone" }
|
||||
Suite.eq(env.printed, { { to = "alice", "alice has already reported bob" } }, "the offline player is skipped")
|
||||
end)
|
||||
|
||||
return Suite.run()
|
||||
@@ -0,0 +1,34 @@
|
||||
local Suite = ... --- @type Suite<ExpReports.TestEnv>
|
||||
|
||||
Suite.test("create_report() sends the report to the controller", function(env)
|
||||
local alice = env.add_player("alice")
|
||||
local bob = env.add_player("bob")
|
||||
env.Reports.create_report(alice, bob, "griefing")
|
||||
Suite.eq(env.sent, {
|
||||
{ channel = "exp_reports:create", data = { player_name = "bob", by_player_name = "alice", reason = "griefing" } },
|
||||
}, "the report names both players")
|
||||
end)
|
||||
|
||||
Suite.test("list_reports() sends the caller and the player", function(env)
|
||||
local alice = env.add_player("alice")
|
||||
local bob = env.add_player("bob")
|
||||
env.Reports.list_reports(alice, bob)
|
||||
env.Reports.list_reports(alice)
|
||||
Suite.eq(env.sent, {
|
||||
{ channel = "exp_reports:list", data = { caller = "alice", player_name = "bob" } },
|
||||
{ channel = "exp_reports:list", data = { caller = "alice" } },
|
||||
}, "the player is left out when listing everyone")
|
||||
end)
|
||||
|
||||
Suite.test("delete_reports() sends the caller, the player and the reporter", function(env)
|
||||
local alice = env.add_player("alice")
|
||||
local bob = env.add_player("bob")
|
||||
env.Reports.delete_reports(alice, bob, "carol")
|
||||
env.Reports.delete_reports(alice, bob)
|
||||
Suite.eq(env.sent, {
|
||||
{ channel = "exp_reports:delete", data = { caller = "alice", player_name = "bob", by_player_name = "carol" } },
|
||||
{ channel = "exp_reports:delete", data = { caller = "alice", player_name = "bob" } },
|
||||
}, "the reporter is left out when deleting every report")
|
||||
end)
|
||||
|
||||
return Suite.run()
|
||||
@@ -0,0 +1,4 @@
|
||||
{
|
||||
"extends": "../tsconfig.browser.json",
|
||||
"include": [ "web/**/*.tsx", "web/**/*.ts", "messages.ts", "package.json" ],
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"files": [],
|
||||
"references": [
|
||||
{ "path": "./tsconfig.node.json" },
|
||||
{ "path": "./tsconfig.browser.json" }
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
{
|
||||
"extends": "../tsconfig.node.json",
|
||||
"include": ["./**/*.ts"],
|
||||
"exclude": ["test/*", "./dist/*"],
|
||||
}
|
||||
@@ -0,0 +1,145 @@
|
||||
import React, { useContext, useState } from "react";
|
||||
import { Button, Form, Input, Modal, Popconfirm, Table } from "antd";
|
||||
|
||||
import {
|
||||
ControlContext, PageHeader, PageLayout, notifyErrorHandler, useAccount,
|
||||
useColumnSearch, useTableQueryState,
|
||||
} from "@clusterio/web_ui";
|
||||
|
||||
import { ReportCreateRequest, ReportDeleteRequest, ReportRecord } from "../../messages";
|
||||
import type { WebPlugin } from "..";
|
||||
|
||||
const strcmp = new Intl.Collator(undefined, { numeric: true, sensitivity: "base" }).compare;
|
||||
|
||||
/** Modal which reports a player in the name of the web user. */
|
||||
function CreateReportButton() {
|
||||
const control = useContext(ControlContext);
|
||||
const [open, setOpen] = useState(false);
|
||||
const [form] = Form.useForm<{ playerName: string, reason: string }>();
|
||||
|
||||
async function createReport() {
|
||||
const values = await form.validateFields();
|
||||
await control.send(new ReportCreateRequest(values.playerName, values.reason));
|
||||
form.resetFields();
|
||||
setOpen(false);
|
||||
}
|
||||
|
||||
return <>
|
||||
<Button type="primary" onClick={() => setOpen(true)}>Create</Button>
|
||||
<Modal
|
||||
title="Report Player"
|
||||
okText="Report"
|
||||
open={open}
|
||||
onOk={() => { createReport().catch(notifyErrorHandler("Error creating report")); }}
|
||||
onCancel={() => setOpen(false)}
|
||||
destroyOnHidden
|
||||
>
|
||||
<Form form={form} layout="vertical">
|
||||
<Form.Item name="playerName" label="Player" rules={[{ required: true }]}>
|
||||
<Input />
|
||||
</Form.Item>
|
||||
<Form.Item name="reason" label="Reason" rules={[{ required: true }]}>
|
||||
<Input.TextArea rows={3} />
|
||||
</Form.Item>
|
||||
</Form>
|
||||
</Modal>
|
||||
</>;
|
||||
}
|
||||
|
||||
/** Table of every report with search on the player, reporter and reason, and a filter on the instance. */
|
||||
function ReportsTable() {
|
||||
const control = useContext(ControlContext);
|
||||
const account = useAccount();
|
||||
const plugin = control.plugins.get("exp_reports") as WebPlugin;
|
||||
const [reports, synced] = plugin.useReports();
|
||||
|
||||
const tableState = useTableQueryState<ReportRecord>({
|
||||
namespace: "report",
|
||||
defaultSortKey: "time",
|
||||
pagination: { defaultPageSize: 50 },
|
||||
});
|
||||
const playerSearch = useColumnSearch<ReportRecord>(tableState, "player", report => report.playerName, "Search players");
|
||||
const bySearch = useColumnSearch<ReportRecord>(tableState, "by", report => report.byPlayerName, "Search reporters");
|
||||
const reasonSearch = useColumnSearch<ReportRecord>(tableState, "reason", report => report.reason, "Search reasons");
|
||||
|
||||
const data = [...reports.values()];
|
||||
const instanceNames = [...new Set(data.map(report => report.instanceName))].sort(strcmp);
|
||||
const instanceFilters = instanceNames.map(name => ({ text: name || "Web UI", value: name }));
|
||||
const canDelete = account.hasPermission("exp_reports.report.delete");
|
||||
|
||||
return <Table
|
||||
size="small"
|
||||
columns={[
|
||||
{
|
||||
title: "Player",
|
||||
key: "player",
|
||||
render: (_, report) => report.playerName,
|
||||
sorter: (a, b) => strcmp(a.playerName, b.playerName),
|
||||
sortOrder: tableState.sortOrder("player"),
|
||||
filteredValue: tableState.filteredValue("player"),
|
||||
...playerSearch,
|
||||
},
|
||||
{
|
||||
title: "Reported by",
|
||||
key: "by",
|
||||
render: (_, report) => report.byPlayerName,
|
||||
sorter: (a, b) => strcmp(a.byPlayerName, b.byPlayerName),
|
||||
sortOrder: tableState.sortOrder("by"),
|
||||
filteredValue: tableState.filteredValue("by"),
|
||||
...bySearch,
|
||||
},
|
||||
{
|
||||
title: "Reason",
|
||||
key: "reason",
|
||||
render: (_, report) => report.reason,
|
||||
filteredValue: tableState.filteredValue("reason"),
|
||||
...reasonSearch,
|
||||
},
|
||||
{
|
||||
title: "Instance",
|
||||
key: "instance",
|
||||
render: (_, report) => report.instanceName || "Web UI",
|
||||
filters: instanceFilters,
|
||||
filteredValue: tableState.filteredValue("instance"),
|
||||
onFilter: (value, report) => report.instanceName === value,
|
||||
sorter: (a, b) => strcmp(a.instanceName, b.instanceName),
|
||||
sortOrder: tableState.sortOrder("instance"),
|
||||
},
|
||||
{
|
||||
title: "Time",
|
||||
key: "time",
|
||||
render: (_, report) => new Date(report.updatedAtMs).toLocaleString(),
|
||||
sorter: (a, b) => a.updatedAtMs - b.updatedAtMs,
|
||||
sortOrder: tableState.sortOrder("time"),
|
||||
defaultSortOrder: "descend",
|
||||
},
|
||||
...canDelete ? [{
|
||||
key: "actions",
|
||||
render: (_: unknown, report: ReportRecord) => <Popconfirm
|
||||
title="Delete this report?"
|
||||
onConfirm={() => {
|
||||
control.send(new ReportDeleteRequest(report.id)).catch(notifyErrorHandler("Error deleting report"));
|
||||
}}
|
||||
>
|
||||
<Button size="small" danger onClick={event => event.stopPropagation()}>Delete</Button>
|
||||
</Popconfirm>,
|
||||
}] : [],
|
||||
]}
|
||||
dataSource={data}
|
||||
loading={!synced}
|
||||
rowKey={report => report.id}
|
||||
pagination={tableState.pagination}
|
||||
onChange={tableState.onChange}
|
||||
/>;
|
||||
}
|
||||
|
||||
export default function ReportsPage() {
|
||||
const account = useAccount();
|
||||
return <PageLayout nav={[{ name: "Reports" }]}>
|
||||
<PageHeader
|
||||
title="Reports"
|
||||
extra={account.hasPermission("exp_reports.report.create") ? <CreateReportButton /> : undefined}
|
||||
/>
|
||||
<ReportsTable />
|
||||
</PageLayout>;
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
import React, { useCallback, useSyncExternalStore } from "react";
|
||||
import { BaseWebPlugin } from "@clusterio/web_ui";
|
||||
|
||||
import * as lib from "@clusterio/lib";
|
||||
import * as messages from "../messages";
|
||||
|
||||
import ReportsPage from "./components/ReportsPage";
|
||||
|
||||
export class WebPlugin extends BaseWebPlugin {
|
||||
reports = new lib.MapSubscriber(messages.ReportUpdatedEvent, this.control);
|
||||
|
||||
async init() {
|
||||
this.pages = [
|
||||
{
|
||||
path: "/reports",
|
||||
sidebarName: "Reports",
|
||||
permission: "exp_reports.report.list",
|
||||
content: <ReportsPage />,
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
useReports() {
|
||||
const subscribe = useCallback((cb: () => void) => this.reports.subscribe(cb), []);
|
||||
return useSyncExternalStore(subscribe, () => this.reports.getSnapshot());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
"use strict";
|
||||
const path = require("path");
|
||||
const webpack = require("webpack");
|
||||
const { merge } = require("webpack-merge");
|
||||
|
||||
const common = require("@clusterio/web_ui/webpack.common");
|
||||
|
||||
module.exports = (env = {}) => merge(common(env), {
|
||||
context: __dirname,
|
||||
entry: "./web/index.tsx",
|
||||
output: {
|
||||
path: path.resolve(__dirname, "dist", "web"),
|
||||
},
|
||||
plugins: [
|
||||
new webpack.container.ModuleFederationPlugin({
|
||||
name: "exp_reports",
|
||||
library: { type: "window", name: "plugin_exp_reports" },
|
||||
exposes: {
|
||||
"./": "./index.ts",
|
||||
"./package.json": "./package.json",
|
||||
"./web": "./web/index.tsx",
|
||||
},
|
||||
shared: {
|
||||
"@clusterio/lib": { import: false },
|
||||
"@clusterio/web_ui": { import: false },
|
||||
"antd": { import: false },
|
||||
"react": { import: false },
|
||||
"react-dom": { import: false },
|
||||
"react-router": { import: false },
|
||||
"react-router-dom": { import: false },
|
||||
},
|
||||
}),
|
||||
],
|
||||
});
|
||||
Reference in new issue
Block a user