-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.ts
401 lines (361 loc) · 13.5 KB
/
index.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
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
import { MatrixClient, SimpleFsStorageProvider, AutojoinRoomsMixin, RustSdkCryptoStorageProvider } from 'matrix-bot-sdk';
import fetch from 'node-fetch';
import Logger from './logger';
import config from './config';
import { ObjectFlags } from 'typescript';
const logger = new Logger();
const storage = new SimpleFsStorageProvider('bot.json');
// const cryptoStore = new RustSdkCryptoStorageProvider('encrypted');
// const client = new MatrixClient(homeserverUrl, accessToken, storage, cryptoStore);
const client = new MatrixClient(config.homeserverUrl, config.accessToken, storage);
AutojoinRoomsMixin.setupOnClient(client);
(async function () {
// client.on('room.event', (roomId, event) => {
// console.log('Event in room ' + roomId, event);
// });
client.on('room.message', (roomId: string, event: any) => {
if (!event['content']) {
return;
}
if (roomId !== config.commandRoomId) {
return;
}
const sender = event['sender'];
const body = event['content']['body'] as string;
logger.log(`[CHAT] ${sender}: ${body}`);
if (sender === config.userId) {
return;
}
if (body.startsWith('!help')) {
help(roomId);
} else if (body.startsWith('!lock')) {
lock(roomId);
} else if (body.startsWith('!lock')) {
lock(roomId);
} else if (body.startsWith('!unlock')) {
unlock(roomId);
} else if (body.startsWith('!invite')) {
invite(roomId, body.substring('!invite'.length).trim());
} else if (body.startsWith('!activate')) {
deactivate(roomId, body.substring('!activate'.length).trim(), false);
} else if (body.startsWith('!deactivate')) {
deactivate(roomId, body.substring('!deactivate'.length).trim(), true);
} else if (body.startsWith('!email')) {
email(roomId, body.substring('!email'.length).trim());
} else if (body.startsWith('!seen')) {
seen(roomId, body.substring('!seen'.length).trim());
} else if (body.startsWith('!serveradmin')) {
serveradmin(roomId, body.substring('!serveradmin'.length).trim());
} else if (body.startsWith('!roomadmin')) {
roomadmin(roomId, body.substring('!roomadmin'.length).trim());
} else if (body.startsWith('!')) {
commandNotFound(roomId);
}
});
// client.on('room.join', (roomId, joinEvent) => {
// console.log('join');
// console.log('roomid: ', roomId);
// console.log('event: ', joinEvent);
// console.log(`Joined ${roomId} as ${joinEvent['state_key']}`);
// });
// client.on('room.leave', (roomId, leaveEvent) => {
// console.log('leave');
// console.log('roomid: ', roomId);
// console.log('event: ', leaveEvent);
// console.log(`Left ${roomId} as ${leaveEvent['state_key']}`);
// });
await client.start().then(() => logger.log('Client started!'));
})();
function commandNotFound(roomId: string) {
client.sendMessage(roomId, {
'msgtype': 'm.notice',
'body': 'Command not found. User !help for help',
});
}
function help(roomId: string) {
client.sendMessage(roomId, {
'msgtype': 'm.notice',
'body': [
'!help - Help',
'!echo <text> - Echos the text',
'!lock - Locks the channels',
'!unlock - Unlocks the channels',
'!invite <username> - Invotes the user to the channels',
'!activate <username> - Activates a deactivated user',
'!deactivate <username> - Deactivates a user',
'!email <username> - Shows the emails of a user',
'!seen <username> - Shows the seen of a user',
'!serveradmin <username> - Toggles server admin of a user',
'!roomadmin <username> - Sets the room admin role for a user',
].join('\n'),
});
}
function echo(roomId: string, command: string) {
const replyText = command.substring('!echo'.length).trim();
client.sendMessage(roomId, {
'msgtype': 'm.notice',
'body': replyText,
});
}
async function lock(commandRoomId: string) {
logger.log('Locking rooms')
let locked: string[] = [];
let failed: string[] = [];
for (let roomId in config.lockRoomInclude) {
logger.log('Locking room:', roomId, config.lockRoomInclude[roomId]);
try {
let resp = await client.getRoomStateEvent(roomId, 'm.room.power_levels', '');
resp.events['m.reaction'] = config.lockLevel;
resp.events_default = config.lockLevel;
await client.sendStateEvent(roomId, 'm.room.power_levels', '', resp);
locked.push(config.lockRoomInclude[roomId]);
} catch (error) {
logger.error(error);
failed.push(config.lockRoomInclude[roomId]);
}
}
client.sendMessage(commandRoomId, {
'msgtype': 'm.notice',
'body': 'Rooms locked: ' + locked.join(', ') + (failed.length ? '\nFailed to lock: ' + failed.join(', ') : ''),
});
}
async function unlock(commandRoomId: string) {
logger.log('Unlocking rooms')
let unlocked: string[] = [];
let failed: string[] = [];
for (let roomId in config.lockRoomInclude) {
logger.log('Unlocking room:', roomId, config.lockRoomInclude[roomId]);
try {
let resp = await client.getRoomStateEvent(roomId, 'm.room.power_levels', '')
resp.events['m.reaction'] = 0;
resp.events_default = 0;
await client.sendStateEvent(roomId, 'm.room.power_levels', '', resp);
unlocked.push(config.lockRoomInclude[roomId]);
} catch (error) {
logger.error(error);
failed.push(config.lockRoomInclude[roomId]);
}
}
client.sendMessage(commandRoomId, {
'msgtype': 'm.notice',
'body': 'Rooms unlocked: ' + unlocked.join(', ') + (failed.length ? '\nFailed to unlock: ' + failed.join(', ') : ''),
});
}
async function invite(commandRoomId: string, username: string) {
let userid = '@' + username + ':' + config.servername;
logger.log('Inviting', userid, 'into rooms');
//check user exists
try {
let j = await getUser(userid);
} catch (error) {
client.sendMessage(commandRoomId, {
'msgtype': 'm.notice',
'body': 'User ' + userid + ' not found',
});
return;
}
//invite
let invited: string[] = [];
let failed: string[] = [];
for (let roomId in config.inviteRoomInclude) {
logger.log('Inviting', userid, 'room: ', roomId, config.inviteRoomInclude[roomId])
try {
await client.inviteUser(userid, roomId);
invited.push(config.lockRoomInclude[roomId]);
} catch (error) {
logger.error(error);
failed.push(config.lockRoomInclude[roomId]);
}
}
client.sendMessage(commandRoomId, {
'msgtype': 'm.notice',
'body': 'Invited ' + userid + ' into rooms: ' + invited.join(', ') + (failed.length ? '\nFailed to invite into: ' + failed.join(', ') : ''),
});
}
async function deactivate(commandRoomId: string, username: string, deactivate: boolean) {
logger.log((deactivate ? 'Dea' : 'A') + 'ctivating user', username);
try {
let userid = '@' + username + ':' + config.servername;
//check if account exists
{
let resp = await fetch(config.homeserverUrl + '/_synapse/admin/v2/users/' + userid, {
headers: { 'Authorization': 'Bearer ' + config.accessToken }
});
if (resp.status !== 200) {
client.sendMessage(commandRoomId, {
'msgtype': 'm.notice',
'body': 'User ' + username + ' does not exist',
});
return;
}
let j: any = await resp.json();
if (j.deactivated === deactivate) {
client.sendMessage(commandRoomId, {
'msgtype': 'm.notice',
'body': 'User ' + username + ' already ' + (deactivate ? 'de' : '') + 'activated',
});
return;
}
}
//(de)activate
{
let resp = await fetch(config.homeserverUrl + '/_synapse/admin/v2/users/' + userid, {
method: 'PUT',
headers: { 'Authorization': 'Bearer ' + config.accessToken, 'Content-Type': 'application/json' },
body: JSON.stringify({ deactivated: deactivate }),
});
if (resp.status === 200) {
client.sendMessage(commandRoomId, {
'msgtype': 'm.notice',
'body': 'User ' + username + ' ' + (deactivate ? 'de' : '') + 'activated',
});
} else {
logger.error(await resp.text());
client.sendMessage(commandRoomId, {
'msgtype': 'm.notice',
'body': 'Failed to ' + (deactivate ? 'de' : '') + 'activate user ' + username,
});
}
}
} catch (error) {
logger.error(error);
client.sendMessage(commandRoomId, {
'msgtype': 'm.notice',
'body': 'Error while ' + (deactivate ? 'de' : '') + 'activating user ' + username,
});
}
}
async function email(commandRoomId: string, username: string) {
logger.log('Fetching emails of', username);
try {
let userid = '@' + username + ':' + config.servername;
let j = await getUser(userid);
let emails = (j.threepids as any[]).filter(e => e.medium === 'email').map(e => e.address);
client.sendMessage(commandRoomId, {
'msgtype': 'm.notice',
'body': 'Emails of ' + username + ': ' + emails.join(', '),
});
} catch (error) {
logger.error(error);
client.sendMessage(commandRoomId, {
'msgtype': 'm.notice',
'body': 'Error while fetching emails of ' + username,
});
}
}
async function seen(commandRoomId: string, username: string) {
logger.log('Fetching seen of', username);
try {
let userid = '@' + username + ':' + config.servername;
let j = await getUser(userid);
let created = new Date(j.creation_ts * 1000);
//last seen
let lastseen = 0;
{
//https://matrix-org.github.io/synapse/latest/admin_api/rooms.html#make-room-admin-api
let resp = await fetch(config.homeserverUrl + '/_synapse/admin/v2/users/' + userid + '/devices', {
headers: { 'Authorization': 'Bearer ' + config.accessToken }
});
let j: any = await resp.json();
lastseen = (j.devices as any[]).map(e => e.last_seen_ts).reduce((l, r) => Math.max(l, r), lastseen);
//https://matrix-org.github.io/synapse/latest/admin_api/user_admin_api.html#query-current-sessions-for-a-user
resp = await fetch(config.homeserverUrl + '/_matrix/client/r0/admin/whois/' + userid, {
headers: { 'Authorization': 'Bearer ' + config.accessToken }
});
j = await resp.json();
lastseen = (j.devices[''].sessions as any[])
.map(e => e.connections)
.reduce((l, r) => l.concat(r), [])
.map(e => e.last_seen)
.reduce((l, r) => Math.max(l, r), lastseen);
}
client.sendMessage(commandRoomId, {
'msgtype': 'm.notice',
'body': 'Created user ' + username + ' on: ' + created.toLocaleString() + '\nLast seen: ' + (lastseen === 0 ? new Date(lastseen).toLocaleString() : 'unknown'),
});
} catch (error) {
logger.error(error);
client.sendMessage(commandRoomId, {
'msgtype': 'm.notice',
'body': 'Error while fetching seen of ' + username,
});
}
}
async function serveradmin(commandRoomId: string, username: string) {
logger.log('Toggling server admin of', username);
try {
let userid = '@' + username + ':' + config.servername;
let j = await getUser(userid);
//toggle admin
{
let resp = await fetch(config.homeserverUrl + '/_synapse/admin/v2/users/' + userid, {
method: 'PUT',
headers: { 'Authorization': 'Bearer ' + config.accessToken, 'Content-Type': 'application/json' },
body: JSON.stringify({ admin: !j.admin }),
});
if (resp.status === 200) {
client.sendMessage(commandRoomId, {
'msgtype': 'm.notice',
'body': 'User ' + username + ' ' + (j.admin ? 'is no admin no more' : 'is now admin'),
});
} else {
logger.error(await resp.text());
client.sendMessage(commandRoomId, {
'msgtype': 'm.notice',
'body': 'Failed to toggle admin for user ' + username,
});
}
}
} catch (error) {
logger.error(error);
client.sendMessage(commandRoomId, {
'msgtype': 'm.notice',
'body': 'Error while fetching seen of ' + username,
});
}
}
async function roomadmin(commandRoomId: string, username: string) {
logger.log('Setting room admin for', username);
let userid = '@' + username + ':' + config.servername;
let success: string[] = [];
let failed: string[] = [];
for (let roomId in config.roomAdminRoomInclude) {
try {
let resp = await fetch(config.homeserverUrl + '/_synapse/admin/v1/rooms/' + roomId + '/make_room_admin', {
method: 'POST',
headers: { 'Authorization': 'Bearer ' + config.accessToken, 'Content-Type': 'application/json' },
body: JSON.stringify({ user_id: userid }),
});
if (resp.status === 200) {
success.push(config.roomAdminRoomInclude[roomId]);
} else {
logger.error(await resp.text());
failed.push(config.roomAdminRoomInclude[roomId]);
}
} catch (error) {
logger.error(error);
failed.push(config.roomAdminRoomInclude[roomId]);
}
}
client.sendMessage(commandRoomId, {
'msgtype': 'm.notice',
'body': 'Admin role set in rooms: ' + success.join(', ') + (failed.length ? '\nFailed to set admin in: ' + failed.join(', ') : ''),
});
}
//utils
async function getUser(userid): Promise<any> {
userid = userid.replace('/', '%2F');
let resp = await dofetch(config.homeserverUrl + '/_synapse/admin/v2/users/' + userid, {
headers: { 'Authorization': 'Bearer ' + config.accessToken }
});
let j: any = await resp.json();
return j;
}
function dofetch(url, opts): Promise<any> {
return fetch(url, opts).then(e => {
if (e.status !== 200 && e.status !== 204) {
throw new Error(e.status + ': ' + e.body);
}
return e;
});
}