@wtfalch/chat 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/README.md +293 -0
- package/dist/chat/admin/admin.css +78 -0
- package/dist/chat/admin/index.d.ts +92 -0
- package/dist/chat/admin/index.js +124 -0
- package/dist/chat/admin/react.d.ts +40 -0
- package/dist/chat/admin/react.js +169 -0
- package/dist/chat/chat.css +1003 -0
- package/dist/chat/client.d.ts +30 -0
- package/dist/chat/client.js +1300 -0
- package/dist/chat/exchange.d.ts +9 -0
- package/dist/chat/exchange.js +31 -0
- package/dist/chat/fake/index.d.ts +27 -0
- package/dist/chat/fake/index.js +48 -0
- package/dist/chat/fake/intercept.d.ts +21 -0
- package/dist/chat/fake/intercept.js +57 -0
- package/dist/chat/fake/sample.d.ts +4 -0
- package/dist/chat/fake/sample.js +6 -0
- package/dist/chat/fake/server.d.ts +168 -0
- package/dist/chat/fake/server.js +811 -0
- package/dist/chat/fake/xhr.d.ts +3 -0
- package/dist/chat/fake/xhr.js +104 -0
- package/dist/chat/index.d.ts +10 -0
- package/dist/chat/index.js +9 -0
- package/dist/chat/markdown.d.ts +29 -0
- package/dist/chat/markdown.js +161 -0
- package/dist/chat/react/Attachment.d.ts +39 -0
- package/dist/chat/react/Attachment.js +113 -0
- package/dist/chat/react/Chat.d.ts +48 -0
- package/dist/chat/react/Chat.js +139 -0
- package/dist/chat/react/Composer.d.ts +25 -0
- package/dist/chat/react/Composer.js +157 -0
- package/dist/chat/react/MessageRow.d.ts +21 -0
- package/dist/chat/react/MessageRow.js +114 -0
- package/dist/chat/react/NewDirectMessage.d.ts +23 -0
- package/dist/chat/react/NewDirectMessage.js +47 -0
- package/dist/chat/react/ThreadPanel.d.ts +25 -0
- package/dist/chat/react/ThreadPanel.js +17 -0
- package/dist/chat/react/Timeline.d.ts +27 -0
- package/dist/chat/react/Timeline.js +120 -0
- package/dist/chat/react/index.d.ts +7 -0
- package/dist/chat/react/index.js +6 -0
- package/dist/chat/react/mentions.d.ts +34 -0
- package/dist/chat/react/mentions.js +70 -0
- package/dist/chat/react/scroll.d.ts +26 -0
- package/dist/chat/react/scroll.js +27 -0
- package/dist/chat/react/timelineLayout.d.ts +26 -0
- package/dist/chat/react/timelineLayout.js +47 -0
- package/dist/chat/sanitize.d.ts +49 -0
- package/dist/chat/sanitize.js +264 -0
- package/dist/chat/store.d.ts +16 -0
- package/dist/chat/store.js +25 -0
- package/dist/chat/types.d.ts +340 -0
- package/dist/chat/types.js +1 -0
- package/package.json +88 -0
|
@@ -0,0 +1,1300 @@
|
|
|
1
|
+
import { ClientEvent, ContentHelpers, EventStatus, EventTimeline, EventType, HttpApiEvent, KnownMembership, MatrixError, MatrixEventEvent, MsgType, NotificationCountType, Preset, RelationType, RoomEvent, SyncState, createClient as createMatrixClient, } from 'matrix-js-sdk';
|
|
2
|
+
import { exchange } from "./exchange.js";
|
|
3
|
+
import { toFormattedBody } from "./markdown.js";
|
|
4
|
+
import { createChatStore } from "./store.js";
|
|
5
|
+
/** A Matrix token never outlives the ZITADEL token it was swapped for (see
|
|
6
|
+
* the chat plan section 4), and Synapse's own introspection cache is only
|
|
7
|
+
* good for two minutes -- so a minute of headroom before `expires_at` is
|
|
8
|
+
* enough to always refresh ahead of a real refusal, without refreshing on
|
|
9
|
+
* every render. */
|
|
10
|
+
const REFRESH_MARGIN_MS = 60_000;
|
|
11
|
+
/** The first wait after a failed proactive refresh; it doubles up to the
|
|
12
|
+
* margin above, so a client that cannot refresh keeps trying while the
|
|
13
|
+
* token it holds is still good. */
|
|
14
|
+
const REFRESH_RETRY_MS = 5_000;
|
|
15
|
+
/** The room tag that takes a direct room out of the sidebar. A tag, not a
|
|
16
|
+
* leave: the person stays joined, so the room's history is exactly where
|
|
17
|
+
* they left it when the DM is reopened (ticket #16). Namespaced, as the
|
|
18
|
+
* Matrix spec requires of any tag outside `m.` and `u.`. */
|
|
19
|
+
const HIDDEN_TAG = 'com.wtfalch.hidden';
|
|
20
|
+
/** Every `startClient()` in this file passes these, including the two
|
|
21
|
+
* recoveries: a restart that dropped `threadSupport` would quietly put
|
|
22
|
+
* every later thread reply back into the room's own timeline. */
|
|
23
|
+
const START_OPTIONS = { threadSupport: true };
|
|
24
|
+
/** What the bootstrap sets Synapse's `max_upload_size` to (chat plan
|
|
25
|
+
* section 8). Checked here so a person who picks a 200 MB video is told
|
|
26
|
+
* so at once, rather than after the whole thing has gone up and Synapse
|
|
27
|
+
* has refused it. */
|
|
28
|
+
export const MAX_UPLOAD_BYTES = 50 * 1024 * 1024;
|
|
29
|
+
/** Synapse serves media only to a request carrying the token
|
|
30
|
+
* (`enable_authenticated_media`), and only on this endpoint. The legacy
|
|
31
|
+
* `/_matrix/media/...` download paths are unauthenticated and are never
|
|
32
|
+
* used by this package (ticket #13). */
|
|
33
|
+
const MEDIA_DOWNLOAD_PATH = '/_matrix/client/v1/media/download';
|
|
34
|
+
/**
|
|
35
|
+
* A chat session behind the exchange: a matrix-js-sdk `MatrixClient` the
|
|
36
|
+
* caller never sees, refreshed on its own, exposing only what a UI needs.
|
|
37
|
+
*
|
|
38
|
+
* **Crypto stays off.** Encryption is not in the first ship (chat plan
|
|
39
|
+
* section 6), so this never calls `initRustCrypto()`. matrix-js-sdk only
|
|
40
|
+
* imports its Rust crypto WASM when that is called (`client.js`: "importing
|
|
41
|
+
* rust-crypto will download the webassembly, so we delay it until we know
|
|
42
|
+
* it will be [needed]") -- so skipping it means the WASM module is never
|
|
43
|
+
* loaded, in the browser or under vitest. No shim or polyfill for it is
|
|
44
|
+
* needed either way.
|
|
45
|
+
*
|
|
46
|
+
* **Refresh, not a Matrix refresh token.** There is no such thing (section
|
|
47
|
+
* 4): a near-expiry timer and a `Session.logged_out` listener (fired by
|
|
48
|
+
* matrix-js-sdk's own HTTP layer on `M_UNKNOWN_TOKEN`, since no
|
|
49
|
+
* `refreshToken` is configured -- see `http-api/fetch.ts`) both call back
|
|
50
|
+
* into the exchange and swap the token in with `setAccessToken`. An
|
|
51
|
+
* unknown-token refresh also has to restart the client: matrix-js-sdk's
|
|
52
|
+
* sync loop treats `M_UNKNOWN_TOKEN` as "the logout already happened" and
|
|
53
|
+
* stops itself (`sync.ts`'s `shouldAbortSync`), and `startClient()` is a
|
|
54
|
+
* no-op while `clientRunning` is still true, so a plain retry would never
|
|
55
|
+
* resume syncing.
|
|
56
|
+
*/
|
|
57
|
+
export function createChatClient(options) {
|
|
58
|
+
const { exchangeUrl, getAccessToken, deviceId, storeName } = options;
|
|
59
|
+
let client;
|
|
60
|
+
let starting;
|
|
61
|
+
let refreshTimer;
|
|
62
|
+
let recovering;
|
|
63
|
+
let resyncing;
|
|
64
|
+
let status = 'offline';
|
|
65
|
+
const listeners = new Set();
|
|
66
|
+
const timelineListeners = new Map();
|
|
67
|
+
/** Files still going up, oldest first, per room. They are not events
|
|
68
|
+
* yet -- nothing has been sent -- so matrix-js-sdk knows nothing about
|
|
69
|
+
* them and `timeline()` appends them itself. */
|
|
70
|
+
const uploads = new Map();
|
|
71
|
+
let uploadSeq = 0;
|
|
72
|
+
const statusListeners = new Set();
|
|
73
|
+
async function performExchange() {
|
|
74
|
+
return exchange(exchangeUrl, getAccessToken, deviceId);
|
|
75
|
+
}
|
|
76
|
+
/** A failed proactive refresh must not end proactive refreshing: nothing
|
|
77
|
+
* else re-arms this timer, so without the retry the client would go
|
|
78
|
+
* quiet and wait for its token to actually die. The exchange is behind a
|
|
79
|
+
* rate limit, so a failure is often just "too soon". */
|
|
80
|
+
function scheduleRefresh(expiresAt, retryIn) {
|
|
81
|
+
clearTimeout(refreshTimer);
|
|
82
|
+
const delay = retryIn ?? Math.max(0, new Date(expiresAt).getTime() - Date.now() - REFRESH_MARGIN_MS);
|
|
83
|
+
refreshTimer = setTimeout(() => {
|
|
84
|
+
refreshToken().catch(() => {
|
|
85
|
+
scheduleRefresh(expiresAt, Math.min((retryIn ?? REFRESH_RETRY_MS) * 2, REFRESH_MARGIN_MS));
|
|
86
|
+
});
|
|
87
|
+
}, delay);
|
|
88
|
+
}
|
|
89
|
+
/** A proactive, near-expiry refresh. The token is still good, so this
|
|
90
|
+
* only swaps it in -- the sync loop keeps running and never notices. */
|
|
91
|
+
async function refreshToken() {
|
|
92
|
+
if (!client)
|
|
93
|
+
return;
|
|
94
|
+
const body = await performExchange();
|
|
95
|
+
client.setAccessToken(body.access_token);
|
|
96
|
+
scheduleRefresh(body.expires_at);
|
|
97
|
+
}
|
|
98
|
+
function setStatus(next) {
|
|
99
|
+
if (status === next)
|
|
100
|
+
return;
|
|
101
|
+
status = next;
|
|
102
|
+
for (const listener of statusListeners)
|
|
103
|
+
listener(status);
|
|
104
|
+
}
|
|
105
|
+
/** `undefined` for `SyncState.Stopped`: that fires as a transient step
|
|
106
|
+
* inside `recoverFromLoggedOut`/`recoverFromRefusedPosition`'s own
|
|
107
|
+
* `stopClient()` + `startClient()`, and flipping the status to 'offline'
|
|
108
|
+
* for that instant, only to flip again a tick later, would be noise the
|
|
109
|
+
* UI never needed to see. */
|
|
110
|
+
function statusForSyncState(state) {
|
|
111
|
+
switch (state) {
|
|
112
|
+
case SyncState.Prepared:
|
|
113
|
+
case SyncState.Syncing:
|
|
114
|
+
return 'connected';
|
|
115
|
+
case SyncState.Catchup:
|
|
116
|
+
case SyncState.Reconnecting:
|
|
117
|
+
return 'catching-up';
|
|
118
|
+
case SyncState.Error:
|
|
119
|
+
return 'offline';
|
|
120
|
+
default:
|
|
121
|
+
return undefined;
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
/** A hard, definite refusal of the *stored* sync position: the server
|
|
125
|
+
* itself said no (a `MatrixError`, `400` -- distinct from the `429`s the
|
|
126
|
+
* sync loop already retries on its own, and from `M_UNKNOWN_TOKEN`'s
|
|
127
|
+
* `401`, which is session death, handled above by
|
|
128
|
+
* `recoverFromLoggedOut`). Guarded on a sync token already being in
|
|
129
|
+
* play: a `400` on the very first, since-less sync is a different
|
|
130
|
+
* problem this does not paper over. */
|
|
131
|
+
function isRefusedSyncPosition(error, target) {
|
|
132
|
+
if (!(error instanceof MatrixError))
|
|
133
|
+
return false;
|
|
134
|
+
if (error.httpStatus !== 400)
|
|
135
|
+
return false;
|
|
136
|
+
// Synapse answers `M_UNKNOWN` "Invalid stream token" for a position it
|
|
137
|
+
// will not take (checked live against v1.161.0). Other 400s mid-sync --
|
|
138
|
+
// `M_INVALID_PARAM` for a filter id it no longer knows, say -- are not
|
|
139
|
+
// that, and this path wipes the local store, so they must not land here.
|
|
140
|
+
if (error.errcode !== 'M_UNKNOWN')
|
|
141
|
+
return false;
|
|
142
|
+
return Boolean(target.store.getSyncToken());
|
|
143
|
+
}
|
|
144
|
+
/** Synapse refused the stored position -- confirmed live to happen after
|
|
145
|
+
* a long enough time offline. Recovery: wipe the local store (rooms,
|
|
146
|
+
* sync token, filters) and let the sync loop start over exactly the way
|
|
147
|
+
* `start()` does the first time, so the next request carries no `since`
|
|
148
|
+
* and Synapse sends a full, authoritative snapshot -- no stale event can
|
|
149
|
+
* linger to duplicate or contradict it. Only one recovery runs at a
|
|
150
|
+
* time. */
|
|
151
|
+
async function recoverFromRefusedPosition() {
|
|
152
|
+
if (resyncing)
|
|
153
|
+
return resyncing;
|
|
154
|
+
const target = client;
|
|
155
|
+
if (!target)
|
|
156
|
+
return;
|
|
157
|
+
resyncing = (async () => {
|
|
158
|
+
target.stopClient();
|
|
159
|
+
await target.store.deleteAllData();
|
|
160
|
+
const outcome = nextSyncOutcome(target);
|
|
161
|
+
await target.startClient(START_OPTIONS);
|
|
162
|
+
await outcome;
|
|
163
|
+
notify();
|
|
164
|
+
})();
|
|
165
|
+
try {
|
|
166
|
+
await resyncing;
|
|
167
|
+
}
|
|
168
|
+
finally {
|
|
169
|
+
resyncing = undefined;
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
/** Waits for the next sync to either land or fail, so callers can await a
|
|
173
|
+
* fresh `startClient()` the way `start()` awaits the first one.
|
|
174
|
+
*
|
|
175
|
+
* An `M_UNKNOWN_TOKEN` error is deliberately not a failure here, and not
|
|
176
|
+
* cause to unsubscribe: the sync loop that failed on the *old* token can
|
|
177
|
+
* still emit its own stale `ERROR` after `recoverFromLoggedOut` has
|
|
178
|
+
* already stopped and restarted the client on a new one -- the two
|
|
179
|
+
* happen on the same event, racing through their own microtasks, in no
|
|
180
|
+
* guaranteed order. That token's fate is `Session.logged_out`'s to
|
|
181
|
+
* handle; this only cares whether the *current* attempt lands. */
|
|
182
|
+
function nextSyncOutcome(target) {
|
|
183
|
+
return new Promise((resolve, reject) => {
|
|
184
|
+
const onOutcome = (state, _prev, data) => {
|
|
185
|
+
if (state === SyncState.Prepared || state === SyncState.Syncing) {
|
|
186
|
+
target.off(ClientEvent.Sync, onOutcome);
|
|
187
|
+
resolve();
|
|
188
|
+
return;
|
|
189
|
+
}
|
|
190
|
+
if (state !== SyncState.Error)
|
|
191
|
+
return;
|
|
192
|
+
const errcode = data?.error?.errcode;
|
|
193
|
+
if (errcode === 'M_UNKNOWN_TOKEN')
|
|
194
|
+
return;
|
|
195
|
+
target.off(ClientEvent.Sync, onOutcome);
|
|
196
|
+
reject(new Error('chat sync did not start'));
|
|
197
|
+
};
|
|
198
|
+
target.on(ClientEvent.Sync, onOutcome);
|
|
199
|
+
});
|
|
200
|
+
}
|
|
201
|
+
/** The token died server-side. Re-exchange, then restart the client:
|
|
202
|
+
* see the module comment for why a plain `setAccessToken` is not enough
|
|
203
|
+
* once the sync loop has stopped itself. Only one recovery runs at a
|
|
204
|
+
* time -- several requests can fail on the same dead token at once. */
|
|
205
|
+
async function recoverFromLoggedOut() {
|
|
206
|
+
if (recovering)
|
|
207
|
+
return recovering;
|
|
208
|
+
const target = client;
|
|
209
|
+
if (!target)
|
|
210
|
+
return;
|
|
211
|
+
recovering = (async () => {
|
|
212
|
+
const body = await performExchange();
|
|
213
|
+
target.stopClient();
|
|
214
|
+
target.setAccessToken(body.access_token);
|
|
215
|
+
scheduleRefresh(body.expires_at);
|
|
216
|
+
const outcome = nextSyncOutcome(target);
|
|
217
|
+
await target.startClient(START_OPTIONS);
|
|
218
|
+
await outcome;
|
|
219
|
+
notify();
|
|
220
|
+
})();
|
|
221
|
+
try {
|
|
222
|
+
await recovering;
|
|
223
|
+
}
|
|
224
|
+
finally {
|
|
225
|
+
recovering = undefined;
|
|
226
|
+
}
|
|
227
|
+
}
|
|
228
|
+
/** matrix-js-sdk only emits this for `M_UNKNOWN_TOKEN` (`http-api/fetch.ts`),
|
|
229
|
+
* so no further check is needed here. Errors are swallowed, not thrown
|
|
230
|
+
* into an unhandled rejection: a refused re-exchange leaves the sync
|
|
231
|
+
* stopped, and the next near-expiry timer or unknown-token event tries
|
|
232
|
+
* again. */
|
|
233
|
+
function onLoggedOut() {
|
|
234
|
+
recoverFromLoggedOut().catch(() => { });
|
|
235
|
+
}
|
|
236
|
+
function directRoomIds(target) {
|
|
237
|
+
const ids = new Set();
|
|
238
|
+
for (const roomIds of Object.values(directContent(target))) {
|
|
239
|
+
for (const id of roomIds ?? [])
|
|
240
|
+
ids.add(id);
|
|
241
|
+
}
|
|
242
|
+
return ids;
|
|
243
|
+
}
|
|
244
|
+
/** The account's `m.direct` data, as `{ userId: roomId[] }`. One room can
|
|
245
|
+
* be listed under several people -- that is how a group DM is recorded --
|
|
246
|
+
* so a lookup by room id has to flatten it (`directRoomIds`) and a lookup
|
|
247
|
+
* by person reads it directly. */
|
|
248
|
+
function directContent(target) {
|
|
249
|
+
return target.getAccountData(EventType.Direct)?.getContent() ?? {};
|
|
250
|
+
}
|
|
251
|
+
/** Joined rooms and invitations that need an answer: matrix-js-sdk's own
|
|
252
|
+
* `getRooms()` keeps a room after the account leaves it (its own
|
|
253
|
+
* `ClientEvent.DeleteRoom` is for an explicit "forget", never fired by a
|
|
254
|
+
* plain sync leave) -- without this filter, a room the person left would
|
|
255
|
+
* linger in the list until the page reloaded.
|
|
256
|
+
*
|
|
257
|
+
* The company space is joined too, and is not a place to read: it is the
|
|
258
|
+
* membership list `people()` reads, so it is a room in Matrix's sense
|
|
259
|
+
* and nothing in Chat's. A hidden direct room is left out for the reason
|
|
260
|
+
* `hideDirectMessage` exists. */
|
|
261
|
+
function readRooms() {
|
|
262
|
+
if (!client)
|
|
263
|
+
return [];
|
|
264
|
+
const direct = directRoomIds(client);
|
|
265
|
+
return client
|
|
266
|
+
.getRooms()
|
|
267
|
+
.filter((room) => room.getMyMembership() === KnownMembership.Join ||
|
|
268
|
+
room.getMyMembership() === KnownMembership.Invite)
|
|
269
|
+
.filter((room) => !room.isSpaceRoom())
|
|
270
|
+
.filter((room) => !(HIDDEN_TAG in room.tags))
|
|
271
|
+
.map((room) => ({
|
|
272
|
+
id: room.roomId,
|
|
273
|
+
name: room.name,
|
|
274
|
+
isDirect: direct.has(room.roomId) || Boolean(room.getDMInviter()),
|
|
275
|
+
membership: room.getMyMembership() === KnownMembership.Invite
|
|
276
|
+
? 'invite'
|
|
277
|
+
: 'join',
|
|
278
|
+
unreadCount: room.getMyMembership() === KnownMembership.Invite
|
|
279
|
+
? 1
|
|
280
|
+
: room.getUnreadNotificationCount(NotificationCountType.Total),
|
|
281
|
+
}));
|
|
282
|
+
}
|
|
283
|
+
/** The company space: the one space the account is joined to (chat plan
|
|
284
|
+
* section 5 -- one agora is one company is one space). `undefined` before
|
|
285
|
+
* the first sync lands, and for a session whose account is in none. */
|
|
286
|
+
function companySpace(target) {
|
|
287
|
+
return target
|
|
288
|
+
.getRooms()
|
|
289
|
+
.find((room) => room.isSpaceRoom() && room.getMyMembership() === KnownMembership.Join);
|
|
290
|
+
}
|
|
291
|
+
function toPerson(member) {
|
|
292
|
+
return { userId: member.userId, name: member.name };
|
|
293
|
+
}
|
|
294
|
+
/** Everyone in the company space but the signed-in person. Guests are not
|
|
295
|
+
* in the space, so this cannot offer one -- see `ChatPerson`. */
|
|
296
|
+
function readPeople() {
|
|
297
|
+
if (!client)
|
|
298
|
+
return [];
|
|
299
|
+
const space = companySpace(client);
|
|
300
|
+
if (!space)
|
|
301
|
+
return [];
|
|
302
|
+
const me = client.getUserId();
|
|
303
|
+
return space
|
|
304
|
+
.getMembersWithMembership(KnownMembership.Join)
|
|
305
|
+
.filter((member) => member.userId !== me)
|
|
306
|
+
.map(toPerson)
|
|
307
|
+
.sort((a, b) => a.name.localeCompare(b.name));
|
|
308
|
+
}
|
|
309
|
+
/** Who else is in a room, joined or still invited -- an invitee counts,
|
|
310
|
+
* or a DM started a second ago would not be found as an existing one
|
|
311
|
+
* until the other person accepted, and the person would create a second
|
|
312
|
+
* room with the same one other member. */
|
|
313
|
+
function otherMemberIds(room, me) {
|
|
314
|
+
const ids = new Set();
|
|
315
|
+
for (const membership of [KnownMembership.Join, KnownMembership.Invite]) {
|
|
316
|
+
for (const member of room.getMembersWithMembership(membership)) {
|
|
317
|
+
if (member.userId !== me)
|
|
318
|
+
ids.add(member.userId);
|
|
319
|
+
}
|
|
320
|
+
}
|
|
321
|
+
return ids;
|
|
322
|
+
}
|
|
323
|
+
function sameSet(a, b) {
|
|
324
|
+
if (a.size !== b.size)
|
|
325
|
+
return false;
|
|
326
|
+
for (const value of a)
|
|
327
|
+
if (!b.has(value))
|
|
328
|
+
return false;
|
|
329
|
+
return true;
|
|
330
|
+
}
|
|
331
|
+
/** Find an existing DM by its complete membership, not by one account-data
|
|
332
|
+
* key. A recipient may record an accepted group only under its inviter,
|
|
333
|
+
* so selecting another participant first must still find that room. */
|
|
334
|
+
function findDirectRoom(target, userIds) {
|
|
335
|
+
const me = target.getUserId();
|
|
336
|
+
for (const roomId of directRoomIds(target)) {
|
|
337
|
+
const room = target.getRoom(roomId);
|
|
338
|
+
if (!room || room.getMyMembership() !== KnownMembership.Join)
|
|
339
|
+
continue;
|
|
340
|
+
if (sameSet(otherMemberIds(room, me), userIds))
|
|
341
|
+
return room;
|
|
342
|
+
}
|
|
343
|
+
return undefined;
|
|
344
|
+
}
|
|
345
|
+
/** Lists the new room under each of its people in `m.direct`, leaving
|
|
346
|
+
* every other entry alone -- the account data is one object for the
|
|
347
|
+
* whole account, so it is read, extended and written back rather than
|
|
348
|
+
* replaced. */
|
|
349
|
+
async function recordDirect(target, roomId, userIds) {
|
|
350
|
+
const next = { ...directContent(target) };
|
|
351
|
+
for (const userId of userIds) {
|
|
352
|
+
const rooms = next[userId] ?? [];
|
|
353
|
+
if (!rooms.includes(roomId))
|
|
354
|
+
next[userId] = [...rooms, roomId];
|
|
355
|
+
}
|
|
356
|
+
await target.setAccountData(EventType.Direct, next);
|
|
357
|
+
}
|
|
358
|
+
/** Resolves once `roomId` is a joined room this client knows *and* its
|
|
359
|
+
* own `m.direct` data says so -- which, for a room the server has just
|
|
360
|
+
* created, means once sync has delivered both. Waiting for the room
|
|
361
|
+
* alone is not enough: the room and the account-data write come back on
|
|
362
|
+
* separate syncs, and between them the room is a channel as far as
|
|
363
|
+
* every other method here can tell -- `rooms()` files it under channels,
|
|
364
|
+
* `hideDirectMessage` refuses it, and a second `startDirectMessage` with
|
|
365
|
+
* the same people finds nothing and creates a duplicate room. */
|
|
366
|
+
function awaitDirectRoom(target, roomId) {
|
|
367
|
+
const ready = () => target.getRoom(roomId)?.getMyMembership() === KnownMembership.Join &&
|
|
368
|
+
directRoomIds(target).has(roomId);
|
|
369
|
+
if (ready())
|
|
370
|
+
return Promise.resolve();
|
|
371
|
+
return new Promise((resolve) => {
|
|
372
|
+
const check = () => {
|
|
373
|
+
if (!ready())
|
|
374
|
+
return;
|
|
375
|
+
target.off(ClientEvent.Room, check);
|
|
376
|
+
target.off(ClientEvent.AccountData, check);
|
|
377
|
+
target.off(RoomEvent.MyMembership, check);
|
|
378
|
+
resolve();
|
|
379
|
+
};
|
|
380
|
+
target.on(ClientEvent.Room, check);
|
|
381
|
+
target.on(ClientEvent.AccountData, check);
|
|
382
|
+
target.on(RoomEvent.MyMembership, check);
|
|
383
|
+
});
|
|
384
|
+
}
|
|
385
|
+
/** Reopens or creates the direct room with exactly these people. See
|
|
386
|
+
* `ChatClient.startDirectMessage`.
|
|
387
|
+
*
|
|
388
|
+
* The creation carries `is_direct` and an invite list and nothing else:
|
|
389
|
+
* the Synapse gate refuses a member-created room that also carries a
|
|
390
|
+
* `name`, a `topic`, `initial_state` or `creation_content`, because a
|
|
391
|
+
* room dressed as a channel is the manage app's to make (chat plan
|
|
392
|
+
* section 5). `private_chat` rather than `trusted_private_chat` for a
|
|
393
|
+
* group too: nobody adds a person to an existing DM here -- a different
|
|
394
|
+
* set of people is a different room -- so there is no reason to hand
|
|
395
|
+
* invitees the power to. */
|
|
396
|
+
async function startDirectMessage(userIds) {
|
|
397
|
+
if (!client)
|
|
398
|
+
throw new Error('chat: startDirectMessage called before start()');
|
|
399
|
+
const target = client;
|
|
400
|
+
const wanted = new Set(userIds);
|
|
401
|
+
if (wanted.size === 0) {
|
|
402
|
+
throw new Error('chat: a direct message needs at least one other person');
|
|
403
|
+
}
|
|
404
|
+
const existing = findDirectRoom(target, wanted);
|
|
405
|
+
if (existing) {
|
|
406
|
+
if (HIDDEN_TAG in existing.tags)
|
|
407
|
+
await target.deleteRoomTag(existing.roomId, HIDDEN_TAG);
|
|
408
|
+
return existing.roomId;
|
|
409
|
+
}
|
|
410
|
+
const { room_id: roomId } = await target.createRoom({
|
|
411
|
+
preset: Preset.PrivateChat,
|
|
412
|
+
is_direct: true,
|
|
413
|
+
invite: [...wanted],
|
|
414
|
+
});
|
|
415
|
+
await recordDirect(target, roomId, wanted);
|
|
416
|
+
await awaitDirectRoom(target, roomId);
|
|
417
|
+
return roomId;
|
|
418
|
+
}
|
|
419
|
+
/** See `ChatClient.hideDirectMessage`. Guarded on the room actually being
|
|
420
|
+
* direct: the tag is what keeps a room out of `rooms()`, and a channel
|
|
421
|
+
* hidden this way could never be got back -- `startDirectMessage` is the
|
|
422
|
+
* only thing that removes it.
|
|
423
|
+
*
|
|
424
|
+
* No local echo, here or in `startDirectMessage`: Synapse pushes the tag
|
|
425
|
+
* straight back down the already-parked `/sync`, and every landed sync
|
|
426
|
+
* runs `notify()` (`onSync`). The room leaves the list a round trip
|
|
427
|
+
* later, not a render later, and a second source of truth for "is this
|
|
428
|
+
* hidden" would have to be reconciled against the first one forever. */
|
|
429
|
+
async function hideDirectMessage(roomId) {
|
|
430
|
+
if (!client)
|
|
431
|
+
return;
|
|
432
|
+
const room = client.getRoom(roomId);
|
|
433
|
+
if (!room || !directRoomIds(client).has(roomId))
|
|
434
|
+
return;
|
|
435
|
+
await client.setRoomTag(roomId, HIDDEN_TAG, {});
|
|
436
|
+
}
|
|
437
|
+
async function acceptInvitation(roomId) {
|
|
438
|
+
const target = client;
|
|
439
|
+
const room = target?.getRoom(roomId);
|
|
440
|
+
if (!target || !room || room.getMyMembership() !== KnownMembership.Invite)
|
|
441
|
+
return;
|
|
442
|
+
const inviter = room.getDMInviter();
|
|
443
|
+
// Persist the direct-room marker before joining: a failed account-data
|
|
444
|
+
// write leaves an answerable invitation instead of an unclassified DM.
|
|
445
|
+
if (inviter)
|
|
446
|
+
await recordDirect(target, roomId, new Set([inviter]));
|
|
447
|
+
await target.joinRoom(roomId);
|
|
448
|
+
if (client === target)
|
|
449
|
+
notify();
|
|
450
|
+
}
|
|
451
|
+
async function declineInvitation(roomId) {
|
|
452
|
+
const target = client;
|
|
453
|
+
if (target?.getRoom(roomId)?.getMyMembership() !== KnownMembership.Invite)
|
|
454
|
+
return;
|
|
455
|
+
await target.leave(roomId);
|
|
456
|
+
if (client === target)
|
|
457
|
+
notify();
|
|
458
|
+
}
|
|
459
|
+
function notify() {
|
|
460
|
+
const current = readRooms();
|
|
461
|
+
for (const listener of listeners)
|
|
462
|
+
listener(current);
|
|
463
|
+
}
|
|
464
|
+
/** Only a landed sync -- `PREPARED` or `SYNCING` -- ever changes the room
|
|
465
|
+
* list; an `ERROR` state (an `M_UNKNOWN_TOKEN` among them, on its way to
|
|
466
|
+
* `recoverFromLoggedOut` below) never does, and notifying on it would
|
|
467
|
+
* race a subscriber against the recovery that is about to fix it. A
|
|
468
|
+
* refused sync position (`isRefusedSyncPosition`) is the other thing an
|
|
469
|
+
* `ERROR` or `RECONNECTING` state can mean; that one needs its own
|
|
470
|
+
* recovery, `recoverFromLoggedOut`'s plain retry never resolves it. */
|
|
471
|
+
function onSync(state, _prev, data) {
|
|
472
|
+
const next = statusForSyncState(state);
|
|
473
|
+
if (next)
|
|
474
|
+
setStatus(next);
|
|
475
|
+
if (state === SyncState.Prepared || state === SyncState.Syncing) {
|
|
476
|
+
notify();
|
|
477
|
+
return;
|
|
478
|
+
}
|
|
479
|
+
if ((state === SyncState.Error || state === SyncState.Reconnecting) &&
|
|
480
|
+
client &&
|
|
481
|
+
isRefusedSyncPosition(data?.error, client)) {
|
|
482
|
+
recoverFromRefusedPosition().catch(() => { });
|
|
483
|
+
}
|
|
484
|
+
}
|
|
485
|
+
function notifyTimeline(roomId) {
|
|
486
|
+
for (const listener of timelineListeners.get(roomId) ?? [])
|
|
487
|
+
listener();
|
|
488
|
+
}
|
|
489
|
+
/** `RoomEvent.Timeline` (a page landing, a new event arriving) and
|
|
490
|
+
* `RoomEvent.LocalEchoUpdated` (an optimistic send's status changing) are
|
|
491
|
+
* both re-emitted onto the client itself for every room (`sync.ts`'s
|
|
492
|
+
* `getOrCreateRoom`), so one listener here covers every room a caller
|
|
493
|
+
* subscribes to -- the same shape `onRoomsChanged` already uses. */
|
|
494
|
+
function onRoomTimelineChanged(event, room) {
|
|
495
|
+
if (!room)
|
|
496
|
+
return;
|
|
497
|
+
watchForEdit(event, room);
|
|
498
|
+
notifyTimeline(room.roomId);
|
|
499
|
+
}
|
|
500
|
+
/** An edit arriving is two things, a tick apart: the `m.replace` event
|
|
501
|
+
* lands in the timeline, and only afterwards does matrix-js-sdk fold its
|
|
502
|
+
* content into the message it replaces -- that aggregation is async
|
|
503
|
+
* (`RelationsContainer.aggregateChildEvent` returns a promise). Only the
|
|
504
|
+
* first fires `RoomEvent.Timeline`, so a caller re-reading `timeline()`
|
|
505
|
+
* then still gets the old text, and would keep it until something else
|
|
506
|
+
* happened in the room.
|
|
507
|
+
*
|
|
508
|
+
* So the replaced message is asked to say when it has actually been
|
|
509
|
+
* replaced, which is the moment there is something new to draw. `once`,
|
|
510
|
+
* because each edit event sets this up again for its own target. */
|
|
511
|
+
function watchForEdit(event, room) {
|
|
512
|
+
if (!event.isRelation(RelationType.Replace))
|
|
513
|
+
return;
|
|
514
|
+
const targetId = event.getRelation()?.event_id;
|
|
515
|
+
const target = targetId ? room.findEventById(targetId) : undefined;
|
|
516
|
+
target?.once(MatrixEventEvent.Replaced, () => notifyTimeline(room.roomId));
|
|
517
|
+
}
|
|
518
|
+
/** A thread's own summary, for the message that started it. `null` when
|
|
519
|
+
* the message has started nothing, and never read for an event inside a
|
|
520
|
+
* thread -- Matrix threads are one level, so a reply can never be a root
|
|
521
|
+
* (chat plan section 9's "threads, one level"). */
|
|
522
|
+
/** Every reply in a thread, oldest first.
|
|
523
|
+
*
|
|
524
|
+
* matrix-js-sdk's own `Thread` is the fast path, but it is not the
|
|
525
|
+
* record, and there are two ways to be left without one.
|
|
526
|
+
*
|
|
527
|
+
* A thread is built from the root's bundled summary, which the person
|
|
528
|
+
* who *wrote* a reply may never be served -- so their own reply can be
|
|
529
|
+
* missing from their own thread panel. And redacting the message that
|
|
530
|
+
* started a thread tears an existing `Thread` down: `Thread.onRedaction`
|
|
531
|
+
* gives up once its reply count has reached zero, and that count is
|
|
532
|
+
* rebuilt from the same bundled summary, which Synapse stops sending as
|
|
533
|
+
* soon as the root is redacted.
|
|
534
|
+
*
|
|
535
|
+
* The replies themselves are untouched in both cases -- a redaction
|
|
536
|
+
* takes one event's content, never anything relating to it -- so this
|
|
537
|
+
* falls back to the room's own relations, where every `m.thread` reply
|
|
538
|
+
* is aggregated the moment it arrives. A thread whose root was deleted
|
|
539
|
+
* keeps its replies (ticket #19).
|
|
540
|
+
*
|
|
541
|
+
* An edit of a reply is routed into the thread as well, and it is not a
|
|
542
|
+
* reply: counting it would say "2 replies" for one sentence somebody
|
|
543
|
+
* fixed a typo in. */
|
|
544
|
+
function threadReplies(room, rootId) {
|
|
545
|
+
const isReply = (event) => event.getId() !== rootId && !event.isRelation(RelationType.Replace);
|
|
546
|
+
const thread = room.getThread(rootId);
|
|
547
|
+
const fromThread = thread?.events.filter(isReply) ?? [];
|
|
548
|
+
if (fromThread.length > 0)
|
|
549
|
+
return fromThread;
|
|
550
|
+
const related = room.relations
|
|
551
|
+
.getChildEventsForEvent(rootId, RelationType.Thread, EventType.RoomMessage)
|
|
552
|
+
?.getRelations() ?? [];
|
|
553
|
+
return related.filter(isReply).sort((a, b) => a.getTs() - b.getTs());
|
|
554
|
+
}
|
|
555
|
+
function toThreadSummary(room, rootId) {
|
|
556
|
+
const thread = room.getThread(rootId);
|
|
557
|
+
// matrix-js-sdk's own count while it still has the thread: it is the
|
|
558
|
+
// number the server bundles onto the root, with a reply still in flight
|
|
559
|
+
// added to it. Counting `thread.events` here instead would be a second
|
|
560
|
+
// answer to a question matrix-js-sdk already answers, and a different
|
|
561
|
+
// one while a send settles.
|
|
562
|
+
if (thread && thread.length > 0) {
|
|
563
|
+
return { replyCount: thread.length, participants: namesOf(room, thread.events) };
|
|
564
|
+
}
|
|
565
|
+
// A thread matrix-js-sdk has torn down -- see `threadReplies`.
|
|
566
|
+
const replies = threadReplies(room, rootId);
|
|
567
|
+
if (replies.length === 0)
|
|
568
|
+
return null;
|
|
569
|
+
const root = room.findEventById(rootId);
|
|
570
|
+
return {
|
|
571
|
+
replyCount: replies.length,
|
|
572
|
+
participants: namesOf(room, root ? [root, ...replies] : replies),
|
|
573
|
+
};
|
|
574
|
+
}
|
|
575
|
+
/** Who wrote these, by display name, first to last, each once. */
|
|
576
|
+
function namesOf(room, events) {
|
|
577
|
+
const names = [];
|
|
578
|
+
for (const event of events) {
|
|
579
|
+
const senderId = event.getSender();
|
|
580
|
+
if (!senderId)
|
|
581
|
+
continue;
|
|
582
|
+
const name = room.getMember(senderId)?.name ?? senderId;
|
|
583
|
+
if (!names.includes(name))
|
|
584
|
+
names.push(name);
|
|
585
|
+
}
|
|
586
|
+
return names;
|
|
587
|
+
}
|
|
588
|
+
/** What people have reacted to `eventId` with. Read off matrix-js-sdk's
|
|
589
|
+
* own relations container, which is where `m.annotation` events are
|
|
590
|
+
* aggregated as they arrive -- this never walks the timeline looking
|
|
591
|
+
* for them.
|
|
592
|
+
*
|
|
593
|
+
* Sorted most-reacted first, then by key, so two people looking at the
|
|
594
|
+
* same message see the same row in the same order. A redacted reaction
|
|
595
|
+
* is skipped rather than counted: Matrix removes a reaction by redacting
|
|
596
|
+
* it, and the tombstone stays in the relation. */
|
|
597
|
+
function readReactions(room, eventId) {
|
|
598
|
+
const relations = room.relations.getChildEventsForEvent(eventId, RelationType.Annotation, EventType.Reaction);
|
|
599
|
+
const byKey = relations?.getSortedAnnotationsByKey();
|
|
600
|
+
if (!byKey)
|
|
601
|
+
return [];
|
|
602
|
+
const me = client?.getUserId();
|
|
603
|
+
const reactions = [];
|
|
604
|
+
for (const [key, events] of byKey) {
|
|
605
|
+
const people = [];
|
|
606
|
+
let mine = false;
|
|
607
|
+
for (const event of events) {
|
|
608
|
+
if (event.isRedacted())
|
|
609
|
+
continue;
|
|
610
|
+
const senderId = event.getSender();
|
|
611
|
+
if (!senderId)
|
|
612
|
+
continue;
|
|
613
|
+
if (senderId === me)
|
|
614
|
+
mine = true;
|
|
615
|
+
const name = room.getMember(senderId)?.name ?? senderId;
|
|
616
|
+
if (!people.includes(name))
|
|
617
|
+
people.push(name);
|
|
618
|
+
}
|
|
619
|
+
if (people.length === 0)
|
|
620
|
+
continue;
|
|
621
|
+
reactions.push({ key, count: people.length, mine, people });
|
|
622
|
+
}
|
|
623
|
+
reactions.sort((a, b) => b.count - a.count || a.key.localeCompare(b.key));
|
|
624
|
+
return reactions;
|
|
625
|
+
}
|
|
626
|
+
/** Whether a message names the signed-in person. `m.mentions.user_ids` is
|
|
627
|
+
* the whole of it: the text may well hold somebody's display name
|
|
628
|
+
* without meaning them, and two people can share one. */
|
|
629
|
+
function mentionsMe(event) {
|
|
630
|
+
const me = client?.getUserId();
|
|
631
|
+
if (!me)
|
|
632
|
+
return false;
|
|
633
|
+
const mentions = event.getContent()['m.mentions'];
|
|
634
|
+
const userIds = mentions?.user_ids;
|
|
635
|
+
return Array.isArray(userIds) && userIds.includes(me);
|
|
636
|
+
}
|
|
637
|
+
/** A `m.room.message` event, reduced to what the timeline draws.
|
|
638
|
+
* `undefined` for anything else -- a membership change, a reaction, a
|
|
639
|
+
* room's own state -- which is out of this ticket's scope (chat plan
|
|
640
|
+
* section 9). */
|
|
641
|
+
function toTimelineEvent(event, room, inThread) {
|
|
642
|
+
if (event.getType() !== EventType.RoomMessage)
|
|
643
|
+
return undefined;
|
|
644
|
+
if (event.isRelation(RelationType.Replace))
|
|
645
|
+
return undefined;
|
|
646
|
+
const id = event.getId();
|
|
647
|
+
const senderId = event.getSender();
|
|
648
|
+
if (!id || !senderId)
|
|
649
|
+
return undefined;
|
|
650
|
+
const content = event.getContent();
|
|
651
|
+
const body = typeof content.body === 'string' ? content.body : '';
|
|
652
|
+
const formattedBody = content.format === 'org.matrix.custom.html' && typeof content.formatted_body === 'string'
|
|
653
|
+
? content.formatted_body
|
|
654
|
+
: null;
|
|
655
|
+
return {
|
|
656
|
+
id,
|
|
657
|
+
senderId,
|
|
658
|
+
senderName: room.getMember(senderId)?.name ?? senderId,
|
|
659
|
+
ts: event.getTs(),
|
|
660
|
+
body,
|
|
661
|
+
formattedBody,
|
|
662
|
+
status: toMessageStatus(event),
|
|
663
|
+
thread: inThread ? null : toThreadSummary(room, id),
|
|
664
|
+
reactions: readReactions(room, id),
|
|
665
|
+
mentionsMe: mentionsMe(event),
|
|
666
|
+
edited: event.replacingEventId() !== undefined,
|
|
667
|
+
deleted: event.isRedacted(),
|
|
668
|
+
attachment: event.isRedacted() ? null : toAttachment(event),
|
|
669
|
+
upload: null,
|
|
670
|
+
mine: senderId === client?.getUserId(),
|
|
671
|
+
};
|
|
672
|
+
}
|
|
673
|
+
/** `event.status` is `null`/`undefined` once the real event has replaced
|
|
674
|
+
* the local echo -- `'sent'` covers that and `EventStatus.SENT` alike
|
|
675
|
+
* (chat's own `ChatMessageStatus` never distinguishes "accepted" from
|
|
676
|
+
* "confirmed"); `NOT_SENT` is `'failed'`; every other local-echo status
|
|
677
|
+
* (`SENDING`, `QUEUED`, `ENCRYPTING`) is still in flight. A `CANCELLED`
|
|
678
|
+
* event is removed from the room's timeline by matrix-js-sdk itself
|
|
679
|
+
* (`Room.updatePendingEvent`), so it never reaches here. */
|
|
680
|
+
function toMessageStatus(event) {
|
|
681
|
+
const status = event.status;
|
|
682
|
+
if (status === EventStatus.NOT_SENT)
|
|
683
|
+
return 'failed';
|
|
684
|
+
if (status === null || status === undefined)
|
|
685
|
+
return 'sent';
|
|
686
|
+
return 'pending';
|
|
687
|
+
}
|
|
688
|
+
function timeline(roomId, threadId) {
|
|
689
|
+
const room = client?.getRoom(roomId);
|
|
690
|
+
if (!room)
|
|
691
|
+
return { events: [], hasMore: true };
|
|
692
|
+
if (threadId)
|
|
693
|
+
return threadTimeline(room, threadId);
|
|
694
|
+
const events = [];
|
|
695
|
+
for (const event of room.getLiveTimeline().getEvents()) {
|
|
696
|
+
const mapped = toTimelineEvent(event, room, false);
|
|
697
|
+
if (mapped)
|
|
698
|
+
events.push(mapped);
|
|
699
|
+
}
|
|
700
|
+
// Files still going up sit at the bottom, where they were dropped.
|
|
701
|
+
events.push(...uploadRows(room, null));
|
|
702
|
+
return { events, hasMore: room.oldState.paginationToken !== null };
|
|
703
|
+
}
|
|
704
|
+
/** A thread's own timeline: the message that started it, then its
|
|
705
|
+
* replies. `thread.events` already holds the root first -- matrix-js-sdk
|
|
706
|
+
* puts it there when it builds the thread -- so nothing here prepends
|
|
707
|
+
* it, which would show it twice.
|
|
708
|
+
*
|
|
709
|
+
* `hasMore` is the thread's own back-pagination token, not the room's:
|
|
710
|
+
* a thread with all of its replies loaded is done even in a room with
|
|
711
|
+
* years of history above it. */
|
|
712
|
+
function threadTimeline(room, threadId) {
|
|
713
|
+
const root = room.findEventById(threadId);
|
|
714
|
+
const events = [];
|
|
715
|
+
const mappedRoot = root ? toTimelineEvent(root, room, true) : undefined;
|
|
716
|
+
if (mappedRoot)
|
|
717
|
+
events.push(mappedRoot);
|
|
718
|
+
for (const event of threadReplies(room, threadId)) {
|
|
719
|
+
const mapped = toTimelineEvent(event, room, true);
|
|
720
|
+
if (mapped)
|
|
721
|
+
events.push(mapped);
|
|
722
|
+
}
|
|
723
|
+
events.push(...uploadRows(room, threadId));
|
|
724
|
+
const thread = room.getThread(threadId);
|
|
725
|
+
return {
|
|
726
|
+
events,
|
|
727
|
+
hasMore: thread
|
|
728
|
+
? thread.liveTimeline.getPaginationToken(EventTimeline.BACKWARDS) !== null
|
|
729
|
+
: false,
|
|
730
|
+
};
|
|
731
|
+
}
|
|
732
|
+
function onTimelineChanged(roomId, listener) {
|
|
733
|
+
let set = timelineListeners.get(roomId);
|
|
734
|
+
if (!set) {
|
|
735
|
+
set = new Set();
|
|
736
|
+
timelineListeners.set(roomId, set);
|
|
737
|
+
}
|
|
738
|
+
set.add(listener);
|
|
739
|
+
return () => set?.delete(listener);
|
|
740
|
+
}
|
|
741
|
+
/** `scrollback` is matrix-js-sdk's own: it walks `/messages` from the
|
|
742
|
+
* room's `oldState.paginationToken`, prepends what comes back to the
|
|
743
|
+
* live timeline (each prepended event firing `RoomEvent.Timeline`, which
|
|
744
|
+
* `onRoomTimelineChanged` already turns into a `timeline()` change), and
|
|
745
|
+
* sets the token to `null` once a page comes back empty -- which is
|
|
746
|
+
* exactly what `timeline()`'s `hasMore` reads. */
|
|
747
|
+
async function paginate(roomId, threadId) {
|
|
748
|
+
if (!client)
|
|
749
|
+
return;
|
|
750
|
+
const room = client.getRoom(roomId);
|
|
751
|
+
if (!room)
|
|
752
|
+
return;
|
|
753
|
+
if (!threadId) {
|
|
754
|
+
await client.scrollback(room, 30);
|
|
755
|
+
return;
|
|
756
|
+
}
|
|
757
|
+
// A thread is not a room, so `scrollback` cannot walk it: it has its
|
|
758
|
+
// own timeline with its own token, and `paginateEventTimeline` is what
|
|
759
|
+
// walks one. Same shape otherwise -- the events it prepends fire
|
|
760
|
+
// `RoomEvent.Timeline`, which `onRoomTimelineChanged` already turns
|
|
761
|
+
// into a timeline change.
|
|
762
|
+
const thread = room.getThread(threadId);
|
|
763
|
+
if (!thread)
|
|
764
|
+
return;
|
|
765
|
+
await client.paginateEventTimeline(thread.liveTimeline, { backwards: true, limit: 30 });
|
|
766
|
+
}
|
|
767
|
+
/** Builds the Matrix content once, here rather than in `markdown.ts`:
|
|
768
|
+
* `msgtype`/`format`/`formatted_body` are Matrix's own shape, and this
|
|
769
|
+
* is the only file in the package that touches matrix-js-sdk (see
|
|
770
|
+
* `index.ts`'s module comment). */
|
|
771
|
+
function toMessageContent(text) {
|
|
772
|
+
const { body, html } = toFormattedBody(text);
|
|
773
|
+
return html ? ContentHelpers.makeHtmlMessage(body, html) : ContentHelpers.makeTextMessage(body);
|
|
774
|
+
}
|
|
775
|
+
/** `room.addPendingEvent` -- and the `RoomEvent.LocalEchoUpdated` it
|
|
776
|
+
* fires -- happens synchronously, before matrix-js-sdk's `sendEvent` so
|
|
777
|
+
* much as reaches the network (`models/room.js`): a listener attached
|
|
778
|
+
* immediately before the call, and removed immediately after, is
|
|
779
|
+
* guaranteed to have already run by the time `sendMessage` returns. That
|
|
780
|
+
* is what lets this hand back the optimistic event's id at once, rather
|
|
781
|
+
* than only once the network round-trip settles. */
|
|
782
|
+
function sendMessage(roomId, text, options) {
|
|
783
|
+
if (!client)
|
|
784
|
+
throw new Error('chat: sendMessage called before start()');
|
|
785
|
+
const room = client.getRoom(roomId);
|
|
786
|
+
if (!room)
|
|
787
|
+
throw new Error(`chat: not in room ${roomId}`);
|
|
788
|
+
const threadId = options?.threadId;
|
|
789
|
+
const mentions = options?.mentions ?? [];
|
|
790
|
+
// `m.mentions` only when there is one: an empty `user_ids` is a
|
|
791
|
+
// meaningful thing to send (it says "mention nobody, not even the
|
|
792
|
+
// room"), and a caller who passed no mentions did not mean to say it.
|
|
793
|
+
const content = mentions.length
|
|
794
|
+
? { ...toMessageContent(text), 'm.mentions': { user_ids: [...new Set(mentions)] } }
|
|
795
|
+
: toMessageContent(text);
|
|
796
|
+
let localId;
|
|
797
|
+
const captureLocalEcho = (event) => {
|
|
798
|
+
if (localId === undefined)
|
|
799
|
+
localId = event.getId();
|
|
800
|
+
};
|
|
801
|
+
room.on(RoomEvent.LocalEchoUpdated, captureLocalEcho);
|
|
802
|
+
// `threadId ?? null` rather than the two-argument overload: passing the
|
|
803
|
+
// thread's root id is what makes the reply relate to the *root*, which
|
|
804
|
+
// is the only shape Matrix has -- there is no replying to a reply.
|
|
805
|
+
client.sendMessage(roomId, threadId ?? null, content).catch(() => {
|
|
806
|
+
// The failure already lives on the event's own status (`NOT_SENT`);
|
|
807
|
+
// a caller reads that through `timeline()`, not this promise.
|
|
808
|
+
});
|
|
809
|
+
room.off(RoomEvent.LocalEchoUpdated, captureLocalEcho);
|
|
810
|
+
if (!localId)
|
|
811
|
+
throw new Error('chat: send did not create a local echo');
|
|
812
|
+
return localId;
|
|
813
|
+
}
|
|
814
|
+
/** The signed-in person's own, still-standing `m.room.message` in a
|
|
815
|
+
* room, or `undefined`. The one gate both `editMessage` and
|
|
816
|
+
* `deleteMessage` go through: somebody else's message is not theirs to
|
|
817
|
+
* change, an already-redacted one has nothing left to change, and an
|
|
818
|
+
* edit or a redaction of anything but a message is not what either
|
|
819
|
+
* method means.
|
|
820
|
+
*
|
|
821
|
+
* Ownership, not power level, is the rule. Matrix ignores an
|
|
822
|
+
* `m.replace` from anybody but the original sender, and the default
|
|
823
|
+
* power levels let a member redact their own event and nobody else's --
|
|
824
|
+
* so this is the same rule Synapse would apply, applied early enough
|
|
825
|
+
* that the UI can draw it. Moderating other people's messages is the
|
|
826
|
+
* manage app's (ticket #19). */
|
|
827
|
+
function ownMessage(roomId, eventId) {
|
|
828
|
+
const room = client?.getRoom(roomId);
|
|
829
|
+
const event = room ? findEvent(room, eventId) : undefined;
|
|
830
|
+
if (!room || !event)
|
|
831
|
+
return undefined;
|
|
832
|
+
if (event.getType() !== EventType.RoomMessage)
|
|
833
|
+
return undefined;
|
|
834
|
+
if (event.getSender() !== client?.getUserId())
|
|
835
|
+
return undefined;
|
|
836
|
+
if (event.isRedacted())
|
|
837
|
+
return undefined;
|
|
838
|
+
return { room, event };
|
|
839
|
+
}
|
|
840
|
+
/** An event in a room, looked for wherever this client can actually see
|
|
841
|
+
* one. `Room.findEventById` walks the room's timeline and whatever
|
|
842
|
+
* threads matrix-js-sdk has built -- and `threadReplies` explains why a
|
|
843
|
+
* reply the reader is looking at may be in neither. The read path shows
|
|
844
|
+
* it, so the write path has to find it: otherwise editing your own
|
|
845
|
+
* reply, right there on the page, silently does nothing.
|
|
846
|
+
*
|
|
847
|
+
* The walk only runs on a miss, which is somebody pressing Edit or
|
|
848
|
+
* Delete -- never a render. */
|
|
849
|
+
function findEvent(room, eventId) {
|
|
850
|
+
const known = room.findEventById(eventId);
|
|
851
|
+
if (known)
|
|
852
|
+
return known;
|
|
853
|
+
for (const event of room.getLiveTimeline().getEvents()) {
|
|
854
|
+
const rootId = event.getId();
|
|
855
|
+
if (!rootId)
|
|
856
|
+
continue;
|
|
857
|
+
const reply = threadReplies(room, rootId).find((child) => child.getId() === eventId);
|
|
858
|
+
if (reply)
|
|
859
|
+
return reply;
|
|
860
|
+
}
|
|
861
|
+
return undefined;
|
|
862
|
+
}
|
|
863
|
+
/** See `ChatClient.editMessage`. The event sent is a whole message in its
|
|
864
|
+
* own right: `body` is the fallback text an old client shows, which the
|
|
865
|
+
* spec asks be marked with a leading `* `, and `m.new_content` is what a
|
|
866
|
+
* client that understands edits actually draws. */
|
|
867
|
+
async function editMessage(roomId, eventId, text) {
|
|
868
|
+
if (!client)
|
|
869
|
+
return;
|
|
870
|
+
if (!ownMessage(roomId, eventId))
|
|
871
|
+
return;
|
|
872
|
+
// The `* ` mark goes on the *converted* content, never on the text
|
|
873
|
+
// going into the converter: `* first` is a Markdown bullet, and
|
|
874
|
+
// converting it would send the fallback as a one-item list.
|
|
875
|
+
const { body, html } = toFormattedBody(text);
|
|
876
|
+
const replacement = html
|
|
877
|
+
? ContentHelpers.makeHtmlMessage(body, html)
|
|
878
|
+
: ContentHelpers.makeTextMessage(body);
|
|
879
|
+
const fallback = html
|
|
880
|
+
? ContentHelpers.makeHtmlMessage(`* ${body}`, `* ${html}`)
|
|
881
|
+
: ContentHelpers.makeTextMessage(`* ${body}`);
|
|
882
|
+
await client.sendMessage(roomId, {
|
|
883
|
+
...fallback,
|
|
884
|
+
'm.new_content': replacement,
|
|
885
|
+
'm.relates_to': { rel_type: RelationType.Replace, event_id: eventId },
|
|
886
|
+
});
|
|
887
|
+
}
|
|
888
|
+
/** See `ChatClient.deleteMessage`. A redaction, which is the only delete
|
|
889
|
+
* Matrix has: the event stays and its content goes. */
|
|
890
|
+
async function deleteMessage(roomId, eventId) {
|
|
891
|
+
if (!client)
|
|
892
|
+
return;
|
|
893
|
+
if (!ownMessage(roomId, eventId))
|
|
894
|
+
return;
|
|
895
|
+
await client.redactEvent(roomId, eventId);
|
|
896
|
+
}
|
|
897
|
+
/** See `ChatClient.sendFile`. The row appears before the upload starts,
|
|
898
|
+
* so a person sees the file they just picked rather than a pause. */
|
|
899
|
+
function sendFile(roomId, file, options) {
|
|
900
|
+
if (!client)
|
|
901
|
+
throw new Error('chat: sendFile called before start()');
|
|
902
|
+
if (!client.getRoom(roomId))
|
|
903
|
+
throw new Error(`chat: not in room ${roomId}`);
|
|
904
|
+
if (file.size > MAX_UPLOAD_BYTES) {
|
|
905
|
+
throw new Error(`chat: ${file.name} is larger than the ${MAX_UPLOAD_BYTES}-byte limit`);
|
|
906
|
+
}
|
|
907
|
+
uploadSeq += 1;
|
|
908
|
+
const pending = {
|
|
909
|
+
id: `upload-${uploadSeq}`,
|
|
910
|
+
ts: Date.now(),
|
|
911
|
+
file,
|
|
912
|
+
threadId: options?.threadId ?? null,
|
|
913
|
+
mentions: options?.mentions ?? [],
|
|
914
|
+
loaded: 0,
|
|
915
|
+
failed: false,
|
|
916
|
+
abort: new AbortController(),
|
|
917
|
+
};
|
|
918
|
+
uploads.set(roomId, [...(uploads.get(roomId) ?? []), pending]);
|
|
919
|
+
notifyTimeline(roomId);
|
|
920
|
+
runUpload(roomId, pending);
|
|
921
|
+
return pending.id;
|
|
922
|
+
}
|
|
923
|
+
/** Uploads the bytes, then sends the message that points at them. A
|
|
924
|
+
* failure at either step leaves the row `'failed'` with the file still
|
|
925
|
+
* held, which is what `retryMessage` needs. An abort is not a failure:
|
|
926
|
+
* `cancelMessage` has already taken the row away. */
|
|
927
|
+
function runUpload(roomId, pending) {
|
|
928
|
+
if (!client)
|
|
929
|
+
return;
|
|
930
|
+
const target = client;
|
|
931
|
+
target
|
|
932
|
+
.uploadContent(pending.file, {
|
|
933
|
+
name: pending.file.name,
|
|
934
|
+
type: pending.file.type || 'application/octet-stream',
|
|
935
|
+
abortController: pending.abort,
|
|
936
|
+
progressHandler: (progress) => {
|
|
937
|
+
pending.loaded = progress.loaded;
|
|
938
|
+
notifyTimeline(roomId);
|
|
939
|
+
},
|
|
940
|
+
})
|
|
941
|
+
.then(({ content_uri: url }) => {
|
|
942
|
+
if (pending.abort.signal.aborted || client !== target)
|
|
943
|
+
return;
|
|
944
|
+
const isImage = pending.file.type.startsWith('image/');
|
|
945
|
+
const content = {
|
|
946
|
+
msgtype: isImage ? MsgType.Image : MsgType.File,
|
|
947
|
+
// The file's name *is* the body: that is what a client with no
|
|
948
|
+
// idea what to do with the file still shows, and what Synapse's
|
|
949
|
+
// own search indexes (chat plan section 8).
|
|
950
|
+
body: pending.file.name,
|
|
951
|
+
url,
|
|
952
|
+
info: {
|
|
953
|
+
mimetype: pending.file.type || 'application/octet-stream',
|
|
954
|
+
size: pending.file.size,
|
|
955
|
+
},
|
|
956
|
+
};
|
|
957
|
+
if (pending.mentions.length) {
|
|
958
|
+
content['m.mentions'] = { user_ids: [...new Set(pending.mentions)] };
|
|
959
|
+
}
|
|
960
|
+
// The upload row goes first, and `sendMessage` puts its own local
|
|
961
|
+
// echo in the same turn -- so the file is never drawn twice, and
|
|
962
|
+
// there is never a gap where it is drawn not at all. From here on
|
|
963
|
+
// it is an ordinary message: a send that fails is retried and
|
|
964
|
+
// cancelled through the event, with the bytes already up.
|
|
965
|
+
dropUpload(roomId, pending.id);
|
|
966
|
+
void target.sendMessage(roomId, pending.threadId, content).catch(() => { });
|
|
967
|
+
})
|
|
968
|
+
.catch(() => {
|
|
969
|
+
if (pending.abort.signal.aborted)
|
|
970
|
+
return;
|
|
971
|
+
pending.failed = true;
|
|
972
|
+
notifyTimeline(roomId);
|
|
973
|
+
});
|
|
974
|
+
}
|
|
975
|
+
function findUpload(roomId, id) {
|
|
976
|
+
return uploads.get(roomId)?.find((upload) => upload.id === id);
|
|
977
|
+
}
|
|
978
|
+
function dropUpload(roomId, id) {
|
|
979
|
+
const rest = (uploads.get(roomId) ?? []).filter((upload) => upload.id !== id);
|
|
980
|
+
if (rest.length)
|
|
981
|
+
uploads.set(roomId, rest);
|
|
982
|
+
else
|
|
983
|
+
uploads.delete(roomId);
|
|
984
|
+
notifyTimeline(roomId);
|
|
985
|
+
}
|
|
986
|
+
/** A file still going up, as a row in the timeline. It is not an event:
|
|
987
|
+
* it has no sender on the server, no timestamp anyone else will agree
|
|
988
|
+
* with, and an id only this client knows. Drawing it through the same
|
|
989
|
+
* shape as a message is what lets one `MessageRow` handle both, and
|
|
990
|
+
* what lets `retryMessage`/`cancelMessage` take the same id. */
|
|
991
|
+
function toUploadEvent(room, upload) {
|
|
992
|
+
const senderId = client?.getUserId() ?? '';
|
|
993
|
+
return {
|
|
994
|
+
id: upload.id,
|
|
995
|
+
senderId,
|
|
996
|
+
senderName: room.getMember(senderId)?.name ?? senderId,
|
|
997
|
+
ts: upload.ts,
|
|
998
|
+
body: upload.file.name,
|
|
999
|
+
formattedBody: null,
|
|
1000
|
+
status: upload.failed ? 'failed' : 'pending',
|
|
1001
|
+
thread: null,
|
|
1002
|
+
reactions: [],
|
|
1003
|
+
mentionsMe: false,
|
|
1004
|
+
edited: false,
|
|
1005
|
+
deleted: false,
|
|
1006
|
+
attachment: {
|
|
1007
|
+
name: upload.file.name,
|
|
1008
|
+
mimeType: upload.file.type || 'application/octet-stream',
|
|
1009
|
+
size: upload.file.size,
|
|
1010
|
+
// Nothing to point at yet: the bytes have no id until the upload
|
|
1011
|
+
// finishes, and by then this row is gone.
|
|
1012
|
+
mxcUri: '',
|
|
1013
|
+
isImage: upload.file.type.startsWith('image/'),
|
|
1014
|
+
},
|
|
1015
|
+
upload: { loaded: upload.loaded, total: upload.file.size },
|
|
1016
|
+
mine: true,
|
|
1017
|
+
};
|
|
1018
|
+
}
|
|
1019
|
+
function uploadRows(room, threadId) {
|
|
1020
|
+
return (uploads.get(room.roomId) ?? [])
|
|
1021
|
+
.filter((upload) => (upload.threadId ?? null) === threadId)
|
|
1022
|
+
.map((upload) => toUploadEvent(room, upload));
|
|
1023
|
+
}
|
|
1024
|
+
function findPendingEvent(roomId, localId) {
|
|
1025
|
+
const room = client?.getRoom(roomId);
|
|
1026
|
+
const event = room?.findEventById(localId);
|
|
1027
|
+
return room && event ? { room, event } : undefined;
|
|
1028
|
+
}
|
|
1029
|
+
function retryMessage(roomId, localId) {
|
|
1030
|
+
if (!client)
|
|
1031
|
+
return;
|
|
1032
|
+
// A file that never got up is retried from the file itself, not from a
|
|
1033
|
+
// pending event: there is no event to resend until the bytes are
|
|
1034
|
+
// there. Same id, same two buttons, either way.
|
|
1035
|
+
const upload = findUpload(roomId, localId);
|
|
1036
|
+
if (upload) {
|
|
1037
|
+
if (!upload.failed)
|
|
1038
|
+
return;
|
|
1039
|
+
upload.failed = false;
|
|
1040
|
+
upload.loaded = 0;
|
|
1041
|
+
upload.abort = new AbortController();
|
|
1042
|
+
notifyTimeline(roomId);
|
|
1043
|
+
runUpload(roomId, upload);
|
|
1044
|
+
return;
|
|
1045
|
+
}
|
|
1046
|
+
const found = findPendingEvent(roomId, localId);
|
|
1047
|
+
if (!found)
|
|
1048
|
+
return;
|
|
1049
|
+
client.resendEvent(found.event, found.room).catch(() => { });
|
|
1050
|
+
}
|
|
1051
|
+
function cancelMessage(roomId, localId) {
|
|
1052
|
+
if (!client)
|
|
1053
|
+
return;
|
|
1054
|
+
const upload = findUpload(roomId, localId);
|
|
1055
|
+
if (upload) {
|
|
1056
|
+
upload.abort.abort();
|
|
1057
|
+
dropUpload(roomId, localId);
|
|
1058
|
+
return;
|
|
1059
|
+
}
|
|
1060
|
+
const found = findPendingEvent(roomId, localId);
|
|
1061
|
+
if (!found)
|
|
1062
|
+
return;
|
|
1063
|
+
client.cancelPendingEvent(found.event);
|
|
1064
|
+
}
|
|
1065
|
+
/** Everyone joined to a room -- see `ChatClient.roomMembers`. */
|
|
1066
|
+
function roomMembers(roomId) {
|
|
1067
|
+
const room = client?.getRoom(roomId);
|
|
1068
|
+
if (!room)
|
|
1069
|
+
return [];
|
|
1070
|
+
return room
|
|
1071
|
+
.getMembersWithMembership(KnownMembership.Join)
|
|
1072
|
+
.map(toPerson)
|
|
1073
|
+
.sort((a, b) => a.name.localeCompare(b.name));
|
|
1074
|
+
}
|
|
1075
|
+
/** See `ChatClient.toggleReaction`. Removing is a redaction of the
|
|
1076
|
+
* person's own reaction event, which is the only way Matrix has to take
|
|
1077
|
+
* one back. */
|
|
1078
|
+
async function toggleReaction(roomId, eventId, key) {
|
|
1079
|
+
if (!client)
|
|
1080
|
+
return;
|
|
1081
|
+
const room = client.getRoom(roomId);
|
|
1082
|
+
if (!room)
|
|
1083
|
+
return;
|
|
1084
|
+
const mine = room.relations
|
|
1085
|
+
.getChildEventsForEvent(eventId, RelationType.Annotation, EventType.Reaction)
|
|
1086
|
+
?.getRelations()
|
|
1087
|
+
.find((event) => event.getSender() === client?.getUserId() &&
|
|
1088
|
+
!event.isRedacted() &&
|
|
1089
|
+
event.getContent()['m.relates_to']?.key === key);
|
|
1090
|
+
if (mine) {
|
|
1091
|
+
const id = mine.getId();
|
|
1092
|
+
if (id)
|
|
1093
|
+
await client.redactEvent(roomId, id);
|
|
1094
|
+
return;
|
|
1095
|
+
}
|
|
1096
|
+
await client.sendEvent(roomId, EventType.Reaction, {
|
|
1097
|
+
'm.relates_to': { rel_type: RelationType.Annotation, event_id: eventId, key },
|
|
1098
|
+
});
|
|
1099
|
+
}
|
|
1100
|
+
function readUpToEventId(roomId) {
|
|
1101
|
+
const room = client?.getRoom(roomId);
|
|
1102
|
+
const userId = client?.getUserId();
|
|
1103
|
+
if (!room || !userId)
|
|
1104
|
+
return null;
|
|
1105
|
+
return room.getEventReadUpTo(userId);
|
|
1106
|
+
}
|
|
1107
|
+
/** `mxc://<server>/<id>` on *this* homeserver, split -- or `undefined`
|
|
1108
|
+
* for anything else. The one place a media reference is parsed, so
|
|
1109
|
+
* "somebody else's server" is refused once rather than in each caller. */
|
|
1110
|
+
function parseMxc(mxcUri) {
|
|
1111
|
+
const match = /^mxc:\/\/([^/]+)\/([^/?#]+)$/.exec(mxcUri);
|
|
1112
|
+
if (!match || !client)
|
|
1113
|
+
return undefined;
|
|
1114
|
+
const [, serverName, mediaId] = match;
|
|
1115
|
+
// The session's own server, as its user id names it -- not the base
|
|
1116
|
+
// URL, which can be a different host entirely from the server name.
|
|
1117
|
+
const mine = client.getUserId()?.split(':').slice(1).join(':');
|
|
1118
|
+
return serverName === mine && mediaId !== '.' && mediaId !== '..'
|
|
1119
|
+
? { serverName, mediaId }
|
|
1120
|
+
: undefined;
|
|
1121
|
+
}
|
|
1122
|
+
/** See `ChatClient.canLoadMedia`. */
|
|
1123
|
+
function canLoadMedia(mxcUri) {
|
|
1124
|
+
return parseMxc(mxcUri) !== undefined;
|
|
1125
|
+
}
|
|
1126
|
+
/** See `ChatClient.loadMedia`. The request is made by hand rather than
|
|
1127
|
+
* through matrix-js-sdk's `mxcUrlToHttp`, which answers with a URL: a
|
|
1128
|
+
* URL is exactly what cannot work here, because Synapse serves media
|
|
1129
|
+
* only to a request carrying the token. So the bytes are fetched with
|
|
1130
|
+
* the header on and handed back as an object URL. */
|
|
1131
|
+
async function loadMedia(mxcUri) {
|
|
1132
|
+
const parsed = parseMxc(mxcUri);
|
|
1133
|
+
if (!parsed || !client)
|
|
1134
|
+
return null;
|
|
1135
|
+
const target = client;
|
|
1136
|
+
const url = `${target.baseUrl}${MEDIA_DOWNLOAD_PATH}/${encodeURIComponent(parsed.serverName)}/${encodeURIComponent(parsed.mediaId)}`;
|
|
1137
|
+
try {
|
|
1138
|
+
const request = () => fetch(url, {
|
|
1139
|
+
headers: { Authorization: `Bearer ${target.getAccessToken() ?? ''}` },
|
|
1140
|
+
redirect: 'error',
|
|
1141
|
+
credentials: 'omit',
|
|
1142
|
+
});
|
|
1143
|
+
let response = await request();
|
|
1144
|
+
if (response.status === 401 && client === target) {
|
|
1145
|
+
await refreshToken();
|
|
1146
|
+
if (client !== target)
|
|
1147
|
+
return null;
|
|
1148
|
+
response = await request();
|
|
1149
|
+
}
|
|
1150
|
+
if (!response.ok || client !== target)
|
|
1151
|
+
return null;
|
|
1152
|
+
const blob = await response.blob();
|
|
1153
|
+
return client === target ? URL.createObjectURL(blob) : null;
|
|
1154
|
+
}
|
|
1155
|
+
catch {
|
|
1156
|
+
// Offline, or the token went stale between the refresh and here. The
|
|
1157
|
+
// caller draws the file as a file rather than as a picture; nothing
|
|
1158
|
+
// is lost, and the next look tries again.
|
|
1159
|
+
return null;
|
|
1160
|
+
}
|
|
1161
|
+
}
|
|
1162
|
+
/** The file a message carries, or `null`. Only `m.image` and `m.file`:
|
|
1163
|
+
* audio and video are their own `msgtype`s with their own players, and
|
|
1164
|
+
* neither is in the first ship. */
|
|
1165
|
+
function toAttachment(event) {
|
|
1166
|
+
const content = event.getContent();
|
|
1167
|
+
const msgtype = content.msgtype;
|
|
1168
|
+
if (msgtype !== MsgType.Image && msgtype !== MsgType.File)
|
|
1169
|
+
return null;
|
|
1170
|
+
const mxcUri = typeof content.url === 'string' ? content.url : '';
|
|
1171
|
+
if (!mxcUri)
|
|
1172
|
+
return null;
|
|
1173
|
+
const info = (content.info ?? {});
|
|
1174
|
+
const mimeType = typeof info.mimetype === 'string' ? info.mimetype : '';
|
|
1175
|
+
return {
|
|
1176
|
+
name: typeof content.body === 'string' && content.body ? content.body : 'file',
|
|
1177
|
+
mimeType,
|
|
1178
|
+
size: typeof info.size === 'number' ? info.size : 0,
|
|
1179
|
+
mxcUri,
|
|
1180
|
+
// The sender's own `msgtype` decides, not the name: a `.png` that is
|
|
1181
|
+
// not one would draw a broken picture, and the preview is fetched
|
|
1182
|
+
// through `loadMedia` either way.
|
|
1183
|
+
isImage: msgtype === MsgType.Image && mimeType.startsWith('image/'),
|
|
1184
|
+
};
|
|
1185
|
+
}
|
|
1186
|
+
async function start() {
|
|
1187
|
+
if (starting)
|
|
1188
|
+
return starting;
|
|
1189
|
+
starting = (async () => {
|
|
1190
|
+
const body = await performExchange();
|
|
1191
|
+
const store = createChatStore(storeName);
|
|
1192
|
+
// Loads any previously-persisted sync data before the sync loop can
|
|
1193
|
+
// touch the store; skipping it leaves `store.backend` unset, and the
|
|
1194
|
+
// store silently degrades to an in-memory one on first access
|
|
1195
|
+
// (`IndexedDBStore`'s own `degradable()`), defeating `storeName`.
|
|
1196
|
+
await store.startup();
|
|
1197
|
+
const created = createMatrixClient({
|
|
1198
|
+
baseUrl: body.homeserver,
|
|
1199
|
+
userId: body.user_id,
|
|
1200
|
+
accessToken: body.access_token,
|
|
1201
|
+
deviceId: body.device_id,
|
|
1202
|
+
store,
|
|
1203
|
+
});
|
|
1204
|
+
client = created;
|
|
1205
|
+
created.on(HttpApiEvent.SessionLoggedOut, onLoggedOut);
|
|
1206
|
+
created.on(ClientEvent.Sync, onSync);
|
|
1207
|
+
created.on(RoomEvent.Timeline, onRoomTimelineChanged);
|
|
1208
|
+
created.on(RoomEvent.LocalEchoUpdated, onRoomTimelineChanged);
|
|
1209
|
+
scheduleRefresh(body.expires_at);
|
|
1210
|
+
const outcome = nextSyncOutcome(created);
|
|
1211
|
+
// Without `threadSupport`, matrix-js-sdk puts every `m.thread` reply
|
|
1212
|
+
// straight into the room's own timeline, and a room with one busy
|
|
1213
|
+
// thread becomes unreadable. With it, a reply is routed to its thread
|
|
1214
|
+
// and the room keeps only the message that started it (ticket #17).
|
|
1215
|
+
// It is a `startClient` option, not a `createClient` one.
|
|
1216
|
+
await created.startClient(START_OPTIONS);
|
|
1217
|
+
await outcome;
|
|
1218
|
+
})();
|
|
1219
|
+
return starting;
|
|
1220
|
+
}
|
|
1221
|
+
function stop() {
|
|
1222
|
+
for (const pending of uploads.values()) {
|
|
1223
|
+
for (const upload of pending)
|
|
1224
|
+
upload.abort.abort();
|
|
1225
|
+
}
|
|
1226
|
+
uploads.clear();
|
|
1227
|
+
starting = undefined;
|
|
1228
|
+
clearTimeout(refreshTimer);
|
|
1229
|
+
refreshTimer = undefined;
|
|
1230
|
+
if (client) {
|
|
1231
|
+
client.removeListener(HttpApiEvent.SessionLoggedOut, onLoggedOut);
|
|
1232
|
+
client.removeListener(ClientEvent.Sync, onSync);
|
|
1233
|
+
client.removeListener(RoomEvent.Timeline, onRoomTimelineChanged);
|
|
1234
|
+
client.removeListener(RoomEvent.LocalEchoUpdated, onRoomTimelineChanged);
|
|
1235
|
+
client.stopClient();
|
|
1236
|
+
}
|
|
1237
|
+
client = undefined;
|
|
1238
|
+
setStatus('offline');
|
|
1239
|
+
}
|
|
1240
|
+
function onRoomsChanged(listener) {
|
|
1241
|
+
listeners.add(listener);
|
|
1242
|
+
return () => listeners.delete(listener);
|
|
1243
|
+
}
|
|
1244
|
+
function onConnectionStatusChanged(listener) {
|
|
1245
|
+
statusListeners.add(listener);
|
|
1246
|
+
return () => statusListeners.delete(listener);
|
|
1247
|
+
}
|
|
1248
|
+
/** Sends `m.read` for the newest event in the room's live timeline and
|
|
1249
|
+
* clears the count right away, rather than waiting for the server to
|
|
1250
|
+
* echo the receipt back on a later sync -- matrix-js-sdk's own local
|
|
1251
|
+
* echo only clears a room's count for the narrow case of reading back
|
|
1252
|
+
* your own last message (`ReadReceipt.addReceipt`'s live-timeline
|
|
1253
|
+
* check), not the general "caught up on someone else's message" case
|
|
1254
|
+
* this method exists for. A no-op if the room is unknown or has no
|
|
1255
|
+
* events yet -- there is nothing to point a receipt at. */
|
|
1256
|
+
async function markRoomRead(roomId) {
|
|
1257
|
+
if (!client)
|
|
1258
|
+
return;
|
|
1259
|
+
const room = client.getRoom(roomId);
|
|
1260
|
+
if (!room)
|
|
1261
|
+
return;
|
|
1262
|
+
const events = room.getLiveTimeline().getEvents();
|
|
1263
|
+
const newest = events[events.length - 1];
|
|
1264
|
+
if (newest)
|
|
1265
|
+
await client.sendReadReceipt(newest);
|
|
1266
|
+
room.setUnreadNotificationCount(NotificationCountType.Total, 0);
|
|
1267
|
+
room.setUnreadNotificationCount(NotificationCountType.Highlight, 0);
|
|
1268
|
+
notify();
|
|
1269
|
+
}
|
|
1270
|
+
return {
|
|
1271
|
+
start,
|
|
1272
|
+
stop,
|
|
1273
|
+
rooms: readRooms,
|
|
1274
|
+
totalUnreadCount: () => readRooms().reduce((sum, room) => sum + room.unreadCount, 0),
|
|
1275
|
+
markRoomRead,
|
|
1276
|
+
connectionStatus: () => status,
|
|
1277
|
+
onConnectionStatusChanged,
|
|
1278
|
+
onRoomsChanged,
|
|
1279
|
+
userId: () => client?.getUserId() ?? null,
|
|
1280
|
+
people: readPeople,
|
|
1281
|
+
roomMembers,
|
|
1282
|
+
toggleReaction,
|
|
1283
|
+
startDirectMessage,
|
|
1284
|
+
hideDirectMessage,
|
|
1285
|
+
acceptInvitation,
|
|
1286
|
+
declineInvitation,
|
|
1287
|
+
timeline,
|
|
1288
|
+
onTimelineChanged,
|
|
1289
|
+
paginate,
|
|
1290
|
+
sendMessage,
|
|
1291
|
+
editMessage,
|
|
1292
|
+
deleteMessage,
|
|
1293
|
+
retryMessage,
|
|
1294
|
+
cancelMessage,
|
|
1295
|
+
readUpToEventId,
|
|
1296
|
+
canLoadMedia,
|
|
1297
|
+
loadMedia,
|
|
1298
|
+
sendFile,
|
|
1299
|
+
};
|
|
1300
|
+
}
|