@alexsun-top/opencode-chat-room 0.2.3 → 0.3.1
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/CHANGELOG.md +21 -0
- package/README.md +44 -7
- package/README.zh-CN.md +44 -7
- package/package.json +6 -2
- package/plugin.ts +21 -6
- package/server/assets/DOMPURIFY-LICENSE +202 -0
- package/server/assets/MARKED-LICENSE +44 -0
- package/server/assets/NOTICE.txt +6 -0
- package/server/assets/base.css +225 -0
- package/server/assets/chat/events.js +148 -0
- package/server/assets/chat/index.js +12 -0
- package/server/assets/chat/markdown.js +65 -0
- package/server/assets/chat/members.js +201 -0
- package/server/assets/chat/mentions.js +131 -0
- package/server/assets/chat/messages.js +489 -0
- package/server/assets/chat/rooms.js +443 -0
- package/server/assets/chat/state.js +327 -0
- package/server/assets/conversation.css +364 -0
- package/server/assets/dompurify-3.4.7.js +3 -0
- package/server/assets/marked-18.0.4.js +79 -0
- package/server/assets/responsive.css +119 -0
- package/server/chat-server.ts +39 -43
- package/server/chat.html +27 -1984
- package/server/history-route.ts +2 -1
- package/server/inbox.ts +1 -1
- package/server/member-routes.ts +117 -0
- package/server/newrooms.ts +86 -0
- package/server/wake.ts +13 -14
- package/src/agent-presence.ts +60 -0
- package/src/agent-receipts.ts +107 -0
- package/src/background.ts +70 -25
- package/src/center-client.ts +25 -6
- package/src/center-inbox.ts +77 -37
- package/src/center-wake.ts +43 -9
- package/src/member-state.ts +25 -0
- package/src/mentions.ts +7 -0
- package/src/plugin-notifications.ts +75 -23
- package/src/queue-transport.ts +17 -1
- package/src/queue.ts +36 -2
- package/src/receiver-state.ts +108 -6
- package/src/room-service.ts +19 -1
- package/src/sqlite-state.ts +123 -16
- package/src/store.ts +28 -1
- package/src/v2-plugin.ts +10 -2
- package/src/v2-receiver.ts +67 -45
- package/src/watch.ts +17 -3
|
@@ -0,0 +1,489 @@
|
|
|
1
|
+
import { createRandomId, LS } from "./state.js";
|
|
2
|
+
import { renderMarkdown } from "./markdown.js";
|
|
3
|
+
|
|
4
|
+
export function initMessages(app) {
|
|
5
|
+
const $ = app.$;
|
|
6
|
+
let pollDelay = 2000;
|
|
7
|
+
|
|
8
|
+
app.autoGrow = (textarea) => {
|
|
9
|
+
textarea.style.height = "auto";
|
|
10
|
+
textarea.style.height = `${Math.min(textarea.scrollHeight, 132)}px`;
|
|
11
|
+
};
|
|
12
|
+
app.updateSendState = () => { $("#btnSend").disabled = !$("#msgInput").value.trim(); };
|
|
13
|
+
app.updateDraftCount = () => app.setText($("#draftCount"), "messageCount", { count: $("#msgInput").value.length });
|
|
14
|
+
app.renderFailedMessages = () => {
|
|
15
|
+
const composer = $("#msgInput").closest(".composer");
|
|
16
|
+
let panel = composer.querySelector(".failed-messages");
|
|
17
|
+
if (!panel) {
|
|
18
|
+
panel = document.createElement("section");
|
|
19
|
+
panel.className = "failed-messages";
|
|
20
|
+
panel.setAttribute("aria-live", "polite");
|
|
21
|
+
composer.insertBefore(panel, $(".composer-row"));
|
|
22
|
+
}
|
|
23
|
+
const roomId = app.state.room?.id, items = roomId && app.state.failedMessages.get(roomId) || [];
|
|
24
|
+
panel.textContent = "";
|
|
25
|
+
panel.hidden = !items.length;
|
|
26
|
+
if (!items.length) return;
|
|
27
|
+
const heading = document.createElement("h3");
|
|
28
|
+
heading.textContent = app.t("failedMessages");
|
|
29
|
+
panel.append(heading);
|
|
30
|
+
for (const item of items) {
|
|
31
|
+
const row = document.createElement("article"), text = document.createElement("p");
|
|
32
|
+
row.className = "failed-message";
|
|
33
|
+
text.textContent = item.text;
|
|
34
|
+
row.append(text, failedAction("retryFailed", roomId, item.id, app), failedAction("discardFailed", roomId, item.id, app));
|
|
35
|
+
panel.append(row);
|
|
36
|
+
}
|
|
37
|
+
};
|
|
38
|
+
app.discardFailedMessage = (roomId, failedId) => {
|
|
39
|
+
app.saveFailedMessages(roomId, (app.state.failedMessages.get(roomId) || []).filter((item) => item.id !== failedId));
|
|
40
|
+
app.renderFailedMessages();
|
|
41
|
+
};
|
|
42
|
+
app.retryFailedMessage = async (roomId, failedId) => {
|
|
43
|
+
const item = app.state.failedMessages.get(roomId)?.find((message) => message.id === failedId);
|
|
44
|
+
if (!item || app.state.retryingFailedIds.has(failedId)) return;
|
|
45
|
+
app.state.retryingFailedIds.add(failedId);
|
|
46
|
+
app.renderFailedMessages();
|
|
47
|
+
try {
|
|
48
|
+
const updated = await app.api(`/rooms/${encodeURIComponent(roomId)}/messages`, {
|
|
49
|
+
method: "POST", body: JSON.stringify({ sessionID: LS.sessionID, text: item.text }),
|
|
50
|
+
});
|
|
51
|
+
const entry = app.state.rooms.get(roomId);
|
|
52
|
+
if (entry) {
|
|
53
|
+
entry.room = mergeRoom(entry.room, updated);
|
|
54
|
+
const latest = entry.room.messages.at(-1);
|
|
55
|
+
if (latest && latest.createdAt >= entry.previewAt) { entry.preview = latest.text; entry.previewAt = latest.createdAt; }
|
|
56
|
+
}
|
|
57
|
+
app.discardFailedMessage(roomId, failedId);
|
|
58
|
+
if (app.state.room?.id === roomId && entry) {
|
|
59
|
+
app.state.room = entry.room;
|
|
60
|
+
app.renderMessages(true);
|
|
61
|
+
app.renderMembers();
|
|
62
|
+
app.markActiveRoomRead();
|
|
63
|
+
app.renderRoomOptions($("#roomList"), app.state.availableRooms || []);
|
|
64
|
+
app.renderRoomOptions($("#roomListChat"), app.state.availableRooms || []);
|
|
65
|
+
}
|
|
66
|
+
} catch (error) {
|
|
67
|
+
if (app.state.room?.id === roomId) app.showSendError(error.status === 401 ? "sendAuth" : error.network ? "sendNetwork" : "sendFailed", { message: error.message });
|
|
68
|
+
} finally {
|
|
69
|
+
app.state.retryingFailedIds.delete(failedId);
|
|
70
|
+
app.renderFailedMessages();
|
|
71
|
+
}
|
|
72
|
+
};
|
|
73
|
+
app.jumpToBottom = () => {
|
|
74
|
+
$("#thread").scrollTop = $("#thread").scrollHeight;
|
|
75
|
+
const entry = app.state.room && app.state.rooms.get(app.state.room.id);
|
|
76
|
+
app.state.unread = entry ? entry.unreadIds.size + (entry.unreadOverflow ? 100 : 0) : 0;
|
|
77
|
+
app.updateBadge();
|
|
78
|
+
app.updateJump();
|
|
79
|
+
void app.markActiveRoomRead();
|
|
80
|
+
};
|
|
81
|
+
app.updateJump = () => {
|
|
82
|
+
const thread = $("#thread");
|
|
83
|
+
const away = thread.scrollHeight - thread.scrollTop - thread.clientHeight > 160;
|
|
84
|
+
$("#btnJump").hidden = !(away || app.state.unread > 0);
|
|
85
|
+
};
|
|
86
|
+
app.updateBadge = () => {
|
|
87
|
+
const badge = $("#jumpBadge");
|
|
88
|
+
badge.textContent = app.state.unread > 99 ? "99+" : String(app.state.unread);
|
|
89
|
+
badge.hidden = app.state.unread === 0;
|
|
90
|
+
app.updateTitle();
|
|
91
|
+
};
|
|
92
|
+
app.markActiveRoomRead = async () => {
|
|
93
|
+
const room = app.state.room, entry = room && app.state.rooms.get(room.id);
|
|
94
|
+
const generation = app.state.pollGeneration;
|
|
95
|
+
const thread = $("#thread");
|
|
96
|
+
if (!room || !entry || document.hidden || !document.hasFocus()
|
|
97
|
+
|| thread.scrollHeight - thread.scrollTop - thread.clientHeight >= 80) return;
|
|
98
|
+
const timestamp = room.messages.reduce((latest, message) => Math.max(latest, message.createdAt), entry.readTs);
|
|
99
|
+
if (!timestamp || timestamp <= entry.readTs) return;
|
|
100
|
+
try {
|
|
101
|
+
await app.api("/read", {
|
|
102
|
+
method: "POST", body: JSON.stringify({ roomId: room.id, sessionID: LS.sessionID, ts: timestamp }),
|
|
103
|
+
});
|
|
104
|
+
if (app.state.room?.id !== room.id || app.state.pollGeneration !== generation) return;
|
|
105
|
+
entry.readTs = timestamp;
|
|
106
|
+
entry.unreadOverflow = false;
|
|
107
|
+
for (const [id, message] of entry.unreadIds) if (message.createdAt <= timestamp) entry.unreadIds.delete(id);
|
|
108
|
+
app.state.unread = entry.unreadIds.size + (entry.unreadOverflow ? 100 : 0);
|
|
109
|
+
app.updateBadge();
|
|
110
|
+
app.renderRoomOptions($("#roomList"), app.state.availableRooms || []);
|
|
111
|
+
app.renderRoomOptions($("#roomListChat"), app.state.availableRooms || []);
|
|
112
|
+
} catch { /* The next active poll will retry the read watermark. */ }
|
|
113
|
+
};
|
|
114
|
+
|
|
115
|
+
app.renderMessage = (message, live) => {
|
|
116
|
+
const row = document.createElement("li");
|
|
117
|
+
row.dataset.sender = message.senderId;
|
|
118
|
+
row.dataset.ts = message.createdAt;
|
|
119
|
+
row.dataset.msgId = message.id;
|
|
120
|
+
if (message.senderId === "system") {
|
|
121
|
+
row.className = "sys";
|
|
122
|
+
const text = document.createElement("span");
|
|
123
|
+
text.textContent = systemMessage(message.text, app);
|
|
124
|
+
row.append(text);
|
|
125
|
+
} else {
|
|
126
|
+
const direct = app.state.room.kind === "direct";
|
|
127
|
+
const sameName = app.state.memberSessions.get(app.state.room.id)?.filter((member) => member.name === message.senderId);
|
|
128
|
+
const own = direct ? message.senderId === LS.sessionID
|
|
129
|
+
: message.senderSessionID ? message.senderSessionID === LS.sessionID
|
|
130
|
+
: message.senderId === app.state.myName && sameName?.length === 1 && sameName[0].sessionID === LS.sessionID;
|
|
131
|
+
const sender = direct
|
|
132
|
+
? app.state.room.participants.find((person) => person.id === message.senderId)?.name || app.t("guest")
|
|
133
|
+
: message.senderId;
|
|
134
|
+
row.className = `msg${own ? " own" : ""}`;
|
|
135
|
+
const meta = document.createElement("div"), name = document.createElement("span"), time = document.createElement("span");
|
|
136
|
+
meta.className = "msg-meta";
|
|
137
|
+
name.className = "msg-name";
|
|
138
|
+
name.textContent = own ? app.t("you") : sender;
|
|
139
|
+
time.className = "msg-time";
|
|
140
|
+
time.textContent = app.timeHM(message.createdAt);
|
|
141
|
+
meta.append(name, time);
|
|
142
|
+
const body = document.createElement("div");
|
|
143
|
+
body.className = "msg-text";
|
|
144
|
+
renderMarkdown(body, message.text, app);
|
|
145
|
+
row.append(meta, body, receiptDetails(message, app));
|
|
146
|
+
}
|
|
147
|
+
if (live) row.classList.add("in");
|
|
148
|
+
return row;
|
|
149
|
+
};
|
|
150
|
+
|
|
151
|
+
app.renderReceiptData = (roomId, receipts) => {
|
|
152
|
+
const thread = $("#thread"), edge = thread.getBoundingClientRect();
|
|
153
|
+
const atBottom = thread.scrollHeight - thread.scrollTop - thread.clientHeight <= 2;
|
|
154
|
+
const anchor = Array.from($("#msgList").querySelectorAll("[data-msg-id]")).find((node) => node.getBoundingClientRect().bottom > edge.top);
|
|
155
|
+
const anchorId = anchor?.dataset.msgId, anchorTop = anchor ? anchor.getBoundingClientRect().top - edge.top : 0;
|
|
156
|
+
for (const receipt of receipts) app.state.receipts.set(`${roomId}\0${receipt.messageID}`, receipt.readers);
|
|
157
|
+
for (const row of document.querySelectorAll(`#msgList [data-msg-id]`)) {
|
|
158
|
+
const message = app.state.room?.messages.find((item) => item.id === row.dataset.msgId);
|
|
159
|
+
if (message?.roomId === roomId || app.state.room?.id === roomId && message) updateReceiptDetails(row, message, app);
|
|
160
|
+
}
|
|
161
|
+
if (atBottom) thread.scrollTop = thread.scrollHeight;
|
|
162
|
+
else if (anchorId) {
|
|
163
|
+
const next = $("#msgList").querySelector(`[data-msg-id="${CSS.escape(anchorId)}"]`);
|
|
164
|
+
if (next) thread.scrollTop += next.getBoundingClientRect().top - thread.getBoundingClientRect().top - anchorTop;
|
|
165
|
+
}
|
|
166
|
+
};
|
|
167
|
+
|
|
168
|
+
app.renderMessages = (live = false) => {
|
|
169
|
+
const thread = $("#thread"), list = $("#msgList"), messages = app.state.room.messages;
|
|
170
|
+
const nearBottom = thread.scrollHeight - thread.scrollTop - thread.clientHeight <= 2;
|
|
171
|
+
let last = list.lastElementChild, skipped = 0;
|
|
172
|
+
let anchorId = null, anchorOffset = 0, oldTop = thread.scrollTop;
|
|
173
|
+
let renderedIds = new Set([...list.children].map((node) => node.dataset.msgId).filter(Boolean));
|
|
174
|
+
const viewport = thread.getBoundingClientRect();
|
|
175
|
+
const firstVisible = [...list.children].find((node) => node.dataset.msgId && node.getBoundingClientRect().bottom > viewport.top);
|
|
176
|
+
anchorId = firstVisible?.dataset.msgId || null;
|
|
177
|
+
anchorOffset = firstVisible ? firstVisible.getBoundingClientRect().top - viewport.top : 0;
|
|
178
|
+
if (messages.length && app.firstMessageId && messages[0].id !== app.firstMessageId) {
|
|
179
|
+
list.textContent = "";
|
|
180
|
+
app.rendered = 0;
|
|
181
|
+
last = null;
|
|
182
|
+
renderedIds = new Set();
|
|
183
|
+
}
|
|
184
|
+
for (let index = app.rendered; index < messages.length; index++) {
|
|
185
|
+
const message = messages[index];
|
|
186
|
+
if (renderedIds.has(message.id)) continue;
|
|
187
|
+
try {
|
|
188
|
+
const day = new Date(message.createdAt).toDateString();
|
|
189
|
+
if (!last || last.dataset.day !== day) {
|
|
190
|
+
const separator = document.createElement("li");
|
|
191
|
+
separator.className = "day-sep";
|
|
192
|
+
separator.dataset.day = day;
|
|
193
|
+
separator.textContent = app.dayText(message.createdAt);
|
|
194
|
+
list.append(separator);
|
|
195
|
+
last = separator;
|
|
196
|
+
}
|
|
197
|
+
const row = app.renderMessage(message, live);
|
|
198
|
+
row.dataset.day = day;
|
|
199
|
+
if (last.classList.contains("msg") && last.dataset.sender === message.senderId
|
|
200
|
+
&& message.createdAt - Number(last.dataset.ts) < 8 * 60 * 1000) row.classList.add("repeat");
|
|
201
|
+
list.append(row);
|
|
202
|
+
last = row;
|
|
203
|
+
renderedIds.add(message.id);
|
|
204
|
+
} catch (error) {
|
|
205
|
+
console.error("[chat] Message could not render", error);
|
|
206
|
+
skipped++;
|
|
207
|
+
app.failedRenderIds.add(message.id);
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
app.rendered = messages.length;
|
|
211
|
+
app.firstMessageId = messages[0]?.id || app.firstMessageId;
|
|
212
|
+
$("#msgEmpty").hidden = messages.length > 0;
|
|
213
|
+
if (nearBottom) thread.scrollTop = thread.scrollHeight;
|
|
214
|
+
else if (anchorId) {
|
|
215
|
+
const anchor = list.querySelector(`[data-msg-id="${CSS.escape(anchorId)}"]`);
|
|
216
|
+
if (anchor) thread.scrollTop += anchor.getBoundingClientRect().top - viewport.top - anchorOffset;
|
|
217
|
+
else thread.scrollTop = oldTop;
|
|
218
|
+
} else if (!live || nearBottom) thread.scrollTop = thread.scrollHeight;
|
|
219
|
+
app.updateJump();
|
|
220
|
+
trimMessages(list, app);
|
|
221
|
+
if (nearBottom) {
|
|
222
|
+
thread.scrollTop = thread.scrollHeight;
|
|
223
|
+
const roomId = app.state.room?.id, generation = app.state.pollGeneration;
|
|
224
|
+
requestAnimationFrame(() => {
|
|
225
|
+
if (app.state.room?.id === roomId && app.state.pollGeneration === generation
|
|
226
|
+
&& thread.scrollHeight - thread.scrollTop - thread.clientHeight < 80) thread.scrollTop = thread.scrollHeight;
|
|
227
|
+
});
|
|
228
|
+
}
|
|
229
|
+
else if (anchorId) {
|
|
230
|
+
const anchor = list.querySelector(`[data-msg-id="${CSS.escape(anchorId)}"]`);
|
|
231
|
+
if (anchor) thread.scrollTop += anchor.getBoundingClientRect().top - thread.getBoundingClientRect().top - anchorOffset;
|
|
232
|
+
else thread.scrollTop = oldTop;
|
|
233
|
+
}
|
|
234
|
+
app.queueReceiptRefresh?.();
|
|
235
|
+
app.queueReceiptObservation?.();
|
|
236
|
+
return { skipped };
|
|
237
|
+
};
|
|
238
|
+
|
|
239
|
+
app.rerenderMessages = () => {
|
|
240
|
+
if (!app.state.room) return { skipped: 0 };
|
|
241
|
+
const thread = $("#thread"), list = $("#msgList"), oldTop = thread.scrollTop;
|
|
242
|
+
const atBottom = thread.scrollHeight - oldTop - thread.clientHeight < 80;
|
|
243
|
+
const edge = thread.getBoundingClientRect();
|
|
244
|
+
const anchor = [...list.querySelectorAll("[data-msg-id]")].find((node) => node.getBoundingClientRect().bottom > edge.top);
|
|
245
|
+
const anchorId = anchor?.dataset.msgId;
|
|
246
|
+
const anchorOffset = anchor ? anchor.getBoundingClientRect().top - edge.top : 0;
|
|
247
|
+
$("#msgList").textContent = "";
|
|
248
|
+
app.rendered = 0;
|
|
249
|
+
app.firstMessageId = null;
|
|
250
|
+
app.failedRenderIds.clear();
|
|
251
|
+
const result = app.renderMessages(false);
|
|
252
|
+
const nextAnchor = anchorId && list.querySelector(`[data-msg-id="${CSS.escape(anchorId)}"]`);
|
|
253
|
+
if (atBottom) thread.scrollTop = thread.scrollHeight;
|
|
254
|
+
else if (nextAnchor) thread.scrollTop += nextAnchor.getBoundingClientRect().top - edge.top - anchorOffset;
|
|
255
|
+
else thread.scrollTop = oldTop;
|
|
256
|
+
return result;
|
|
257
|
+
};
|
|
258
|
+
|
|
259
|
+
app.send = async () => {
|
|
260
|
+
const input = $("#msgInput"), text = input.value.trim(), room = app.state.room;
|
|
261
|
+
if (!text || !room) return;
|
|
262
|
+
const revision = app.state.draftRevision.get(room.id) || 0;
|
|
263
|
+
app.closeMention();
|
|
264
|
+
input.value = "";
|
|
265
|
+
app.clearDraft(room.id);
|
|
266
|
+
app.autoGrow(input);
|
|
267
|
+
app.updateSendState();
|
|
268
|
+
app.updateDraftCount();
|
|
269
|
+
app.hideSendError();
|
|
270
|
+
try {
|
|
271
|
+
const updated = await app.api(`/rooms/${encodeURIComponent(room.id)}/messages`, {
|
|
272
|
+
method: "POST", body: JSON.stringify({ sessionID: LS.sessionID, text }),
|
|
273
|
+
});
|
|
274
|
+
if (app.state.room?.id !== room.id) return;
|
|
275
|
+
app.state.room = updated;
|
|
276
|
+
const entry = app.state.rooms.get(room.id);
|
|
277
|
+
if (entry) {
|
|
278
|
+
entry.room = updated;
|
|
279
|
+
const latest = updated.messages.at(-1);
|
|
280
|
+
if (latest) { entry.preview = latest.text; entry.previewAt = latest.createdAt; }
|
|
281
|
+
}
|
|
282
|
+
app.renderMessages(true);
|
|
283
|
+
$("#thread").scrollTop = $("#thread").scrollHeight;
|
|
284
|
+
app.renderMembers();
|
|
285
|
+
app.state.unread = entry ? entry.unreadIds.size + (entry.unreadOverflow ? 100 : 0) : 0;
|
|
286
|
+
app.updateBadge();
|
|
287
|
+
void app.markActiveRoomRead();
|
|
288
|
+
app.renderRoomOptions($("#roomList"), app.state.availableRooms || []);
|
|
289
|
+
app.renderRoomOptions($("#roomListChat"), app.state.availableRooms || []);
|
|
290
|
+
} catch (error) {
|
|
291
|
+
const unchanged = (app.state.draftRevision.get(room.id) || 0) === revision;
|
|
292
|
+
const failures = app.state.failedMessages.get(room.id) || [];
|
|
293
|
+
app.saveFailedMessages(room.id, [...failures, { id: createRandomId(), text }]);
|
|
294
|
+
app.renderFailedMessages();
|
|
295
|
+
if (app.state.room?.id !== room.id) return;
|
|
296
|
+
if (unchanged) app.clearDraft(room.id);
|
|
297
|
+
app.autoGrow(input);
|
|
298
|
+
app.updateSendState();
|
|
299
|
+
app.updateDraftCount();
|
|
300
|
+
if (error.status === 401) { app.openChatSettings(); app.showSendError("sendAuth"); }
|
|
301
|
+
else app.showSendError(error.network ? "sendNetwork" : "sendFailed", { message: error.message });
|
|
302
|
+
}
|
|
303
|
+
};
|
|
304
|
+
|
|
305
|
+
function isCurrentPoll(roomId, generation) {
|
|
306
|
+
return app.state.polling && app.state.pollGeneration === generation && app.state.room?.id === roomId;
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
app.startPolling = () => {
|
|
310
|
+
app.stopPolling();
|
|
311
|
+
const generation = ++app.state.pollGeneration;
|
|
312
|
+
const controller = new AbortController();
|
|
313
|
+
app.state.pollController = controller;
|
|
314
|
+
app.state.polling = true;
|
|
315
|
+
pollDelay = 2000;
|
|
316
|
+
void pollLoop(generation, controller.signal);
|
|
317
|
+
};
|
|
318
|
+
app.stopPolling = () => {
|
|
319
|
+
app.state.polling = false;
|
|
320
|
+
app.state.pollGeneration++;
|
|
321
|
+
app.state.pollController?.abort();
|
|
322
|
+
app.state.pollController = null;
|
|
323
|
+
};
|
|
324
|
+
|
|
325
|
+
async function pollLoop(generation, signal) {
|
|
326
|
+
while (app.state.polling && app.state.room && generation === app.state.pollGeneration) {
|
|
327
|
+
await poll(generation, signal).catch(() => {});
|
|
328
|
+
if (!app.state.polling || generation !== app.state.pollGeneration) break;
|
|
329
|
+
await new Promise((resolve) => setTimeout(resolve, pollDelay));
|
|
330
|
+
}
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
async function poll(generation, signal) {
|
|
334
|
+
const roomId = app.state.room?.id;
|
|
335
|
+
if (!roomId || !isCurrentPoll(roomId, generation)) return;
|
|
336
|
+
try {
|
|
337
|
+
const query = new URLSearchParams({ sessionID: LS.sessionID, roomId, excludeSelf: "0", timeout: "25000" });
|
|
338
|
+
const data = await app.api(`/inbox?${query}`, { signal });
|
|
339
|
+
if (!isCurrentPoll(roomId, generation)) return;
|
|
340
|
+
if (!data.member) {
|
|
341
|
+
void app.removeJoinedRoom(roomId, { reason: true });
|
|
342
|
+
return;
|
|
343
|
+
}
|
|
344
|
+
const items = Array.isArray(data.items) ? data.items : [];
|
|
345
|
+
const entry = app.state.rooms.get(roomId), messages = app.state.room.messages;
|
|
346
|
+
const known = new Set(messages.map((message) => message.id));
|
|
347
|
+
let sawSystem = false, added = 0;
|
|
348
|
+
for (const item of items) {
|
|
349
|
+
if (item.senderId === "system") sawSystem = true;
|
|
350
|
+
if (known.has(item.id)) continue;
|
|
351
|
+
messages.push({ ...item, roomId });
|
|
352
|
+
known.add(item.id);
|
|
353
|
+
entry?.unreadIds.set(item.id, item);
|
|
354
|
+
if (entry && item.createdAt >= entry.previewAt) { entry.preview = item.text; entry.previewAt = item.createdAt; }
|
|
355
|
+
added++;
|
|
356
|
+
}
|
|
357
|
+
if (entry) entry.unreadOverflow = Boolean(data.hasMore);
|
|
358
|
+
if (messages.length > 500) messages.splice(0, messages.length - 500);
|
|
359
|
+
const rendered = app.renderMessages(true);
|
|
360
|
+
if (sawSystem) {
|
|
361
|
+
await app.refreshRoomMeta(roomId, generation);
|
|
362
|
+
if (!isCurrentPoll(roomId, generation)) return;
|
|
363
|
+
}
|
|
364
|
+
if (added) {
|
|
365
|
+
app.state.unread = entry ? entry.unreadIds.size + (entry.unreadOverflow ? 100 : 0) : app.state.unread + added;
|
|
366
|
+
app.updateBadge();
|
|
367
|
+
}
|
|
368
|
+
if (rendered.skipped === 0) void app.markActiveRoomRead();
|
|
369
|
+
app.renderRoomOptions($("#roomList"), app.state.availableRooms || []);
|
|
370
|
+
app.renderRoomOptions($("#roomListChat"), app.state.availableRooms || []);
|
|
371
|
+
if (!app.lastReconcileAt || Date.now() - app.lastReconcileAt > 120000) {
|
|
372
|
+
app.lastReconcileAt = Date.now();
|
|
373
|
+
void app.reconcileRoom(roomId, generation);
|
|
374
|
+
}
|
|
375
|
+
app.setOnline(true);
|
|
376
|
+
pollDelay = 2000;
|
|
377
|
+
} catch (error) {
|
|
378
|
+
if (!isCurrentPoll(roomId, generation)) return;
|
|
379
|
+
if (error.status === 401) {
|
|
380
|
+
app.setOnline(false);
|
|
381
|
+
if ($("#chatSettings").hidden) app.openChatSettings();
|
|
382
|
+
pollDelay = Math.min(pollDelay * 2, 30000);
|
|
383
|
+
} else if (error.status === 404) {
|
|
384
|
+
void app.removeJoinedRoom(roomId, { reason: true });
|
|
385
|
+
} else {
|
|
386
|
+
app.setOnline(false);
|
|
387
|
+
pollDelay = 2000;
|
|
388
|
+
}
|
|
389
|
+
}
|
|
390
|
+
}
|
|
391
|
+
|
|
392
|
+
app.refreshRoomMeta = async (roomId = app.state.room?.id, generation = app.state.pollGeneration) => {
|
|
393
|
+
if (!roomId) return;
|
|
394
|
+
try {
|
|
395
|
+
const room = await app.api(`/rooms/${encodeURIComponent(roomId)}`);
|
|
396
|
+
if (!isCurrentPoll(roomId, generation)) return;
|
|
397
|
+
app.state.room.participants = room.participants;
|
|
398
|
+
app.renderMembers();
|
|
399
|
+
} catch { /* The next room event will retry. */ }
|
|
400
|
+
};
|
|
401
|
+
|
|
402
|
+
app.reconcileRoom = async (roomId, generation = app.state.pollGeneration) => {
|
|
403
|
+
try {
|
|
404
|
+
const room = await app.api(`/rooms/${encodeURIComponent(roomId)}`);
|
|
405
|
+
if (!isCurrentPoll(roomId, generation)) return;
|
|
406
|
+
const current = app.state.room.messages;
|
|
407
|
+
const ids = new Set(current.map((message) => message.id));
|
|
408
|
+
const missing = room.messages.filter((message) => !ids.has(message.id));
|
|
409
|
+
if (!missing.length && !app.failedRenderIds.size) return;
|
|
410
|
+
for (const message of missing) {
|
|
411
|
+
const index = current.findIndex((item) => item.createdAt > message.createdAt);
|
|
412
|
+
current.splice(index < 0 ? current.length : index, 0, message);
|
|
413
|
+
}
|
|
414
|
+
if (current.length > 500) current.splice(0, current.length - 500);
|
|
415
|
+
const result = app.rerenderMessages();
|
|
416
|
+
if (result.skipped === 0) void app.markActiveRoomRead();
|
|
417
|
+
} catch { /* Try again during the next reconciliation. */ }
|
|
418
|
+
};
|
|
419
|
+
|
|
420
|
+
function failedAction(key, roomId, failedId, app) {
|
|
421
|
+
const button = document.createElement("button");
|
|
422
|
+
button.type = "button";
|
|
423
|
+
button.textContent = app.t(key);
|
|
424
|
+
button.dataset.failedAction = key === "retryFailed" ? "retry" : "discard";
|
|
425
|
+
button.dataset.failedRoom = roomId;
|
|
426
|
+
button.dataset.failedId = failedId;
|
|
427
|
+
button.disabled = app.state.retryingFailedIds.has(failedId);
|
|
428
|
+
return button;
|
|
429
|
+
}
|
|
430
|
+
|
|
431
|
+
function mergeRoom(current, updated) {
|
|
432
|
+
const messages = new Map([...(current?.messages || []), ...updated.messages].map((message) => [message.id, message]));
|
|
433
|
+
return { ...updated, messages: [...messages.values()].sort((a, b) => a.createdAt - b.createdAt).slice(-500) };
|
|
434
|
+
}
|
|
435
|
+
|
|
436
|
+
function trimMessages(list, app) {
|
|
437
|
+
if (list.children.length <= 400) return;
|
|
438
|
+
while (list.children.length > 300) list.removeChild(list.firstChild);
|
|
439
|
+
if (list.firstElementChild && !list.firstElementChild.classList.contains("gap")) {
|
|
440
|
+
const gap = document.createElement("li");
|
|
441
|
+
gap.className = "gap";
|
|
442
|
+
app.setText(gap, "earlierMessages");
|
|
443
|
+
list.insertBefore(gap, list.firstChild);
|
|
444
|
+
}
|
|
445
|
+
}
|
|
446
|
+
|
|
447
|
+
function receiptDetails(message, app) {
|
|
448
|
+
const details = document.createElement("details");
|
|
449
|
+
details.className = "message-readers";
|
|
450
|
+
const summary = document.createElement("summary"), count = document.createElement("span"), list = document.createElement("ul");
|
|
451
|
+
count.className = "receipt-count";
|
|
452
|
+
list.className = "receipt-reader-list";
|
|
453
|
+
summary.append(count);
|
|
454
|
+
details.append(summary, list);
|
|
455
|
+
updateReceiptDetails(details.closest("li") || details, message, app);
|
|
456
|
+
return details;
|
|
457
|
+
}
|
|
458
|
+
|
|
459
|
+
function updateReceiptDetails(row, message, app) {
|
|
460
|
+
const details = row.matches?.("details.message-readers") ? row : row.querySelector("details.message-readers");
|
|
461
|
+
if (!details) return;
|
|
462
|
+
const detailsKey = `${app.state.room?.id || message.roomId || ""}\0${message.id}`;
|
|
463
|
+
const senderID = message.senderSessionID || (app.state.room?.kind === "direct" ? message.senderId : "");
|
|
464
|
+
const readers = (app.state.receipts.get(detailsKey) || []).filter((reader) => reader.sessionID !== senderID);
|
|
465
|
+
details.hidden = readers.length === 0;
|
|
466
|
+
details.querySelector(".receipt-count").textContent = app.t("receiptCount", { count: readers.length });
|
|
467
|
+
const list = details.querySelector(".receipt-reader-list");
|
|
468
|
+
list.textContent = "";
|
|
469
|
+
const members = app.state.memberSessions.get(app.state.room?.id) || [];
|
|
470
|
+
for (const reader of readers) {
|
|
471
|
+
const row = document.createElement("li"), name = document.createElement("span"), evidence = document.createElement("span");
|
|
472
|
+
const duplicates = members.filter((member) => member.name === reader.name).length > 1 || readers.filter((item) => item.name === reader.name).length > 1;
|
|
473
|
+
name.textContent = `${reader.name}${duplicates ? ` · ${reader.sessionID.slice(0, 8)}` : ""}${reader.currentMember === false ? ` · ${app.t("departedMember")}` : ""}`;
|
|
474
|
+
evidence.textContent = app.t(`receiptEvidence_${reader.evidence}`);
|
|
475
|
+
evidence.title = evidence.textContent;
|
|
476
|
+
evidence.setAttribute("aria-label", evidence.textContent);
|
|
477
|
+
row.dataset.readerSessionId = reader.sessionID;
|
|
478
|
+
row.append(name, evidence);
|
|
479
|
+
list.append(row);
|
|
480
|
+
}
|
|
481
|
+
}
|
|
482
|
+
|
|
483
|
+
function systemMessage(text, app) {
|
|
484
|
+
const joined = /^(.*?)\s+joined the room$/.exec(String(text));
|
|
485
|
+
if (joined) return app.t("systemJoined", { name: joined[1] });
|
|
486
|
+
const left = /^(.*?)\s+left the room$/.exec(String(text));
|
|
487
|
+
return left ? app.t("systemLeft", { name: left[1] }) : String(text);
|
|
488
|
+
}
|
|
489
|
+
}
|