@wtfalch/chat 0.1.0 → 0.3.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.
@@ -1,4 +1,4 @@
1
- import { ClientEvent, ContentHelpers, EventStatus, EventTimeline, EventType, HttpApiEvent, KnownMembership, MatrixError, MatrixEventEvent, MsgType, NotificationCountType, Preset, RelationType, RoomEvent, SyncState, createClient as createMatrixClient, } from 'matrix-js-sdk';
1
+ import { ClientEvent, ContentHelpers, Direction, EventStatus, EventTimeline, EventType, Filter, HttpApiEvent, KnownMembership, MatrixError, MatrixEventEvent, Method, MsgType, NotificationCountType, Preset, PushRuleActionName, RelationType, RoomEvent, RoomMemberEvent, SetPresence, SyncState, UserEvent, createClient as createMatrixClient, } from 'matrix-js-sdk';
2
2
  import { exchange } from "./exchange.js";
3
3
  import { toFormattedBody } from "./markdown.js";
4
4
  import { createChatStore } from "./store.js";
@@ -26,11 +26,32 @@ const START_OPTIONS = { threadSupport: true };
26
26
  * so at once, rather than after the whole thing has gone up and Synapse
27
27
  * has refused it. */
28
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
29
+ /** Where `loadMedia` asks for bytes: `apps/chat-service`'s media proxy,
30
+ * next to `exchangeUrl`, never Synapse's `/_matrix/client/v1/media/download`
31
+ * directly. Synapse serves media to any valid token without checking the
32
+ * room it was posted in (wtfalch/chat#32); the proxy checks. The legacy
31
33
  * `/_matrix/media/...` download paths are unauthenticated and are never
32
34
  * used by this package (ticket #13). */
33
- const MEDIA_DOWNLOAD_PATH = '/_matrix/client/v1/media/download';
35
+ function mediaProxyUrl(exchangeUrl, mxc, roomId, eventId) {
36
+ const base = exchangeUrl.replace(/\/_chat\/exchange\/?$/, '');
37
+ const url = new URL(`${base}/_chat/media/${encodeURIComponent(mxc.serverName)}/${encodeURIComponent(mxc.mediaId)}`);
38
+ url.searchParams.set('roomId', roomId);
39
+ url.searchParams.set('eventId', eventId);
40
+ return url.toString();
41
+ }
42
+ /** What `sendTyping` asks the server to auto-expire a typing state after,
43
+ * in ms -- matrix-js-sdk's own default when a caller passes none
44
+ * (`client.js`'s `sendTyping`), used explicitly here since this package's
45
+ * own `sendTyping(roomId, typing)` takes no timeout of its own. A caller
46
+ * wanting the far end to keep seeing "typing" through a long pause calls
47
+ * this again itself; nothing here renews it on a timer. */
48
+ const TYPING_TIMEOUT_MS = 20_000;
49
+ /** How many *matching* events `roomFiles` asks Synapse for per request.
50
+ * Unlike `paginate`'s 30 (which bounds how much plain conversation a
51
+ * person scrolls through at once), this only ever counts events that
52
+ * already passed the `contains_url` filter server-side, so a larger page
53
+ * costs one round trip, not one screenful. */
54
+ const ROOM_FILES_PAGE_SIZE = 50;
34
55
  /**
35
56
  * A chat session behind the exchange: a matrix-js-sdk `MatrixClient` the
36
57
  * caller never sees, refreshed on its own, exposing only what a UI needs.
@@ -70,6 +91,33 @@ export function createChatClient(options) {
70
91
  const uploads = new Map();
71
92
  let uploadSeq = 0;
72
93
  const statusListeners = new Set();
94
+ const presenceListeners = new Set();
95
+ const typingListeners = new Map();
96
+ /** Who is currently typing, per room -- built up from `RoomMemberEvent.
97
+ * Typing` one member at a time, the signed-in person's own id never
98
+ * added (see `ChatClient.onTypingChanged`). Cleared on `stop()`: it is
99
+ * exactly as ephemeral as the `m.typing` it is built from, and a fresh
100
+ * `start()` has to rebuild it from whatever sync delivers next rather
101
+ * than carry a stale room's list into a new session. */
102
+ const typingUsers = new Map();
103
+ /** What `announcePresence` last said, so every restart can re-apply it --
104
+ * see `reapplyAnnouncedPresence`. `undefined` until a caller announces
105
+ * anything, which leaves matrix-js-sdk to omit `set_presence` entirely
106
+ * and Matrix to default it to `'online'`, exactly as before. Deliberately
107
+ * not cleared by `stop()`: a person idle when their session was torn down
108
+ * is still idle when it comes back, and re-reporting them online for the
109
+ * gap would be the very flicker this exists to stop. */
110
+ let announced;
111
+ /** Rooms `muteRoom` has touched since their last real read. Synapse
112
+ * evaluates a room's `dont_notify` rule once, at receive time, and never
113
+ * recomputes `notification_count` for events already counted under it --
114
+ * confirmed live, unmuting does not make the server's own count catch
115
+ * up, not right away and not on a later poll. So a room stays in this
116
+ * set, and `readRooms()` keeps comparing against the local walk, from
117
+ * the moment it is muted until the next `markRoomRead` proves the two
118
+ * have agreed again -- an unmute alone is not that proof. Every other
119
+ * room never pays for the walk at all. */
120
+ const unreliableServerCount = new Set();
73
121
  async function performExchange() {
74
122
  return exchange(exchangeUrl, getAccessToken, deviceId);
75
123
  }
@@ -159,6 +207,7 @@ export function createChatClient(options) {
159
207
  await target.store.deleteAllData();
160
208
  const outcome = nextSyncOutcome(target);
161
209
  await target.startClient(START_OPTIONS);
210
+ reapplyAnnouncedPresence(target);
162
211
  await outcome;
163
212
  notify();
164
213
  })();
@@ -215,6 +264,7 @@ export function createChatClient(options) {
215
264
  scheduleRefresh(body.expires_at);
216
265
  const outcome = nextSyncOutcome(target);
217
266
  await target.startClient(START_OPTIONS);
267
+ reapplyAnnouncedPresence(target);
218
268
  await outcome;
219
269
  notify();
220
270
  })();
@@ -259,26 +309,87 @@ export function createChatClient(options) {
259
309
  * and nothing in Chat's. A hidden direct room is left out for the reason
260
310
  * `hideDirectMessage` exists. */
261
311
  function readRooms() {
262
- if (!client)
312
+ const target = client;
313
+ if (!target)
263
314
  return [];
264
- const direct = directRoomIds(client);
265
- return client
315
+ const direct = directRoomIds(target);
316
+ return target
266
317
  .getRooms()
267
318
  .filter((room) => room.getMyMembership() === KnownMembership.Join ||
268
319
  room.getMyMembership() === KnownMembership.Invite)
269
320
  .filter((room) => !room.isSpaceRoom())
270
321
  .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
- }));
322
+ .map((room) => {
323
+ const muted = isMuted(target, room.roomId);
324
+ return {
325
+ id: room.roomId,
326
+ name: room.name,
327
+ isDirect: direct.has(room.roomId) || Boolean(room.getDMInviter()),
328
+ membership: room.getMyMembership() === KnownMembership.Invite
329
+ ? 'invite'
330
+ : 'join',
331
+ unreadCount: room.getMyMembership() === KnownMembership.Invite
332
+ ? 1
333
+ : roomUnreadCount(target, room, muted),
334
+ muted,
335
+ };
336
+ });
337
+ }
338
+ /** A room's own `unreadCount` -- see `ChatRoomSummary.unreadCount` for
339
+ * why a muted room (or one `unreliableServerCount` still distrusts)
340
+ * takes the larger of Synapse's own count and the local walk, rather
341
+ * than either alone: Synapse's count is what a room with more unread
342
+ * history than the currently-loaded timeline holds is right about, and
343
+ * the local walk is what a room Synapse has stopped counting for is
344
+ * right about. Every other room skips the walk and costs nothing more
345
+ * than it already did. */
346
+ function roomUnreadCount(target, room, muted) {
347
+ const serverCount = room.getUnreadNotificationCount(NotificationCountType.Total);
348
+ if (!muted && !unreliableServerCount.has(room.roomId))
349
+ return serverCount;
350
+ return Math.max(serverCount, unreadTimelineCount(target, room));
351
+ }
352
+ /** Whether `roomId` carries the room-scoped `dont_notify` rule
353
+ * `muteRoom` writes -- see `ChatClient.muteRoom`. `client.pushRules` is
354
+ * unset only in the narrow window before the pre-sync `getPushRules()`
355
+ * call has landed (`start()` has not resolved yet); reading as unmuted
356
+ * there is the same answer a room with no rule at all gets. */
357
+ function isMuted(target, roomId) {
358
+ const rule = target.pushRules && target.getRoomPushRule('global', roomId);
359
+ return Boolean(rule?.actions.includes(PushRuleActionName.DontNotify));
360
+ }
361
+ /** A muted room's own `unreadCount`, counted here rather than read off
362
+ * Synapse. Confirmed live against Synapse v1.161.0: the room-scoped
363
+ * `dont_notify` rule `muteRoom` writes does not merely withhold the
364
+ * push -- it stops `unread_notifications.notification_count` climbing
365
+ * for that room at all, because Synapse derives that count from the
366
+ * same push-rule evaluation. Reading it here would report zero for
367
+ * exactly the rooms this ticket needs to keep counting, so a muted
368
+ * room counts itself instead: every `m.room.message` in the room's own
369
+ * live timeline, after the local read-up-to marker, sent by somebody
370
+ * else. The same receipt `markRoomRead` sends already moves that
371
+ * marker past everything currently unread, so reading a muted room
372
+ * still clears it. */
373
+ function unreadTimelineCount(target, room) {
374
+ const me = target.getUserId();
375
+ const readUpToId = me ? room.getEventReadUpTo(me) : null;
376
+ const events = room.getLiveTimeline().getEvents();
377
+ const startIndex = readUpToId
378
+ ? events.findIndex((event) => event.getId() === readUpToId) + 1
379
+ : 0;
380
+ let count = 0;
381
+ for (const event of events.slice(startIndex)) {
382
+ if (event.getType() !== EventType.RoomMessage)
383
+ continue;
384
+ if (event.isRelation(RelationType.Replace))
385
+ continue;
386
+ if (event.isRedacted())
387
+ continue;
388
+ if (event.getSender() === me)
389
+ continue;
390
+ count += 1;
391
+ }
392
+ return count;
282
393
  }
283
394
  /** The company space: the one space the account is joined to (chat plan
284
395
  * section 5 -- one agora is one company is one space). `undefined` before
@@ -495,6 +606,7 @@ export function createChatClient(options) {
495
606
  if (!room)
496
607
  return;
497
608
  watchForEdit(event, room);
609
+ watchForPinnedEvents(event, room);
498
610
  notifyTimeline(room.roomId);
499
611
  }
500
612
  /** An edit arriving is two things, a tick apart: the `m.replace` event
@@ -764,6 +876,52 @@ export function createChatClient(options) {
764
876
  return;
765
877
  await client.paginateEventTimeline(thread.liveTimeline, { backwards: true, limit: 30 });
766
878
  }
879
+ /** See `ChatClient.roomFiles`. Walks `/messages` backward with a
880
+ * `contains_url` filter rather than `paginate`'s plain scrollback:
881
+ * Synapse answers with only file-bearing events, so this costs one
882
+ * request per page of *files*, never one per page of conversation.
883
+ * `target`/`client === target` guards the loop the same way
884
+ * `loadMedia` does: a long walk that outlives a `stop()` call returns
885
+ * whatever it already has rather than carrying on against a session
886
+ * the caller has torn down. */
887
+ async function roomFiles(roomId, options) {
888
+ if (!client)
889
+ return { files: [], next: null };
890
+ const target = client;
891
+ if (!target.getRoom(roomId))
892
+ return { files: [], next: null };
893
+ const filter = new Filter(target.getUserId());
894
+ filter.setDefinition({
895
+ room: { timeline: { types: [EventType.RoomMessage], contains_url: true } },
896
+ });
897
+ const mapper = target.getEventMapper();
898
+ const limit = options?.limit;
899
+ const files = [];
900
+ let from = options?.before ?? null;
901
+ while (client === target) {
902
+ if (limit !== undefined && files.length >= limit)
903
+ break;
904
+ // Never ask for more than the limit still wants. Every event in a
905
+ // page is then either returned or skipped, so the page's own `end`
906
+ // is an exact cursor for the next call.
907
+ const size = limit === undefined
908
+ ? ROOM_FILES_PAGE_SIZE
909
+ : Math.min(ROOM_FILES_PAGE_SIZE, limit - files.length);
910
+ const page = await target.createMessagesRequest(roomId, from, size, Direction.Backward, filter);
911
+ for (const raw of page.chunk) {
912
+ const event = mapper(raw);
913
+ if (event.isRedacted())
914
+ continue;
915
+ const attachment = toAttachment(event);
916
+ if (attachment)
917
+ files.push(attachment);
918
+ }
919
+ from = page.end && page.chunk.length > 0 ? page.end : null;
920
+ if (from === null)
921
+ break;
922
+ }
923
+ return { files, next: from };
924
+ }
767
925
  /** Builds the Matrix content once, here rather than in `markdown.ts`:
768
926
  * `msgtype`/`format`/`formatted_body` are Matrix's own shape, and this
769
927
  * is the only file in the package that touches matrix-js-sdk (see
@@ -894,6 +1052,14 @@ export function createChatClient(options) {
894
1052
  return;
895
1053
  await client.redactEvent(roomId, eventId);
896
1054
  }
1055
+ /** See `ChatClient.reportMessage`. Sent by hand rather than through
1056
+ * matrix-js-sdk's `reportEvent`, which always attaches a `score` the
1057
+ * spec has deprecated; a report here carries only the reason. */
1058
+ async function reportMessage(roomId, eventId, reason) {
1059
+ if (!client)
1060
+ throw new Error('chat: reportMessage called before start()');
1061
+ await client.http.authedRequest(Method.Post, `/rooms/${encodeURIComponent(roomId)}/report/${encodeURIComponent(eventId)}`, undefined, { reason });
1062
+ }
897
1063
  /** See `ChatClient.sendFile`. The row appears before the upload starts,
898
1064
  * so a person sees the file they just picked rather than a pause. */
899
1065
  function sendFile(roomId, file, options) {
@@ -1010,6 +1176,7 @@ export function createChatClient(options) {
1010
1176
  // Nothing to point at yet: the bytes have no id until the upload
1011
1177
  // finishes, and by then this row is gone.
1012
1178
  mxcUri: '',
1179
+ eventId: '',
1013
1180
  isImage: upload.file.type.startsWith('image/'),
1014
1181
  },
1015
1182
  upload: { loaded: upload.loaded, total: upload.file.size },
@@ -1072,6 +1239,27 @@ export function createChatClient(options) {
1072
1239
  .map(toPerson)
1073
1240
  .sort((a, b) => a.name.localeCompare(b.name));
1074
1241
  }
1242
+ /** See `ChatClient.readBy`. matrix-js-sdk's `getUsersReadUpTo` only
1243
+ * names receipts sitting *on* this event, so a person whose receipt has
1244
+ * since moved to a newer message would drop out. `hasUserReadEvent`
1245
+ * compares positions instead, which is what "seen" means. */
1246
+ function readBy(roomId, eventId) {
1247
+ const room = client?.getRoom(roomId);
1248
+ const event = room?.findEventById(eventId);
1249
+ if (!room || !event)
1250
+ return [];
1251
+ const skip = new Set([client?.getUserId(), event.getSender()]);
1252
+ return room
1253
+ .getMembersWithMembership(KnownMembership.Join)
1254
+ .filter((member) => !skip.has(member.userId) && room.hasUserReadEvent(member.userId, eventId))
1255
+ .map(toPerson)
1256
+ .sort((a, b) => a.name.localeCompare(b.name));
1257
+ }
1258
+ /** A receipt moving changes what `readBy` answers, so a view drawing it
1259
+ * is told the same way it is told about a new message. */
1260
+ function onRoomReceipt(_event, room) {
1261
+ notifyTimeline(room.roomId);
1262
+ }
1075
1263
  /** See `ChatClient.toggleReaction`. Removing is a redaction of the
1076
1264
  * person's own reaction event, which is the only way Matrix has to take
1077
1265
  * one back. */
@@ -1097,6 +1285,136 @@ export function createChatClient(options) {
1097
1285
  'm.relates_to': { rel_type: RelationType.Annotation, event_id: eventId, key },
1098
1286
  });
1099
1287
  }
1288
+ /** The room's `m.room.pinned_events` content, read straight off
1289
+ * matrix-js-sdk's own current state -- there is no higher-level helper
1290
+ * for it the way `room.name` is one for `m.room.name`. `[]` for a room
1291
+ * with no such state at all, which is every room until the first pin. */
1292
+ function pinnedEventIds(room) {
1293
+ const content = room.currentState
1294
+ .getStateEvents(EventType.RoomPinnedEvents, '')
1295
+ ?.getContent();
1296
+ const pinned = content?.pinned;
1297
+ return Array.isArray(pinned) ? pinned.filter((id) => typeof id === 'string') : [];
1298
+ }
1299
+ /** A room `pinMessage`/`unpinMessage` is currently writing to, chained so
1300
+ * a second call for the same room queues behind the first rather than
1301
+ * racing it -- see `chainPinnedWrite`. Never cleared once a room has
1302
+ * one: an already-settled promise here costs nothing, and clearing it
1303
+ * on a timer or "nothing queued behind this" check is exactly the kind
1304
+ * of race this whole mechanism exists to avoid (an earlier version of
1305
+ * this file tried that and lost a pin to it -- see the report). */
1306
+ const pinnedChain = new Map();
1307
+ /** This client's own best knowledge of a room's pinned list -- not a
1308
+ * cache with a lifetime, but a value kept current two ways: a
1309
+ * successful write updates it immediately (see `chainPinnedWrite`),
1310
+ * and `watchForPinnedEvents` updates it the moment any
1311
+ * `m.room.pinned_events` -- this client's own echo, or another
1312
+ * client's -- lands through `/sync`. So it is never "expired"; it is
1313
+ * either right now, or about to be corrected by the next sync, exactly
1314
+ * like `room.currentState` itself. */
1315
+ const pinnedKnown = new Map();
1316
+ /** Keeps `pinnedKnown` current with whatever this client has actually
1317
+ * seen land, own write or somebody else's -- called from
1318
+ * `onRoomTimelineChanged` for every event, same as `watchForEdit`. */
1319
+ function watchForPinnedEvents(event, room) {
1320
+ if (event.getType() !== EventType.RoomPinnedEvents)
1321
+ return;
1322
+ const pinned = event.getContent().pinned;
1323
+ if (!Array.isArray(pinned))
1324
+ return;
1325
+ pinnedKnown.set(room.roomId, pinned.filter((id) => typeof id === 'string'));
1326
+ }
1327
+ /** Queues one read-modify-write of `room`'s `m.room.pinned_events`
1328
+ * behind whatever `pinMessage`/`unpinMessage` already have in flight
1329
+ * for it, so `await pinMessage(a); await pinMessage(b);` -- or even
1330
+ * neither awaited before the next call starts -- ends with both pinned
1331
+ * rather than losing `a`.
1332
+ *
1333
+ * The loss without this: `sendStateEvent`'s promise resolves on
1334
+ * Synapse's HTTP response, before the echo has come back through
1335
+ * `/sync` and landed in `room.currentState` (confirmed live -- a
1336
+ * second call's read of `pinnedEventIds(room)` still saw the list from
1337
+ * *before* the first call, even after a full `await`). Both calls
1338
+ * reported success; the server ended up with only the second id.
1339
+ *
1340
+ * The fix: `mutate` is handed `pinnedKnown`, this client's own running
1341
+ * idea of the list, rather than a fresh read that has not caught up --
1342
+ * seeded from `room.currentState` only the first time this room is
1343
+ * touched, when there is nothing of this client's own yet.
1344
+ *
1345
+ * What this does not fix: two different `ChatClient`s -- two accounts,
1346
+ * or two devices of one account -- writing to the same room's pinned
1347
+ * list at once. Each keeps its own `pinnedChain`/`pinnedKnown`, so
1348
+ * nothing here (or anywhere) sequences across clients. Matrix gives
1349
+ * `m.room.pinned_events` no compare-and-swap: it is one state value,
1350
+ * replaced whole, and Synapse's own state resolution -- never a merge
1351
+ * -- decides which of two concurrent writes wins, silently, the same
1352
+ * way it always has. This narrows the hazard to that one,
1353
+ * protocol-level case; it does not remove it. */
1354
+ function chainPinnedWrite(target, room, mutate) {
1355
+ const roomId = room.roomId;
1356
+ const queuedAfter = pinnedChain.get(roomId) ?? Promise.resolve();
1357
+ const result = queuedAfter
1358
+ .catch(() => { })
1359
+ .then(async () => {
1360
+ if (client !== target)
1361
+ return;
1362
+ const current = pinnedKnown.get(roomId) ?? pinnedEventIds(room);
1363
+ const wanted = mutate(current);
1364
+ if (!wanted)
1365
+ return;
1366
+ await target.sendStateEvent(roomId, EventType.RoomPinnedEvents, { pinned: wanted }, '');
1367
+ if (client === target)
1368
+ pinnedKnown.set(roomId, wanted);
1369
+ });
1370
+ pinnedChain.set(roomId, result.catch(() => { }));
1371
+ return result;
1372
+ }
1373
+ /** See `ChatClient.pinMessage`. Already-pinned is a no-op resolved
1374
+ * without a round trip -- there is nothing Synapse could refuse, and
1375
+ * refusing here would be wrong: the caller asked for a state that
1376
+ * already holds. Everything else is a plain `sendStateEvent`, chained
1377
+ * through `chainPinnedWrite` so a second call for this room is safe,
1378
+ * and its rejection is handed straight back -- see the module's house
1379
+ * rule (ticket #8: a member's pin in a room whose power levels predate
1380
+ * the change must reject, never resolve as if it had worked). */
1381
+ async function pinMessage(roomId, eventId) {
1382
+ if (!client)
1383
+ throw new Error('chat: pinMessage called before start()');
1384
+ const target = client;
1385
+ const room = target.getRoom(roomId);
1386
+ if (!room)
1387
+ throw new Error(`chat: not in room ${roomId}`);
1388
+ await chainPinnedWrite(target, room, (current) => current.includes(eventId) ? undefined : [...current, eventId]);
1389
+ }
1390
+ /** See `ChatClient.unpinMessage`. Not-pinned is a no-op for the same
1391
+ * reason `pinMessage`'s already-pinned is one, and the same chain. */
1392
+ async function unpinMessage(roomId, eventId) {
1393
+ if (!client)
1394
+ throw new Error('chat: unpinMessage called before start()');
1395
+ const target = client;
1396
+ const room = target.getRoom(roomId);
1397
+ if (!room)
1398
+ throw new Error(`chat: not in room ${roomId}`);
1399
+ await chainPinnedWrite(target, room, (current) => current.includes(eventId) ? current.filter((id) => id !== eventId) : undefined);
1400
+ }
1401
+ /** See `ChatClient.pinnedMessages`. `findEvent` rather than
1402
+ * `room.findEventById`: a pinned reply lives wherever `threadReplies`
1403
+ * says a reply can live, the same gap `editMessage`/`deleteMessage`
1404
+ * already close for the write side. */
1405
+ function pinnedMessages(roomId) {
1406
+ const room = client?.getRoom(roomId);
1407
+ if (!room)
1408
+ return [];
1409
+ const events = [];
1410
+ for (const eventId of pinnedEventIds(room)) {
1411
+ const found = findEvent(room, eventId);
1412
+ const mapped = found ? toTimelineEvent(found, room, false) : undefined;
1413
+ if (mapped)
1414
+ events.push(mapped);
1415
+ }
1416
+ return events;
1417
+ }
1100
1418
  function readUpToEventId(roomId) {
1101
1419
  const room = client?.getRoom(roomId);
1102
1420
  const userId = client?.getUserId();
@@ -1125,15 +1443,15 @@ export function createChatClient(options) {
1125
1443
  }
1126
1444
  /** See `ChatClient.loadMedia`. The request is made by hand rather than
1127
1445
  * through matrix-js-sdk's `mxcUrlToHttp`, which answers with a URL: a
1128
- * URL is exactly what cannot work here, because Synapse serves media
1446
+ * URL is exactly what cannot work here, because the proxy serves media
1129
1447
  * only to a request carrying the token. So the bytes are fetched with
1130
1448
  * the header on and handed back as an object URL. */
1131
- async function loadMedia(mxcUri) {
1449
+ async function loadMedia(mxcUri, roomId, eventId) {
1132
1450
  const parsed = parseMxc(mxcUri);
1133
1451
  if (!parsed || !client)
1134
1452
  return null;
1135
1453
  const target = client;
1136
- const url = `${target.baseUrl}${MEDIA_DOWNLOAD_PATH}/${encodeURIComponent(parsed.serverName)}/${encodeURIComponent(parsed.mediaId)}`;
1454
+ const url = mediaProxyUrl(exchangeUrl, parsed, roomId, eventId);
1137
1455
  try {
1138
1456
  const request = () => fetch(url, {
1139
1457
  headers: { Authorization: `Bearer ${target.getAccessToken() ?? ''}` },
@@ -1163,6 +1481,9 @@ export function createChatClient(options) {
1163
1481
  * audio and video are their own `msgtype`s with their own players, and
1164
1482
  * neither is in the first ship. */
1165
1483
  function toAttachment(event) {
1484
+ const eventId = event.getId();
1485
+ if (!eventId)
1486
+ return null;
1166
1487
  const content = event.getContent();
1167
1488
  const msgtype = content.msgtype;
1168
1489
  if (msgtype !== MsgType.Image && msgtype !== MsgType.File)
@@ -1177,6 +1498,7 @@ export function createChatClient(options) {
1177
1498
  mimeType,
1178
1499
  size: typeof info.size === 'number' ? info.size : 0,
1179
1500
  mxcUri,
1501
+ eventId,
1180
1502
  // The sender's own `msgtype` decides, not the name: a `.png` that is
1181
1503
  // not one would draw a broken picture, and the preview is fetched
1182
1504
  // through `loadMedia` either way.
@@ -1189,11 +1511,6 @@ export function createChatClient(options) {
1189
1511
  starting = (async () => {
1190
1512
  const body = await performExchange();
1191
1513
  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
1514
  const created = createMatrixClient({
1198
1515
  baseUrl: body.homeserver,
1199
1516
  userId: body.user_id,
@@ -1201,11 +1518,33 @@ export function createChatClient(options) {
1201
1518
  deviceId: body.device_id,
1202
1519
  store,
1203
1520
  });
1521
+ // Loads any previously-persisted sync data before the sync loop can
1522
+ // touch the store; skipping it leaves `store.backend` unset, and the
1523
+ // store silently degrades to an in-memory one on first access
1524
+ // (`IndexedDBStore`'s own `degradable()`), defeating `storeName`.
1525
+ //
1526
+ // Must run after `createMatrixClient`, not before: matrix-js-sdk's
1527
+ // own constructor is what calls `store.setUserCreator` (`client.ts`'s
1528
+ // `this._store.setUserCreator(...)`), and `IndexedDBStore.startup`
1529
+ // needs that already set before it can replay any `m.presence`
1530
+ // persisted from a earlier session -- calling this any earlier
1531
+ // throws matrix-js-sdk's own "IndexedDBStore.startup must be called
1532
+ // after assigning it to the client, not before!" the moment a store
1533
+ // actually has presence to replay. Dormant the whole time presence
1534
+ // was off (ticket #7): every store's persisted `userPresenceEvents`
1535
+ // was empty, so the guard this trips was never reached. Confirmed
1536
+ // live: `test/integration/sync.test.ts`'s restarted-client case is
1537
+ // the one that surfaced it, the moment the test stack turned
1538
+ // presence on.
1539
+ await store.startup();
1204
1540
  client = created;
1205
1541
  created.on(HttpApiEvent.SessionLoggedOut, onLoggedOut);
1206
1542
  created.on(ClientEvent.Sync, onSync);
1207
1543
  created.on(RoomEvent.Timeline, onRoomTimelineChanged);
1208
1544
  created.on(RoomEvent.LocalEchoUpdated, onRoomTimelineChanged);
1545
+ created.on(RoomEvent.Receipt, onRoomReceipt);
1546
+ created.on(UserEvent.Presence, onUserPresence);
1547
+ created.on(RoomMemberEvent.Typing, onRoomMemberTyping);
1209
1548
  scheduleRefresh(body.expires_at);
1210
1549
  const outcome = nextSyncOutcome(created);
1211
1550
  // Without `threadSupport`, matrix-js-sdk puts every `m.thread` reply
@@ -1214,6 +1553,7 @@ export function createChatClient(options) {
1214
1553
  // and the room keeps only the message that started it (ticket #17).
1215
1554
  // It is a `startClient` option, not a `createClient` one.
1216
1555
  await created.startClient(START_OPTIONS);
1556
+ reapplyAnnouncedPresence(created);
1217
1557
  await outcome;
1218
1558
  })();
1219
1559
  return starting;
@@ -1224,6 +1564,13 @@ export function createChatClient(options) {
1224
1564
  upload.abort.abort();
1225
1565
  }
1226
1566
  uploads.clear();
1567
+ // A restart gets a brand-new `MatrixClient`; `chainPinnedWrite`'s own
1568
+ // `client !== target` check already keeps a still-running chain from
1569
+ // writing through the old one, but there is nothing left worth basing
1570
+ // a future write on either.
1571
+ pinnedChain.clear();
1572
+ pinnedKnown.clear();
1573
+ typingUsers.clear();
1227
1574
  starting = undefined;
1228
1575
  clearTimeout(refreshTimer);
1229
1576
  refreshTimer = undefined;
@@ -1232,6 +1579,9 @@ export function createChatClient(options) {
1232
1579
  client.removeListener(ClientEvent.Sync, onSync);
1233
1580
  client.removeListener(RoomEvent.Timeline, onRoomTimelineChanged);
1234
1581
  client.removeListener(RoomEvent.LocalEchoUpdated, onRoomTimelineChanged);
1582
+ client.removeListener(RoomEvent.Receipt, onRoomReceipt);
1583
+ client.removeListener(UserEvent.Presence, onUserPresence);
1584
+ client.removeListener(RoomMemberEvent.Typing, onRoomMemberTyping);
1235
1585
  client.stopClient();
1236
1586
  }
1237
1587
  client = undefined;
@@ -1245,6 +1595,153 @@ export function createChatClient(options) {
1245
1595
  statusListeners.add(listener);
1246
1596
  return () => statusListeners.delete(listener);
1247
1597
  }
1598
+ /** Matrix's own three presence strings, plus MSC3026's unstable `busy`,
1599
+ * folded onto the four states `Presence` exposes -- see `Presence`'s own
1600
+ * comment for why anything else, `undefined` included, reads as
1601
+ * `'offline'` rather than being treated as an error. */
1602
+ function toPresence(raw) {
1603
+ switch (raw) {
1604
+ case 'online':
1605
+ return 'online';
1606
+ case 'unavailable':
1607
+ return 'away';
1608
+ case 'busy':
1609
+ case 'org.matrix.msc3026.busy':
1610
+ return 'busy';
1611
+ default:
1612
+ return 'offline';
1613
+ }
1614
+ }
1615
+ /** See `ChatClient.presence`. `client.getUser` is matrix-js-sdk's own
1616
+ * cache, populated the moment an `m.presence` event for that person has
1617
+ * ever arrived -- this never fetches. */
1618
+ function presence(userId) {
1619
+ return toPresence(client?.getUser(userId)?.presence);
1620
+ }
1621
+ /** See `ChatClient.announcePresence`. Two requests, and both are needed:
1622
+ *
1623
+ * `setSyncPresence` changes the `set_presence` this session's *own*
1624
+ * `/sync` carries from here on, which is the only thing that makes an
1625
+ * announcement survive -- Synapse's `user_syncing` feeds that parameter
1626
+ * straight into `set_state(is_sync=True)`, and the only state a sync is
1627
+ * forbidden to overwrite is `'busy'`. Without it a person announced away
1628
+ * is back online within one long poll, by their own client.
1629
+ *
1630
+ * It only reaches the wire on the *next* poll, though (`sync.js` reads
1631
+ * `this.presence` when it builds each request's query string, and never
1632
+ * interrupts one in flight), which for an idle tab is up to 30 seconds
1633
+ * away. The `PUT` closes that gap. Ordered sync-parameter first so that
1634
+ * a poll returning between the two carries the new value rather than
1635
+ * undoing the `PUT` that had not been sent yet.
1636
+ *
1637
+ * **The `PUT` is best-effort, and its failure is not this call's.**
1638
+ * Synapse allows one presence change per ten seconds
1639
+ * (`rc_presence.per_user`, default `per_second: 0.1, burst_count: 1`),
1640
+ * and refuses the rest with a `429` -- so a person who goes idle and
1641
+ * comes straight back would otherwise get a rejection for an
1642
+ * announcement that had in fact taken effect. It had: `setSyncPresence`
1643
+ * is local bookkeeping that cannot fail, and the next poll carries it.
1644
+ * Synapse treats the same limit differently there, ignoring a sync's
1645
+ * `set_presence` for one round rather than refusing the sync
1646
+ * (`rest/client/sync.py`: `affect_presence = False`), so the state
1647
+ * converges on the poll after. Rejecting here would tell the caller
1648
+ * nothing true and nothing it could act on. */
1649
+ async function announcePresence(next) {
1650
+ announced = next === 'away' ? SetPresence.Unavailable : SetPresence.Online;
1651
+ const target = client;
1652
+ if (!target)
1653
+ return;
1654
+ await target.setSyncPresence(announced);
1655
+ try {
1656
+ await target.setPresence({ presence: announced });
1657
+ }
1658
+ catch {
1659
+ // Best-effort by design -- see above. The announcement is already
1660
+ // made; this only decided how soon anybody else would see it.
1661
+ }
1662
+ }
1663
+ /** `stopClient()` drops matrix-js-sdk's `SyncApi` entirely and
1664
+ * `startClient()` builds a fresh one (`client.js`'s `this.syncApi =
1665
+ * undefined` / `new SyncApi(...)`), so the `set_presence` an
1666
+ * announcement set lives exactly as long as one sync loop. Every restart
1667
+ * in this file -- a dead token, a refused sync position, a plain
1668
+ * `stop()` then `start()` -- would otherwise put an idle person silently
1669
+ * back online, which is the failure `announcePresence` exists to
1670
+ * prevent. So each restart re-applies it.
1671
+ *
1672
+ * The earliest this can run is once `startClient` returns, by which time
1673
+ * that restart's own first sync has already gone out carrying nothing --
1674
+ * so an idle person does flicker back to `'online'` for that one poll.
1675
+ * Every poll after it is right. Closing even that would mean reaching
1676
+ * into matrix-js-sdk's sync loop before it starts, which it offers no
1677
+ * hook for, and a restart of an idle session is rare enough not to be
1678
+ * worth a fork. */
1679
+ function reapplyAnnouncedPresence(target) {
1680
+ if (announced === undefined)
1681
+ return;
1682
+ void target.setSyncPresence(announced);
1683
+ }
1684
+ /** `UserEvent.Presence` is re-emitted onto the client itself for every
1685
+ * `User` matrix-js-sdk has ever created (`User.createUser`'s own "events
1686
+ * will also emit on MatrixClient") -- so one listener, attached once in
1687
+ * `start()`, covers every person this session ever hears about, not just
1688
+ * the members of a room a caller happens to be looking at. */
1689
+ function onUserPresence(_event, user) {
1690
+ const changed = new Map([[user.userId, toPresence(user.presence)]]);
1691
+ for (const listener of presenceListeners)
1692
+ listener(changed);
1693
+ }
1694
+ function onPresenceChanged(listener) {
1695
+ presenceListeners.add(listener);
1696
+ return () => presenceListeners.delete(listener);
1697
+ }
1698
+ function notifyTyping(roomId) {
1699
+ const userIds = [...(typingUsers.get(roomId) ?? [])];
1700
+ for (const listener of typingListeners.get(roomId) ?? [])
1701
+ listener(userIds);
1702
+ }
1703
+ /** `RoomMemberEvent.Typing` is re-emitted onto the client for every
1704
+ * member of every room it knows (`_createAndReEmitRoom`'s own
1705
+ * `RoomStateEvent.NewMember` wiring), so -- like `onUserPresence` -- one
1706
+ * listener attached once covers every room. The signed-in person's own
1707
+ * typing is dropped here rather than in `notifyTyping`: `m.typing`
1708
+ * lists everyone currently typing including this session, and a person
1709
+ * is never told they themselves are typing. */
1710
+ function onRoomMemberTyping(_event, member) {
1711
+ if (member.userId === client?.getUserId())
1712
+ return;
1713
+ let set = typingUsers.get(member.roomId);
1714
+ if (member.typing) {
1715
+ if (!set) {
1716
+ set = new Set();
1717
+ typingUsers.set(member.roomId, set);
1718
+ }
1719
+ set.add(member.userId);
1720
+ }
1721
+ else if (set) {
1722
+ set.delete(member.userId);
1723
+ if (set.size === 0)
1724
+ typingUsers.delete(member.roomId);
1725
+ }
1726
+ notifyTyping(member.roomId);
1727
+ }
1728
+ function onTypingChanged(roomId, listener) {
1729
+ let set = typingListeners.get(roomId);
1730
+ if (!set) {
1731
+ set = new Set();
1732
+ typingListeners.set(roomId, set);
1733
+ }
1734
+ set.add(listener);
1735
+ return () => set?.delete(listener);
1736
+ }
1737
+ /** See `ChatClient.sendTyping`. Fire-and-forget, the same as every other
1738
+ * ephemeral signal in this file: a dropped typing notification is not
1739
+ * worth retrying, and there is no local echo to settle either way. */
1740
+ function sendTyping(roomId, typing) {
1741
+ if (!client)
1742
+ return;
1743
+ client.sendTyping(roomId, typing, TYPING_TIMEOUT_MS).catch(() => { });
1744
+ }
1248
1745
  /** Sends `m.read` for the newest event in the room's live timeline and
1249
1746
  * clears the count right away, rather than waiting for the server to
1250
1747
  * echo the receipt back on a later sync -- matrix-js-sdk's own local
@@ -1265,6 +1762,37 @@ export function createChatClient(options) {
1265
1762
  await client.sendReadReceipt(newest);
1266
1763
  room.setUnreadNotificationCount(NotificationCountType.Total, 0);
1267
1764
  room.setUnreadNotificationCount(NotificationCountType.Highlight, 0);
1765
+ // A real read is the only thing that proves Synapse's own count and
1766
+ // the local walk have caught up with each other -- both are 0 now,
1767
+ // whether or not the room is still muted. Until this, calling
1768
+ // `muteRoom(roomId, false)` alone must not be read as that proof: see
1769
+ // `unreliableServerCount`.
1770
+ unreliableServerCount.delete(roomId);
1771
+ notify();
1772
+ }
1773
+ /** See `ChatClient.muteRoom`. `setRoomMutePushRule` PUTs (or, unmuting,
1774
+ * DELETEs) the room-scoped rule and then re-fetches `/pushrules/` on
1775
+ * its own before resolving, so `client.pushRules` -- and so `isMuted`,
1776
+ * and so the next `rooms()` -- already reflects the server's own
1777
+ * answer by the time this returns; nothing here needs to wait for a
1778
+ * fresh `/sync`. `notify()` still runs explicitly because that refresh
1779
+ * is a plain HTTP round trip, not a landed sync, so `onSync` never
1780
+ * fires for it.
1781
+ *
1782
+ * Muting or unmuting both mark the room `unreliableServerCount`: once
1783
+ * muted, Synapse stops climbing on its own count, and unmuting does not
1784
+ * make it recompute what it already decided not to count -- confirmed
1785
+ * live, `notification_count` stays exactly where muting left it, not
1786
+ * just right after unmuting but on every later poll too. So the room
1787
+ * keeps comparing against the local walk across the whole mute ->
1788
+ * traffic -> unmute run, until a real read proves the two agree again. */
1789
+ async function muteRoom(roomId, muted) {
1790
+ if (!client)
1791
+ return;
1792
+ if (!client.getRoom(roomId))
1793
+ return;
1794
+ await client.setRoomMutePushRule('global', roomId, muted);
1795
+ unreliableServerCount.add(roomId);
1268
1796
  notify();
1269
1797
  }
1270
1798
  return {
@@ -1273,13 +1801,19 @@ export function createChatClient(options) {
1273
1801
  rooms: readRooms,
1274
1802
  totalUnreadCount: () => readRooms().reduce((sum, room) => sum + room.unreadCount, 0),
1275
1803
  markRoomRead,
1804
+ muteRoom,
1276
1805
  connectionStatus: () => status,
1277
1806
  onConnectionStatusChanged,
1278
1807
  onRoomsChanged,
1279
1808
  userId: () => client?.getUserId() ?? null,
1280
1809
  people: readPeople,
1281
1810
  roomMembers,
1811
+ readBy,
1812
+ reportMessage,
1282
1813
  toggleReaction,
1814
+ pinMessage,
1815
+ unpinMessage,
1816
+ pinnedMessages,
1283
1817
  startDirectMessage,
1284
1818
  hideDirectMessage,
1285
1819
  acceptInvitation,
@@ -1287,6 +1821,7 @@ export function createChatClient(options) {
1287
1821
  timeline,
1288
1822
  onTimelineChanged,
1289
1823
  paginate,
1824
+ roomFiles,
1290
1825
  sendMessage,
1291
1826
  editMessage,
1292
1827
  deleteMessage,
@@ -1296,5 +1831,10 @@ export function createChatClient(options) {
1296
1831
  canLoadMedia,
1297
1832
  loadMedia,
1298
1833
  sendFile,
1834
+ presence,
1835
+ announcePresence,
1836
+ onPresenceChanged,
1837
+ sendTyping,
1838
+ onTypingChanged,
1299
1839
  };
1300
1840
  }