This repository was archived by the owner on Jan 22, 2026. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 76
Expand file tree
/
Copy pathAdminCommands.ts
More file actions
432 lines (402 loc) · 15.3 KB
/
Copy pathAdminCommands.ts
File metadata and controls
432 lines (402 loc) · 15.3 KB
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
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
/*
Copyright 2019 The Matrix.org Foundation C.I.C.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import { Logger } from "matrix-appservice-bridge";
import * as yargs from "yargs";
import { AdminCommand, IHandlerArgs, ResponseCallback } from "./AdminCommand";
import { Main } from "./Main";
import { BridgedRoom } from "./BridgedRoom";
const log = new Logger("AdminCommands");
const RoomIdCommandOption = {
alias: "R",
demandOption: true,
description: "Matrix Room ID",
};
export class AdminCommands {
private yargs: yargs.Argv;
private commands: AdminCommand[];
private latestCommandWaiterForSender: Map<string, Promise<void>> = new Map();
constructor(private main: Main) {
this.commands = [
this.onUnmatched,
this.list,
this.show,
this.link,
this.unlink,
this.join,
this.leave,
this.stalerooms,
this.doOauth,
this.help,
];
this.yargs = yargs.parserConfiguration({})
.version(false)
.showHelpOnFail(false)
.help(false); // We provide our own help, and version is not required.
// NOTE: setting exitProcess() is unnecessary when parse() is provided a callback.
this.commands.forEach((cmd) => {
this.yargs.command<IHandlerArgs>(
cmd.command,
cmd.description,
() => cmd.options ?? {},
// NOTE: yargs documentation advises against command() returning a Promise
// when parse() will be called multiple times, so instead resolve any
// asynchronous operations of the callbacks elsewhere.
(argv) => void cmd.handler(argv),
);
});
}
public get onUnmatched(): AdminCommand {
return new AdminCommand("*", "", (args) => {
const cmd = args._[0];
log.debug(`Unrecognised command "${cmd}"`);
args.respond(`Unrecognised command "${cmd}"`);
});
}
public get list(): AdminCommand {
return new AdminCommand(
"list",
"list the linked rooms",
async ({respond, team, room}: {
respond: ResponseCallback,
team?: string,
room?: string,
}) => {
const quotemeta = (s: string) => s.replace(/\W/g, "\\$&");
let nameFilter: RegExp;
if (team) {
nameFilter = new RegExp(`^${quotemeta(team)}\\.#`);
}
let found = 0;
this.main.rooms.all.forEach((r) => {
const channelName = r.SlackChannelName || "UNKNOWN";
if (nameFilter && !nameFilter.test(channelName)) {
return;
}
if (room && !r.MatrixRoomId.includes(room)) {
return;
}
const slack = r.SlackChannelId ?
`${channelName} (${r.SlackChannelId})` :
channelName;
let status = r.getStatus();
if (!status.startsWith("ready")) {
status = status.toUpperCase();
}
found++;
respond(`${status} ${slack} -- ${r.MatrixRoomId}`);
});
if (!found) {
respond("No rooms found");
}
},
{
room: {
alias: "R",
description: "Filter only Matrix room IDs containing this string fragment",
},
team: {
alias: "T",
description: "Filter only rooms for this Slack team domain",
},
},
);
}
public get show(): AdminCommand {
return new AdminCommand(
"show",
"show a single connected room",
({respond, channel_id, room}: {
respond: ResponseCallback,
channel_id?: string,
room?: string
}) => {
let bridgedRoom: BridgedRoom|undefined;
if (room) {
bridgedRoom = this.main.rooms.getByMatrixRoomId(room);
} else if (channel_id) {
bridgedRoom = this.main.rooms.getBySlackChannelId(channel_id);
} else {
respond("Require exactly one of room or channel_id");
return;
}
if (!bridgedRoom) {
respond("No such room");
return;
}
respond("Bridged Room:");
respond(" Status: " + bridgedRoom.getStatus());
respond(" Slack Name: " + bridgedRoom.SlackChannelName || "PENDING");
respond(" Slack Team: " + bridgedRoom.SlackTeamId || "PENDING");
if (bridgedRoom.SlackWebhookUri) {
respond(" Webhook URI: " + bridgedRoom.SlackWebhookUri);
}
respond(" Inbound ID: " + bridgedRoom.InboundId);
respond(" Inbound URL: " + this.main.getInboundUrlForRoom(bridgedRoom));
respond(" Matrix room ID: " + bridgedRoom.MatrixRoomId);
respond(" Using RTM: " + (bridgedRoom.SlackTeamId ? this.main.teamIsUsingRtm(bridgedRoom.SlackTeamId) : false).toString());
},
{
channel_id: {
alias: "I",
description: "Slack channel ID",
},
room: { ...RoomIdCommandOption, demandOption: false },
},
);
}
public get link(): AdminCommand {
return new AdminCommand(
"link",
"connect a Matrix and a Slack room together",
async ({respond, room, channel_id, webhook_url, webhook_token, slack_bot_token, team_id}: {
respond: ResponseCallback,
room?: string,
channel_id?: string,
webhook_url?: string,
webhook_token?: string,
slack_bot_token?: string,
team_id?: string,
}) => {
try {
if (!room) {
respond("Room not provided");
return;
}
const r = await this.main.actionLink({
matrix_room_id: room,
slack_bot_token,
team_id,
slack_channel_id: channel_id,
slack_webhook_uri: webhook_url,
slack_webhook_token: webhook_token,
});
respond("Room is now " + r.getStatus());
if (r.SlackWebhookUri) {
respond("Inbound URL is " + this.main.getInboundUrlForRoom(r));
} else {
respond("Remember to invite the slack bot to the slack channel.");
}
} catch (ex) {
log.warn("Failed to link channel", ex);
if ((ex as Error).message === "Failed to get channel info") {
respond("Cannot link - Bot doesn't have visibility on channel. Is it invited on slack?");
} else {
respond("Cannot link - " + ex);
}
}
},
{
channel_id: {
alias: "I",
description: "Slack channel ID",
},
room: RoomIdCommandOption,
slack_bot_token: {
alias: "t",
description: "Slack bot user token. Used with Slack bot user & Events api",
},
team_id: {
alias: "T",
description: "Slack team ID. Used with Slack bot user & Events api",
},
webhook_url: {
alias: "u",
description: "Slack webhook URL. Used with Slack outgoing hooks integration",
},
webhook_token: {
alias: "k",
description: "Slack webhook token. Used with Slack outgoing hooks integration",
},
},
);
}
public get unlink(): AdminCommand {
return new AdminCommand(
"unlink",
"disconnect a linked Matrix and Slack room",
async ({respond, room}: {
respond: ResponseCallback,
room?: string,
}) => {
if (!room) {
respond("Room not provided");
return;
}
try {
await this.main.actionUnlink({
matrix_room_id: room,
});
respond("Unlinked");
} catch (ex) {
respond("Cannot unlink - " + ex);
}
},
{
room: RoomIdCommandOption,
},
);
}
public get join(): AdminCommand {
return new AdminCommand(
"join room",
"join a new room",
async ({respond, room}: {
respond: ResponseCallback,
room?: string,
}) => {
if (!room) {
respond("No room provided");
return;
}
await this.main.botIntent.join(room);
respond("Joined");
},
{
room: RoomIdCommandOption,
},
);
}
public get leave(): AdminCommand {
return new AdminCommand(
"leave room",
"leave an unlinked room",
async ({respond, room}: {
respond: ResponseCallback,
room?: string,
}) => {
if (!room) {
respond("Room not provided");
return;
}
const userIds = await this.main.listGhostUsers(room);
respond(`Draining ${userIds.length} ghosts from ${room}`);
await Promise.all(userIds.map(async (userId) => this.main.getIntent(userId).leave(room)));
await this.main.botIntent.leave(room);
respond("Drained");
},
{
room: RoomIdCommandOption,
},
);
}
public get stalerooms(): AdminCommand {
return new AdminCommand(
"stalerooms",
"list rooms the bot user is a member of that are unlinked",
async ({respond}: { respond: ResponseCallback }) => {
const roomIds = await this.main.listRoomsFor();
roomIds.forEach((id) => {
if (id === this.main.config.matrix_admin_room ||
this.main.rooms.getByMatrixRoomId(id)) {
return;
}
respond(id);
});
},
);
}
public get doOauth(): AdminCommand {
return new AdminCommand(
"oauth userId puppet",
"generate an oauth url to bind your account with",
async ({respond, userId, puppet}: {
respond: ResponseCallback,
userId?: string,
puppet?: boolean,
}) => {
if (!this.main.oauth2) {
respond("Oauth is not configured on this bridge");
return;
}
if (!userId) {
respond("userId not provided");
return;
}
const token = this.main.oauth2.getPreauthToken(userId);
const authUri = this.main.oauth2.makeAuthorizeURL(
token,
token,
puppet,
);
respond(authUri);
},
{
userId: {
type: "string",
description: "The userId to bind to the oauth token",
},
puppet: {
type: "boolean",
description: "Does the user need puppeting permissions",
},
},
);
}
public get help(): AdminCommand {
return new AdminCommand(
"help [command]",
"describes the commands available",
({respond, command}: {
respond: ResponseCallback,
command?: string,
}) => {
if (command) {
const cmd = this.commands.find((adminCommand) => (adminCommand.command.split(' ')[0] === command));
const help = cmd?.detailedHelp();
if (!help) {
respond("Command not found. No help can be provided.");
} else {
help.forEach((s) => respond(s));
}
return;
}
this.commands.forEach((cmd) => {
const help = cmd.simpleHelp();
if (help) {
respond(help);
}
});
},
{
command: {
description: "Get help about a particular command",
},
},
);
}
/**
* Queue a command to be parsed & executed.
* NOTE: Callers should await not on a call of this function, but on its return value.
* Doing so ensures that commands will be queued in the order in which they're issued.
*/
public async parse(argv: string, respond: ResponseCallback, sender: string): Promise<void> {
const currCommandWaiter = new Promise<void>((resolve, reject) => {
const prevCommandWaiter = this.latestCommandWaiterForSender.get(sender) ?? Promise.resolve();
void prevCommandWaiter.finally(() => {
const context: IHandlerArgs = {
respond,
resolve,
reject,
};
this.yargs.parseSync(argv, context, (error) => {
if (error) {
// NOTE: Throwing here makes yargs.argv get stuck on an error object, so reject instead
reject(error);
}
});
}).catch(reject); // NOTE: This catch is here in case something unexpected throws
});
this.latestCommandWaiterForSender.set(sender, currCommandWaiter);
return currCommandWaiter;
}
}