-
Notifications
You must be signed in to change notification settings - Fork 19
/
module_manager.ts
324 lines (296 loc) · 9.3 KB
/
module_manager.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
import * as log from "std/log/mod.ts";
import { join, resolve, toFileUrl } from "std/path/mod.ts";
import { Api, TelegramClient } from "$grm";
import { bold, fmt } from "./deps.ts";
import { CommandHandler, End, Event } from "./handlers/mod.ts";
import { updateMessage } from "./helpers.ts";
import { getHelp, isModule, Module } from "./module.ts";
const externals = "externals";
export function managerModule(manager: ModuleManager): Module {
return {
name: "manager",
handlers: [
new CommandHandler("install", async ({ client, event, args }) => {
let spec = args[0] ?? "";
let path: string | undefined;
if (!spec) {
const reply = await event.message.getReplyMessage();
if (!reply) {
return;
}
const { media } = reply;
if (
!(media instanceof Api.MessageMediaDocument) ||
!(media.document instanceof Api.Document) ||
!(media.document.attributes[0] instanceof
Api.DocumentAttributeFilename) ||
!media.document.attributes[0].fileName.endsWith(".ts") ||
media.document.size.gt(5000)
) {
return;
}
const result = await client.downloadMedia(media, {});
if (!result) {
await updateMessage(event, "Could not download the module.");
return;
}
path = join(externals, `.${media.document.id}.ts`);
await Deno.writeTextFile(
path,
typeof result === "string" ? result : result.toString(),
);
spec = ModuleManager.pathToSpec(path);
}
let module;
try {
module = await ModuleManager.file(spec);
} catch (_err) {
await updateMessage(event, "Not a module.");
return;
}
if (manager.modules.has(module.name)) {
await updateMessage(event, "Module already installed.");
return;
}
manager.install(module, true);
if (path) {
await Deno.rename(path, join(externals, `${module.name}.ts`));
} else {
localStorage.setItem(`module_${module.name}`, spec);
}
await updateMessage(event, "Module installed.");
}),
new CommandHandler("uninstall", async ({ event, args }) => {
let uninstalled = 0;
for (const arg of args) {
const spec = join("externals", `${arg}.ts`);
try {
await Deno.remove(spec);
manager.uninstall(arg);
uninstalled++;
} catch (_err) {
//
}
const key = `module_${arg}`;
const item = localStorage.getItem(key);
if (item) {
localStorage.removeItem(key);
manager.uninstall(arg);
uninstalled++;
}
}
await updateMessage(
event,
`${uninstalled <= 0 ? "No" : uninstalled} module${
uninstalled == 1 ? "" : "s"
} uninstalled.`,
);
}),
new CommandHandler("disable", async ({ event, args }) => {
if (args.length == 0) {
return;
}
let disabled = 0;
for (const arg of args) {
const module = manager.modules.get(arg);
if (
module && module[1] && !manager.disabled.has(arg)
) {
manager.disabled.add(arg);
disabled++;
}
}
await updateMessage(
event,
`${disabled <= 0 ? "No" : disabled} module${
disabled == 1 ? "" : "s"
} disabled.`,
);
}),
new CommandHandler("enable", async ({ event, args }) => {
if (args.length == 0) {
return;
}
let enabled = 0;
for (const arg of args) {
if (manager.disabled.has(arg)) {
manager.disabled.delete(arg);
enabled++;
}
}
await updateMessage(
event,
`${enabled <= 0 ? "No" : enabled} module${
enabled == 1 ? "" : "s"
} enabled.`,
);
}),
new CommandHandler("modules", async ({ event }) => {
const all = Array.from(manager.modules.values());
const nonDisableables = all
.filter(([, disableable]) => !disableable)
.map(([module]) => module.name);
const installed = all
.filter(([, disableable]) => disableable)
.map(([module]) => module.name);
let message = "**Built-in**\n";
for (const module of nonDisableables) {
message += module + "\n";
}
message += "\n**Installed**\n";
if (installed.length == 0) {
message += "No modules installed.";
} else {
for (const module of installed) {
message += module + "\n";
}
}
await event.message.reply({ message, parseMode: "markdown" });
}),
new CommandHandler("help", async ({ event, args }) => {
const name = args[0];
if (!name) {
await updateMessage(event, "Pass a module name as an argument.");
return;
}
const module = manager.modules.get(name);
if (!module) {
await updateMessage(event, "This module is not installed.");
return;
}
const message = getHelp(module[0]);
if (!message) {
await updateMessage(event, "This module has no help.");
return;
}
await event.message.reply({
...(typeof message === "string" ? { message } : message.send),
parseMode: "markdown",
});
}),
],
help: fmt`${bold("Introduction")}
The module manager lets you list the installed modules, get help for them and install external modules.
${bold("Commands")}
- install
Installs an external module from the replied module file.
- uninstall
Uninstalls one or more external modules.
- disable
Disables one or more external modules.
- enable
Enables one or more external modules.
- modules
Lists the installed modules.
- help
Sends the help message of a module if existing.`,
};
}
export class ModuleManager {
modules = new Map<string, [Module, boolean]>();
constructor(
private client: TelegramClient,
public disabled = new Set<string>(),
) {}
handler = async (event: Event) => {
for (const [, [{ name, handlers }, disableable]] of this.modules) {
if (disableable && this.disabled.has(name)) {
return;
}
for (const [index, handler] of Object.entries(handlers)) {
if (await handler.check({ client: this.client, event })) {
try {
const result = await handler.handle({ client: this.client, event });
if (typeof result === "symbol" && result == End) {
break;
}
} catch (err) {
log.error(`handler #${index} of ${name} failed: ${err}`);
try {
let message = String(err);
message = message.length <= 1000 ? message : "An error occurred.";
await event.message.reply({ message });
} catch (_err) {
//
}
}
}
}
}
};
install(module: Module, disableable = false) {
if (this.modules.has(module.name)) {
throw new Error(`Module ${module.name} is already installed`);
}
this.modules.set(module.name, [module, disableable]);
}
installMultiple(modules: Module[], disableable: boolean) {
for (const module of modules) {
this.install(module, disableable);
}
}
uninstall(name: string) {
return this.modules.delete(name);
}
uninstallMultiple(names: string[]) {
return names.map(this.uninstall);
}
uninstallAll() {
const disableables = new Array<string>();
for (const [, [{ name }, disableable]] of this.modules) {
if (disableable) {
disableables.push(name);
}
}
this.uninstallMultiple(disableables);
}
static async file(spec: string) {
const mod = (await import(spec)).default;
if (!isModule(mod)) {
throw new Error("Invalid module");
}
return mod;
}
static async files(specs: string[]) {
const modules = new Array<Module>();
let all = 0;
for (const spec of specs) {
try {
const module = await ModuleManager.file(spec);
modules.push(module);
} catch (err) {
log.warning(`failed to load ${spec}: ${err}`);
} finally {
all++;
}
}
log.info(`loaded ${modules.length}/${all} external modules`);
return modules;
}
static pathToSpec(path: string) {
return toFileUrl(resolve(path)).href;
}
static async directory(path: string) {
const modules = new Array<Module>();
let all = 0;
for await (let { name, isFile, isDirectory } of Deno.readDir(path)) {
if ((!isFile && !isDirectory) || name.startsWith(".")) {
continue;
}
name = name.endsWith(".ts") ? name : `${name}/mod.ts`;
const filePath = join(path, name);
try {
const mod = await ModuleManager.file(
ModuleManager.pathToSpec(filePath),
);
modules.push(mod);
} catch (err) {
log.warning(`failed to load ${filePath} from ${path}: ${err}`);
} finally {
all++;
}
}
log.info(`loaded ${modules.length}/${all} external modules from ${path}`);
return modules;
}
}