@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/src/request.ts
ADDED
|
@@ -0,0 +1,295 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Matrix Client-Server transport: one HTTP path for every endpoint the adapter calls, the standard error envelope
|
|
3
|
+
* (`errcode` / `error`), rate-limit fields, upload bytes and authenticated media download.
|
|
4
|
+
*
|
|
5
|
+
* `Internal` (the migrated upstream client) keeps its upstream method bodies and calls this class through
|
|
6
|
+
* `bot.http`; the adapter's own send/media paths call it directly, so both cannot diverge on base URL or auth.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
import type { Context } from '@deepseek-ai/cordis'
|
|
10
|
+
import type {} from '@deepseek-ai/cordis-plugin-http'
|
|
11
|
+
import { MatrixApiError } from './errors.ts'
|
|
12
|
+
|
|
13
|
+
/** Optional inputs of one Matrix request. */
|
|
14
|
+
export interface MatrixRequestOptions {
|
|
15
|
+
/** Query parameters appended to the path. */
|
|
16
|
+
params?: Record<string, string | number | boolean>
|
|
17
|
+
/** Extra headers (an upload's `content-type`). */
|
|
18
|
+
headers?: Record<string, string>
|
|
19
|
+
signal?: AbortSignal
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/** The standard Matrix error envelope. */
|
|
23
|
+
interface MatrixErrorEnvelope {
|
|
24
|
+
errcode?: unknown
|
|
25
|
+
error?: unknown
|
|
26
|
+
retry_after_ms?: unknown
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** Delay asked for by a `Retry-After` response header (seconds or HTTP-date). */
|
|
30
|
+
function retryAfterHeader(response: Response): number | undefined {
|
|
31
|
+
const header = response.headers.get('retry-after')
|
|
32
|
+
if (header === null) return undefined
|
|
33
|
+
const seconds = Number(header)
|
|
34
|
+
if (Number.isFinite(seconds) && seconds >= 0) return seconds * 1_000
|
|
35
|
+
const date = Date.parse(header)
|
|
36
|
+
if (!Number.isNaN(date)) return Math.max(0, date - Date.now())
|
|
37
|
+
return undefined
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** The retry delay of one failed answer: the body field first, then the standard header. */
|
|
41
|
+
function retryAfterOf(
|
|
42
|
+
body: MatrixErrorEnvelope | undefined,
|
|
43
|
+
response: Response,
|
|
44
|
+
): number | undefined {
|
|
45
|
+
const bodyDelay = body?.retry_after_ms
|
|
46
|
+
if (
|
|
47
|
+
typeof bodyDelay === 'number' &&
|
|
48
|
+
Number.isFinite(bodyDelay) &&
|
|
49
|
+
bodyDelay >= 0
|
|
50
|
+
)
|
|
51
|
+
return bodyDelay
|
|
52
|
+
return retryAfterHeader(response)
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/** Whether a caught value is an abort error, including the `DOMException` a signal produces. */
|
|
56
|
+
function isAbortError(value: unknown): boolean {
|
|
57
|
+
return (
|
|
58
|
+
(value instanceof Error || value instanceof DOMException) &&
|
|
59
|
+
value.name === 'AbortError'
|
|
60
|
+
)
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/** The abort reason carried by a failure, unwrapping a transport error's `cause` chain. */
|
|
64
|
+
function abortReasonOf(error: unknown): unknown {
|
|
65
|
+
if (isAbortError(error)) return error
|
|
66
|
+
if (typeof error === 'object' && error !== null && 'cause' in error) {
|
|
67
|
+
return abortReasonOf((error as { cause?: unknown }).cause)
|
|
68
|
+
}
|
|
69
|
+
return undefined
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/** A message for a failed call, naming status and the server's own error text when it sent one. */
|
|
73
|
+
function failureMessage(
|
|
74
|
+
method: string,
|
|
75
|
+
path: string,
|
|
76
|
+
status: number,
|
|
77
|
+
body: MatrixErrorEnvelope | undefined,
|
|
78
|
+
): string {
|
|
79
|
+
const code = typeof body?.errcode === 'string' ? body.errcode : undefined
|
|
80
|
+
const detail = typeof body?.error === 'string' ? body.error : undefined
|
|
81
|
+
const suffix =
|
|
82
|
+
code === undefined && detail === undefined
|
|
83
|
+
? ''
|
|
84
|
+
: `: ${[code, detail].filter((part): part is string => part !== undefined).join(' ')}`
|
|
85
|
+
return `matrix ${method} ${path} answered ${status}${suffix}`
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/**
|
|
89
|
+
* The Client-Server client of one bot.
|
|
90
|
+
*
|
|
91
|
+
* Requests are relative to the homeserver root with `/_matrix` already appended. The access token is set after
|
|
92
|
+
* `register`/`login`; `register`/`login` themselves go through `ctx.http` with the application service token.
|
|
93
|
+
*/
|
|
94
|
+
export class MatrixClient {
|
|
95
|
+
/** The user access token every Client-Server call carries; empty until `connect` logged in. */
|
|
96
|
+
token: string | undefined
|
|
97
|
+
|
|
98
|
+
/** @param ctx - context whose `http` service performs requests. @param endpoint - homeserver root plus `/_matrix`. */
|
|
99
|
+
constructor(
|
|
100
|
+
readonly ctx: Context,
|
|
101
|
+
readonly endpoint: string,
|
|
102
|
+
) {}
|
|
103
|
+
|
|
104
|
+
/** Set the user access token minted by `m.login.application_service`. */
|
|
105
|
+
setToken(token: string): void {
|
|
106
|
+
this.token = token
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/** The absolute URL of one endpoint path. */
|
|
110
|
+
url(path: string): string {
|
|
111
|
+
return `${this.endpoint}${path.startsWith('/') ? path : `/${path}`}`
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/**
|
|
115
|
+
* Call one GET endpoint.
|
|
116
|
+
* @param path - endpoint below the Matrix root.
|
|
117
|
+
* @param options - query parameters, headers and cancellation.
|
|
118
|
+
* @returns the parsed JSON answer.
|
|
119
|
+
*/
|
|
120
|
+
async get<T = any>(
|
|
121
|
+
path: string,
|
|
122
|
+
options: MatrixRequestOptions = {},
|
|
123
|
+
): Promise<T> {
|
|
124
|
+
return await this.decode<T>(
|
|
125
|
+
await this.send('GET', path, undefined, options),
|
|
126
|
+
'GET',
|
|
127
|
+
path,
|
|
128
|
+
)
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/**
|
|
132
|
+
* Call one PUT endpoint.
|
|
133
|
+
* @param path - endpoint below the Matrix root.
|
|
134
|
+
* @param data - JSON body (`t.rn` events, profile writes).
|
|
135
|
+
* @param options - query parameters, headers and cancellation.
|
|
136
|
+
* @returns the parsed JSON answer.
|
|
137
|
+
*/
|
|
138
|
+
async put<T = any>(
|
|
139
|
+
path: string,
|
|
140
|
+
data?: unknown,
|
|
141
|
+
options: MatrixRequestOptions = {},
|
|
142
|
+
): Promise<T> {
|
|
143
|
+
return await this.decode<T>(
|
|
144
|
+
await this.send('PUT', path, data, options),
|
|
145
|
+
'PUT',
|
|
146
|
+
path,
|
|
147
|
+
)
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
/**
|
|
151
|
+
* Call one POST endpoint.
|
|
152
|
+
* @param path - endpoint below the Matrix root.
|
|
153
|
+
* @param data - JSON body or raw bytes (upload).
|
|
154
|
+
* @param options - query parameters, headers and cancellation.
|
|
155
|
+
* @returns the parsed JSON answer.
|
|
156
|
+
*/
|
|
157
|
+
async post<T = any>(
|
|
158
|
+
path: string,
|
|
159
|
+
data?: unknown,
|
|
160
|
+
options: MatrixRequestOptions = {},
|
|
161
|
+
): Promise<T> {
|
|
162
|
+
return await this.decode<T>(
|
|
163
|
+
await this.send('POST', path, data, options),
|
|
164
|
+
'POST',
|
|
165
|
+
path,
|
|
166
|
+
)
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
/**
|
|
170
|
+
* Upload bytes to the media repository.
|
|
171
|
+
* @param name - file name sent as the `filename` query parameter.
|
|
172
|
+
* @param data - the bytes.
|
|
173
|
+
* @param mimetype - `content-type` of the bytes, when known.
|
|
174
|
+
* @param signal - cancellation.
|
|
175
|
+
* @returns the upload answer (`content_uri` on success).
|
|
176
|
+
*/
|
|
177
|
+
async upload(
|
|
178
|
+
name: string,
|
|
179
|
+
data: Uint8Array,
|
|
180
|
+
mimetype: string | undefined,
|
|
181
|
+
signal?: AbortSignal,
|
|
182
|
+
): Promise<{ content_uri?: string }> {
|
|
183
|
+
return await this.post<{ content_uri?: string }>(
|
|
184
|
+
`/media/v3/upload?filename=${encodeURIComponent(name)}`,
|
|
185
|
+
data,
|
|
186
|
+
{
|
|
187
|
+
...(mimetype === undefined
|
|
188
|
+
? {}
|
|
189
|
+
: { headers: { 'content-type': mimetype } }),
|
|
190
|
+
...(signal === undefined ? {} : { signal }),
|
|
191
|
+
},
|
|
192
|
+
)
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
/**
|
|
196
|
+
* Download one media item through the authenticated endpoint (v1.11's recommended path).
|
|
197
|
+
* @param serverName - the server name of the `mxc://` URI.
|
|
198
|
+
* @param mediaId - the media id of the `mxc://` URI.
|
|
199
|
+
* @param fileName - optional file name path segment.
|
|
200
|
+
* @param signal - cancellation.
|
|
201
|
+
* @returns the platform's answer, body included.
|
|
202
|
+
*/
|
|
203
|
+
async download(
|
|
204
|
+
serverName: string,
|
|
205
|
+
mediaId: string,
|
|
206
|
+
fileName?: string,
|
|
207
|
+
signal?: AbortSignal,
|
|
208
|
+
): Promise<Response> {
|
|
209
|
+
const suffix = fileName === undefined ? '' : `/${fileName}`
|
|
210
|
+
return await this.send(
|
|
211
|
+
'GET',
|
|
212
|
+
`/client/v1/media/download/${serverName}/${mediaId}${suffix}`,
|
|
213
|
+
undefined,
|
|
214
|
+
signal === undefined ? {} : { signal },
|
|
215
|
+
)
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
/** Perform one request and return the raw answer; transport failures become `MatrixApiError`s. */
|
|
219
|
+
private async send(
|
|
220
|
+
method: string,
|
|
221
|
+
path: string,
|
|
222
|
+
data: unknown,
|
|
223
|
+
options: MatrixRequestOptions,
|
|
224
|
+
): Promise<Response> {
|
|
225
|
+
const headers: Record<string, string> = { ...options.headers }
|
|
226
|
+
if (this.token !== undefined) headers.authorization = `Bearer ${this.token}`
|
|
227
|
+
let response: Response
|
|
228
|
+
try {
|
|
229
|
+
response = await this.ctx.http(this.url(path), {
|
|
230
|
+
method,
|
|
231
|
+
...(data === undefined ? {} : { data }),
|
|
232
|
+
...(options.params === undefined ? {} : { params: options.params }),
|
|
233
|
+
headers,
|
|
234
|
+
...(options.signal === undefined ? {} : { signal: options.signal }),
|
|
235
|
+
})
|
|
236
|
+
} catch (cause) {
|
|
237
|
+
if (options.signal?.aborted === true) throw options.signal.reason
|
|
238
|
+
const abort = abortReasonOf(cause)
|
|
239
|
+
if (abort !== undefined) throw abort
|
|
240
|
+
throw new MatrixApiError(`matrix ${method} ${path} request failed`, {
|
|
241
|
+
method,
|
|
242
|
+
path,
|
|
243
|
+
cause,
|
|
244
|
+
})
|
|
245
|
+
}
|
|
246
|
+
if (options.signal?.aborted === true) throw options.signal.reason
|
|
247
|
+
return response
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
/** Decode one answer: JSON object on success, `MatrixApiError` for every refusal. */
|
|
251
|
+
private async decode<T>(
|
|
252
|
+
response: Response,
|
|
253
|
+
method: string,
|
|
254
|
+
path: string,
|
|
255
|
+
): Promise<T> {
|
|
256
|
+
const status = response.status
|
|
257
|
+
let text: string
|
|
258
|
+
try {
|
|
259
|
+
text = await response.text()
|
|
260
|
+
} catch (cause) {
|
|
261
|
+
throw new MatrixApiError('matrix answered without a readable body', {
|
|
262
|
+
status,
|
|
263
|
+
cause,
|
|
264
|
+
})
|
|
265
|
+
}
|
|
266
|
+
let parsed: unknown
|
|
267
|
+
if (text !== '') {
|
|
268
|
+
try {
|
|
269
|
+
parsed = JSON.parse(text)
|
|
270
|
+
} catch {
|
|
271
|
+
parsed = undefined
|
|
272
|
+
}
|
|
273
|
+
}
|
|
274
|
+
const body =
|
|
275
|
+
typeof parsed === 'object' && parsed !== null
|
|
276
|
+
? (parsed as MatrixErrorEnvelope)
|
|
277
|
+
: undefined
|
|
278
|
+
if (status >= 400) {
|
|
279
|
+
const retryAfterMs = retryAfterOf(body, response)
|
|
280
|
+
throw new MatrixApiError(failureMessage(method, path, status, body), {
|
|
281
|
+
status,
|
|
282
|
+
...(typeof body?.errcode === 'string' ? { errcode: body.errcode } : {}),
|
|
283
|
+
...(typeof body?.error === 'string' ? { error: body.error } : {}),
|
|
284
|
+
...(retryAfterMs === undefined ? {} : { retryAfterMs }),
|
|
285
|
+
})
|
|
286
|
+
}
|
|
287
|
+
if (parsed === undefined) {
|
|
288
|
+
throw new MatrixApiError(
|
|
289
|
+
`matrix answered ${status} without a JSON body`,
|
|
290
|
+
{ status },
|
|
291
|
+
)
|
|
292
|
+
}
|
|
293
|
+
return parsed as T
|
|
294
|
+
}
|
|
295
|
+
}
|
package/src/rooms.ts
ADDED
|
@@ -0,0 +1,232 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The room cache and the one-shot full-state `/sync` that fills it.
|
|
3
|
+
*
|
|
4
|
+
* Application Service pushes carry events only: no room list, name, member set or summary. `connect` therefore asks the
|
|
5
|
+
* homeserver for one full-state sync (`full_state=true` makes the answer immediate, so it is a query, not a poll),
|
|
6
|
+
* uses the joined rooms for names/members/summaries/`m.direct`/encryption markers, and joins the invited rooms when
|
|
7
|
+
* `autoJoin` is on. The same query runs once more after the bot joins a room on its own.
|
|
8
|
+
*
|
|
9
|
+
* A room is reported as direct when the bot's own `m.direct` names it, else when the summary says two joined members,
|
|
10
|
+
* else when the observed joined members are exactly the bot and one other user. Everything else is a group.
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
import type { Sync } from './types.ts'
|
|
14
|
+
|
|
15
|
+
/** One member the cache has seen, with the display name its state events carried. */
|
|
16
|
+
export interface CachedMember {
|
|
17
|
+
joined: boolean
|
|
18
|
+
displayname?: string
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/** The cached state of one room. */
|
|
22
|
+
export interface CachedRoom {
|
|
23
|
+
name?: string
|
|
24
|
+
members: Map<string, CachedMember>
|
|
25
|
+
/** `summary['m.joined_member_count']` of the full-state sync. */
|
|
26
|
+
joinedMemberCount?: number
|
|
27
|
+
encrypted: boolean
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** A minimal client surface the enumeration needs (the migrated `Internal` satisfies it). */
|
|
31
|
+
export interface RoomEnumerator {
|
|
32
|
+
sync(fullState?: boolean): Promise<Sync>
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** The rooms the bot's own `m.direct` account data names. */
|
|
36
|
+
function directRoomIds(sync: Sync): string[] {
|
|
37
|
+
const out: string[] = []
|
|
38
|
+
for (const event of sync.account_data?.events ?? []) {
|
|
39
|
+
if (event.type !== 'm.direct') continue
|
|
40
|
+
const content = event.content as Record<string, unknown>
|
|
41
|
+
for (const value of Object.values(content)) {
|
|
42
|
+
if (!Array.isArray(value)) continue
|
|
43
|
+
for (const roomId of value) {
|
|
44
|
+
if (typeof roomId === 'string') out.push(roomId)
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
return out
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/** In-memory room state shared by decode, enumeration and member reads. */
|
|
52
|
+
export class RoomCache {
|
|
53
|
+
private readonly rooms = new Map<string, CachedRoom>()
|
|
54
|
+
private readonly directRooms = new Set<string>()
|
|
55
|
+
|
|
56
|
+
/** The cached state of one room, created on first use. */
|
|
57
|
+
room(roomId: string): CachedRoom {
|
|
58
|
+
let room = this.rooms.get(roomId)
|
|
59
|
+
if (room === undefined) {
|
|
60
|
+
room = { members: new Map(), encrypted: false }
|
|
61
|
+
this.rooms.set(roomId, room)
|
|
62
|
+
}
|
|
63
|
+
return room
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/** The room name last seen, if any. */
|
|
67
|
+
nameOf(roomId: string): string | undefined {
|
|
68
|
+
return this.rooms.get(roomId)?.name
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/** The display name last seen for one member of a room. */
|
|
72
|
+
displayNameOf(roomId: string, userId: string): string | undefined {
|
|
73
|
+
return this.rooms.get(roomId)?.members.get(userId)?.displayname
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/** Whether a room's state says it enabled end-to-end encryption. */
|
|
77
|
+
isEncrypted(roomId: string): boolean {
|
|
78
|
+
return this.rooms.get(roomId)?.encrypted === true
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/**
|
|
82
|
+
* Record that a room is encrypted.
|
|
83
|
+
* @param roomId - the room.
|
|
84
|
+
* @returns true when this is the first observation, so the caller logs its warning once.
|
|
85
|
+
*/
|
|
86
|
+
markEncrypted(roomId: string): boolean {
|
|
87
|
+
const room = this.room(roomId)
|
|
88
|
+
if (room.encrypted) return false
|
|
89
|
+
room.encrypted = true
|
|
90
|
+
return true
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/** Record one `m.room.name` event. */
|
|
94
|
+
setName(roomId: string, name: string): void {
|
|
95
|
+
this.room(roomId).name = name
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/** Record one `m.room.member` event. */
|
|
99
|
+
applyMember(
|
|
100
|
+
roomId: string,
|
|
101
|
+
userId: string,
|
|
102
|
+
membership: string | undefined,
|
|
103
|
+
displayname: string | undefined,
|
|
104
|
+
): void {
|
|
105
|
+
const room = this.room(roomId)
|
|
106
|
+
const member = room.members.get(userId) ?? { joined: false }
|
|
107
|
+
member.joined = membership === 'join'
|
|
108
|
+
if (displayname !== undefined) member.displayname = displayname
|
|
109
|
+
room.members.set(userId, member)
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/** The joined members of one room, in insertion order. */
|
|
113
|
+
joinedMembers(roomId: string): string[] {
|
|
114
|
+
const room = this.rooms.get(roomId)
|
|
115
|
+
if (room === undefined) return []
|
|
116
|
+
return [...room.members]
|
|
117
|
+
.filter(([, member]) => member.joined)
|
|
118
|
+
.map(([userId]) => userId)
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/**
|
|
122
|
+
* Whether a room is a direct chat.
|
|
123
|
+
* @param roomId - the room.
|
|
124
|
+
* @param selfId - the bot's Matrix user id.
|
|
125
|
+
* @returns true for a room the judgement chain reports as direct.
|
|
126
|
+
*/
|
|
127
|
+
isDirect(roomId: string, selfId: string): boolean {
|
|
128
|
+
if (this.directRooms.has(roomId)) return true
|
|
129
|
+
const room = this.rooms.get(roomId)
|
|
130
|
+
if (room === undefined) return false
|
|
131
|
+
if (room.joinedMemberCount === 2) return true
|
|
132
|
+
const joined = [...room.members.values()].filter((member) => member.joined)
|
|
133
|
+
return joined.length === 2 && room.members.get(selfId)?.joined === true
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
/** Record one state event that arrived by push. */
|
|
137
|
+
applyStateEvent(
|
|
138
|
+
roomId: string,
|
|
139
|
+
type: string,
|
|
140
|
+
stateKey: string | undefined,
|
|
141
|
+
content: Record<string, unknown>,
|
|
142
|
+
): void {
|
|
143
|
+
switch (type) {
|
|
144
|
+
case 'm.room.name':
|
|
145
|
+
if (typeof content.name === 'string') this.setName(roomId, content.name)
|
|
146
|
+
return
|
|
147
|
+
case 'm.room.member':
|
|
148
|
+
if (stateKey !== undefined) {
|
|
149
|
+
this.applyMember(
|
|
150
|
+
roomId,
|
|
151
|
+
stateKey,
|
|
152
|
+
typeof content.membership === 'string'
|
|
153
|
+
? content.membership
|
|
154
|
+
: undefined,
|
|
155
|
+
typeof content.displayname === 'string'
|
|
156
|
+
? content.displayname
|
|
157
|
+
: undefined,
|
|
158
|
+
)
|
|
159
|
+
}
|
|
160
|
+
return
|
|
161
|
+
case 'm.room.encryption':
|
|
162
|
+
this.markEncrypted(roomId)
|
|
163
|
+
return
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
/**
|
|
168
|
+
* Apply one full-state sync answer.
|
|
169
|
+
* @param sync - the answer of `GET /client/v3/sync?full_state=true`.
|
|
170
|
+
* @param selfId - the bot's Matrix user id.
|
|
171
|
+
* @returns the rooms that invited the bot, in answer order.
|
|
172
|
+
*/
|
|
173
|
+
applySync(sync: Sync, selfId: string): string[] {
|
|
174
|
+
for (const roomId of directRoomIds(sync)) this.directRooms.add(roomId)
|
|
175
|
+
|
|
176
|
+
for (const [roomId, joined] of Object.entries(sync.rooms?.join ?? {})) {
|
|
177
|
+
const room = this.room(roomId)
|
|
178
|
+
for (const event of joined.state?.events ?? []) {
|
|
179
|
+
this.applyStateEvent(
|
|
180
|
+
roomId,
|
|
181
|
+
event.type,
|
|
182
|
+
event.state_key,
|
|
183
|
+
event.content as Record<string, unknown>,
|
|
184
|
+
)
|
|
185
|
+
}
|
|
186
|
+
const count = joined.summary?.['m.joined_member_count']
|
|
187
|
+
if (typeof count === 'number') room.joinedMemberCount = count
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
const invites: string[] = []
|
|
191
|
+
for (const [roomId, invited] of Object.entries(sync.rooms?.invite ?? {})) {
|
|
192
|
+
let invitedSelf = false
|
|
193
|
+
for (const event of invited.invite_state?.events ?? []) {
|
|
194
|
+
this.applyStateEvent(
|
|
195
|
+
roomId,
|
|
196
|
+
event.type,
|
|
197
|
+
event.state_key,
|
|
198
|
+
event.content as Record<string, unknown>,
|
|
199
|
+
)
|
|
200
|
+
if (
|
|
201
|
+
event.type === 'm.room.member' &&
|
|
202
|
+
event.state_key === selfId &&
|
|
203
|
+
(event.content as { membership?: string }).membership === 'invite'
|
|
204
|
+
) {
|
|
205
|
+
invitedSelf = true
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
if (invitedSelf) invites.push(roomId)
|
|
209
|
+
}
|
|
210
|
+
return invites
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
/**
|
|
215
|
+
* Run the one-shot full-state sync and apply it.
|
|
216
|
+
*
|
|
217
|
+
* The response's `next_batch` is deliberately dropped: an Application Service has no cursor, and the timeline of this
|
|
218
|
+
* query is history that the host's store already owns.
|
|
219
|
+
*
|
|
220
|
+
* @param internal - the room enumerator (the migrated `Internal`).
|
|
221
|
+
* @param cache - the room cache to fill.
|
|
222
|
+
* @param selfId - the bot's Matrix user id.
|
|
223
|
+
* @returns the rooms that invited the bot.
|
|
224
|
+
*/
|
|
225
|
+
export async function enumerateRooms(
|
|
226
|
+
internal: RoomEnumerator,
|
|
227
|
+
cache: RoomCache,
|
|
228
|
+
selfId: string,
|
|
229
|
+
): Promise<string[]> {
|
|
230
|
+
const sync = await internal.sync(true)
|
|
231
|
+
return cache.applySync(sync, selfId)
|
|
232
|
+
}
|