Files
factorio-clusterio/plugins/global_chat/instance.js
T
Hornwitser 7f8a700716 Refactor message registration and validation
Split up the action of registring an event or request data class to be
decoded by the Link class and the action of registring a handler for
those requests and events.  This moves the validation work from Link
instantiation time to startup initialisation which makes logic errors
fail on startup instead of failing instantiation of the link when a
connection attempt is made.

Additionally implement a partial validation logic for messages received
using the newly refactored message registration.  This unfortunately
ended up merged with the registration refactor.
2023-06-03 16:47:47 +02:00

64 lines
1.5 KiB
JavaScript

/**
* @module
*/
"use strict";
const libPlugin = require("@clusterio/lib/plugin");
const libLuaTools = require("@clusterio/lib/lua_tools");
const { ChatEvent } = require("./messages");
/**
* Removes gps and train tags from messags
*
* @param {string} content - string to strip tags from.
* @returns {string} stripped string.
*/
function removeTags(content) {
return content.replace(/(\[gps=-?\d+,-?\d+\]|\[train=\d+\])/g, "");
}
class InstancePlugin extends libPlugin.BaseInstancePlugin {
async init() {
this.messageQueue = [];
this.instance.handle(ChatEvent, this.handleChatEvent.bind(this));
}
onControllerConnectionEvent(event) {
if (event === "connect") {
for (let message of this.messageQueue) {
this.sendChat(message);
}
this.messageQueue = [];
}
}
async handleChatEvent(event) {
// TODO check if cross server chat is enabled
let content = `[${event.instanceName}] ${removeTags(event.content)}`;
await this.sendRcon(`/sc game.print('${libLuaTools.escapeString(content)}')`, true);
}
sendChat(message) {
this.instance.sendTo(new ChatEvent(this.instance.name, message), "allInstances");
}
async onOutput(output) {
if (output.type === "action" && output.action === "CHAT") {
if (this.host.connector.connected) {
this.sendChat(output.message);
} else {
this.messageQueue.push(output.message);
}
}
}
// TODO implement info command in lua?
}
module.exports = {
InstancePlugin,
// For testing only
_removeTags: removeTags,
};