plugins-core/simplecommands/plugin.ts

533 lines
13 KiB
TypeScript
Raw Normal View History

2020-11-29 18:54:25 +00:00
import {
Plugin,
EventListener,
Configurable,
DependencyLoad,
DependencyUnload
} from '@squeebot/core/lib/plugin';
2020-12-13 10:17:04 +00:00
import { EMessageType, IMessage, MessageResolver } from '@squeebot/core/lib/types';
2020-11-29 18:54:25 +00:00
import { fullIDMatcher } from '@squeebot/core/lib/common';
import { logger } from '@squeebot/core/lib/core';
import { IChannel } from '@squeebot/core/lib/channel';
2020-11-29 18:54:25 +00:00
declare type Matcher = (msg: IMessage) => any;
2020-11-29 18:54:25 +00:00
interface CommandSpec {
name: string;
plugin: string;
description?: string;
usage?: string;
source?: string | string[] | Matcher;
tags?: string[];
aliases?: string[];
alias?: string;
match?: string | Matcher;
hidden?: boolean;
permissions?: string[];
tempargv?: any[];
2020-12-13 10:17:04 +00:00
execute(
msg: IMessage,
msr: MessageResolver,
command: CommandSpec,
prefix: string,
...args: any[]): Promise<boolean>;
2020-11-29 18:54:25 +00:00
}
2020-12-05 10:26:38 +00:00
interface RateLimit {
rooms: string[];
perSecond: number;
cooldown: number;
}
interface Rate {
lastMessage: number;
messages: number;
}
const rates: {[key: string]: Rate} = {};
2020-11-29 18:54:25 +00:00
@Configurable({
prefix: {
'*': '!'
},
2020-12-05 10:26:38 +00:00
rateLimits: [],
channelMatching: false,
2020-11-29 18:54:25 +00:00
})
class SqueebotCommandsAPIPlugin extends Plugin {
private commands: CommandSpec[] = [];
private permissions: any = null;
2020-12-05 10:26:38 +00:00
public getRateLimit(room: string): RateLimit | null {
for (const rm of this.config.get('rateLimits', [])) {
if (rm.rooms && (rm.rooms.indexOf(room) !== -1 || rm.rooms.indexOf('*') !== -1)) {
return rm;
}
}
return null;
}
public doLimiting(room: string, sender: string): boolean {
const rl = this.getRateLimit(room);
if (!rl) {
return false;
}
// Hasn't been limited yet
if (!rates[sender]) {
rates[sender] = {
lastMessage: Date.now(),
messages: 1,
};
return false;
}
const r = rates[sender];
if (r.lastMessage > Date.now() - rl.cooldown) {
if (r.messages >= rl.perSecond) {
// Rate limited
return true;
}
r.lastMessage = Date.now();
r.messages++;
return false;
}
r.lastMessage = Date.now();
r.messages = 1;
return false;
}
2020-11-29 18:54:25 +00:00
private roomMatcher(msg: IMessage, specList: CommandSpec[]): CommandSpec[] {
const roomMatches = [];
for (const spec of specList) {
if (spec.source) {
// This message can't room match
if (!msg.fullRoomID) {
continue;
}
if (typeof spec.source === 'function') {
try {
if (spec.source(msg)) {
roomMatches.push(spec);
}
} catch (e) {}
} else if (typeof spec.source === 'string') {
if (fullIDMatcher(msg.fullRoomID, spec.source)) {
roomMatches.push(spec);
}
} else if (Array.isArray(spec.source)) {
for (const room of spec.source) {
if (fullIDMatcher(msg.fullRoomID, room)) {
roomMatches.push(spec);
break;
}
}
}
continue;
}
// No source requirement
roomMatches.push(spec);
}
return roomMatches;
}
public permissionMatcher(msg: IMessage, specList: CommandSpec[]): CommandSpec[] {
const permitted = [];
for (const spec of specList) {
if (!spec.permissions) {
permitted.push(spec);
continue;
}
if (!this.permissions) {
continue;
}
if (!this.permissions.userPermitted(msg, spec.permissions)) {
continue;
}
permitted.push(spec);
}
return permitted;
}
2020-12-13 10:17:04 +00:00
public async handlePrefix(
msg: IMessage,
prefix: string,
plugins: string[],
msr: MessageResolver): Promise<void> {
const text = msg.text;
2020-11-29 18:54:25 +00:00
const separate = text.split(' ');
if (separate[0].indexOf(prefix) === 0) {
separate[0] = separate[0].substring(prefix.length);
}
// Iteration 1: Resolve commands by name and by aliases
const withAliases = [];
for (const spec of this.commands) {
if (plugins.length && plugins.indexOf(spec.plugin) === -1) {
continue;
}
2020-11-29 18:54:25 +00:00
if (spec.aliases && spec.aliases.indexOf(separate[0]) !== -1) {
const copy = Object.assign({}, spec);
copy.alias = spec.name;
withAliases.push(copy);
continue;
}
if (spec.name !== separate[0]) {
continue;
}
withAliases.push(spec);
}
// Iteration 2: Match rooms, if needed
const roomMatches = this.roomMatcher(msg, withAliases);
// Nothing matches room requirements
if (!roomMatches.length) {
return;
}
// Iteration 3: Sort the array so that the ones that had room matching come up first
const sorted = [];
for (const spec of roomMatches) {
if (spec.source) {
sorted.push(spec);
continue;
}
sorted.push(spec);
}
// Iteration 4: Match permissions for user
const permitted = this.permissionMatcher(msg, sorted);
2020-12-05 10:26:38 +00:00
// Rate limit check
if (permitted.length &&
this.config.get('rateLimits', []).length &&
this.doLimiting(msg.fullRoomID!, msg.fullSenderID!)) {
logger.warn('[%s] User %s rate limited', this.name, msg.fullSenderID);
return;
}
2020-11-29 18:54:25 +00:00
// Start executing
for (const spec of permitted) {
2020-12-06 13:40:54 +00:00
const argv: any[] = separate.slice(1);
if (spec.plugin === this.name) {
argv.unshift(plugins);
}
2020-12-13 10:17:04 +00:00
const success = await spec.execute(msg, msr, spec, prefix, ...argv);
2020-11-29 18:54:25 +00:00
if (success) {
break;
}
}
// Done
}
2020-11-29 19:07:06 +00:00
@EventListener('message')
2020-12-13 10:17:04 +00:00
public digest(msg: IMessage, chan: IChannel, msr: MessageResolver): void {
2020-11-29 18:54:25 +00:00
if (msg.type !== EMessageType.message) {
return;
}
let allowedPlugins: string[] = [];
if (chan && this.config.get('channelMatching', false) === true) {
allowedPlugins = chan.plugins;
}
2020-12-05 16:16:15 +00:00
const text = msg.text;
2020-11-29 18:54:25 +00:00
const prefixes = this.config.config.prefix;
if (!prefixes) {
return;
}
// Attempt to match prefixes, prefers room-specific ones
let prefix = '!';
if (typeof prefixes === 'string') {
prefix = prefixes;
} else if (typeof prefixes === 'object') {
if (msg.fullRoomID) {
for (const idtag in prefixes) {
if (idtag === '*') {
prefix = prefixes[idtag];
continue;
}
if (fullIDMatcher(msg.fullRoomID, idtag)) {
prefix = prefixes[idtag];
break;
}
}
}
}
if (!prefix || text.indexOf(prefix) !== 0) {
return;
}
2020-12-13 10:17:04 +00:00
this.handlePrefix(msg, prefix, allowedPlugins, msr).catch(e =>
2020-11-29 18:54:25 +00:00
logger.error('[%s] Command handler threw an error:', this.name, e.stack));
}
2020-12-05 10:00:55 +00:00
public registerCommand(spec: CommandSpec | CommandSpec[], bulk = false): boolean {
2020-11-29 18:54:25 +00:00
if (Array.isArray(spec)) {
if (!spec.length) {
return false;
}
logger.log('[%s] Plugin %s registered commands %s', this.name,
spec[0].plugin || 'unknown', spec.map(x => x.name).join(', '));
let success = true;
for (const sp of spec) {
2020-12-05 10:00:55 +00:00
if (!this.registerCommand(sp, true)) {
2020-11-29 18:54:25 +00:00
success = false;
}
}
return success;
2020-12-05 10:00:55 +00:00
} else if (!bulk) {
2020-11-29 18:54:25 +00:00
logger.log('[%s] Plugin %s registered command %s', this.name,
spec.plugin, spec.name);
}
if (!spec.name || !spec.execute || !spec.plugin) {
throw new Error('Invalid command specification!');
}
for (const cmd of this.commands) {
if (cmd.name === spec.name && cmd.plugin === spec.plugin) {
return false;
}
}
this.commands.push(spec);
return true;
}
public unregisterPlugin(plugin: string): void {
const remaining: CommandSpec[] = [];
const removed: CommandSpec[] = [];
for (const cmd of this.commands) {
if (cmd.plugin !== plugin) {
remaining.push(cmd);
continue;
}
removed.push(cmd);
}
if (removed.length) {
logger.log('[%s] Plugin %s unregistered command(s):', this.name,
plugin, removed.map(x => x.name).join(', '));
this.commands = remaining;
}
}
2020-12-06 13:40:54 +00:00
private withAliases(msg: IMessage, plugins: string[]): CommandSpec[] {
2020-11-29 18:54:25 +00:00
const withAliases = [];
for (const spec of this.commands) {
if (plugins.length && plugins.indexOf(spec.plugin) === -1) {
continue;
}
2020-11-29 18:54:25 +00:00
if (spec.aliases && spec.aliases.length) {
for (const alias of spec.aliases) {
const copy = Object.assign({}, spec);
copy.name = alias;
copy.alias = spec.name;
withAliases.push(copy);
}
}
withAliases.push(spec);
}
2020-12-06 13:40:54 +00:00
return withAliases;
}
private aliasesCommand(msg: IMessage, prefix: string, args: any[]): void {
// First argument could be a passed plugin array within this plugin
let plugins: string[] = [];
let cmdarg = 0;
if (args && args.length && Array.isArray(args[0])) {
plugins = args[0];
cmdarg += 1;
}
// Iteration 1: Resolve commands (with aliases)
const withAliases = this.withAliases(msg, plugins);
2020-11-29 18:54:25 +00:00
2020-11-29 19:07:06 +00:00
// Iteration 2: Match rooms for message
let matching = this.roomMatcher(msg, withAliases);
2020-11-29 18:54:25 +00:00
2020-11-29 19:07:06 +00:00
// Iteration 3: Match permissions for user
matching = this.permissionMatcher(msg, matching);
2020-11-29 18:54:25 +00:00
2021-10-07 15:46:24 +00:00
const b = (t: string) => msg.source.format.format('bold', t);
2020-11-29 18:54:25 +00:00
2020-12-06 13:40:54 +00:00
if (!args[cmdarg]) {
msg.resolve('A command name is required.');
return;
}
let found: CommandSpec | null = null;
for (const spec of matching) {
if (spec.name === args[cmdarg]) {
found = spec;
break;
}
}
if (!found) {
msg.resolve('aliases: No such command "%s"!', args[cmdarg]);
return;
}
if (!found.aliases || found.aliases.length === 0) {
msg.resolve('%s - No aliases found.', b(prefix + found.name));
return;
}
let list = found.aliases;
let aliasText = '';
if (found.alias) {
aliasText = b(`[alias of ${found.alias}]`);
list = list.filter((x) => x !== found?.name);
}
msg.resolve(b('Aliases of %s:'), prefix + found.name, list.join(', '), aliasText);
}
private helpCommand(msg: IMessage, prefix: string, args: any[]): void {
// First argument could be a passed plugin array within this plugin
let plugins: string[] = [];
let cmdarg = 0;
if (args && args.length && Array.isArray(args[0])) {
plugins = args[0];
cmdarg += 1;
}
// Iteration 1: Resolve commands (with aliases)
const withAliases = this.withAliases(msg, plugins);
// Iteration 2: Match rooms for message
let matching = this.roomMatcher(msg, withAliases);
// Iteration 3: Match permissions for user
matching = this.permissionMatcher(msg, matching);
2021-10-07 15:46:24 +00:00
const b = (t: string) => msg.source.format.format('bold', t);
2020-12-06 13:40:54 +00:00
if (args[cmdarg]) {
2020-11-29 18:54:25 +00:00
let found: CommandSpec | null = null;
for (const spec of matching) {
2020-12-06 13:40:54 +00:00
if (spec.name === args[cmdarg]) {
2020-11-29 18:54:25 +00:00
found = spec;
break;
}
}
if (!found) {
2020-12-06 13:40:54 +00:00
msg.resolve('help: No such command "%s"!', args[cmdarg]);
2020-11-29 18:54:25 +00:00
return;
}
let aliasText = '';
if (found.alias) {
aliasText = b(`[alias of ${found.alias}]`);
}
if (found.usage) {
msg.resolve('%s %s -', b(prefix + found.name), found.usage,
found.description || 'No description :(', aliasText);
return;
}
msg.resolve('%s -', b(prefix + found.name), found.description || 'No description :(', aliasText);
return;
}
msg.resolve('All commands start with a "%s" prefix!\n%s', prefix,
b(`List of commands in ${msg.target?.name}:`),
matching
.filter(x => x.alias == null && x.hidden !== true)
.map(x => x.name).join(', ')
);
}
initialize(): void {
this.registerCommand({
plugin: this.name,
name: 'help',
aliases: ['commands'],
usage: '[<command>]',
2020-12-06 13:40:54 +00:00
description: 'Show command usage or list all available commands',
2020-12-13 10:17:04 +00:00
execute: async (
msg: IMessage,
msr: MessageResolver,
spec: CommandSpec,
prefix: string,
...args: any[]): Promise<boolean> => {
2020-12-06 13:40:54 +00:00
this.helpCommand(msg, prefix, args);
return true;
}
});
this.registerCommand({
plugin: this.name,
name: 'aliases',
aliases: ['alias'],
usage: '<command>',
description: 'Show the list of aliases for command',
2020-12-13 10:17:04 +00:00
execute: async (
msg: IMessage,
msr: MessageResolver,
spec: CommandSpec,
prefix: string,
...args: any[]): Promise<boolean> => {
2020-12-06 13:40:54 +00:00
this.aliasesCommand(msg, prefix, args);
2020-11-29 18:54:25 +00:00
return true;
}
});
}
@DependencyLoad('permissions')
permissionsAdded(plugin: Plugin): void {
this.permissions = plugin;
}
@DependencyUnload('permissions')
permissionsRemoved(): void {
this.permissions = null;
}
@EventListener('pluginUnload')
unloadEventHandler(plugin: string | Plugin): void {
if (plugin === this.name || plugin === this) {
logger.debug('[%s] shutting down..', this.name);
2021-10-02 09:35:06 +00:00
this.emit('pluginUnloaded', this);
2020-11-29 18:54:25 +00:00
}
}
2020-12-05 10:00:55 +00:00
@EventListener('pluginUnloaded')
unloadedPlugin(plugin: string | Plugin): void {
this.unregisterPlugin((typeof plugin === 'string' ? plugin : plugin.manifest.name));
}
2020-11-29 18:54:25 +00:00
}
module.exports = SqueebotCommandsAPIPlugin;