@im-more/dsh-matrix 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/cordis.patch.yml +14 -0
- package/lib/index.js +2401 -0
- package/lib/index.js.map +1 -0
- package/lib/types/as.d.ts +33 -0
- package/lib/types/as.d.ts.map +1 -0
- package/lib/types/as.js +237 -0
- package/lib/types/as.js.map +1 -0
- package/lib/types/bot.d.ts +109 -0
- package/lib/types/bot.d.ts.map +1 -0
- package/lib/types/bot.js +234 -0
- package/lib/types/bot.js.map +1 -0
- package/lib/types/config.d.ts +59 -0
- package/lib/types/config.d.ts.map +1 -0
- package/lib/types/config.js +67 -0
- package/lib/types/config.js.map +1 -0
- package/lib/types/decode.d.ts +56 -0
- package/lib/types/decode.d.ts.map +1 -0
- package/lib/types/decode.js +298 -0
- package/lib/types/decode.js.map +1 -0
- package/lib/types/errors.d.ts +45 -0
- package/lib/types/errors.d.ts.map +1 -0
- package/lib/types/errors.js +120 -0
- package/lib/types/errors.js.map +1 -0
- package/lib/types/html.d.ts +44 -0
- package/lib/types/html.d.ts.map +1 -0
- package/lib/types/html.js +286 -0
- package/lib/types/html.js.map +1 -0
- package/lib/types/identity.d.ts +20 -0
- package/lib/types/identity.d.ts.map +1 -0
- package/lib/types/identity.js +136 -0
- package/lib/types/identity.js.map +1 -0
- package/lib/types/index.d.ts +5 -0
- package/lib/types/index.d.ts.map +1 -0
- package/lib/types/index.js +5 -0
- package/lib/types/index.js.map +1 -0
- package/lib/types/media.d.ts +54 -0
- package/lib/types/media.d.ts.map +1 -0
- package/lib/types/media.js +94 -0
- package/lib/types/media.js.map +1 -0
- package/lib/types/mentions.d.ts +58 -0
- package/lib/types/mentions.d.ts.map +1 -0
- package/lib/types/mentions.js +94 -0
- package/lib/types/mentions.js.map +1 -0
- package/lib/types/modes/html.d.ts +13 -0
- package/lib/types/modes/html.d.ts.map +1 -0
- package/lib/types/modes/html.js +242 -0
- package/lib/types/modes/html.js.map +1 -0
- package/lib/types/modes/shared.d.ts +164 -0
- package/lib/types/modes/shared.d.ts.map +1 -0
- package/lib/types/modes/shared.js +312 -0
- package/lib/types/modes/shared.js.map +1 -0
- package/lib/types/request.d.ts +82 -0
- package/lib/types/request.d.ts.map +1 -0
- package/lib/types/request.js +206 -0
- package/lib/types/request.js.map +1 -0
- package/lib/types/rooms.d.ts +83 -0
- package/lib/types/rooms.d.ts.map +1 -0
- package/lib/types/rooms.js +177 -0
- package/lib/types/rooms.js.map +1 -0
- package/lib/types/send.d.ts +76 -0
- package/lib/types/send.d.ts.map +1 -0
- package/lib/types/send.js +172 -0
- package/lib/types/send.js.map +1 -0
- package/lib/types/types.d.ts +418 -0
- package/lib/types/types.d.ts.map +1 -0
- package/lib/types/types.js +134 -0
- package/lib/types/types.js.map +1 -0
- package/package.json +65 -3
- package/src/as.ts +293 -0
- package/src/bot.ts +338 -0
- package/src/config.ts +100 -0
- package/src/decode.ts +392 -0
- package/src/errors.ts +149 -0
- package/src/html.ts +325 -0
- package/src/identity.ts +165 -0
- package/src/index.ts +14 -0
- package/src/media.ts +132 -0
- package/src/mentions.ts +134 -0
- package/src/modes/html.ts +346 -0
- package/src/modes/shared.ts +485 -0
- package/src/request.ts +295 -0
- package/src/rooms.ts +232 -0
- package/src/send.ts +275 -0
- package/src/types.ts +633 -0
- package/README.md +0 -3
package/lib/index.js
ADDED
|
@@ -0,0 +1,2401 @@
|
|
|
1
|
+
import { Adapter, ElementRegistry, PlatformError, h } from "@deepseek-ai/cordis-plugin-im-core";
|
|
2
|
+
import { createHash, timingSafeEqual } from "node:crypto";
|
|
3
|
+
import z from "@deepseek-ai/schemastery";
|
|
4
|
+
import { h as h$1, isPhrasingContainer } from "@deepseek-ai/satori-element";
|
|
5
|
+
import { SyntaxKind, parse } from "html5parser";
|
|
6
|
+
import imageSize from "image-size";
|
|
7
|
+
// lib/types/config.js
|
|
8
|
+
/**
|
|
9
|
+
* The Application Service configuration: the registration credentials, the virtual user, the inbound route and the
|
|
10
|
+
* media request defaults. There is no transport switch — the homeserver's transaction push is the only intake.
|
|
11
|
+
*
|
|
12
|
+
* `endpoint` defaults to `https://<host>`; trailing slashes are removed so the client can append `/_matrix` once.
|
|
13
|
+
*/
|
|
14
|
+
/** A schema-required field, narrowed from the transform's nullable view of an object schema. */
|
|
15
|
+
function required(value, field) {
|
|
16
|
+
if (value === void 0 || value === null || value === "") throw new Error(`matrix: ${field} is required`);
|
|
17
|
+
return value;
|
|
18
|
+
}
|
|
19
|
+
/** Validated Matrix adapter configuration; `endpoint` is always resolved. */
|
|
20
|
+
const Config = z.transform(z.object({
|
|
21
|
+
endpoint: z.string().role("url"),
|
|
22
|
+
host: z.string().required(),
|
|
23
|
+
id: z.string().required(),
|
|
24
|
+
asToken: z.string().role("secret").required(),
|
|
25
|
+
hsToken: z.string().role("secret").required(),
|
|
26
|
+
path: z.string().default("/matrix"),
|
|
27
|
+
name: z.string(),
|
|
28
|
+
avatar: z.string(),
|
|
29
|
+
autoJoin: z.boolean().default(true)
|
|
30
|
+
}), (value) => ({
|
|
31
|
+
...value,
|
|
32
|
+
endpoint: (value.endpoint ?? `https://${required(value.host, "host")}`).replace(/\/+$/, ""),
|
|
33
|
+
host: required(value.host, "host"),
|
|
34
|
+
id: required(value.id, "id"),
|
|
35
|
+
asToken: required(value.asToken, "asToken"),
|
|
36
|
+
hsToken: required(value.hsToken, "hsToken"),
|
|
37
|
+
path: value.path ?? "/matrix",
|
|
38
|
+
autoJoin: value.autoJoin ?? true
|
|
39
|
+
}));
|
|
40
|
+
/**
|
|
41
|
+
* The endpoint the adapter refuses to start with.
|
|
42
|
+
*
|
|
43
|
+
* The schema marks `endpoint` as a URL for profile renderers, but only this check makes a malformed root fail before
|
|
44
|
+
* the first request instead of on every call.
|
|
45
|
+
*
|
|
46
|
+
* @param config - the validated configuration.
|
|
47
|
+
* @returns the configuration error, or undefined when the endpoint is usable.
|
|
48
|
+
*/
|
|
49
|
+
function configError(config) {
|
|
50
|
+
let url;
|
|
51
|
+
try {
|
|
52
|
+
url = new URL(config.endpoint);
|
|
53
|
+
} catch {
|
|
54
|
+
return /* @__PURE__ */ new Error("matrix: endpoint must be an absolute http(s) URL");
|
|
55
|
+
}
|
|
56
|
+
if (url.protocol !== "http:" && url.protocol !== "https:") return /* @__PURE__ */ new Error("matrix: endpoint must be an absolute http(s) URL");
|
|
57
|
+
}
|
|
58
|
+
/**
|
|
59
|
+
* Normalize an inbound route path: absolute, no trailing slash.
|
|
60
|
+
* @param path - the configured `path`.
|
|
61
|
+
* @returns the pathname to register.
|
|
62
|
+
*/
|
|
63
|
+
function routePath(path) {
|
|
64
|
+
const withSlash = path.startsWith("/") ? path : `/${path}`;
|
|
65
|
+
return withSlash.length > 1 ? withSlash.replace(/\/+$/, "") : withSlash;
|
|
66
|
+
}
|
|
67
|
+
// lib/types/as.js
|
|
68
|
+
/**
|
|
69
|
+
* The Application Service inbound transport.
|
|
70
|
+
*
|
|
71
|
+
* The profile's `webServer` owns the listener, so this transport registers one anonymous prefix route at the configured
|
|
72
|
+
* path and implements the Application Service API under it: transaction pushes (current and legacy path forms), the
|
|
73
|
+
* `users` query, the `rooms` query (always unknown) and the v1.7 `ping`. Every request is authenticated by `hs_token`,
|
|
74
|
+
* with the legacy `?access_token=` form accepted and refused when it contradicts a Bearer header.
|
|
75
|
+
*
|
|
76
|
+
* A transaction is confirmed only after every event reached intake: a failed event answers `500`, so the homeserver
|
|
77
|
+
* redelivers the batch with the same transaction id and the host's event-id deduplication removes the copies it already
|
|
78
|
+
* stored. That is the opposite of the upstream adapter's confirm-first order, which loses an event whose store failed.
|
|
79
|
+
*/
|
|
80
|
+
/** The prefixes a transaction push uses: the current Application Service path and the legacy one. */
|
|
81
|
+
const TRANSACTION_PREFIXES = ["/_matrix/app/v1/transactions/", "/transactions/"];
|
|
82
|
+
/** The route families whose methods are fixed. */
|
|
83
|
+
const PING_PATH = "/_matrix/app/v1/ping";
|
|
84
|
+
const USERS_PREFIX = "/_matrix/app/v1/users/";
|
|
85
|
+
const ROOMS_PREFIX = "/_matrix/app/v1/rooms/";
|
|
86
|
+
/** Compare two secrets without leaking where they differ. */
|
|
87
|
+
function secretMatches(expected, received) {
|
|
88
|
+
const left = Buffer.from(expected, "utf8");
|
|
89
|
+
const right = Buffer.from(received, "utf8");
|
|
90
|
+
if (left.length !== right.length) return false;
|
|
91
|
+
return timingSafeEqual(left, right);
|
|
92
|
+
}
|
|
93
|
+
/** The Bearer token of a request, when it used the current scheme. */
|
|
94
|
+
function bearerOf(request) {
|
|
95
|
+
const header = request.headers.authorization;
|
|
96
|
+
if (typeof header !== "string") return void 0;
|
|
97
|
+
return /^Bearer\s+(.+)$/i.exec(header)?.[1];
|
|
98
|
+
}
|
|
99
|
+
/** Read a request body to its end. The adapter imposes no size limit of its own. */
|
|
100
|
+
async function readBody(request) {
|
|
101
|
+
const chunks = [];
|
|
102
|
+
for await (const chunk of request) chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
|
|
103
|
+
return Buffer.concat(chunks).toString("utf8");
|
|
104
|
+
}
|
|
105
|
+
/** Write one bodiless answer. */
|
|
106
|
+
function writeStatus(response, status, headers = {}) {
|
|
107
|
+
if (response.headersSent) {
|
|
108
|
+
response.end();
|
|
109
|
+
return;
|
|
110
|
+
}
|
|
111
|
+
response.writeHead(status, headers);
|
|
112
|
+
response.end();
|
|
113
|
+
}
|
|
114
|
+
/** Write one JSON answer. */
|
|
115
|
+
function writeJson(response, status, body) {
|
|
116
|
+
if (response.headersSent) {
|
|
117
|
+
response.end();
|
|
118
|
+
return;
|
|
119
|
+
}
|
|
120
|
+
response.writeHead(status, { "content-type": "application/json" });
|
|
121
|
+
response.end(JSON.stringify(body));
|
|
122
|
+
}
|
|
123
|
+
/** The `M_UNRECOGNIZED` answer the specification asks unknown routes to use. */
|
|
124
|
+
function writeUnrecognized(response) {
|
|
125
|
+
writeJson(response, 404, {
|
|
126
|
+
errcode: "M_UNRECOGNIZED",
|
|
127
|
+
error: "Unrecognized request"
|
|
128
|
+
});
|
|
129
|
+
}
|
|
130
|
+
/** Message of any caught value, for a log line. */
|
|
131
|
+
function messageOf$1(error) {
|
|
132
|
+
return error instanceof Error ? error.message : String(error);
|
|
133
|
+
}
|
|
134
|
+
/** The transaction id of one subpath, when the subpath is a transaction route. */
|
|
135
|
+
function transactionIdOf(sub) {
|
|
136
|
+
for (const prefix of TRANSACTION_PREFIXES) {
|
|
137
|
+
if (!sub.startsWith(prefix)) continue;
|
|
138
|
+
const id = sub.slice(prefix.length);
|
|
139
|
+
return id === "" ? void 0 : id;
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
/** The Application Service transport of one bot. */
|
|
143
|
+
var MatrixAppService = class {
|
|
144
|
+
bot;
|
|
145
|
+
dispose;
|
|
146
|
+
constructor(bot) {
|
|
147
|
+
this.bot = bot;
|
|
148
|
+
}
|
|
149
|
+
/** Register the prefix route; a profile without a web server fails with an actionable message. */
|
|
150
|
+
async start() {
|
|
151
|
+
const webServer = this.bot.ctx.get("webServer");
|
|
152
|
+
if (webServer === void 0) throw this.fail("matrix: the Application Service needs a profile-provided webServer; the homeserver must reach the route named by the registration's url");
|
|
153
|
+
this.dispose = webServer.register({
|
|
154
|
+
kind: "prefix",
|
|
155
|
+
path: routePath(this.bot.config.path),
|
|
156
|
+
auth: "anonymous",
|
|
157
|
+
handler: (request, response) => this.handle(request, response)
|
|
158
|
+
});
|
|
159
|
+
}
|
|
160
|
+
/** Release the route. */
|
|
161
|
+
async stop() {
|
|
162
|
+
this.dispose?.();
|
|
163
|
+
this.dispose = void 0;
|
|
164
|
+
}
|
|
165
|
+
/** Log a fatal start failure before the caller throws it (`Bot.start` only stores a connect failure). */
|
|
166
|
+
fail(message) {
|
|
167
|
+
this.bot.ctx.logger.error(message);
|
|
168
|
+
return new Error(message);
|
|
169
|
+
}
|
|
170
|
+
async handle(request, response) {
|
|
171
|
+
try {
|
|
172
|
+
const base = routePath(this.bot.config.path);
|
|
173
|
+
const url = new URL(request.url ?? "/", "http://matrix.invalid");
|
|
174
|
+
if (!(base === "/" || url.pathname === base || url.pathname.startsWith(`${base}/`))) {
|
|
175
|
+
writeUnrecognized(response);
|
|
176
|
+
return;
|
|
177
|
+
}
|
|
178
|
+
if (!this.authorized(request, url.searchParams)) {
|
|
179
|
+
writeStatus(response, 403);
|
|
180
|
+
return;
|
|
181
|
+
}
|
|
182
|
+
const sub = base === "/" ? url.pathname : url.pathname.slice(base.length);
|
|
183
|
+
const txnId = transactionIdOf(sub);
|
|
184
|
+
if (txnId !== void 0) {
|
|
185
|
+
if (request.method !== "PUT") {
|
|
186
|
+
writeStatus(response, 405, { allow: "PUT" });
|
|
187
|
+
return;
|
|
188
|
+
}
|
|
189
|
+
await this.transaction(request, response, txnId);
|
|
190
|
+
return;
|
|
191
|
+
}
|
|
192
|
+
if (sub === PING_PATH) {
|
|
193
|
+
if (request.method !== "POST") {
|
|
194
|
+
writeStatus(response, 405, { allow: "POST" });
|
|
195
|
+
return;
|
|
196
|
+
}
|
|
197
|
+
writeJson(response, 200, {});
|
|
198
|
+
return;
|
|
199
|
+
}
|
|
200
|
+
if (sub.startsWith(USERS_PREFIX)) {
|
|
201
|
+
if (request.method !== "GET") {
|
|
202
|
+
writeStatus(response, 405, { allow: "GET" });
|
|
203
|
+
return;
|
|
204
|
+
}
|
|
205
|
+
this.users(response, sub.slice(22));
|
|
206
|
+
return;
|
|
207
|
+
}
|
|
208
|
+
if (sub.startsWith(ROOMS_PREFIX)) {
|
|
209
|
+
if (request.method !== "GET") {
|
|
210
|
+
writeStatus(response, 405, { allow: "GET" });
|
|
211
|
+
return;
|
|
212
|
+
}
|
|
213
|
+
writeUnrecognized(response);
|
|
214
|
+
return;
|
|
215
|
+
}
|
|
216
|
+
writeUnrecognized(response);
|
|
217
|
+
} catch (error) {
|
|
218
|
+
this.bot.ctx.logger.warn("matrix: Application Service request failed: %s", messageOf$1(error));
|
|
219
|
+
writeStatus(response, 500);
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
/** Whether one request carries the registration's `hs_token` in exactly one consistent form. */
|
|
223
|
+
authorized(request, query) {
|
|
224
|
+
const bearer = bearerOf(request);
|
|
225
|
+
const legacy = query.get("access_token") ?? void 0;
|
|
226
|
+
if (bearer !== void 0 && legacy !== void 0 && bearer !== legacy) return false;
|
|
227
|
+
const token = bearer ?? legacy;
|
|
228
|
+
if (token === void 0) return false;
|
|
229
|
+
return secretMatches(this.bot.config.hsToken, token);
|
|
230
|
+
}
|
|
231
|
+
/** Read and process one transaction; the answer is `200 {}` only after every event reached intake. */
|
|
232
|
+
async transaction(request, response, txnId) {
|
|
233
|
+
const body = await readBody(request);
|
|
234
|
+
let parsed;
|
|
235
|
+
try {
|
|
236
|
+
parsed = JSON.parse(body);
|
|
237
|
+
} catch (error) {
|
|
238
|
+
this.bot.ctx.logger.warn("matrix: cannot parse transaction %s: %s", txnId, messageOf$1(error));
|
|
239
|
+
writeStatus(response, 400);
|
|
240
|
+
return;
|
|
241
|
+
}
|
|
242
|
+
if (typeof parsed !== "object" || parsed === null) {
|
|
243
|
+
writeStatus(response, 400);
|
|
244
|
+
return;
|
|
245
|
+
}
|
|
246
|
+
const events = parsed.events;
|
|
247
|
+
if (!Array.isArray(events)) {
|
|
248
|
+
writeStatus(response, 400);
|
|
249
|
+
return;
|
|
250
|
+
}
|
|
251
|
+
try {
|
|
252
|
+
for (const raw of events) {
|
|
253
|
+
if (typeof raw !== "object" || raw === null) continue;
|
|
254
|
+
const session = await this.bot.decode(raw);
|
|
255
|
+
if (session !== void 0) await this.bot.receive(session);
|
|
256
|
+
}
|
|
257
|
+
} catch (error) {
|
|
258
|
+
this.bot.noteRuntimeError(error);
|
|
259
|
+
this.bot.ctx.logger.warn("matrix: transaction %s failed; the homeserver redelivers it: %s", txnId, messageOf$1(error));
|
|
260
|
+
writeStatus(response, 500);
|
|
261
|
+
return;
|
|
262
|
+
}
|
|
263
|
+
writeJson(response, 200, {});
|
|
264
|
+
}
|
|
265
|
+
/** Answer the `users` query: only the AS virtual user exists. */
|
|
266
|
+
users(response, encoded) {
|
|
267
|
+
let userId = encoded;
|
|
268
|
+
try {
|
|
269
|
+
userId = decodeURIComponent(encoded);
|
|
270
|
+
} catch {}
|
|
271
|
+
if (userId !== this.bot.selfId) {
|
|
272
|
+
writeUnrecognized(response);
|
|
273
|
+
return;
|
|
274
|
+
}
|
|
275
|
+
writeJson(response, 200, {});
|
|
276
|
+
}
|
|
277
|
+
};
|
|
278
|
+
// lib/types/html.js
|
|
279
|
+
/**
|
|
280
|
+
* `formatted_body` decoding: Matrix's HTML subset becomes Satori elements.
|
|
281
|
+
*
|
|
282
|
+
* The traversal follows the upstream adapter (`html5parser` + a tag table) and keeps two one-line bug fixes from the
|
|
283
|
+
* migration: an unknown named character reference stays as written instead of duplicating the whole text node, and an
|
|
284
|
+
* image's `alt` is read from `alt` rather than from `src`. A Matrix rich reply carries a duplicated fallback block
|
|
285
|
+
* (`<mx-reply>`); the whole block is dropped, as the specification tells clients to strip it.
|
|
286
|
+
*/
|
|
287
|
+
/** The named character references the traversal decodes (the upstream adapter's table). */
|
|
288
|
+
const ENTITIES = {
|
|
289
|
+
nbsp: " ",
|
|
290
|
+
cent: "¢",
|
|
291
|
+
pound: "£",
|
|
292
|
+
yen: "¥",
|
|
293
|
+
euro: "€",
|
|
294
|
+
copy: "©",
|
|
295
|
+
reg: "®",
|
|
296
|
+
lt: "<",
|
|
297
|
+
gt: ">",
|
|
298
|
+
quot: "\"",
|
|
299
|
+
amp: "&",
|
|
300
|
+
apos: "'"
|
|
301
|
+
};
|
|
302
|
+
/**
|
|
303
|
+
* Decode named, decimal and hexadecimal character references of one text run.
|
|
304
|
+
*
|
|
305
|
+
* A named reference outside {@link ENTITIES} is not an error: it stays as written. (Upstream returned the whole text
|
|
306
|
+
* node in that case, which duplicated everything around the unknown reference.)
|
|
307
|
+
*
|
|
308
|
+
* @param text - raw character data of one HTML text node.
|
|
309
|
+
* @returns the text with the known references decoded.
|
|
310
|
+
*/
|
|
311
|
+
function decodeHE(text) {
|
|
312
|
+
return text.replace(/&(([a-z0-9]+)|(#[0-9]{1,6})|(#x[0-9a-fA-F]{1,6}));/gi, (raw, _whole, name, dec, hex) => {
|
|
313
|
+
if (name) return ENTITIES[name] ?? raw;
|
|
314
|
+
if (dec) return String.fromCharCode(Number(dec.substring(1)));
|
|
315
|
+
if (hex) return String.fromCharCode(parseInt(hex.substring(2), 16));
|
|
316
|
+
return raw;
|
|
317
|
+
});
|
|
318
|
+
}
|
|
319
|
+
/** One attribute of a parsed tag, as written in the source. */
|
|
320
|
+
function attribute(node, name) {
|
|
321
|
+
return node.attributeMap?.[name]?.value?.value;
|
|
322
|
+
}
|
|
323
|
+
/** Whether the attribute is present (an HTML boolean attribute such as `checked`). */
|
|
324
|
+
function hasAttribute(node, name) {
|
|
325
|
+
return node.attributeMap?.[name] !== void 0;
|
|
326
|
+
}
|
|
327
|
+
/** A numeric attribute, or undefined when it is absent or not a number. */
|
|
328
|
+
function numericAttribute(node, name) {
|
|
329
|
+
const value = attribute(node, name);
|
|
330
|
+
if (value === void 0 || value.trim() === "") return void 0;
|
|
331
|
+
const parsed = Number(value);
|
|
332
|
+
return Number.isFinite(parsed) ? parsed : void 0;
|
|
333
|
+
}
|
|
334
|
+
/** Tags whose whole subtree is not part of the message body. */
|
|
335
|
+
const IGNORED = /* @__PURE__ */ new Set([
|
|
336
|
+
"head",
|
|
337
|
+
"script",
|
|
338
|
+
"style",
|
|
339
|
+
"meta",
|
|
340
|
+
"title",
|
|
341
|
+
"template"
|
|
342
|
+
]);
|
|
343
|
+
/** The language of a `<pre><code class="language-x">` pair, when the client wrote one. */
|
|
344
|
+
function languageOf(body) {
|
|
345
|
+
for (const child of body) {
|
|
346
|
+
if (child.type !== SyntaxKind.Tag || child.name !== "code") continue;
|
|
347
|
+
const className = attribute(child, "class");
|
|
348
|
+
if (className === void 0) continue;
|
|
349
|
+
const match = /(?:^|\s)language-(\S+)/.exec(className);
|
|
350
|
+
if (match?.[1] !== void 0) return match[1];
|
|
351
|
+
}
|
|
352
|
+
}
|
|
353
|
+
/** The label and destination of one `matrix.to` link, when it is one. */
|
|
354
|
+
const MATRIX_TO = "https://matrix.to/#/";
|
|
355
|
+
/**
|
|
356
|
+
* Convert one HTML string into elements.
|
|
357
|
+
*
|
|
358
|
+
* @param html - the `formatted_body` of an `m.room.message`.
|
|
359
|
+
* @param options - how to fetch media.
|
|
360
|
+
* @returns the elements of the body, in document order.
|
|
361
|
+
*/
|
|
362
|
+
function htmlToElements(html, options) {
|
|
363
|
+
const visit = (nodes) => {
|
|
364
|
+
const out = [];
|
|
365
|
+
for (const node of nodes) {
|
|
366
|
+
if (node.type === SyntaxKind.Text) {
|
|
367
|
+
const text = decodeHE(node.value);
|
|
368
|
+
if (text !== "") out.push(h$1.text(text));
|
|
369
|
+
continue;
|
|
370
|
+
}
|
|
371
|
+
const body = node.body ?? [];
|
|
372
|
+
switch (node.name) {
|
|
373
|
+
case "mx-reply": break;
|
|
374
|
+
case "p":
|
|
375
|
+
out.push(h$1("p", ...visit(body)));
|
|
376
|
+
break;
|
|
377
|
+
case "br":
|
|
378
|
+
out.push(h$1("br"));
|
|
379
|
+
break;
|
|
380
|
+
case "hr":
|
|
381
|
+
out.push(h$1("hr"));
|
|
382
|
+
break;
|
|
383
|
+
case "b":
|
|
384
|
+
case "strong":
|
|
385
|
+
out.push(h$1("b", ...visit(body)));
|
|
386
|
+
break;
|
|
387
|
+
case "i":
|
|
388
|
+
case "em":
|
|
389
|
+
out.push(h$1("i", ...visit(body)));
|
|
390
|
+
break;
|
|
391
|
+
case "u":
|
|
392
|
+
out.push(h$1("u", ...visit(body)));
|
|
393
|
+
break;
|
|
394
|
+
case "s":
|
|
395
|
+
case "del":
|
|
396
|
+
case "strike":
|
|
397
|
+
out.push(h$1("s", ...visit(body)));
|
|
398
|
+
break;
|
|
399
|
+
case "code":
|
|
400
|
+
out.push(h$1("code", ...visit(body)));
|
|
401
|
+
break;
|
|
402
|
+
case "pre": {
|
|
403
|
+
const language = languageOf(body);
|
|
404
|
+
out.push(h$1("pre", language === void 0 ? {} : { lang: language }, ...visit(body)));
|
|
405
|
+
break;
|
|
406
|
+
}
|
|
407
|
+
case "a": {
|
|
408
|
+
const href = attribute(node, "href") ?? "#";
|
|
409
|
+
const children = visit(body);
|
|
410
|
+
const plain = href.startsWith(MATRIX_TO) ? href.slice(20) : void 0;
|
|
411
|
+
if (plain?.startsWith("@")) out.push(h$1("at", {
|
|
412
|
+
type: "user",
|
|
413
|
+
id: plain
|
|
414
|
+
}, ...children));
|
|
415
|
+
else if (plain?.startsWith("#") || plain?.startsWith("!")) out.push(h$1("channel", { id: plain }, ...children));
|
|
416
|
+
else out.push(h$1("a", { href }, ...children));
|
|
417
|
+
break;
|
|
418
|
+
}
|
|
419
|
+
case "img": {
|
|
420
|
+
const src = attribute(node, "src");
|
|
421
|
+
const alt = attribute(node, "alt");
|
|
422
|
+
const width = numericAttribute(node, "width");
|
|
423
|
+
const height = numericAttribute(node, "height");
|
|
424
|
+
if (src === void 0 || src === "") {
|
|
425
|
+
if (alt !== void 0 && alt !== "") out.push(h$1.text(alt));
|
|
426
|
+
break;
|
|
427
|
+
}
|
|
428
|
+
const resolved = src.startsWith("mxc://") ? options.mediaSource(src) : src;
|
|
429
|
+
out.push(h$1("img", {
|
|
430
|
+
src: resolved,
|
|
431
|
+
...alt === void 0 ? {} : { alt },
|
|
432
|
+
...width === void 0 ? {} : { width },
|
|
433
|
+
...height === void 0 ? {} : { height }
|
|
434
|
+
}));
|
|
435
|
+
break;
|
|
436
|
+
}
|
|
437
|
+
case "blockquote":
|
|
438
|
+
out.push(h$1("blockquote", ...visit(body)));
|
|
439
|
+
break;
|
|
440
|
+
case "span":
|
|
441
|
+
if (hasAttribute(node, "data-mx-spoiler")) out.push(h$1("spoiler", ...visit(body)));
|
|
442
|
+
else out.push(...visit(body));
|
|
443
|
+
break;
|
|
444
|
+
case "ul":
|
|
445
|
+
out.push(h$1("ul", ...visit(body)));
|
|
446
|
+
break;
|
|
447
|
+
case "ol": {
|
|
448
|
+
const start = numericAttribute(node, "start");
|
|
449
|
+
out.push(h$1("ol", start === void 0 ? {} : { start }, ...visit(body)));
|
|
450
|
+
break;
|
|
451
|
+
}
|
|
452
|
+
case "li": {
|
|
453
|
+
let checked;
|
|
454
|
+
const children = [];
|
|
455
|
+
for (const child of body) {
|
|
456
|
+
if (child.type === SyntaxKind.Tag && child.name === "input" && attribute(child, "type") === "checkbox") {
|
|
457
|
+
checked = hasAttribute(child, "checked");
|
|
458
|
+
continue;
|
|
459
|
+
}
|
|
460
|
+
children.push(child);
|
|
461
|
+
}
|
|
462
|
+
out.push(h$1("li", checked === void 0 ? {} : { checked }, ...visit(children)));
|
|
463
|
+
break;
|
|
464
|
+
}
|
|
465
|
+
case "table":
|
|
466
|
+
out.push(h$1("table", ...visit(body)));
|
|
467
|
+
break;
|
|
468
|
+
case "tr":
|
|
469
|
+
out.push(h$1("tr", ...visit(body)));
|
|
470
|
+
break;
|
|
471
|
+
case "th":
|
|
472
|
+
case "td": {
|
|
473
|
+
const align = attribute(node, "align");
|
|
474
|
+
const attrs = align === "left" || align === "center" || align === "right" ? { align } : {};
|
|
475
|
+
out.push(h$1(node.name, attrs, ...visit(body)));
|
|
476
|
+
break;
|
|
477
|
+
}
|
|
478
|
+
case "details":
|
|
479
|
+
out.push(h$1("details", hasAttribute(node, "open") ? { open: true } : {}, ...visit(body)));
|
|
480
|
+
break;
|
|
481
|
+
case "summary":
|
|
482
|
+
out.push(h$1("summary", ...visit(body)));
|
|
483
|
+
break;
|
|
484
|
+
case "h1":
|
|
485
|
+
case "h2":
|
|
486
|
+
case "h3":
|
|
487
|
+
case "h4":
|
|
488
|
+
case "h5":
|
|
489
|
+
case "h6":
|
|
490
|
+
out.push(h$1(node.name, ...visit(body)));
|
|
491
|
+
break;
|
|
492
|
+
case "sup":
|
|
493
|
+
case "sub":
|
|
494
|
+
case "font":
|
|
495
|
+
case "div":
|
|
496
|
+
case "caption":
|
|
497
|
+
case "thead":
|
|
498
|
+
case "tbody":
|
|
499
|
+
out.push(...visit(body));
|
|
500
|
+
break;
|
|
501
|
+
default:
|
|
502
|
+
if (IGNORED.has(node.name)) break;
|
|
503
|
+
out.push(...visit(body));
|
|
504
|
+
}
|
|
505
|
+
}
|
|
506
|
+
return out;
|
|
507
|
+
};
|
|
508
|
+
return visit(parse(html, { setAttributeMap: true }));
|
|
509
|
+
}
|
|
510
|
+
/**
|
|
511
|
+
* Strip the rich-reply fallback of a plain `body`.
|
|
512
|
+
*
|
|
513
|
+
* A client that writes `format: org.matrix.custom.html` duplicates the quoted message inside `<mx-reply>`, and a plain
|
|
514
|
+
* body carries the same duplicate as leading `> ` lines. Only the leading block is removed, followed by the one blank
|
|
515
|
+
* line the fallback spec puts after it.
|
|
516
|
+
*
|
|
517
|
+
* @param body - the plain-text body of an `m.room.message`.
|
|
518
|
+
* @returns the body without a leading quote fallback.
|
|
519
|
+
*/
|
|
520
|
+
function stripPlainFallback(body) {
|
|
521
|
+
const lines = body.split("\n");
|
|
522
|
+
let index = 0;
|
|
523
|
+
while (index < lines.length && lines[index].startsWith("> ")) index++;
|
|
524
|
+
if (index === 0) return body;
|
|
525
|
+
if (lines[index] === "") index++;
|
|
526
|
+
return lines.slice(index).join("\n");
|
|
527
|
+
}
|
|
528
|
+
// lib/types/media.js
|
|
529
|
+
/**
|
|
530
|
+
* Media in both directions.
|
|
531
|
+
*
|
|
532
|
+
* Outbound: Matrix has a standalone upload endpoint, so `upload` fetches the bytes and posts them to
|
|
533
|
+
* `/_matrix/media/v3/upload`, returning the `mxc://` content URI as the platform key. Inbound: an `mxc://` source needs
|
|
534
|
+
* credentials, so decoding rewrites it to the bot's `satori:` route and the route downloads through the authenticated
|
|
535
|
+
* `/_matrix/client/v1/media/download` endpoint (v1.11 retired the unauthenticated form).
|
|
536
|
+
*/
|
|
537
|
+
/**
|
|
538
|
+
* Parse one Matrix content URI.
|
|
539
|
+
* @param uri - an `mxc://` URI.
|
|
540
|
+
* @returns its server name and media id, or undefined for any other URI.
|
|
541
|
+
*/
|
|
542
|
+
function parseMxc(uri) {
|
|
543
|
+
if (!uri.startsWith("mxc://")) return void 0;
|
|
544
|
+
const rest = uri.slice(6);
|
|
545
|
+
const slash = rest.indexOf("/");
|
|
546
|
+
if (slash <= 0 || slash === rest.length - 1) return void 0;
|
|
547
|
+
return {
|
|
548
|
+
serverName: rest.slice(0, slash),
|
|
549
|
+
mediaId: rest.slice(slash + 1)
|
|
550
|
+
};
|
|
551
|
+
}
|
|
552
|
+
/**
|
|
553
|
+
* The `satori:` source of one content URI, served through the bot's `/media` route.
|
|
554
|
+
* @param host - the receiving bot.
|
|
555
|
+
* @param uri - an `mxc://` URI.
|
|
556
|
+
* @returns the internal source, or undefined when the URI is not a content URI.
|
|
557
|
+
*/
|
|
558
|
+
function internalMediaSource(host, uri) {
|
|
559
|
+
const parsed = parseMxc(uri);
|
|
560
|
+
if (parsed === void 0) return void 0;
|
|
561
|
+
return host.getInternalUrl("/media", { mxc: `${parsed.serverName}/${parsed.mediaId}` });
|
|
562
|
+
}
|
|
563
|
+
/**
|
|
564
|
+
* Upload one resource and return its `mxc://` key.
|
|
565
|
+
*
|
|
566
|
+
* @param client - the bot's Client-Server client.
|
|
567
|
+
* @param ref - the resource placeholder produced by a mode handler.
|
|
568
|
+
* @param ctx - prepare context (fetch and cancellation).
|
|
569
|
+
* @returns the platform key and the name/MIME/size the event carries.
|
|
570
|
+
*/
|
|
571
|
+
async function uploadResource(client, ref, ctx) {
|
|
572
|
+
let fetched;
|
|
573
|
+
try {
|
|
574
|
+
fetched = await ctx.fetch(ref.src, ctx.signal);
|
|
575
|
+
} catch (error) {
|
|
576
|
+
throw new PlatformError("invalid", `matrix: the resource "${ref.src}" could not be read`, {
|
|
577
|
+
published: "no",
|
|
578
|
+
cause: error
|
|
579
|
+
});
|
|
580
|
+
}
|
|
581
|
+
const name = ref.meta.name ?? fetched.name ?? "file";
|
|
582
|
+
const mime = ref.meta.mime ?? fetched.mime;
|
|
583
|
+
const contentUri = (await client.upload(name, fetched.data, mime, ctx.signal)).content_uri;
|
|
584
|
+
if (contentUri === void 0 || contentUri === "") throw new PlatformError("invalid", "matrix: the upload answered without a content_uri", { published: "no" });
|
|
585
|
+
return {
|
|
586
|
+
key: contentUri,
|
|
587
|
+
extra: {
|
|
588
|
+
name,
|
|
589
|
+
...mime === void 0 ? {} : { mime },
|
|
590
|
+
size: fetched.data.byteLength
|
|
591
|
+
}
|
|
592
|
+
};
|
|
593
|
+
}
|
|
594
|
+
/** Response headers a `satori:` media route mirrors from the homeserver. The length is left to the response body. */
|
|
595
|
+
const MIRRORED_HEADERS = ["content-type", "content-disposition"];
|
|
596
|
+
/**
|
|
597
|
+
* Turn one homeserver media answer into the response the host sees.
|
|
598
|
+
* @param response - the authenticated download answer.
|
|
599
|
+
* @returns the same bytes and metadata, or `502` when the homeserver refused or lost them.
|
|
600
|
+
*/
|
|
601
|
+
function mediaResponse(response) {
|
|
602
|
+
if (!response.ok) return new Response(null, { status: 502 });
|
|
603
|
+
const headers = new Headers();
|
|
604
|
+
for (const name of MIRRORED_HEADERS) {
|
|
605
|
+
const value = response.headers.get(name);
|
|
606
|
+
if (value !== null) headers.set(name, value);
|
|
607
|
+
}
|
|
608
|
+
return new Response(response.body, {
|
|
609
|
+
status: response.status,
|
|
610
|
+
headers
|
|
611
|
+
});
|
|
612
|
+
}
|
|
613
|
+
// lib/types/mentions.js
|
|
614
|
+
/**
|
|
615
|
+
* Mentions in both directions.
|
|
616
|
+
*
|
|
617
|
+
* Inbound, `m.mentions` is authoritative for `self`/`all`, because guessing from a display name is what the
|
|
618
|
+
* specification warns against; a `matrix.to` link decoded into an `at` element covers older clients that did not write
|
|
619
|
+
* the field, and a bare `@room` in the body covers the pre-v1.7 room mention. Outbound, `at` elements collect into
|
|
620
|
+
* `m.mentions` (one object per draft, always present) and render as `matrix.to` links.
|
|
621
|
+
*/
|
|
622
|
+
/** A new empty collection. */
|
|
623
|
+
function createMentionSet() {
|
|
624
|
+
return {
|
|
625
|
+
users: [],
|
|
626
|
+
room: false
|
|
627
|
+
};
|
|
628
|
+
}
|
|
629
|
+
/**
|
|
630
|
+
* Add one handler's mention to a draft's collection.
|
|
631
|
+
* @param set - the draft's collection.
|
|
632
|
+
* @param mention - the mention; a user id or a room mention.
|
|
633
|
+
*/
|
|
634
|
+
function addMention(set, mention) {
|
|
635
|
+
if (mention === void 0) return;
|
|
636
|
+
if (mention.user !== void 0 && !set.users.includes(mention.user)) set.users.push(mention.user);
|
|
637
|
+
if (mention.room === true) set.room = true;
|
|
638
|
+
}
|
|
639
|
+
/** The wire object of one collection; `{}` when it mentions nobody. */
|
|
640
|
+
function mentionWire(set) {
|
|
641
|
+
return {
|
|
642
|
+
...set.users.length === 0 ? {} : { user_ids: [...set.users] },
|
|
643
|
+
...set.room ? { room: true } : {}
|
|
644
|
+
};
|
|
645
|
+
}
|
|
646
|
+
/** Whether the plain body carries the old standalone `@room` form. */
|
|
647
|
+
function bodyMentionsRoom(body) {
|
|
648
|
+
if (body === void 0) return false;
|
|
649
|
+
return /(^|\s)@room(?=\s|$)/.test(body);
|
|
650
|
+
}
|
|
651
|
+
/** Every `at[type=user]` of a decoded tree, in document order. */
|
|
652
|
+
function atElements(elements) {
|
|
653
|
+
const out = [];
|
|
654
|
+
const walk = (nodes) => {
|
|
655
|
+
for (const node of nodes) {
|
|
656
|
+
if (node.type === "at") {
|
|
657
|
+
if (node.attrs.type === "user") out.push(node);
|
|
658
|
+
continue;
|
|
659
|
+
}
|
|
660
|
+
walk(node.children);
|
|
661
|
+
}
|
|
662
|
+
};
|
|
663
|
+
walk(elements);
|
|
664
|
+
return out;
|
|
665
|
+
}
|
|
666
|
+
/**
|
|
667
|
+
* Decode the mention facts of one inbound event.
|
|
668
|
+
*
|
|
669
|
+
* @param content - the event content, whose `m.mentions` is authoritative when present.
|
|
670
|
+
* @param body - the plain body, for the legacy `@room` form.
|
|
671
|
+
* @param elements - the decoded content tree, for `matrix.to` links and mention labels.
|
|
672
|
+
* @param selfId - the bot's Matrix user id.
|
|
673
|
+
* @returns `self`/`all` flags and the users the message mentions.
|
|
674
|
+
*/
|
|
675
|
+
function decodeMentions(content, body, elements, selfId) {
|
|
676
|
+
const declared = content["m.mentions"];
|
|
677
|
+
const declaredIds = Array.isArray(declared?.user_ids) ? declared.user_ids.filter((id) => typeof id === "string") : [];
|
|
678
|
+
const users = [];
|
|
679
|
+
const seen = /* @__PURE__ */ new Set();
|
|
680
|
+
for (const element of atElements(elements)) {
|
|
681
|
+
const id = element.attrs.id;
|
|
682
|
+
if (id === void 0 || seen.has(id)) continue;
|
|
683
|
+
seen.add(id);
|
|
684
|
+
users.push({
|
|
685
|
+
id,
|
|
686
|
+
...element.attrs.name === void 0 ? {} : { name: element.attrs.name }
|
|
687
|
+
});
|
|
688
|
+
}
|
|
689
|
+
for (const id of declaredIds) {
|
|
690
|
+
if (seen.has(id)) continue;
|
|
691
|
+
seen.add(id);
|
|
692
|
+
users.push({ id });
|
|
693
|
+
}
|
|
694
|
+
const selfByElement = users.some((user) => user.id === selfId);
|
|
695
|
+
return {
|
|
696
|
+
self: selfId !== "" && (declaredIds.includes(selfId) || selfByElement),
|
|
697
|
+
all: declared?.room === true || bodyMentionsRoom(body),
|
|
698
|
+
users
|
|
699
|
+
};
|
|
700
|
+
}
|
|
701
|
+
// lib/types/decode.js
|
|
702
|
+
/**
|
|
703
|
+
* Inbound decoding: one Application Service event becomes one `Session`.
|
|
704
|
+
*
|
|
705
|
+
* `m.room.message` becomes a message (text/emote/notice through `formatted_body` or the plain body, media through the
|
|
706
|
+
* authenticated `satori:` route); `m.reaction` becomes `reaction-added`; `m.room.redaction` becomes
|
|
707
|
+
* `message-deleted` (room v11 moved the target into `content.redacts`). Membership and room-name events only update
|
|
708
|
+
* the room cache, and an invitation of the bot itself is joined when `autoJoin` is on. Everything else is dropped;
|
|
709
|
+
* `m.room.encrypted` is the visible consequence of the no-E2EE decision.
|
|
710
|
+
*/
|
|
711
|
+
/** Rooms whose first `m.room.encrypted` event has already been logged. */
|
|
712
|
+
const encryptedLogged = /* @__PURE__ */ new WeakMap();
|
|
713
|
+
/** The message types this adapter decodes; every other `msgtype` is dropped whole. */
|
|
714
|
+
const MESSAGE_TYPES = /* @__PURE__ */ new Set([
|
|
715
|
+
"m.text",
|
|
716
|
+
"m.emote",
|
|
717
|
+
"m.notice",
|
|
718
|
+
"m.image",
|
|
719
|
+
"m.file",
|
|
720
|
+
"m.audio",
|
|
721
|
+
"m.video"
|
|
722
|
+
]);
|
|
723
|
+
/** The chat of one room, from the cache. */
|
|
724
|
+
function chatOf(host, roomId) {
|
|
725
|
+
const name = host.rooms.nameOf(roomId);
|
|
726
|
+
return {
|
|
727
|
+
id: roomId,
|
|
728
|
+
type: host.rooms.isDirect(roomId, host.selfId) ? "direct" : "group",
|
|
729
|
+
...name === void 0 ? {} : { name }
|
|
730
|
+
};
|
|
731
|
+
}
|
|
732
|
+
/** The `satori:` source of one `mxc://` URI, or the raw address when it is not one. */
|
|
733
|
+
function mediaSource(host, uri) {
|
|
734
|
+
if (uri === void 0 || uri === "") return void 0;
|
|
735
|
+
return internalMediaSource(host, uri) ?? uri;
|
|
736
|
+
}
|
|
737
|
+
/** The sender of one event, with the display name the room cache knows. */
|
|
738
|
+
function senderOf(host, event) {
|
|
739
|
+
const name = host.rooms.displayNameOf(event.room_id, event.sender);
|
|
740
|
+
return {
|
|
741
|
+
id: event.sender,
|
|
742
|
+
...name === void 0 ? {} : { name },
|
|
743
|
+
isBot: false
|
|
744
|
+
};
|
|
745
|
+
}
|
|
746
|
+
/** The elements of one `m.room.message` content, or undefined for a msgtype this adapter drops. */
|
|
747
|
+
function messageElements(host, event) {
|
|
748
|
+
const content = event.content;
|
|
749
|
+
switch (content.msgtype) {
|
|
750
|
+
case "m.text":
|
|
751
|
+
case "m.emote":
|
|
752
|
+
case "m.notice": {
|
|
753
|
+
const formatted = content;
|
|
754
|
+
if (formatted.format === "org.matrix.custom.html" && typeof formatted.formatted_body === "string" && formatted.formatted_body !== "") return htmlToElements(formatted.formatted_body, { mediaSource: (mxc) => mediaSource(host, mxc) ?? mxc });
|
|
755
|
+
return [h.text(stripPlainFallback(content.body ?? ""))];
|
|
756
|
+
}
|
|
757
|
+
case "m.image": {
|
|
758
|
+
const image = content;
|
|
759
|
+
const src = mediaSource(host, image.url);
|
|
760
|
+
if (src === void 0) return void 0;
|
|
761
|
+
return [h("img", {
|
|
762
|
+
src,
|
|
763
|
+
...image.body === "" ? {} : { alt: image.body },
|
|
764
|
+
...image.info?.w === void 0 ? {} : { width: image.info.w },
|
|
765
|
+
...image.info?.h === void 0 ? {} : { height: image.info.h }
|
|
766
|
+
})];
|
|
767
|
+
}
|
|
768
|
+
case "m.file": {
|
|
769
|
+
const file = content;
|
|
770
|
+
const src = mediaSource(host, file.url);
|
|
771
|
+
if (src === void 0) return void 0;
|
|
772
|
+
const name = file.filename ?? file.body;
|
|
773
|
+
return [h("file", {
|
|
774
|
+
src,
|
|
775
|
+
...name === "" ? {} : { name }
|
|
776
|
+
})];
|
|
777
|
+
}
|
|
778
|
+
case "m.audio": {
|
|
779
|
+
const audio = content;
|
|
780
|
+
const src = mediaSource(host, audio.url);
|
|
781
|
+
if (src === void 0) return void 0;
|
|
782
|
+
const name = audio.filename ?? audio.body;
|
|
783
|
+
return [h("audio", {
|
|
784
|
+
src,
|
|
785
|
+
...name === "" ? {} : { name },
|
|
786
|
+
...audio.info?.duration === void 0 ? {} : { duration: audio.info.duration }
|
|
787
|
+
})];
|
|
788
|
+
}
|
|
789
|
+
case "m.video": {
|
|
790
|
+
const video = content;
|
|
791
|
+
const src = mediaSource(host, video.url);
|
|
792
|
+
if (src === void 0) return void 0;
|
|
793
|
+
const name = video.body;
|
|
794
|
+
return [h("video", {
|
|
795
|
+
src,
|
|
796
|
+
...name === "" ? {} : { name },
|
|
797
|
+
...video.info?.duration === void 0 ? {} : { duration: video.info.duration }
|
|
798
|
+
})];
|
|
799
|
+
}
|
|
800
|
+
default: return;
|
|
801
|
+
}
|
|
802
|
+
}
|
|
803
|
+
/**
|
|
804
|
+
* Decode one `m.room.message` event.
|
|
805
|
+
*
|
|
806
|
+
* @param host - the receiving adapter.
|
|
807
|
+
* @param event - one message event.
|
|
808
|
+
* @param chat - the chat to report, when the caller already knows it (`getMessage` uses the requested one).
|
|
809
|
+
* @returns the decoded message, whose content is never empty.
|
|
810
|
+
*/
|
|
811
|
+
function decodeMessage(host, event, chat) {
|
|
812
|
+
const content = event.content;
|
|
813
|
+
const elements = messageElements(host, event);
|
|
814
|
+
if (elements === void 0) host.log(`matrix: ignored msgtype "${content.msgtype ?? "unknown"}"`);
|
|
815
|
+
const usable = (elements ?? []).filter((element) => element.type !== "text" || element.attrs.content !== "");
|
|
816
|
+
const children = usable.length > 0 ? usable : [h("raw", {
|
|
817
|
+
platform: "matrix",
|
|
818
|
+
type: "m.room.message",
|
|
819
|
+
data: event.content
|
|
820
|
+
}, h.text(""))];
|
|
821
|
+
const message = h("message", {}, ...children);
|
|
822
|
+
const relates = content["m.relates_to"];
|
|
823
|
+
const threadRoot = relates?.rel_type === "m.thread" ? relates.event_id : void 0;
|
|
824
|
+
const quoteId = relates?.["m.in_reply_to"]?.event_id;
|
|
825
|
+
const referrer = {
|
|
826
|
+
roomId: event.room_id,
|
|
827
|
+
eventId: event.event_id,
|
|
828
|
+
sender: event.sender,
|
|
829
|
+
...threadRoot === void 0 ? {} : { threadRoot }
|
|
830
|
+
};
|
|
831
|
+
return {
|
|
832
|
+
id: event.event_id,
|
|
833
|
+
chat: chat ?? chatOf(host, event.room_id),
|
|
834
|
+
...threadRoot === void 0 ? {} : { thread: {
|
|
835
|
+
id: threadRoot,
|
|
836
|
+
root: threadRoot
|
|
837
|
+
} },
|
|
838
|
+
sender: senderOf(host, event),
|
|
839
|
+
content: message,
|
|
840
|
+
...quoteId === void 0 ? {} : { quote: { id: quoteId } },
|
|
841
|
+
mentions: decodeMentions(content, content.body, message.children, host.selfId),
|
|
842
|
+
time: event.origin_server_ts,
|
|
843
|
+
referrer,
|
|
844
|
+
raw: event
|
|
845
|
+
};
|
|
846
|
+
}
|
|
847
|
+
/** Decode one received event.
|
|
848
|
+
*
|
|
849
|
+
* @param host - the receiving adapter.
|
|
850
|
+
* @param event - one event of an Application Service transaction.
|
|
851
|
+
* @returns the session to publish, or undefined for an event this adapter does not carry.
|
|
852
|
+
*/
|
|
853
|
+
async function decodeEvent(host, event) {
|
|
854
|
+
if (event.sender === host.selfId) return void 0;
|
|
855
|
+
const timestamp = event.origin_server_ts;
|
|
856
|
+
switch (event.type) {
|
|
857
|
+
case "m.room.message": {
|
|
858
|
+
const content = event.content;
|
|
859
|
+
if (content["m.new_content"] !== void 0) {
|
|
860
|
+
host.log("matrix: ignored an edited message (m.new_content)");
|
|
861
|
+
return;
|
|
862
|
+
}
|
|
863
|
+
if (!MESSAGE_TYPES.has(content.msgtype)) {
|
|
864
|
+
host.log(`matrix: ignored msgtype "${content.msgtype ?? "unknown"}"`);
|
|
865
|
+
return;
|
|
866
|
+
}
|
|
867
|
+
const message = decodeMessage(host, event);
|
|
868
|
+
return host.session({
|
|
869
|
+
type: "message",
|
|
870
|
+
id: event.event_id,
|
|
871
|
+
timestamp,
|
|
872
|
+
message,
|
|
873
|
+
raw: event
|
|
874
|
+
});
|
|
875
|
+
}
|
|
876
|
+
case "m.reaction": {
|
|
877
|
+
const relation = event.content["m.relates_to"];
|
|
878
|
+
if (relation?.rel_type !== "m.annotation") {
|
|
879
|
+
host.log("matrix: ignored a reaction without an m.annotation relation");
|
|
880
|
+
return;
|
|
881
|
+
}
|
|
882
|
+
if (relation.event_id === void 0 || relation.key === void 0) {
|
|
883
|
+
host.log("matrix: ignored a reaction without an event id or key");
|
|
884
|
+
return;
|
|
885
|
+
}
|
|
886
|
+
return host.session({
|
|
887
|
+
type: "reaction-added",
|
|
888
|
+
id: event.event_id,
|
|
889
|
+
timestamp,
|
|
890
|
+
reaction: {
|
|
891
|
+
message: {
|
|
892
|
+
id: relation.event_id,
|
|
893
|
+
chat: chatOf(host, event.room_id)
|
|
894
|
+
},
|
|
895
|
+
emoji: relation.key,
|
|
896
|
+
user: { id: event.sender }
|
|
897
|
+
},
|
|
898
|
+
raw: event
|
|
899
|
+
});
|
|
900
|
+
}
|
|
901
|
+
case "m.room.redaction": {
|
|
902
|
+
const content = event.content;
|
|
903
|
+
const target = event.redacts ?? content.redacts;
|
|
904
|
+
if (target === void 0) return void 0;
|
|
905
|
+
return host.session({
|
|
906
|
+
type: "message-deleted",
|
|
907
|
+
id: event.event_id,
|
|
908
|
+
timestamp,
|
|
909
|
+
deleted: {
|
|
910
|
+
id: target,
|
|
911
|
+
chat: chatOf(host, event.room_id)
|
|
912
|
+
},
|
|
913
|
+
raw: event
|
|
914
|
+
});
|
|
915
|
+
}
|
|
916
|
+
case "m.room.member": {
|
|
917
|
+
const member = event.content;
|
|
918
|
+
const stateKey = event.state_key;
|
|
919
|
+
if (stateKey === void 0) return void 0;
|
|
920
|
+
host.rooms.applyMember(event.room_id, stateKey, member.membership, member.displayname);
|
|
921
|
+
if (stateKey !== host.selfId) return void 0;
|
|
922
|
+
if (member.membership === "invite") {
|
|
923
|
+
if (!host.autoJoin) {
|
|
924
|
+
host.log(`matrix: invited to ${event.room_id}; autoJoin is off, so it is not joined`);
|
|
925
|
+
return;
|
|
926
|
+
}
|
|
927
|
+
try {
|
|
928
|
+
await host.joinRoom(event.room_id);
|
|
929
|
+
} catch (error) {
|
|
930
|
+
host.warn(`matrix: could not join ${event.room_id}: ${error instanceof Error ? error.message : String(error)}`);
|
|
931
|
+
}
|
|
932
|
+
return;
|
|
933
|
+
}
|
|
934
|
+
if (member.membership === "join") try {
|
|
935
|
+
await host.refreshRooms();
|
|
936
|
+
} catch (error) {
|
|
937
|
+
host.warn(`matrix: could not refresh rooms after joining ${event.room_id}: ${error instanceof Error ? error.message : String(error)}`);
|
|
938
|
+
}
|
|
939
|
+
return;
|
|
940
|
+
}
|
|
941
|
+
case "m.room.name": {
|
|
942
|
+
const content = event.content;
|
|
943
|
+
if (typeof content.name === "string") host.rooms.setName(event.room_id, content.name);
|
|
944
|
+
return;
|
|
945
|
+
}
|
|
946
|
+
case "m.room.encryption":
|
|
947
|
+
if (host.rooms.markEncrypted(event.room_id)) host.warn(`matrix: room ${event.room_id} enabled end-to-end encryption; this adapter cannot decrypt its messages`);
|
|
948
|
+
return;
|
|
949
|
+
case "m.room.encrypted": {
|
|
950
|
+
let logged = encryptedLogged.get(host.rooms);
|
|
951
|
+
if (logged === void 0) {
|
|
952
|
+
logged = /* @__PURE__ */ new Set();
|
|
953
|
+
encryptedLogged.set(host.rooms, logged);
|
|
954
|
+
}
|
|
955
|
+
if (!logged.has(event.room_id)) {
|
|
956
|
+
logged.add(event.room_id);
|
|
957
|
+
host.log(`matrix: dropped an encrypted message in ${event.room_id} (E2EE is not supported)`);
|
|
958
|
+
}
|
|
959
|
+
return;
|
|
960
|
+
}
|
|
961
|
+
default:
|
|
962
|
+
host.log(`matrix: ignored ${event.type} event`);
|
|
963
|
+
return;
|
|
964
|
+
}
|
|
965
|
+
}
|
|
966
|
+
// lib/types/errors.js
|
|
967
|
+
/**
|
|
968
|
+
* Matrix failures and their mapping onto the core platform taxonomy.
|
|
969
|
+
*
|
|
970
|
+
* Matrix answers with one JSON envelope (`errcode`, `error`) and asks clients to decide from `errcode`, falling back
|
|
971
|
+
* to the HTTP status only for `M_UNKNOWN`. A refused write is atomic, so every 4xx means nothing was published;
|
|
972
|
+
* transport failures and 5xx answers leave the outcome unknown. The token-failure codes also mark the bot offline at
|
|
973
|
+
* the transport layer, because the AS-issued user token has no refresh path.
|
|
974
|
+
*/
|
|
975
|
+
/** One failed Matrix API call, with the fields `classify` reads. */
|
|
976
|
+
var MatrixApiError = class extends Error {
|
|
977
|
+
method;
|
|
978
|
+
path;
|
|
979
|
+
status;
|
|
980
|
+
errcode;
|
|
981
|
+
error;
|
|
982
|
+
retryAfterMs;
|
|
983
|
+
constructor(message, init = {}) {
|
|
984
|
+
super(message, init.cause === void 0 ? void 0 : { cause: init.cause });
|
|
985
|
+
this.name = "MatrixApiError";
|
|
986
|
+
this.method = init.method;
|
|
987
|
+
this.path = init.path;
|
|
988
|
+
this.status = init.status;
|
|
989
|
+
this.errcode = init.errcode;
|
|
990
|
+
this.error = init.error;
|
|
991
|
+
this.retryAfterMs = init.retryAfterMs;
|
|
992
|
+
}
|
|
993
|
+
};
|
|
994
|
+
/** Whether a failure means the user token is gone; the bot has to be re-logged in from scratch. */
|
|
995
|
+
function isTokenFailure(error) {
|
|
996
|
+
if (error instanceof MatrixApiError) {
|
|
997
|
+
if (error.errcode === "M_UNKNOWN_TOKEN" || error.errcode === "M_MISSING_TOKEN") return true;
|
|
998
|
+
return error.errcode === void 0 && error.status === 401;
|
|
999
|
+
}
|
|
1000
|
+
return false;
|
|
1001
|
+
}
|
|
1002
|
+
/** The kind and publish state implied by one `errcode`. */
|
|
1003
|
+
function byErrcode(errcode) {
|
|
1004
|
+
switch (errcode) {
|
|
1005
|
+
case "M_LIMIT_EXCEEDED": return {
|
|
1006
|
+
kind: "rate-limit",
|
|
1007
|
+
published: "no"
|
|
1008
|
+
};
|
|
1009
|
+
case "M_UNKNOWN_TOKEN":
|
|
1010
|
+
case "M_MISSING_TOKEN":
|
|
1011
|
+
case "M_FORBIDDEN":
|
|
1012
|
+
case "M_EXCLUSIVE":
|
|
1013
|
+
case "M_USER_DEACTIVATED":
|
|
1014
|
+
case "M_CONSENT_NOT_GIVEN": return {
|
|
1015
|
+
kind: "permission",
|
|
1016
|
+
published: "no"
|
|
1017
|
+
};
|
|
1018
|
+
case "M_RESOURCE_LIMIT_EXCEEDED": return {
|
|
1019
|
+
kind: "retryable",
|
|
1020
|
+
published: "no"
|
|
1021
|
+
};
|
|
1022
|
+
case "M_NOT_FOUND": return {
|
|
1023
|
+
kind: "not-found",
|
|
1024
|
+
published: "no"
|
|
1025
|
+
};
|
|
1026
|
+
case "M_BAD_JSON":
|
|
1027
|
+
case "M_NOT_JSON":
|
|
1028
|
+
case "M_MISSING_PARAM":
|
|
1029
|
+
case "M_INVALID_PARAM": return {
|
|
1030
|
+
kind: "invalid",
|
|
1031
|
+
published: "no"
|
|
1032
|
+
};
|
|
1033
|
+
case "M_TOO_LARGE": return {
|
|
1034
|
+
kind: "limit",
|
|
1035
|
+
published: "no"
|
|
1036
|
+
};
|
|
1037
|
+
default: return;
|
|
1038
|
+
}
|
|
1039
|
+
}
|
|
1040
|
+
/** The kind and publish state implied by a status when no `errcode` decides it. */
|
|
1041
|
+
function byStatus(status) {
|
|
1042
|
+
if (status === 429) return {
|
|
1043
|
+
kind: "rate-limit",
|
|
1044
|
+
published: "no"
|
|
1045
|
+
};
|
|
1046
|
+
if (status !== void 0 && status >= 500) return {
|
|
1047
|
+
kind: "retryable",
|
|
1048
|
+
published: "unknown"
|
|
1049
|
+
};
|
|
1050
|
+
if (status !== void 0 && status >= 200 && status < 300) return {
|
|
1051
|
+
kind: "retryable",
|
|
1052
|
+
published: "unknown"
|
|
1053
|
+
};
|
|
1054
|
+
if (status !== void 0) return {
|
|
1055
|
+
kind: "invalid",
|
|
1056
|
+
published: "no"
|
|
1057
|
+
};
|
|
1058
|
+
return {
|
|
1059
|
+
kind: "retryable",
|
|
1060
|
+
published: "unknown"
|
|
1061
|
+
};
|
|
1062
|
+
}
|
|
1063
|
+
/**
|
|
1064
|
+
* Map any failure onto the core platform taxonomy.
|
|
1065
|
+
*
|
|
1066
|
+
* @param error - the caught failure.
|
|
1067
|
+
* @returns the classified platform error, with `retryAfterMs` when the platform named a delay.
|
|
1068
|
+
*/
|
|
1069
|
+
function classifyMatrixError(error) {
|
|
1070
|
+
if (error instanceof PlatformError) return error;
|
|
1071
|
+
if (error instanceof MatrixApiError) {
|
|
1072
|
+
const { kind, published } = (error.errcode === void 0 || error.errcode === "M_UNKNOWN" ? void 0 : byErrcode(error.errcode)) ?? byStatus(error.status);
|
|
1073
|
+
const code = error.errcode ?? error.status;
|
|
1074
|
+
return new PlatformError(kind, error.message, {
|
|
1075
|
+
...code === void 0 ? {} : { code },
|
|
1076
|
+
...error.retryAfterMs === void 0 ? {} : { retryAfterMs: error.retryAfterMs },
|
|
1077
|
+
published,
|
|
1078
|
+
cause: error
|
|
1079
|
+
});
|
|
1080
|
+
}
|
|
1081
|
+
if (error instanceof Error && error.name === "AbortError") return new PlatformError("fatal", error.message, {
|
|
1082
|
+
published: "unknown",
|
|
1083
|
+
cause: error
|
|
1084
|
+
});
|
|
1085
|
+
if (error instanceof DOMException && error.name === "AbortError") return new PlatformError("fatal", error.message, {
|
|
1086
|
+
published: "unknown",
|
|
1087
|
+
cause: error
|
|
1088
|
+
});
|
|
1089
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
1090
|
+
return new PlatformError("retryable", `matrix request failed: ${message}`, {
|
|
1091
|
+
published: "unknown",
|
|
1092
|
+
cause: error
|
|
1093
|
+
});
|
|
1094
|
+
}
|
|
1095
|
+
// lib/types/identity.js
|
|
1096
|
+
/**
|
|
1097
|
+
* Application Service identity: register the virtual user with `m.login.application_service`, fall back to login when
|
|
1098
|
+
* the homeserver reports `M_USER_IN_USE` (the normal case after the first start), check the answered `user_id`, read
|
|
1099
|
+
* the profile and write the configured display name / avatar.
|
|
1100
|
+
*
|
|
1101
|
+
* The AS user has no password and no second login entry, so the returned user access token is the only credential the
|
|
1102
|
+
* Client-Server calls carry.
|
|
1103
|
+
*/
|
|
1104
|
+
/** The virtual user id of the configured localpart. */
|
|
1105
|
+
function matrixUserId(config) {
|
|
1106
|
+
return `@${config.id}:${config.host}`;
|
|
1107
|
+
}
|
|
1108
|
+
/** The response of a failed convenience request, recovered structurally (`ctx.http.post` throws an `HttpError`). */
|
|
1109
|
+
function responseOf(error) {
|
|
1110
|
+
if (typeof error !== "object" || error === null || !("response" in error)) return void 0;
|
|
1111
|
+
const response = error.response;
|
|
1112
|
+
return response instanceof Response ? response : void 0;
|
|
1113
|
+
}
|
|
1114
|
+
/** One JSON envelope of a failed answer. */
|
|
1115
|
+
async function envelopeOf(response) {
|
|
1116
|
+
try {
|
|
1117
|
+
const parsed = await response.clone().json();
|
|
1118
|
+
if (typeof parsed !== "object" || parsed === null) return {};
|
|
1119
|
+
const value = parsed;
|
|
1120
|
+
return {
|
|
1121
|
+
...typeof value.errcode === "string" ? { errcode: value.errcode } : {},
|
|
1122
|
+
...typeof value.error === "string" ? { error: value.error } : {}
|
|
1123
|
+
};
|
|
1124
|
+
} catch {
|
|
1125
|
+
return {};
|
|
1126
|
+
}
|
|
1127
|
+
}
|
|
1128
|
+
/** Convert a convenience-request failure into the adapter's own error type. */
|
|
1129
|
+
async function apiErrorOf(error, method) {
|
|
1130
|
+
if (error instanceof MatrixApiError) return error;
|
|
1131
|
+
const failed = responseOf(error);
|
|
1132
|
+
if (failed !== void 0) {
|
|
1133
|
+
const body = await envelopeOf(failed);
|
|
1134
|
+
return new MatrixApiError(`matrix ${method} answered ${failed.status}${body.errcode === void 0 ? "" : `: ${body.errcode}`}${body.error === void 0 ? "" : ` ${body.error}`}`, {
|
|
1135
|
+
method,
|
|
1136
|
+
status: failed.status,
|
|
1137
|
+
...body.errcode === void 0 ? {} : { errcode: body.errcode },
|
|
1138
|
+
...body.error === void 0 ? {} : { error: body.error },
|
|
1139
|
+
cause: error
|
|
1140
|
+
});
|
|
1141
|
+
}
|
|
1142
|
+
return new MatrixApiError(`matrix ${method} request failed`, {
|
|
1143
|
+
method,
|
|
1144
|
+
cause: error
|
|
1145
|
+
});
|
|
1146
|
+
}
|
|
1147
|
+
/**
|
|
1148
|
+
* Whether a failed registration means the virtual user already exists, so login is the right next step.
|
|
1149
|
+
* @param error - the failure of `POST /register`.
|
|
1150
|
+
* @returns true for a 400 `M_USER_IN_USE` (or a 400 without an envelope, which some homeservers send).
|
|
1151
|
+
*/
|
|
1152
|
+
async function isUserInUse(error) {
|
|
1153
|
+
const failed = responseOf(error);
|
|
1154
|
+
if (failed === void 0 || failed.status !== 400) return false;
|
|
1155
|
+
const body = await envelopeOf(failed);
|
|
1156
|
+
return body.errcode === void 0 || body.errcode === "M_USER_IN_USE";
|
|
1157
|
+
}
|
|
1158
|
+
/** Read the avatar bytes with the platform's own content type. */
|
|
1159
|
+
async function downloadAvatar(ctx, url) {
|
|
1160
|
+
const response = await ctx.http.get(url, { responseType: (raw) => raw });
|
|
1161
|
+
const type = response.headers.get("content-type");
|
|
1162
|
+
return {
|
|
1163
|
+
data: new Uint8Array(await response.arrayBuffer()),
|
|
1164
|
+
mime: type === null || type === "" ? "application/octet-stream" : type.split(";")[0].trim()
|
|
1165
|
+
};
|
|
1166
|
+
}
|
|
1167
|
+
/**
|
|
1168
|
+
* Establish the bot identity and store it on the adapter.
|
|
1169
|
+
*
|
|
1170
|
+
* @param bot - the adapter being connected.
|
|
1171
|
+
* @throws MatrixApiError when the credentials, the namespace or the answered identity are wrong.
|
|
1172
|
+
*/
|
|
1173
|
+
async function establishIdentity(bot) {
|
|
1174
|
+
const config = bot.config;
|
|
1175
|
+
const selfId = bot.selfId;
|
|
1176
|
+
let user;
|
|
1177
|
+
try {
|
|
1178
|
+
user = await bot.internal.register(config.id, config.asToken);
|
|
1179
|
+
} catch (error) {
|
|
1180
|
+
if (!await isUserInUse(error)) throw await apiErrorOf(error, "/client/v3/register");
|
|
1181
|
+
try {
|
|
1182
|
+
user = await bot.internal.login(config.id, config.asToken);
|
|
1183
|
+
} catch (loginError) {
|
|
1184
|
+
throw await apiErrorOf(loginError, "/client/v3/login");
|
|
1185
|
+
}
|
|
1186
|
+
}
|
|
1187
|
+
if (user.user_id !== selfId) throw new MatrixApiError(`matrix: the homeserver answered user_id "${user.user_id ?? ""}" instead of "${selfId}"; check the registration's users namespaces`, { method: "/client/v3/register" });
|
|
1188
|
+
if (user.access_token === void 0 || user.access_token === "") throw new MatrixApiError("matrix: the homeserver answered no access_token; check as_token and the registration", { method: "/client/v3/register" });
|
|
1189
|
+
bot.request.setToken(user.access_token);
|
|
1190
|
+
if (config.name !== void 0 && config.name !== null && config.name !== "") await bot.internal.setDisplayName(selfId, config.name);
|
|
1191
|
+
if (config.avatar !== void 0 && config.avatar !== null && config.avatar !== "") {
|
|
1192
|
+
const { data, mime } = await downloadAvatar(bot.ctx, config.avatar);
|
|
1193
|
+
await bot.internal.setAvatar(selfId, Buffer.from(data), mime);
|
|
1194
|
+
}
|
|
1195
|
+
const profile = await bot.internal.getProfile(selfId);
|
|
1196
|
+
bot.user = {
|
|
1197
|
+
id: selfId,
|
|
1198
|
+
name: profile.displayname ?? config.name ?? config.id,
|
|
1199
|
+
...profile.avatar_url === void 0 || profile.avatar_url === "" ? {} : { avatar: internalMediaSource(bot, profile.avatar_url) ?? profile.avatar_url },
|
|
1200
|
+
isBot: true
|
|
1201
|
+
};
|
|
1202
|
+
}
|
|
1203
|
+
// lib/types/request.js
|
|
1204
|
+
/**
|
|
1205
|
+
* Matrix Client-Server transport: one HTTP path for every endpoint the adapter calls, the standard error envelope
|
|
1206
|
+
* (`errcode` / `error`), rate-limit fields, upload bytes and authenticated media download.
|
|
1207
|
+
*
|
|
1208
|
+
* `Internal` (the migrated upstream client) keeps its upstream method bodies and calls this class through
|
|
1209
|
+
* `bot.http`; the adapter's own send/media paths call it directly, so both cannot diverge on base URL or auth.
|
|
1210
|
+
*/
|
|
1211
|
+
/** Delay asked for by a `Retry-After` response header (seconds or HTTP-date). */
|
|
1212
|
+
function retryAfterHeader(response) {
|
|
1213
|
+
const header = response.headers.get("retry-after");
|
|
1214
|
+
if (header === null) return void 0;
|
|
1215
|
+
const seconds = Number(header);
|
|
1216
|
+
if (Number.isFinite(seconds) && seconds >= 0) return seconds * 1e3;
|
|
1217
|
+
const date = Date.parse(header);
|
|
1218
|
+
if (!Number.isNaN(date)) return Math.max(0, date - Date.now());
|
|
1219
|
+
}
|
|
1220
|
+
/** The retry delay of one failed answer: the body field first, then the standard header. */
|
|
1221
|
+
function retryAfterOf(body, response) {
|
|
1222
|
+
const bodyDelay = body?.retry_after_ms;
|
|
1223
|
+
if (typeof bodyDelay === "number" && Number.isFinite(bodyDelay) && bodyDelay >= 0) return bodyDelay;
|
|
1224
|
+
return retryAfterHeader(response);
|
|
1225
|
+
}
|
|
1226
|
+
/** Whether a caught value is an abort error, including the `DOMException` a signal produces. */
|
|
1227
|
+
function isAbortError(value) {
|
|
1228
|
+
return (value instanceof Error || value instanceof DOMException) && value.name === "AbortError";
|
|
1229
|
+
}
|
|
1230
|
+
/** The abort reason carried by a failure, unwrapping a transport error's `cause` chain. */
|
|
1231
|
+
function abortReasonOf(error) {
|
|
1232
|
+
if (isAbortError(error)) return error;
|
|
1233
|
+
if (typeof error === "object" && error !== null && "cause" in error) return abortReasonOf(error.cause);
|
|
1234
|
+
}
|
|
1235
|
+
/** A message for a failed call, naming status and the server's own error text when it sent one. */
|
|
1236
|
+
function failureMessage(method, path, status, body) {
|
|
1237
|
+
const code = typeof body?.errcode === "string" ? body.errcode : void 0;
|
|
1238
|
+
const detail = typeof body?.error === "string" ? body.error : void 0;
|
|
1239
|
+
return `matrix ${method} ${path} answered ${status}${code === void 0 && detail === void 0 ? "" : `: ${[code, detail].filter((part) => part !== void 0).join(" ")}`}`;
|
|
1240
|
+
}
|
|
1241
|
+
/**
|
|
1242
|
+
* The Client-Server client of one bot.
|
|
1243
|
+
*
|
|
1244
|
+
* Requests are relative to the homeserver root with `/_matrix` already appended. The access token is set after
|
|
1245
|
+
* `register`/`login`; `register`/`login` themselves go through `ctx.http` with the application service token.
|
|
1246
|
+
*/
|
|
1247
|
+
var MatrixClient = class {
|
|
1248
|
+
ctx;
|
|
1249
|
+
endpoint;
|
|
1250
|
+
/** The user access token every Client-Server call carries; empty until `connect` logged in. */
|
|
1251
|
+
token;
|
|
1252
|
+
/** @param ctx - context whose `http` service performs requests. @param endpoint - homeserver root plus `/_matrix`. */
|
|
1253
|
+
constructor(ctx, endpoint) {
|
|
1254
|
+
this.ctx = ctx;
|
|
1255
|
+
this.endpoint = endpoint;
|
|
1256
|
+
}
|
|
1257
|
+
/** Set the user access token minted by `m.login.application_service`. */
|
|
1258
|
+
setToken(token) {
|
|
1259
|
+
this.token = token;
|
|
1260
|
+
}
|
|
1261
|
+
/** The absolute URL of one endpoint path. */
|
|
1262
|
+
url(path) {
|
|
1263
|
+
return `${this.endpoint}${path.startsWith("/") ? path : `/${path}`}`;
|
|
1264
|
+
}
|
|
1265
|
+
/**
|
|
1266
|
+
* Call one GET endpoint.
|
|
1267
|
+
* @param path - endpoint below the Matrix root.
|
|
1268
|
+
* @param options - query parameters, headers and cancellation.
|
|
1269
|
+
* @returns the parsed JSON answer.
|
|
1270
|
+
*/
|
|
1271
|
+
async get(path, options = {}) {
|
|
1272
|
+
return await this.decode(await this.send("GET", path, void 0, options), "GET", path);
|
|
1273
|
+
}
|
|
1274
|
+
/**
|
|
1275
|
+
* Call one PUT endpoint.
|
|
1276
|
+
* @param path - endpoint below the Matrix root.
|
|
1277
|
+
* @param data - JSON body (`t.rn` events, profile writes).
|
|
1278
|
+
* @param options - query parameters, headers and cancellation.
|
|
1279
|
+
* @returns the parsed JSON answer.
|
|
1280
|
+
*/
|
|
1281
|
+
async put(path, data, options = {}) {
|
|
1282
|
+
return await this.decode(await this.send("PUT", path, data, options), "PUT", path);
|
|
1283
|
+
}
|
|
1284
|
+
/**
|
|
1285
|
+
* Call one POST endpoint.
|
|
1286
|
+
* @param path - endpoint below the Matrix root.
|
|
1287
|
+
* @param data - JSON body or raw bytes (upload).
|
|
1288
|
+
* @param options - query parameters, headers and cancellation.
|
|
1289
|
+
* @returns the parsed JSON answer.
|
|
1290
|
+
*/
|
|
1291
|
+
async post(path, data, options = {}) {
|
|
1292
|
+
return await this.decode(await this.send("POST", path, data, options), "POST", path);
|
|
1293
|
+
}
|
|
1294
|
+
/**
|
|
1295
|
+
* Upload bytes to the media repository.
|
|
1296
|
+
* @param name - file name sent as the `filename` query parameter.
|
|
1297
|
+
* @param data - the bytes.
|
|
1298
|
+
* @param mimetype - `content-type` of the bytes, when known.
|
|
1299
|
+
* @param signal - cancellation.
|
|
1300
|
+
* @returns the upload answer (`content_uri` on success).
|
|
1301
|
+
*/
|
|
1302
|
+
async upload(name, data, mimetype, signal) {
|
|
1303
|
+
return await this.post(`/media/v3/upload?filename=${encodeURIComponent(name)}`, data, {
|
|
1304
|
+
...mimetype === void 0 ? {} : { headers: { "content-type": mimetype } },
|
|
1305
|
+
...signal === void 0 ? {} : { signal }
|
|
1306
|
+
});
|
|
1307
|
+
}
|
|
1308
|
+
/**
|
|
1309
|
+
* Download one media item through the authenticated endpoint (v1.11's recommended path).
|
|
1310
|
+
* @param serverName - the server name of the `mxc://` URI.
|
|
1311
|
+
* @param mediaId - the media id of the `mxc://` URI.
|
|
1312
|
+
* @param fileName - optional file name path segment.
|
|
1313
|
+
* @param signal - cancellation.
|
|
1314
|
+
* @returns the platform's answer, body included.
|
|
1315
|
+
*/
|
|
1316
|
+
async download(serverName, mediaId, fileName, signal) {
|
|
1317
|
+
const suffix = fileName === void 0 ? "" : `/${fileName}`;
|
|
1318
|
+
return await this.send("GET", `/client/v1/media/download/${serverName}/${mediaId}${suffix}`, void 0, signal === void 0 ? {} : { signal });
|
|
1319
|
+
}
|
|
1320
|
+
/** Perform one request and return the raw answer; transport failures become `MatrixApiError`s. */
|
|
1321
|
+
async send(method, path, data, options) {
|
|
1322
|
+
const headers = { ...options.headers };
|
|
1323
|
+
if (this.token !== void 0) headers.authorization = `Bearer ${this.token}`;
|
|
1324
|
+
let response;
|
|
1325
|
+
try {
|
|
1326
|
+
response = await this.ctx.http(this.url(path), {
|
|
1327
|
+
method,
|
|
1328
|
+
...data === void 0 ? {} : { data },
|
|
1329
|
+
...options.params === void 0 ? {} : { params: options.params },
|
|
1330
|
+
headers,
|
|
1331
|
+
...options.signal === void 0 ? {} : { signal: options.signal }
|
|
1332
|
+
});
|
|
1333
|
+
} catch (cause) {
|
|
1334
|
+
if (options.signal?.aborted === true) throw options.signal.reason;
|
|
1335
|
+
const abort = abortReasonOf(cause);
|
|
1336
|
+
if (abort !== void 0) throw abort;
|
|
1337
|
+
throw new MatrixApiError(`matrix ${method} ${path} request failed`, {
|
|
1338
|
+
method,
|
|
1339
|
+
path,
|
|
1340
|
+
cause
|
|
1341
|
+
});
|
|
1342
|
+
}
|
|
1343
|
+
if (options.signal?.aborted === true) throw options.signal.reason;
|
|
1344
|
+
return response;
|
|
1345
|
+
}
|
|
1346
|
+
/** Decode one answer: JSON object on success, `MatrixApiError` for every refusal. */
|
|
1347
|
+
async decode(response, method, path) {
|
|
1348
|
+
const status = response.status;
|
|
1349
|
+
let text;
|
|
1350
|
+
try {
|
|
1351
|
+
text = await response.text();
|
|
1352
|
+
} catch (cause) {
|
|
1353
|
+
throw new MatrixApiError("matrix answered without a readable body", {
|
|
1354
|
+
status,
|
|
1355
|
+
cause
|
|
1356
|
+
});
|
|
1357
|
+
}
|
|
1358
|
+
let parsed;
|
|
1359
|
+
if (text !== "") try {
|
|
1360
|
+
parsed = JSON.parse(text);
|
|
1361
|
+
} catch {
|
|
1362
|
+
parsed = void 0;
|
|
1363
|
+
}
|
|
1364
|
+
const body = typeof parsed === "object" && parsed !== null ? parsed : void 0;
|
|
1365
|
+
if (status >= 400) {
|
|
1366
|
+
const retryAfterMs = retryAfterOf(body, response);
|
|
1367
|
+
throw new MatrixApiError(failureMessage(method, path, status, body), {
|
|
1368
|
+
status,
|
|
1369
|
+
...typeof body?.errcode === "string" ? { errcode: body.errcode } : {},
|
|
1370
|
+
...typeof body?.error === "string" ? { error: body.error } : {},
|
|
1371
|
+
...retryAfterMs === void 0 ? {} : { retryAfterMs }
|
|
1372
|
+
});
|
|
1373
|
+
}
|
|
1374
|
+
if (parsed === void 0) throw new MatrixApiError(`matrix answered ${status} without a JSON body`, { status });
|
|
1375
|
+
return parsed;
|
|
1376
|
+
}
|
|
1377
|
+
};
|
|
1378
|
+
// lib/types/rooms.js
|
|
1379
|
+
/**
|
|
1380
|
+
* The room cache and the one-shot full-state `/sync` that fills it.
|
|
1381
|
+
*
|
|
1382
|
+
* Application Service pushes carry events only: no room list, name, member set or summary. `connect` therefore asks the
|
|
1383
|
+
* homeserver for one full-state sync (`full_state=true` makes the answer immediate, so it is a query, not a poll),
|
|
1384
|
+
* uses the joined rooms for names/members/summaries/`m.direct`/encryption markers, and joins the invited rooms when
|
|
1385
|
+
* `autoJoin` is on. The same query runs once more after the bot joins a room on its own.
|
|
1386
|
+
*
|
|
1387
|
+
* A room is reported as direct when the bot's own `m.direct` names it, else when the summary says two joined members,
|
|
1388
|
+
* else when the observed joined members are exactly the bot and one other user. Everything else is a group.
|
|
1389
|
+
*/
|
|
1390
|
+
/** The rooms the bot's own `m.direct` account data names. */
|
|
1391
|
+
function directRoomIds(sync) {
|
|
1392
|
+
const out = [];
|
|
1393
|
+
for (const event of sync.account_data?.events ?? []) {
|
|
1394
|
+
if (event.type !== "m.direct") continue;
|
|
1395
|
+
const content = event.content;
|
|
1396
|
+
for (const value of Object.values(content)) {
|
|
1397
|
+
if (!Array.isArray(value)) continue;
|
|
1398
|
+
for (const roomId of value) if (typeof roomId === "string") out.push(roomId);
|
|
1399
|
+
}
|
|
1400
|
+
}
|
|
1401
|
+
return out;
|
|
1402
|
+
}
|
|
1403
|
+
/** In-memory room state shared by decode, enumeration and member reads. */
|
|
1404
|
+
var RoomCache = class {
|
|
1405
|
+
rooms = /* @__PURE__ */ new Map();
|
|
1406
|
+
directRooms = /* @__PURE__ */ new Set();
|
|
1407
|
+
/** The cached state of one room, created on first use. */
|
|
1408
|
+
room(roomId) {
|
|
1409
|
+
let room = this.rooms.get(roomId);
|
|
1410
|
+
if (room === void 0) {
|
|
1411
|
+
room = {
|
|
1412
|
+
members: /* @__PURE__ */ new Map(),
|
|
1413
|
+
encrypted: false
|
|
1414
|
+
};
|
|
1415
|
+
this.rooms.set(roomId, room);
|
|
1416
|
+
}
|
|
1417
|
+
return room;
|
|
1418
|
+
}
|
|
1419
|
+
/** The room name last seen, if any. */
|
|
1420
|
+
nameOf(roomId) {
|
|
1421
|
+
return this.rooms.get(roomId)?.name;
|
|
1422
|
+
}
|
|
1423
|
+
/** The display name last seen for one member of a room. */
|
|
1424
|
+
displayNameOf(roomId, userId) {
|
|
1425
|
+
return this.rooms.get(roomId)?.members.get(userId)?.displayname;
|
|
1426
|
+
}
|
|
1427
|
+
/** Whether a room's state says it enabled end-to-end encryption. */
|
|
1428
|
+
isEncrypted(roomId) {
|
|
1429
|
+
return this.rooms.get(roomId)?.encrypted === true;
|
|
1430
|
+
}
|
|
1431
|
+
/**
|
|
1432
|
+
* Record that a room is encrypted.
|
|
1433
|
+
* @param roomId - the room.
|
|
1434
|
+
* @returns true when this is the first observation, so the caller logs its warning once.
|
|
1435
|
+
*/
|
|
1436
|
+
markEncrypted(roomId) {
|
|
1437
|
+
const room = this.room(roomId);
|
|
1438
|
+
if (room.encrypted) return false;
|
|
1439
|
+
room.encrypted = true;
|
|
1440
|
+
return true;
|
|
1441
|
+
}
|
|
1442
|
+
/** Record one `m.room.name` event. */
|
|
1443
|
+
setName(roomId, name) {
|
|
1444
|
+
this.room(roomId).name = name;
|
|
1445
|
+
}
|
|
1446
|
+
/** Record one `m.room.member` event. */
|
|
1447
|
+
applyMember(roomId, userId, membership, displayname) {
|
|
1448
|
+
const room = this.room(roomId);
|
|
1449
|
+
const member = room.members.get(userId) ?? { joined: false };
|
|
1450
|
+
member.joined = membership === "join";
|
|
1451
|
+
if (displayname !== void 0) member.displayname = displayname;
|
|
1452
|
+
room.members.set(userId, member);
|
|
1453
|
+
}
|
|
1454
|
+
/** The joined members of one room, in insertion order. */
|
|
1455
|
+
joinedMembers(roomId) {
|
|
1456
|
+
const room = this.rooms.get(roomId);
|
|
1457
|
+
if (room === void 0) return [];
|
|
1458
|
+
return [...room.members].filter(([, member]) => member.joined).map(([userId]) => userId);
|
|
1459
|
+
}
|
|
1460
|
+
/**
|
|
1461
|
+
* Whether a room is a direct chat.
|
|
1462
|
+
* @param roomId - the room.
|
|
1463
|
+
* @param selfId - the bot's Matrix user id.
|
|
1464
|
+
* @returns true for a room the judgement chain reports as direct.
|
|
1465
|
+
*/
|
|
1466
|
+
isDirect(roomId, selfId) {
|
|
1467
|
+
if (this.directRooms.has(roomId)) return true;
|
|
1468
|
+
const room = this.rooms.get(roomId);
|
|
1469
|
+
if (room === void 0) return false;
|
|
1470
|
+
if (room.joinedMemberCount === 2) return true;
|
|
1471
|
+
return [...room.members.values()].filter((member) => member.joined).length === 2 && room.members.get(selfId)?.joined === true;
|
|
1472
|
+
}
|
|
1473
|
+
/** Record one state event that arrived by push. */
|
|
1474
|
+
applyStateEvent(roomId, type, stateKey, content) {
|
|
1475
|
+
switch (type) {
|
|
1476
|
+
case "m.room.name":
|
|
1477
|
+
if (typeof content.name === "string") this.setName(roomId, content.name);
|
|
1478
|
+
return;
|
|
1479
|
+
case "m.room.member":
|
|
1480
|
+
if (stateKey !== void 0) this.applyMember(roomId, stateKey, typeof content.membership === "string" ? content.membership : void 0, typeof content.displayname === "string" ? content.displayname : void 0);
|
|
1481
|
+
return;
|
|
1482
|
+
case "m.room.encryption":
|
|
1483
|
+
this.markEncrypted(roomId);
|
|
1484
|
+
return;
|
|
1485
|
+
}
|
|
1486
|
+
}
|
|
1487
|
+
/**
|
|
1488
|
+
* Apply one full-state sync answer.
|
|
1489
|
+
* @param sync - the answer of `GET /client/v3/sync?full_state=true`.
|
|
1490
|
+
* @param selfId - the bot's Matrix user id.
|
|
1491
|
+
* @returns the rooms that invited the bot, in answer order.
|
|
1492
|
+
*/
|
|
1493
|
+
applySync(sync, selfId) {
|
|
1494
|
+
for (const roomId of directRoomIds(sync)) this.directRooms.add(roomId);
|
|
1495
|
+
for (const [roomId, joined] of Object.entries(sync.rooms?.join ?? {})) {
|
|
1496
|
+
const room = this.room(roomId);
|
|
1497
|
+
for (const event of joined.state?.events ?? []) this.applyStateEvent(roomId, event.type, event.state_key, event.content);
|
|
1498
|
+
const count = joined.summary?.["m.joined_member_count"];
|
|
1499
|
+
if (typeof count === "number") room.joinedMemberCount = count;
|
|
1500
|
+
}
|
|
1501
|
+
const invites = [];
|
|
1502
|
+
for (const [roomId, invited] of Object.entries(sync.rooms?.invite ?? {})) {
|
|
1503
|
+
let invitedSelf = false;
|
|
1504
|
+
for (const event of invited.invite_state?.events ?? []) {
|
|
1505
|
+
this.applyStateEvent(roomId, event.type, event.state_key, event.content);
|
|
1506
|
+
if (event.type === "m.room.member" && event.state_key === selfId && event.content.membership === "invite") invitedSelf = true;
|
|
1507
|
+
}
|
|
1508
|
+
if (invitedSelf) invites.push(roomId);
|
|
1509
|
+
}
|
|
1510
|
+
return invites;
|
|
1511
|
+
}
|
|
1512
|
+
};
|
|
1513
|
+
/**
|
|
1514
|
+
* Run the one-shot full-state sync and apply it.
|
|
1515
|
+
*
|
|
1516
|
+
* The response's `next_batch` is deliberately dropped: an Application Service has no cursor, and the timeline of this
|
|
1517
|
+
* query is history that the host's store already owns.
|
|
1518
|
+
*
|
|
1519
|
+
* @param internal - the room enumerator (the migrated `Internal`).
|
|
1520
|
+
* @param cache - the room cache to fill.
|
|
1521
|
+
* @param selfId - the bot's Matrix user id.
|
|
1522
|
+
* @returns the rooms that invited the bot.
|
|
1523
|
+
*/
|
|
1524
|
+
async function enumerateRooms(internal, cache, selfId) {
|
|
1525
|
+
const sync = await internal.sync(true);
|
|
1526
|
+
return cache.applySync(sync, selfId);
|
|
1527
|
+
}
|
|
1528
|
+
// lib/types/send.js
|
|
1529
|
+
/**
|
|
1530
|
+
* Outbound hooks: send, delete, reaction, members and message reads.
|
|
1531
|
+
*
|
|
1532
|
+
* Every write is one `PUT /rooms/{roomId}/send|redact/...` with a transaction id; `txtId` is derived from the caller's
|
|
1533
|
+
* idempotency key when there is one (Matrix deduplicates a retransmission with the same id), else from a per-process
|
|
1534
|
+
* random base plus a counter. Matrix returns only an `event_id`, so a published part carries no platform timestamp.
|
|
1535
|
+
*/
|
|
1536
|
+
/** The transaction id of one request: idempotency key first, counter otherwise. */
|
|
1537
|
+
function txnIdOf(deps, ctx) {
|
|
1538
|
+
const key = ctx.options.idempotencyKey;
|
|
1539
|
+
if (key !== void 0) return createHash("sha256").update(`${key}#${ctx.index}`).digest("hex").slice(0, 32);
|
|
1540
|
+
return String(deps.nextTxn());
|
|
1541
|
+
}
|
|
1542
|
+
/**
|
|
1543
|
+
* Whether a retry of one send is deduplicated by Matrix. Only a call with an idempotency key is: the spec returns the
|
|
1544
|
+
* first answer for a retransmission of the same `(endpoint, txnId)` pair.
|
|
1545
|
+
*/
|
|
1546
|
+
function idempotentSend(_target, ctx) {
|
|
1547
|
+
return ctx.options.idempotencyKey !== void 0;
|
|
1548
|
+
}
|
|
1549
|
+
/** The event content of one serialized payload. */
|
|
1550
|
+
function eventContent(payload) {
|
|
1551
|
+
const relates = payload.relates;
|
|
1552
|
+
const common = {
|
|
1553
|
+
"m.mentions": payload.mentions,
|
|
1554
|
+
...relates === void 0 ? {} : { "m.relates_to": relates }
|
|
1555
|
+
};
|
|
1556
|
+
if (payload.kind === "text") return {
|
|
1557
|
+
msgtype: "m.text",
|
|
1558
|
+
body: payload.body,
|
|
1559
|
+
...payload.html === void 0 ? {} : {
|
|
1560
|
+
format: "org.matrix.custom.html",
|
|
1561
|
+
formatted_body: payload.html
|
|
1562
|
+
},
|
|
1563
|
+
...common
|
|
1564
|
+
};
|
|
1565
|
+
return {
|
|
1566
|
+
msgtype: payload.msgtype,
|
|
1567
|
+
body: payload.body,
|
|
1568
|
+
filename: payload.body,
|
|
1569
|
+
url: payload.url,
|
|
1570
|
+
...payload.info === void 0 ? {} : { info: payload.info },
|
|
1571
|
+
...common
|
|
1572
|
+
};
|
|
1573
|
+
}
|
|
1574
|
+
/** The published part of one accepted event. */
|
|
1575
|
+
function partOf(deps, payload, eventId) {
|
|
1576
|
+
if (typeof eventId !== "string" || eventId === "") throw new PlatformError("invalid", "matrix: the homeserver answered without an event_id", { published: "unknown" });
|
|
1577
|
+
const thread = payload.thread;
|
|
1578
|
+
const referrer = {
|
|
1579
|
+
roomId: payload.roomId,
|
|
1580
|
+
eventId,
|
|
1581
|
+
sender: deps.selfId,
|
|
1582
|
+
...thread === void 0 ? {} : { threadRoot: thread.root }
|
|
1583
|
+
};
|
|
1584
|
+
return {
|
|
1585
|
+
id: eventId,
|
|
1586
|
+
kind: "message",
|
|
1587
|
+
time: Date.now(),
|
|
1588
|
+
...thread === void 0 ? {} : { thread: {
|
|
1589
|
+
id: thread.root,
|
|
1590
|
+
root: thread.root
|
|
1591
|
+
} },
|
|
1592
|
+
referrer
|
|
1593
|
+
};
|
|
1594
|
+
}
|
|
1595
|
+
/**
|
|
1596
|
+
* Send one serialized payload.
|
|
1597
|
+
* @param deps - adapter services.
|
|
1598
|
+
* @param payload - the serialized payload.
|
|
1599
|
+
* @param _target - the chat being published to (the payload already names it).
|
|
1600
|
+
* @param ctx - core send context (signal, part index, idempotency key).
|
|
1601
|
+
* @returns the published part.
|
|
1602
|
+
*/
|
|
1603
|
+
async function sendPayload(deps, payload, _target, ctx) {
|
|
1604
|
+
const txn = txnIdOf(deps, ctx);
|
|
1605
|
+
const path = `/client/v3/rooms/${payload.roomId}/send/m.room.message/${txn}`;
|
|
1606
|
+
return partOf(deps, payload, (await deps.client.put(path, eventContent(payload), ctx.options.signal === void 0 ? {} : { signal: ctx.options.signal })).event_id);
|
|
1607
|
+
}
|
|
1608
|
+
/**
|
|
1609
|
+
* Redact one published event.
|
|
1610
|
+
* @param deps - adapter services.
|
|
1611
|
+
* @param part - the part to delete.
|
|
1612
|
+
* @param handle - the message the part belongs to (its target names the room).
|
|
1613
|
+
*/
|
|
1614
|
+
async function deletePart(deps, part, handle) {
|
|
1615
|
+
if (part.id === "") throw new PlatformError("invalid", "matrix: an empty event id cannot be redacted", { published: "no" });
|
|
1616
|
+
await deps.client.put(`/client/v3/rooms/${handle.target.chat.id}/redact/${part.id}/${deps.nextTxn()}`, {});
|
|
1617
|
+
}
|
|
1618
|
+
/**
|
|
1619
|
+
* Add an annotation (`m.reaction`) to one message.
|
|
1620
|
+
* @param deps - adapter services.
|
|
1621
|
+
* @param message - the message to react to.
|
|
1622
|
+
* @param emoji - the annotation key, passed through as written (`:shortcode:` included).
|
|
1623
|
+
*/
|
|
1624
|
+
async function createReaction(deps, message, emoji) {
|
|
1625
|
+
await deps.client.put(`/client/v3/rooms/${message.chat.id}/send/m.reaction/${deps.nextTxn()}`, { "m.relates_to": {
|
|
1626
|
+
rel_type: "m.annotation",
|
|
1627
|
+
event_id: message.id,
|
|
1628
|
+
key: emoji
|
|
1629
|
+
} });
|
|
1630
|
+
}
|
|
1631
|
+
/**
|
|
1632
|
+
* List the joined members of a room.
|
|
1633
|
+
*
|
|
1634
|
+
* The room state endpoint returns the whole member set at once, so there is no cursor; `limit` truncates the page.
|
|
1635
|
+
*
|
|
1636
|
+
* @param deps - adapter services.
|
|
1637
|
+
* @param chat - the room.
|
|
1638
|
+
* @param _cursor - ignored; the state read is one full page.
|
|
1639
|
+
* @param limit - page size bound.
|
|
1640
|
+
* @returns the joined members, each with the display name its membership event carried.
|
|
1641
|
+
*/
|
|
1642
|
+
async function members(deps, chat, _cursor, limit) {
|
|
1643
|
+
const state = await deps.client.get(`/client/v3/rooms/${chat.id}/state`);
|
|
1644
|
+
const data = [];
|
|
1645
|
+
for (const event of state) {
|
|
1646
|
+
if (event.type !== "m.room.member" || event.state_key === void 0) continue;
|
|
1647
|
+
const content = event.content;
|
|
1648
|
+
if (content.membership !== "join") continue;
|
|
1649
|
+
if (content.displayname !== void 0) deps.rooms.applyMember(chat.id, event.state_key, "join", content.displayname);
|
|
1650
|
+
data.push({
|
|
1651
|
+
id: event.state_key,
|
|
1652
|
+
...content.displayname === void 0 ? {} : { name: content.displayname },
|
|
1653
|
+
isBot: deps.isBot(event.state_key)
|
|
1654
|
+
});
|
|
1655
|
+
}
|
|
1656
|
+
return { data: limit === void 0 ? data : data.slice(0, Math.max(0, limit)) };
|
|
1657
|
+
}
|
|
1658
|
+
/**
|
|
1659
|
+
* Read one message by id.
|
|
1660
|
+
* @param deps - adapter services.
|
|
1661
|
+
* @param chat - the chat the caller asked about; the decoded message reports it unchanged.
|
|
1662
|
+
* @param id - the event id.
|
|
1663
|
+
* @returns the decoded message.
|
|
1664
|
+
*/
|
|
1665
|
+
async function getMessage(deps, chat, id) {
|
|
1666
|
+
const event = await deps.client.get(`/client/v3/rooms/${chat.id}/event/${id}`);
|
|
1667
|
+
if (event.type !== "m.room.message") throw new PlatformError("not-found", `matrix: event ${id} in ${chat.id} is not a message`, { published: "no" });
|
|
1668
|
+
const content = event.content;
|
|
1669
|
+
if (content.msgtype === void 0 || !MESSAGE_TYPES.has(content.msgtype)) throw new PlatformError("not-found", `matrix: event ${id} in ${chat.id} is not a readable message`, { published: "no" });
|
|
1670
|
+
return deps.decode(chat, event);
|
|
1671
|
+
}
|
|
1672
|
+
// lib/types/modes/shared.js
|
|
1673
|
+
/**
|
|
1674
|
+
* The single `html` mode's node, draft and payload types, HTML escaping, media promotion, reply/thread relations and
|
|
1675
|
+
* payload assembly.
|
|
1676
|
+
*
|
|
1677
|
+
* A Matrix message is either one `m.text` event with `body` + `formatted_body`, or one media event per media element.
|
|
1678
|
+
* Every handler therefore returns an HTML fragment and its plain-text projection from the same traversal, so the two
|
|
1679
|
+
* sides cannot drift; `assemble` flushes a text draft around each media element.
|
|
1680
|
+
*/
|
|
1681
|
+
/** Escape character data of `formatted_body`. */
|
|
1682
|
+
function escapeHtml(text) {
|
|
1683
|
+
return text.replaceAll("&", "&").replaceAll("<", "<").replaceAll(">", ">");
|
|
1684
|
+
}
|
|
1685
|
+
/** Escape one HTML attribute value (double-quoted). */
|
|
1686
|
+
function escapeAttribute(text) {
|
|
1687
|
+
return escapeHtml(text).replaceAll("\"", """);
|
|
1688
|
+
}
|
|
1689
|
+
/** One inline node. */
|
|
1690
|
+
function htmlNode(html, text, mentions) {
|
|
1691
|
+
return {
|
|
1692
|
+
type: "html",
|
|
1693
|
+
html,
|
|
1694
|
+
text,
|
|
1695
|
+
...mentions === void 0 || mentions.length === 0 ? {} : { mentions }
|
|
1696
|
+
};
|
|
1697
|
+
}
|
|
1698
|
+
/** One mention node per collected user and one for the room mention. */
|
|
1699
|
+
function mentionNodes(set) {
|
|
1700
|
+
return [...set.users.map((user) => ({ user })), ...set.room ? [{ room: true }] : []];
|
|
1701
|
+
}
|
|
1702
|
+
/**
|
|
1703
|
+
* Split rendered children into one inline run and the media nodes that follow it.
|
|
1704
|
+
* @param nodes - rendered children.
|
|
1705
|
+
* @returns the concatenated HTML/text, the collected mentions and the media nodes, in source order.
|
|
1706
|
+
*/
|
|
1707
|
+
function inlineRun(nodes) {
|
|
1708
|
+
let html = "";
|
|
1709
|
+
let text = "";
|
|
1710
|
+
const mentions = createMentionSet();
|
|
1711
|
+
const rest = [];
|
|
1712
|
+
for (const node of nodes) {
|
|
1713
|
+
if (node.type === "media") {
|
|
1714
|
+
rest.push(node);
|
|
1715
|
+
continue;
|
|
1716
|
+
}
|
|
1717
|
+
html += node.html;
|
|
1718
|
+
text += node.text;
|
|
1719
|
+
for (const mention of node.mentions ?? []) addMention(mentions, mention);
|
|
1720
|
+
}
|
|
1721
|
+
return {
|
|
1722
|
+
html,
|
|
1723
|
+
text,
|
|
1724
|
+
mentions,
|
|
1725
|
+
rest
|
|
1726
|
+
};
|
|
1727
|
+
}
|
|
1728
|
+
/**
|
|
1729
|
+
* Wrap the inline text of rendered children in one HTML tag; media of the subtree follows the wrapper.
|
|
1730
|
+
* @param tag - the HTML tag name.
|
|
1731
|
+
* @param nodes - rendered children.
|
|
1732
|
+
* @param textSuffix - plain-text separator this block adds after its inline text.
|
|
1733
|
+
* @returns the wrapper (when it has text) and the media nodes.
|
|
1734
|
+
*/
|
|
1735
|
+
function inlineWrapper(tag, nodes, textSuffix = "") {
|
|
1736
|
+
const { html, text, mentions, rest } = inlineRun(nodes);
|
|
1737
|
+
const out = [];
|
|
1738
|
+
if (html !== "") out.push(htmlNode(`<${tag}>${html}</${tag}>`, text + textSuffix, mentionNodes(mentions)));
|
|
1739
|
+
out.push(...rest);
|
|
1740
|
+
return out;
|
|
1741
|
+
}
|
|
1742
|
+
/**
|
|
1743
|
+
* Turn one media element into its node.
|
|
1744
|
+
*
|
|
1745
|
+
* Matrix clients render inline `mxc:` images inconsistently and a media message is the standard presentation, so every
|
|
1746
|
+
* media element becomes its own event. Media standing in phrasing content is reported as `moved`: nothing is lost,
|
|
1747
|
+
* only repositioned.
|
|
1748
|
+
*
|
|
1749
|
+
* @param el - one of `img`/`audio`/`video`/`file`.
|
|
1750
|
+
* @param ctx - render context of the mode.
|
|
1751
|
+
* @returns the media node, to be published after the text run it was found in.
|
|
1752
|
+
*/
|
|
1753
|
+
function mediaNode(el, ctx) {
|
|
1754
|
+
const parent = ctx.ancestors[ctx.ancestors.length - 1];
|
|
1755
|
+
if (parent !== void 0 && isPhrasingContainer(parent.type)) ctx.report.moved.push({
|
|
1756
|
+
tag: el.type,
|
|
1757
|
+
reason: "matrix-media-split",
|
|
1758
|
+
path: ctx.stableId(el)
|
|
1759
|
+
});
|
|
1760
|
+
switch (el.type) {
|
|
1761
|
+
case "img": return {
|
|
1762
|
+
type: "media",
|
|
1763
|
+
tag: "img",
|
|
1764
|
+
ref: ctx.resource("image", el.attrs.src, {
|
|
1765
|
+
...el.attrs.alt === void 0 ? {} : { name: el.attrs.alt },
|
|
1766
|
+
...el.attrs.width === void 0 ? {} : { width: el.attrs.width },
|
|
1767
|
+
...el.attrs.height === void 0 ? {} : { height: el.attrs.height }
|
|
1768
|
+
}),
|
|
1769
|
+
...el.attrs.alt === void 0 ? {} : { name: el.attrs.alt },
|
|
1770
|
+
...el.attrs.width === void 0 ? {} : { width: el.attrs.width },
|
|
1771
|
+
...el.attrs.height === void 0 ? {} : { height: el.attrs.height }
|
|
1772
|
+
};
|
|
1773
|
+
case "audio": return {
|
|
1774
|
+
type: "media",
|
|
1775
|
+
tag: "audio",
|
|
1776
|
+
ref: ctx.resource("audio", el.attrs.src, {
|
|
1777
|
+
...el.attrs.name === void 0 ? {} : { name: el.attrs.name },
|
|
1778
|
+
...el.attrs.duration === void 0 ? {} : { duration: el.attrs.duration }
|
|
1779
|
+
}),
|
|
1780
|
+
...el.attrs.name === void 0 ? {} : { name: el.attrs.name },
|
|
1781
|
+
...el.attrs.duration === void 0 ? {} : { duration: el.attrs.duration }
|
|
1782
|
+
};
|
|
1783
|
+
case "video": return {
|
|
1784
|
+
type: "media",
|
|
1785
|
+
tag: "video",
|
|
1786
|
+
ref: ctx.resource("video", el.attrs.src, {
|
|
1787
|
+
...el.attrs.name === void 0 ? {} : { name: el.attrs.name },
|
|
1788
|
+
...el.attrs.duration === void 0 ? {} : { duration: el.attrs.duration }
|
|
1789
|
+
}),
|
|
1790
|
+
...el.attrs.name === void 0 ? {} : { name: el.attrs.name },
|
|
1791
|
+
...el.attrs.duration === void 0 ? {} : { duration: el.attrs.duration }
|
|
1792
|
+
};
|
|
1793
|
+
case "file": return {
|
|
1794
|
+
type: "media",
|
|
1795
|
+
tag: "file",
|
|
1796
|
+
ref: ctx.resource("file", el.attrs.src, el.attrs.name === void 0 ? {} : { name: el.attrs.name }),
|
|
1797
|
+
...el.attrs.name === void 0 ? {} : { name: el.attrs.name }
|
|
1798
|
+
};
|
|
1799
|
+
}
|
|
1800
|
+
}
|
|
1801
|
+
/** The Matrix `msgtype` of one media tag. */
|
|
1802
|
+
function msgtypeOf(tag) {
|
|
1803
|
+
switch (tag) {
|
|
1804
|
+
case "img": return "m.image";
|
|
1805
|
+
case "audio": return "m.audio";
|
|
1806
|
+
case "video": return "m.video";
|
|
1807
|
+
case "file": return "m.file";
|
|
1808
|
+
}
|
|
1809
|
+
}
|
|
1810
|
+
/**
|
|
1811
|
+
* Fold a node stream into platform events: a text run around each media node.
|
|
1812
|
+
* @param nodes - rendered nodes, in source order.
|
|
1813
|
+
* @returns the drafts to publish, at least one for any content a handler produced.
|
|
1814
|
+
*/
|
|
1815
|
+
function assembleDrafts(nodes) {
|
|
1816
|
+
const drafts = [];
|
|
1817
|
+
let html = "";
|
|
1818
|
+
let text = "";
|
|
1819
|
+
let mentions = createMentionSet();
|
|
1820
|
+
const flush = () => {
|
|
1821
|
+
if (html.trim() === "" && text.trim() === "") {
|
|
1822
|
+
html = "";
|
|
1823
|
+
text = "";
|
|
1824
|
+
mentions = createMentionSet();
|
|
1825
|
+
return;
|
|
1826
|
+
}
|
|
1827
|
+
drafts.push({
|
|
1828
|
+
kind: "text",
|
|
1829
|
+
html,
|
|
1830
|
+
text,
|
|
1831
|
+
mentions: mentionWire(mentions)
|
|
1832
|
+
});
|
|
1833
|
+
html = "";
|
|
1834
|
+
text = "";
|
|
1835
|
+
mentions = createMentionSet();
|
|
1836
|
+
};
|
|
1837
|
+
for (const node of nodes) {
|
|
1838
|
+
if (node.type === "media") {
|
|
1839
|
+
flush();
|
|
1840
|
+
drafts.push({
|
|
1841
|
+
kind: "media",
|
|
1842
|
+
tag: node.tag,
|
|
1843
|
+
ref: node.ref,
|
|
1844
|
+
...node.name === void 0 ? {} : { name: node.name },
|
|
1845
|
+
...node.width === void 0 ? {} : { width: node.width },
|
|
1846
|
+
...node.height === void 0 ? {} : { height: node.height },
|
|
1847
|
+
...node.duration === void 0 ? {} : { duration: node.duration },
|
|
1848
|
+
mentions: {}
|
|
1849
|
+
});
|
|
1850
|
+
continue;
|
|
1851
|
+
}
|
|
1852
|
+
html += node.html;
|
|
1853
|
+
text += node.text;
|
|
1854
|
+
for (const mention of node.mentions ?? []) addMention(mentions, mention);
|
|
1855
|
+
}
|
|
1856
|
+
flush();
|
|
1857
|
+
return drafts;
|
|
1858
|
+
}
|
|
1859
|
+
/** The adapter-private reply context of a publication, when the target carries one. */
|
|
1860
|
+
function referrerOf(target) {
|
|
1861
|
+
const referrer = target.referrer;
|
|
1862
|
+
if (typeof referrer !== "object" || referrer === null) return void 0;
|
|
1863
|
+
return referrer;
|
|
1864
|
+
}
|
|
1865
|
+
/** The thread root a target names: an explicit id, else the referrer's root for `thread: true`. */
|
|
1866
|
+
function threadRootOf(target) {
|
|
1867
|
+
if (typeof target.thread === "string") return target.thread;
|
|
1868
|
+
if (target.thread !== true) return void 0;
|
|
1869
|
+
return referrerOf(target)?.threadRoot;
|
|
1870
|
+
}
|
|
1871
|
+
/**
|
|
1872
|
+
* Build the `m.relates_to` object of one event.
|
|
1873
|
+
*
|
|
1874
|
+
* A reply names only the quoted event id: the fallback body needs the quoted text, which this adapter does not fetch.
|
|
1875
|
+
* A thread carries its root, and — because the specification requires an unthreaded-client fallback — an
|
|
1876
|
+
* `m.in_reply_to` naming the latest known event (`is_falling_back: true`).
|
|
1877
|
+
*/
|
|
1878
|
+
function relationOf(ctx) {
|
|
1879
|
+
const referrer = referrerOf(ctx.target);
|
|
1880
|
+
const threadRoot = threadRootOf(ctx.target);
|
|
1881
|
+
const quote = ctx.index === 0 ? ctx.quote : void 0;
|
|
1882
|
+
if (threadRoot === void 0) return quote === void 0 ? void 0 : { "m.in_reply_to": { event_id: quote } };
|
|
1883
|
+
const reply = quote ?? referrer?.eventId;
|
|
1884
|
+
return {
|
|
1885
|
+
rel_type: "m.thread",
|
|
1886
|
+
event_id: threadRoot,
|
|
1887
|
+
...reply === void 0 ? {} : {
|
|
1888
|
+
is_falling_back: true,
|
|
1889
|
+
"m.in_reply_to": { event_id: reply }
|
|
1890
|
+
}
|
|
1891
|
+
};
|
|
1892
|
+
}
|
|
1893
|
+
/** One media key resolved by `prepare`. */
|
|
1894
|
+
function resolvedKey(prepared, ref) {
|
|
1895
|
+
const resolved = prepared.resolved.get(ref);
|
|
1896
|
+
if (resolved === void 0) throw new PlatformError("invalid", "matrix: media was not prepared before serialize", { published: "no" });
|
|
1897
|
+
return resolved.key;
|
|
1898
|
+
}
|
|
1899
|
+
/** The extra fields `upload` recorded for one prepared media key. */
|
|
1900
|
+
function extraOf(prepared, ref) {
|
|
1901
|
+
const resolved = prepared.resolved.get(ref);
|
|
1902
|
+
if (resolved === void 0) return {};
|
|
1903
|
+
const extra = resolved.extra;
|
|
1904
|
+
if (typeof extra !== "object" || extra === null) return {};
|
|
1905
|
+
return extra;
|
|
1906
|
+
}
|
|
1907
|
+
/**
|
|
1908
|
+
* Build the request payload of one draft.
|
|
1909
|
+
*
|
|
1910
|
+
* @param prepared - one assembled draft with its resolved media.
|
|
1911
|
+
* @param ctx - serialize context (target, part index, quote).
|
|
1912
|
+
* @returns the exact request data `sendPayload` posts.
|
|
1913
|
+
*/
|
|
1914
|
+
function serializeDraft(prepared, ctx) {
|
|
1915
|
+
const draft = prepared.draft;
|
|
1916
|
+
const relates = relationOf(ctx);
|
|
1917
|
+
const thread = threadRootOf(ctx.target);
|
|
1918
|
+
const common = {
|
|
1919
|
+
roomId: ctx.target.chat.id,
|
|
1920
|
+
mentions: draft.mentions,
|
|
1921
|
+
...relates === void 0 ? {} : { relates },
|
|
1922
|
+
...thread === void 0 ? {} : { thread: { root: thread } }
|
|
1923
|
+
};
|
|
1924
|
+
if (draft.kind === "text") {
|
|
1925
|
+
const body = draft.text.trim();
|
|
1926
|
+
const html = draft.html.trim();
|
|
1927
|
+
return {
|
|
1928
|
+
kind: "text",
|
|
1929
|
+
...common,
|
|
1930
|
+
body: body === "" ? " " : body,
|
|
1931
|
+
...html === "" ? {} : { html }
|
|
1932
|
+
};
|
|
1933
|
+
}
|
|
1934
|
+
const extra = extraOf(prepared, draft.ref);
|
|
1935
|
+
const body = draft.name ?? extra.name ?? "file";
|
|
1936
|
+
const info = {
|
|
1937
|
+
...draft.width === void 0 ? {} : { w: draft.width },
|
|
1938
|
+
...draft.height === void 0 ? {} : { h: draft.height },
|
|
1939
|
+
...draft.duration === void 0 ? {} : { duration: draft.duration },
|
|
1940
|
+
...extra.mime === void 0 ? {} : { mimetype: extra.mime },
|
|
1941
|
+
...extra.size === void 0 ? {} : { size: extra.size }
|
|
1942
|
+
};
|
|
1943
|
+
return {
|
|
1944
|
+
kind: "media",
|
|
1945
|
+
...common,
|
|
1946
|
+
msgtype: msgtypeOf(draft.tag),
|
|
1947
|
+
url: resolvedKey(prepared, draft.ref),
|
|
1948
|
+
body,
|
|
1949
|
+
...Object.keys(info).length === 0 ? {} : { info }
|
|
1950
|
+
};
|
|
1951
|
+
}
|
|
1952
|
+
// lib/types/modes/html.js
|
|
1953
|
+
/**
|
|
1954
|
+
* `html` mode: Matrix's `org.matrix.custom.html` rich text, with the plain `body` produced from the same traversal.
|
|
1955
|
+
*
|
|
1956
|
+
* Native tags are the specification's allowed subset (`b`/`i`/`u`/`s`/`del`/`code`/`pre`/`a`/`p`/`blockquote`/lists/
|
|
1957
|
+
* headings/table/details/spoiler); everything else takes the core fallback and is reported as degraded. A user mention
|
|
1958
|
+
* renders as a `matrix.to` link and collects into `m.mentions`; `@room` is the room mention. Media never stays inline:
|
|
1959
|
+
* each media element becomes its own event and is reported as moved when it stood in phrasing content.
|
|
1960
|
+
*/
|
|
1961
|
+
/** The `matrix.to` prefix of a room or user link. */
|
|
1962
|
+
const MATRIX_LINK = "https://matrix.to/#/";
|
|
1963
|
+
/** Wrap the inline text of `children` in one tag, letting media of the subtree follow it. */
|
|
1964
|
+
function wrap(tag, ctx, children, textSuffix = "") {
|
|
1965
|
+
return inlineWrapper(tag, ctx.render(children), textSuffix);
|
|
1966
|
+
}
|
|
1967
|
+
/** Prefix every line of a blockquote text projection with `> `. */
|
|
1968
|
+
function quoteText(text) {
|
|
1969
|
+
const body = text.replace(/\n+$/, "");
|
|
1970
|
+
if (body === "") return "\n\n";
|
|
1971
|
+
return `${body.split("\n").map((line) => `> ${line}`).join("\n")}\n\n`;
|
|
1972
|
+
}
|
|
1973
|
+
/** The text of one table cell, with block children separated by a space. */
|
|
1974
|
+
function cellText(ctx, cell) {
|
|
1975
|
+
return cell.children.map((child) => ctx.text([child])).filter((part) => part.trim() !== "").join(" ").replace(/\s+/g, " ").trim();
|
|
1976
|
+
}
|
|
1977
|
+
/** The `- ` / `1. ` marker of one list item, plus its task-list box. */
|
|
1978
|
+
function listMarker(el, ctx) {
|
|
1979
|
+
const parent = ctx.ancestors[ctx.ancestors.length - 1];
|
|
1980
|
+
let marker = "- ";
|
|
1981
|
+
if (parent?.type === "ol") {
|
|
1982
|
+
const start = typeof parent.attrs.start === "number" ? parent.attrs.start : 1;
|
|
1983
|
+
const index = parent.children.indexOf(el);
|
|
1984
|
+
marker = `${start + Math.max(0, index)}. `;
|
|
1985
|
+
}
|
|
1986
|
+
if (el.attrs.checked === true) marker += "[x] ";
|
|
1987
|
+
else if (el.attrs.checked === false) marker += "[ ] ";
|
|
1988
|
+
return marker;
|
|
1989
|
+
}
|
|
1990
|
+
/** Build the `html` mode. */
|
|
1991
|
+
function createHtmlMode() {
|
|
1992
|
+
return {
|
|
1993
|
+
id: "html",
|
|
1994
|
+
elements: new ElementRegistry().register("text", (el) => htmlNode(escapeHtml(el.attrs.content), el.attrs.content)).register("br", () => htmlNode("<br/>", "\n")).register("p", (el, ctx) => wrap("p", ctx, el.children, "\n\n")).register("b", (el, ctx) => wrap("strong", ctx, el.children)).register("i", (el, ctx) => wrap("em", ctx, el.children)).register("u", (el, ctx) => wrap("u", ctx, el.children)).register("s", (el, ctx) => wrap("del", ctx, el.children)).register("spoiler", (el, ctx) => {
|
|
1995
|
+
const run = inlineRun(ctx.render(el.children));
|
|
1996
|
+
return [htmlNode(`<span data-mx-spoiler>${run.html}</span>`, "[剧透]", mentionNodes(run.mentions)), ...run.rest];
|
|
1997
|
+
}).register("code", (el, ctx) => {
|
|
1998
|
+
const content = ctx.text(el.children);
|
|
1999
|
+
return htmlNode(`<code>${escapeHtml(content)}</code>`, content);
|
|
2000
|
+
}).register("pre", (el, ctx) => {
|
|
2001
|
+
const content = ctx.text(el.children);
|
|
2002
|
+
const language = el.attrs.lang;
|
|
2003
|
+
return htmlNode(language === void 0 || language === "" ? `<pre>${escapeHtml(content)}</pre>` : `<pre><code class="language-${escapeAttribute(language)}">${escapeHtml(content)}</code></pre>`, `${content}\n\n`);
|
|
2004
|
+
}, { variants: ["lang"] }).register("a", (el, ctx) => {
|
|
2005
|
+
const run = inlineRun(ctx.render(el.children));
|
|
2006
|
+
const href = el.attrs.href;
|
|
2007
|
+
const label = run.html === "" ? escapeHtml(href) : run.html;
|
|
2008
|
+
const plain = run.text === "" ? href : run.text;
|
|
2009
|
+
return [htmlNode(`<a href="${escapeAttribute(href)}">${label}</a>`, plain === href ? href : `${plain} (${href})`, mentionNodes(run.mentions)), ...run.rest];
|
|
2010
|
+
}).register("at", (el) => {
|
|
2011
|
+
if (el.attrs.type === "all") return htmlNode("@room", "@room", [{ room: true }]);
|
|
2012
|
+
if (el.attrs.type === "user" && el.attrs.id !== void 0) {
|
|
2013
|
+
const id = el.attrs.id;
|
|
2014
|
+
const label = escapeHtml(el.attrs.name ?? id);
|
|
2015
|
+
return htmlNode(`<a href="${MATRIX_LINK}${escapeAttribute(id)}">${label}</a>`, el.attrs.name ?? id, [{ user: id }]);
|
|
2016
|
+
}
|
|
2017
|
+
return htmlNode(escapeHtml(el.attrs.name ?? el.attrs.id ?? el.attrs.type), el.attrs.name ?? el.attrs.id ?? "");
|
|
2018
|
+
}, { variants: ["user", "all"] }).register("channel", (el) => {
|
|
2019
|
+
const id = el.attrs.id;
|
|
2020
|
+
const label = escapeHtml(el.attrs.name ?? id);
|
|
2021
|
+
return htmlNode(`<a href="${MATRIX_LINK}${escapeAttribute(id)}">${label}</a>`, el.attrs.name ?? id);
|
|
2022
|
+
}).register("emoji", (el) => {
|
|
2023
|
+
const label = `:${el.attrs.name ?? el.attrs.id}:`;
|
|
2024
|
+
return htmlNode(escapeHtml(label), label);
|
|
2025
|
+
}).register("h1", (el, ctx) => wrap("h1", ctx, el.children, "\n\n")).register("h2", (el, ctx) => wrap("h2", ctx, el.children, "\n\n")).register("h3", (el, ctx) => wrap("h3", ctx, el.children, "\n\n")).register("h4", (el, ctx) => wrap("h4", ctx, el.children, "\n\n")).register("h5", (el, ctx) => wrap("h5", ctx, el.children, "\n\n")).register("h6", (el, ctx) => wrap("h6", ctx, el.children, "\n\n")).register("blockquote", (el, ctx) => {
|
|
2026
|
+
const run = inlineRun(ctx.render(el.children));
|
|
2027
|
+
return [htmlNode(`<blockquote>${run.html}</blockquote>`, quoteText(run.text), mentionNodes(run.mentions)), ...run.rest];
|
|
2028
|
+
}).register("ul", (el, ctx) => wrap("ul", ctx, el.children)).register("ol", (el, ctx) => {
|
|
2029
|
+
const run = inlineRun(ctx.render(el.children));
|
|
2030
|
+
return [htmlNode(`<ol${typeof el.attrs.start === "number" ? ` start="${el.attrs.start}"` : ""}>${run.html}</ol>`, run.text, mentionNodes(run.mentions)), ...run.rest];
|
|
2031
|
+
}).register("li", (el, ctx) => {
|
|
2032
|
+
const run = inlineRun(ctx.render(el.children));
|
|
2033
|
+
return [htmlNode(`<li>${el.attrs.checked === true ? "[x] " : el.attrs.checked === false ? "[ ] " : ""}${run.html}</li>`, `${listMarker(el, ctx)}${run.text}\n`, mentionNodes(run.mentions)), ...run.rest];
|
|
2034
|
+
}, { variants: ["checked", "nested"] }).register("hr", () => htmlNode("<hr/>", "\n---\n")).register("table", (el, ctx) => {
|
|
2035
|
+
const rows = el.children.filter((child) => child.type === "tr");
|
|
2036
|
+
const first = rows[0];
|
|
2037
|
+
const header = first !== void 0 && first.children.length > 0 && first.children.every((cell) => cell.type === "th") ? first : void 0;
|
|
2038
|
+
const bodyRows = header === void 0 ? rows : rows.slice(1);
|
|
2039
|
+
const renderedRow = (row) => inlineRun(ctx.render([row]));
|
|
2040
|
+
const headerRun = header === void 0 ? void 0 : renderedRow(header);
|
|
2041
|
+
const bodyRuns = bodyRows.map(renderedRow);
|
|
2042
|
+
const html = [
|
|
2043
|
+
"<table>",
|
|
2044
|
+
headerRun === void 0 ? "" : `<thead>${headerRun.html}</thead>`,
|
|
2045
|
+
`<tbody>${bodyRuns.map((run) => run.html).join("")}</tbody>`,
|
|
2046
|
+
"</table>"
|
|
2047
|
+
].join("");
|
|
2048
|
+
const headerCells = header === void 0 ? [] : header.children.filter((cell) => cell.type === "th" || cell.type === "td").map((cell) => cellText(ctx, cell));
|
|
2049
|
+
const lines = bodyRows.map((row) => row.children.filter((cell) => cell.type === "th" || cell.type === "td").map((cell, index) => {
|
|
2050
|
+
const value = cellText(ctx, cell);
|
|
2051
|
+
const head = headerCells[index];
|
|
2052
|
+
return head === void 0 || head === "" ? value : `${head}: ${value}`;
|
|
2053
|
+
}).join(" | "));
|
|
2054
|
+
const mentions = createMentionSet();
|
|
2055
|
+
for (const run of [headerRun, ...bodyRuns]) {
|
|
2056
|
+
if (run === void 0) continue;
|
|
2057
|
+
for (const mention of mentionNodes(run.mentions)) addMention(mentions, mention);
|
|
2058
|
+
}
|
|
2059
|
+
const text = lines.join("\n");
|
|
2060
|
+
return [
|
|
2061
|
+
htmlNode(html, text === "" ? "" : `${text}\n`, mentionNodes(mentions)),
|
|
2062
|
+
...headerRun?.rest ?? [],
|
|
2063
|
+
...bodyRuns.flatMap((run) => run.rest)
|
|
2064
|
+
];
|
|
2065
|
+
}, { variants: ["align"] }).register("tr", (el, ctx) => {
|
|
2066
|
+
const run = inlineRun(ctx.render(el.children));
|
|
2067
|
+
return [htmlNode(`<tr>${run.html}</tr>`, run.text, mentionNodes(run.mentions)), ...run.rest];
|
|
2068
|
+
}).register("th", (el, ctx) => {
|
|
2069
|
+
const run = inlineRun(ctx.render(el.children));
|
|
2070
|
+
return [htmlNode(`<th${el.attrs.align === void 0 ? "" : ` align="${escapeAttribute(el.attrs.align)}"`}>${run.html}</th>`, run.text, mentionNodes(run.mentions)), ...run.rest];
|
|
2071
|
+
}).register("td", (el, ctx) => {
|
|
2072
|
+
const run = inlineRun(ctx.render(el.children));
|
|
2073
|
+
return [htmlNode(`<td${el.attrs.align === void 0 ? "" : ` align="${escapeAttribute(el.attrs.align)}"`}>${run.html}</td>`, run.text, mentionNodes(run.mentions)), ...run.rest];
|
|
2074
|
+
}, { variants: ["block"] }).register("details", (el, ctx) => {
|
|
2075
|
+
const run = inlineRun(ctx.render(el.children));
|
|
2076
|
+
return [htmlNode(`<details${el.attrs.open === true ? " open" : ""}>${run.html}</details>`, `▸ ${run.text}`, mentionNodes(run.mentions)), ...run.rest];
|
|
2077
|
+
}).register("summary", (el, ctx) => wrap("summary", ctx, el.children, "\n")).register("small", (el, ctx) => ctx.render(el.children)).register("img", (el, ctx) => mediaNode(el, ctx), { variants: ["inline"] }).register("audio", (el, ctx) => mediaNode(el, ctx)).register("video", (el, ctx) => mediaNode(el, ctx)).register("file", (el, ctx) => mediaNode(el, ctx)),
|
|
2078
|
+
limits: {},
|
|
2079
|
+
assemble: (nodes) => assembleDrafts(nodes),
|
|
2080
|
+
serialize: (prepared, ctx) => serializeDraft(prepared, ctx)
|
|
2081
|
+
};
|
|
2082
|
+
}
|
|
2083
|
+
// lib/types/types.js
|
|
2084
|
+
var Internal = class {
|
|
2085
|
+
bot;
|
|
2086
|
+
txnId = Math.round(Math.random() * 1e3);
|
|
2087
|
+
constructor(bot) {
|
|
2088
|
+
this.bot = bot;
|
|
2089
|
+
}
|
|
2090
|
+
async uploadFile(filename, buffer, mimetype) {
|
|
2091
|
+
const headers = {};
|
|
2092
|
+
if (mimetype) headers["content-type"] = mimetype;
|
|
2093
|
+
return (await this.bot.http.post(`/media/v3/upload?filename=${filename}`, buffer, { headers })).content_uri;
|
|
2094
|
+
}
|
|
2095
|
+
async sendTextMessage(roomId, content, reply) {
|
|
2096
|
+
const eventContent = {
|
|
2097
|
+
msgtype: "m.text",
|
|
2098
|
+
body: content
|
|
2099
|
+
};
|
|
2100
|
+
if (reply) eventContent["m.relates_to"] = { "m.in_reply_to": { "event_id": reply } };
|
|
2101
|
+
return (await this.bot.http.put(`/client/v3/rooms/${roomId}/send/m.room.message/${this.txnId++}`, eventContent)).event_id;
|
|
2102
|
+
}
|
|
2103
|
+
async sendMediaMessage(roomId, type, buffer, reply, mimetype, filename = "file") {
|
|
2104
|
+
const uri = await this.uploadFile(filename, buffer, mimetype);
|
|
2105
|
+
let info;
|
|
2106
|
+
if (type === "image") {
|
|
2107
|
+
const { width, height } = imageSize(buffer);
|
|
2108
|
+
info = {
|
|
2109
|
+
size: buffer.byteLength,
|
|
2110
|
+
h: height,
|
|
2111
|
+
w: width,
|
|
2112
|
+
...mimetype === void 0 ? {} : { mimetype }
|
|
2113
|
+
};
|
|
2114
|
+
}
|
|
2115
|
+
const eventContent = {
|
|
2116
|
+
msgtype: `m.${type}`,
|
|
2117
|
+
body: filename,
|
|
2118
|
+
url: uri,
|
|
2119
|
+
...info === void 0 ? {} : { info }
|
|
2120
|
+
};
|
|
2121
|
+
if (reply) eventContent["m.relates_to"] = { "m.in_reply_to": { "event_id": reply } };
|
|
2122
|
+
return (await this.bot.http.put(`/client/v3/rooms/${roomId}/send/m.room.message/${this.txnId++}`, eventContent)).event_id;
|
|
2123
|
+
}
|
|
2124
|
+
async sendReaction(roomId, messageId, key) {
|
|
2125
|
+
const eventContent = { "m.relates_to": {
|
|
2126
|
+
rel_type: "m.annotation",
|
|
2127
|
+
event_id: messageId,
|
|
2128
|
+
key
|
|
2129
|
+
} };
|
|
2130
|
+
return (await this.bot.http.put(`/client/v3/rooms/${roomId}/send/m.reaction/${this.txnId++}`, eventContent)).event_id;
|
|
2131
|
+
}
|
|
2132
|
+
async getEvent(roomId, eventId) {
|
|
2133
|
+
return await this.bot.http.get(`/client/v3/rooms/${roomId}/event/${eventId}`);
|
|
2134
|
+
}
|
|
2135
|
+
async redactEvent(roomId, eventId, reason) {
|
|
2136
|
+
return (await this.bot.http.put(`/client/v3/rooms/${roomId}/redact/${eventId}/${this.txnId++}`, { reason })).event_id;
|
|
2137
|
+
}
|
|
2138
|
+
async getProfile(userId) {
|
|
2139
|
+
return await this.bot.http.get(`/client/v3/profile/${userId}`);
|
|
2140
|
+
}
|
|
2141
|
+
async setDisplayName(userId, displayname) {
|
|
2142
|
+
await this.bot.http.put(`/client/v3/profile/${userId}/displayname`, { displayname });
|
|
2143
|
+
}
|
|
2144
|
+
async setAvatar(userId, buffer, mimetype) {
|
|
2145
|
+
const uri = await this.uploadFile("avatar", buffer, mimetype);
|
|
2146
|
+
await this.bot.http.put(`/client/v3/profile/${userId}/avatar_url`, { avatar_url: uri });
|
|
2147
|
+
}
|
|
2148
|
+
async createRoom(creation) {
|
|
2149
|
+
return (await this.bot.http.post("/client/v3/createRoom", creation)).room_id;
|
|
2150
|
+
}
|
|
2151
|
+
async joinRoom(roomId, reason) {
|
|
2152
|
+
return (await this.bot.http.post(`/client/v3/join/${roomId}`, { reason })).room_id;
|
|
2153
|
+
}
|
|
2154
|
+
async leaveRoom(roomId, reason) {
|
|
2155
|
+
return (await this.bot.http.post(`/client/v3/rooms/${roomId}/leave`, { reason })).room_id;
|
|
2156
|
+
}
|
|
2157
|
+
async invite(roomId, userId, reason) {
|
|
2158
|
+
await this.bot.http.post(`/client/v3/rooms/${roomId}/invite`, {
|
|
2159
|
+
user_id: userId,
|
|
2160
|
+
reason
|
|
2161
|
+
});
|
|
2162
|
+
}
|
|
2163
|
+
async sync(fullSstate = false) {
|
|
2164
|
+
return await this.bot.http.get("/client/v3/sync", { params: { full_state: fullSstate } });
|
|
2165
|
+
}
|
|
2166
|
+
async getState(roomId) {
|
|
2167
|
+
return await this.bot.http.get(`/client/v3/rooms/${roomId}/state`);
|
|
2168
|
+
}
|
|
2169
|
+
async setState(roomId, eventType, event, state) {
|
|
2170
|
+
const statePath = state ? `/${state}` : "";
|
|
2171
|
+
return (await this.bot.http.put(`/client/v3/rooms/${roomId}/state/${eventType}${statePath}`, event)).event_id;
|
|
2172
|
+
}
|
|
2173
|
+
async getJoinedRooms() {
|
|
2174
|
+
return await this.bot.http.get("/client/v3/joined_rooms");
|
|
2175
|
+
}
|
|
2176
|
+
async register(username, asToken) {
|
|
2177
|
+
return await this.bot.ctx.http.post(this.bot.endpoint + "/client/v3/register", {
|
|
2178
|
+
type: "m.login.application_service",
|
|
2179
|
+
username
|
|
2180
|
+
}, { headers: { "Authorization": `Bearer ${asToken}` } });
|
|
2181
|
+
}
|
|
2182
|
+
async login(username, asToken) {
|
|
2183
|
+
return await this.bot.ctx.http.post(this.bot.endpoint + "/client/v3/login", {
|
|
2184
|
+
type: "m.login.application_service",
|
|
2185
|
+
identifier: {
|
|
2186
|
+
type: "m.id.user",
|
|
2187
|
+
user: username
|
|
2188
|
+
}
|
|
2189
|
+
}, { headers: { "Authorization": `Bearer ${asToken}` } });
|
|
2190
|
+
}
|
|
2191
|
+
getAssetUrl(mxc) {
|
|
2192
|
+
return `${this.bot.endpoint}/client/v1/media/download/${mxc.substring(6)}`;
|
|
2193
|
+
}
|
|
2194
|
+
};
|
|
2195
|
+
// lib/types/bot.js
|
|
2196
|
+
/**
|
|
2197
|
+
* Matrix Application Service adapter.
|
|
2198
|
+
*
|
|
2199
|
+
* The only transport is the homeserver's transaction push into a profile-provided `webServer`; the bot first registers
|
|
2200
|
+
* its virtual user (`m.login.application_service`), then runs one full-state sync to learn its rooms, then registers
|
|
2201
|
+
* the transaction route and goes online. There is no `/sync` message loop and no end-to-end encryption: encrypted
|
|
2202
|
+
* rooms are unusable, and `m.room.encrypted` events are dropped.
|
|
2203
|
+
*
|
|
2204
|
+
* The mode is `html` only: Matrix's rich text is `org.matrix.custom.html` plus a plain `body`, and a plain-only mode
|
|
2205
|
+
* would be the same payload without the two format fields. Media is uploaded to the media repository; inbound `mxc:`
|
|
2206
|
+
* URIs are served through the authenticated download endpoint behind the bot's own `satori:` route.
|
|
2207
|
+
*/
|
|
2208
|
+
/** Message of any caught value, for a log line. */
|
|
2209
|
+
function messageOf(error) {
|
|
2210
|
+
return error instanceof Error ? error.message : String(error);
|
|
2211
|
+
}
|
|
2212
|
+
/**
|
|
2213
|
+
* Matrix Application Service adapter.
|
|
2214
|
+
*
|
|
2215
|
+
* Identity is the configured virtual user (`@<id>:<host>`), registered or logged in on connect; the inbound route is
|
|
2216
|
+
* the Application Service API below `path`; the room cache is filled by the one-shot full-state sync.
|
|
2217
|
+
*/
|
|
2218
|
+
var MatrixBot = class extends Adapter {
|
|
2219
|
+
/** The adapter needs the Satori service and the isolated `http` service. */
|
|
2220
|
+
static inject = ["satori", "http"];
|
|
2221
|
+
/** The Loader applies this schema to a profile row's `config` before the constructor runs. */
|
|
2222
|
+
static Config = Config;
|
|
2223
|
+
modes = { html: createHtmlMode() };
|
|
2224
|
+
modeOrder = ["html"];
|
|
2225
|
+
/** Homeserver root plus `/_matrix`, without a trailing slash. */
|
|
2226
|
+
endpoint;
|
|
2227
|
+
/** Client-Server transport shared by `Internal` and the adapter's own calls. */
|
|
2228
|
+
request;
|
|
2229
|
+
/** The same client under the name the migrated upstream `Internal` uses (`bot.http`). */
|
|
2230
|
+
http;
|
|
2231
|
+
/** Full typed Client-Server / Application Service surface (the migrated upstream client). */
|
|
2232
|
+
internal;
|
|
2233
|
+
/** Names, members, summaries, direct markers and encryption markers per room. */
|
|
2234
|
+
rooms = new RoomCache();
|
|
2235
|
+
/** Random process base of transaction ids, so a restart cannot collide with an old id. */
|
|
2236
|
+
txnBase = Math.round(Math.random() * 1e3);
|
|
2237
|
+
/** Monotonic transaction id counter. */
|
|
2238
|
+
txnCounter = 0;
|
|
2239
|
+
appService;
|
|
2240
|
+
/** Whether an invitation of the bot itself is joined automatically. */
|
|
2241
|
+
get autoJoin() {
|
|
2242
|
+
return this.config.autoJoin;
|
|
2243
|
+
}
|
|
2244
|
+
constructor(ctx, config) {
|
|
2245
|
+
const invalid = configError(config);
|
|
2246
|
+
if (invalid !== void 0) throw invalid;
|
|
2247
|
+
const selfId = matrixUserId(config);
|
|
2248
|
+
super(ctx, config, {
|
|
2249
|
+
id: `matrix:${selfId}`,
|
|
2250
|
+
platform: "matrix",
|
|
2251
|
+
adapter: "matrix"
|
|
2252
|
+
});
|
|
2253
|
+
this.selfId = selfId;
|
|
2254
|
+
this.user = {
|
|
2255
|
+
id: selfId,
|
|
2256
|
+
name: config.name ?? config.id,
|
|
2257
|
+
isBot: true
|
|
2258
|
+
};
|
|
2259
|
+
this.endpoint = `${config.endpoint}/_matrix`;
|
|
2260
|
+
this.request = new MatrixClient(ctx, this.endpoint);
|
|
2261
|
+
this.http = this.request;
|
|
2262
|
+
this.internal = new Internal(this);
|
|
2263
|
+
this.defineInternalRoute("/media", (request) => this.serveMedia(request));
|
|
2264
|
+
}
|
|
2265
|
+
async connect() {
|
|
2266
|
+
try {
|
|
2267
|
+
await establishIdentity(this);
|
|
2268
|
+
await this.refreshRooms();
|
|
2269
|
+
const appService = new MatrixAppService(this);
|
|
2270
|
+
await appService.start();
|
|
2271
|
+
this.appService = appService;
|
|
2272
|
+
this.online();
|
|
2273
|
+
} catch (error) {
|
|
2274
|
+
this.ctx.logger.error("matrix: connect failed: %s", messageOf(error));
|
|
2275
|
+
await this.appService?.stop();
|
|
2276
|
+
this.appService = void 0;
|
|
2277
|
+
throw error;
|
|
2278
|
+
}
|
|
2279
|
+
}
|
|
2280
|
+
async disconnect() {
|
|
2281
|
+
const appService = this.appService;
|
|
2282
|
+
this.appService = void 0;
|
|
2283
|
+
await appService?.stop();
|
|
2284
|
+
}
|
|
2285
|
+
async upload(ref, _scope, ctx) {
|
|
2286
|
+
return await this.withApi(() => uploadResource(this.request, ref, ctx));
|
|
2287
|
+
}
|
|
2288
|
+
resourceScope(_target, _kind) {
|
|
2289
|
+
return this.id;
|
|
2290
|
+
}
|
|
2291
|
+
async sendPayload(payload, target, ctx) {
|
|
2292
|
+
try {
|
|
2293
|
+
return await this.withApi(() => sendPayload(this.sendDeps(), payload, target, ctx));
|
|
2294
|
+
} catch (error) {
|
|
2295
|
+
const value = payload;
|
|
2296
|
+
if (value.kind === "media") this.ctx.logger.warn("matrix: a send attempt for uploaded media %s failed: %s", value.url, messageOf(error));
|
|
2297
|
+
throw error;
|
|
2298
|
+
}
|
|
2299
|
+
}
|
|
2300
|
+
idempotentSend(target, ctx) {
|
|
2301
|
+
return idempotentSend(target, ctx);
|
|
2302
|
+
}
|
|
2303
|
+
async deletePart(part, handle) {
|
|
2304
|
+
await this.withApi(() => deletePart(this.sendDeps(), part, handle));
|
|
2305
|
+
}
|
|
2306
|
+
async createReaction(message, emoji) {
|
|
2307
|
+
await this.withApi(() => createReaction(this.sendDeps(), message, emoji));
|
|
2308
|
+
}
|
|
2309
|
+
async members(chat, cursor, limit) {
|
|
2310
|
+
return await this.withApi(() => members(this.sendDeps(), chat, cursor, limit));
|
|
2311
|
+
}
|
|
2312
|
+
async getMessage(chat, id) {
|
|
2313
|
+
return await this.withApi(() => getMessage(this.sendDeps(), chat, id));
|
|
2314
|
+
}
|
|
2315
|
+
classify(error) {
|
|
2316
|
+
return classifyMatrixError(error);
|
|
2317
|
+
}
|
|
2318
|
+
/** Decode one Application Service event into the session the transport publishes. */
|
|
2319
|
+
async decode(event) {
|
|
2320
|
+
return await decodeEvent(this, event);
|
|
2321
|
+
}
|
|
2322
|
+
/** Debug log of one dropped inbound event. */
|
|
2323
|
+
log(message) {
|
|
2324
|
+
this.ctx.logger.debug(message);
|
|
2325
|
+
}
|
|
2326
|
+
/** Warning log of an unreadable room or a failed state refresh. */
|
|
2327
|
+
warn(message) {
|
|
2328
|
+
this.ctx.logger.warn(message);
|
|
2329
|
+
}
|
|
2330
|
+
/** Join one room without refreshing; the self-join event triggers the refresh. */
|
|
2331
|
+
async joinRoom(roomId) {
|
|
2332
|
+
await this.internal.joinRoom(roomId);
|
|
2333
|
+
}
|
|
2334
|
+
/**
|
|
2335
|
+
* Run the one-shot full-state sync and apply it, joining the rooms the bot was invited into when `autoJoin` is on.
|
|
2336
|
+
*
|
|
2337
|
+
* The sync's timeline is history the host store already owns, so it is only read for state. A successful join runs
|
|
2338
|
+
* the same query once more, which is what puts the new room's name, members and summary in the cache.
|
|
2339
|
+
*/
|
|
2340
|
+
async refreshRooms() {
|
|
2341
|
+
const invites = await enumerateRooms(this.internal, this.rooms, this.selfId);
|
|
2342
|
+
if (invites.length === 0) return;
|
|
2343
|
+
if (!this.config.autoJoin) {
|
|
2344
|
+
for (const roomId of invites) this.ctx.logger.info(`matrix: invited to ${roomId}; autoJoin is off, so it is not joined`);
|
|
2345
|
+
return;
|
|
2346
|
+
}
|
|
2347
|
+
let joined = false;
|
|
2348
|
+
for (const roomId of invites) try {
|
|
2349
|
+
await this.internal.joinRoom(roomId);
|
|
2350
|
+
joined = true;
|
|
2351
|
+
} catch (error) {
|
|
2352
|
+
this.ctx.logger.warn(`matrix: could not join invited room ${roomId}: ${messageOf(error)}`);
|
|
2353
|
+
}
|
|
2354
|
+
if (joined) await enumerateRooms(this.internal, this.rooms, this.selfId);
|
|
2355
|
+
}
|
|
2356
|
+
/**
|
|
2357
|
+
* Take the bot offline when a Client-Server call reports that its token is gone.
|
|
2358
|
+
* @param error - the caught failure of an outbound call or an inbound event handler.
|
|
2359
|
+
*/
|
|
2360
|
+
noteRuntimeError(error) {
|
|
2361
|
+
if (!isTokenFailure(error)) return;
|
|
2362
|
+
this.ctx.logger.error("matrix: the user access token was rejected (%s); replace the registration credentials and restart", messageOf(error));
|
|
2363
|
+
this.offline(error);
|
|
2364
|
+
}
|
|
2365
|
+
/** Adapt one authenticated media download into the host's response. */
|
|
2366
|
+
async serveMedia(request) {
|
|
2367
|
+
const value = request.query.get("mxc");
|
|
2368
|
+
if (value === null) return new Response(null, { status: 400 });
|
|
2369
|
+
const parsed = parseMxc(value.startsWith("mxc://") ? value : `mxc://${value}`);
|
|
2370
|
+
if (parsed === void 0) return new Response(null, { status: 400 });
|
|
2371
|
+
try {
|
|
2372
|
+
return mediaResponse(await this.request.download(parsed.serverName, parsed.mediaId));
|
|
2373
|
+
} catch (error) {
|
|
2374
|
+
this.noteRuntimeError(error);
|
|
2375
|
+
this.ctx.logger.warn("matrix: media %s/%s could not be served: %s", parsed.serverName, parsed.mediaId, messageOf(error));
|
|
2376
|
+
return new Response(null, { status: 502 });
|
|
2377
|
+
}
|
|
2378
|
+
}
|
|
2379
|
+
/** Run one outbound call, marking the bot offline when the failure is a dead token. */
|
|
2380
|
+
async withApi(run) {
|
|
2381
|
+
try {
|
|
2382
|
+
return await run();
|
|
2383
|
+
} catch (error) {
|
|
2384
|
+
this.noteRuntimeError(error);
|
|
2385
|
+
throw error;
|
|
2386
|
+
}
|
|
2387
|
+
}
|
|
2388
|
+
sendDeps() {
|
|
2389
|
+
return {
|
|
2390
|
+
client: this.request,
|
|
2391
|
+
selfId: this.selfId,
|
|
2392
|
+
nextTxn: () => this.txnBase + this.txnCounter++,
|
|
2393
|
+
rooms: this.rooms,
|
|
2394
|
+
isBot: (userId) => this.ctx.bots.some((bot) => bot.platform === "matrix" && bot.selfId === userId),
|
|
2395
|
+
decode: (chat, event) => decodeMessage(this, event, chat)
|
|
2396
|
+
};
|
|
2397
|
+
}
|
|
2398
|
+
};
|
|
2399
|
+
export { Config, MatrixApiError, MatrixBot, MatrixBot as default, MatrixClient, classifyMatrixError, configError, isTokenFailure, routePath };
|
|
2400
|
+
|
|
2401
|
+
//# sourceMappingURL=index.js.map
|