@alexsun-top/opencode-chat-room 0.8.2 → 0.8.3
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 +10 -0
- package/README.md +18 -62
- package/README.zh-CN.md +25 -69
- package/dist/cli.js +466 -188
- package/package.json +8 -5
- package/packages/chat-room-channeld/README.md +25 -3
- package/packages/chat-room-channeld/dist/mock-adapter.js +5 -5
- package/packages/chat-room-channeld/src/adapter.ts +5 -0
- package/packages/chat-room-channeld/src/cli.ts +72 -5
- package/packages/chat-room-channeld/src/host.ts +17 -2
- package/packages/chat-room-channeld/src/pg/database.ts +187 -0
- package/packages/chat-room-channeld/src/pg/migrate.ts +150 -0
- package/packages/chat-room-channeld/src/pg/schema.ts +60 -0
- package/packages/chat-room-channeld/src/pg/sql.mjs +175 -0
- package/packages/chat-room-channeld/src/pg/sqlite.ts +100 -0
- package/packages/chat-room-channeld/src/pg/worker.mjs +133 -0
- package/packages/chat-room-channeld/src/protocol.ts +1 -0
- package/packages/chat-room-channeld/src/state.ts +73 -97
- package/packages/chat-room-channeld/src/stats.ts +140 -109
- package/server/assets/base.css +3 -1
- package/server/assets/chat/admin-badge.js +32 -30
- package/server/assets/chat/admin.js +198 -161
- package/server/assets/chat/announcements.js +295 -208
- package/server/assets/chat/attachment-store.js +106 -75
- package/server/assets/chat/attachments.js +686 -441
- package/server/assets/chat/chat-background.js +185 -156
- package/server/assets/chat/clipboard.js +44 -25
- package/server/assets/chat/confirm-dialog.js +36 -33
- package/server/assets/chat/copy-action.js +40 -40
- package/server/assets/chat/create-room-dialog.js +50 -47
- package/server/assets/chat/diagram-viewer.js +293 -234
- package/server/assets/chat/doc-preview.js +507 -441
- package/server/assets/chat/editor.js +423 -335
- package/server/assets/chat/events.js +637 -510
- package/server/assets/chat/files.js +476 -430
- package/server/assets/chat/history-loader.js +79 -73
- package/server/assets/chat/icons.js +9 -11
- package/server/assets/chat/image-zoom.js +239 -176
- package/server/assets/chat/index.js +2 -3
- package/server/assets/chat/install-prompt.js +86 -66
- package/server/assets/chat/integration-account-schema.js +88 -86
- package/server/assets/chat/integration-editor.js +162 -153
- package/server/assets/chat/integration-values.js +109 -100
- package/server/assets/chat/integrations.js +689 -622
- package/server/assets/chat/join-requests.js +408 -358
- package/server/assets/chat/locales/de.js +193 -194
- package/server/assets/chat/locales/es.js +193 -194
- package/server/assets/chat/locales/fr.js +193 -194
- package/server/assets/chat/locales/index.js +1 -2
- package/server/assets/chat/locales/it.js +193 -194
- package/server/assets/chat/locales/ja.js +193 -193
- package/server/assets/chat/locales/ko.js +193 -193
- package/server/assets/chat/markdown-footnotes.js +134 -102
- package/server/assets/chat/markdown.js +547 -403
- package/server/assets/chat/members.js +236 -197
- package/server/assets/chat/mentions.js +157 -133
- package/server/assets/chat/message-cache.js +40 -33
- package/server/assets/chat/message-polling.js +280 -227
- package/server/assets/chat/message-window.js +74 -55
- package/server/assets/chat/messages.js +552 -480
- package/server/assets/chat/office-preview.js +46 -45
- package/server/assets/chat/palette.js +450 -417
- package/server/assets/chat/panels.js +94 -78
- package/server/assets/chat/pwa.js +144 -73
- package/server/assets/chat/questions.js +372 -302
- package/server/assets/chat/recall.js +320 -273
- package/server/assets/chat/receipts.js +149 -121
- package/server/assets/chat/reminders.js +331 -214
- package/server/assets/chat/replies.js +165 -130
- package/server/assets/chat/resource-format.js +59 -62
- package/server/assets/chat/room-list.js +58 -55
- package/server/assets/chat/room-watcher.js +72 -50
- package/server/assets/chat/rooms.js +623 -500
- package/server/assets/chat/search.js +136 -114
- package/server/assets/chat/settings.js +223 -200
- package/server/assets/chat/shiki.js +61 -62
- package/server/assets/chat/shortcuts.js +212 -187
- package/server/assets/chat/side-pane.js +160 -150
- package/server/assets/chat/state.js +849 -735
- package/server/assets/chat/system-events.js +45 -43
- package/server/assets/chat/system-messages.js +57 -56
- package/server/assets/chat/task-form.js +178 -182
- package/server/assets/chat/task-row.js +158 -155
- package/server/assets/chat/tasks.js +653 -587
- package/server/assets/chat/viewport.js +32 -29
- package/server/assets/chat/window-controls.js +32 -32
- package/server/assets/conversation.css +10 -4
- package/server/chat-server.ts +9 -1
- package/server/chat.html +2 -1
- package/server/routes/pages.ts +7 -5
- package/server/sw.js +346 -268
- package/src/web/integration-rules-editor.ts +2 -0
|
@@ -1,463 +1,708 @@
|
|
|
1
1
|
import { LS } from "./state.js";
|
|
2
2
|
import { followsBottom } from "./message-window.js";
|
|
3
3
|
import { persist, forget, recover, forgetTextSource } from "./attachment-store.js";
|
|
4
|
-
|
|
5
4
|
const MAX_PARALLEL_UPLOADS = 2;
|
|
6
5
|
const MAX_BUFFERED_BYTES = 32 * 1024 * 1024; // Pasted files are small; larger ones stream to keep the heap bounded.
|
|
7
6
|
const TEXT_LIMIT = 5000;
|
|
8
7
|
const previewTypes = new Set(["image/png", "image/jpeg", "image/gif", "image/webp", "image/avif", "image/bmp"]);
|
|
9
|
-
|
|
10
8
|
export function initAttachments(app) {
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
// Pasted files are read at paste time so a handle the browser cannot read fails
|
|
30
|
-
// as a read error, not later as a misleading network error. Eager reads only take
|
|
31
|
-
// the free upload slots; the rest read when they start uploading, so at most
|
|
32
|
-
// MAX_PARALLEL_UPLOADS buffers are held.
|
|
33
|
-
function releaseEager(item) {
|
|
34
|
-
if (item.eagerQueued) { item.eagerQueued = false; eagerQueued--; }
|
|
35
|
-
}
|
|
36
|
-
function releaseBuffer(item) {
|
|
37
|
-
item.buffer = null;
|
|
38
|
-
if (item.readPending) item.released = true;
|
|
39
|
-
else { item.read = null; releaseEager(item); }
|
|
40
|
-
}
|
|
41
|
-
function startRead(item, eager = false) {
|
|
42
|
-
if (!item.pasted || item.file.size > MAX_BUFFERED_BYTES) return null;
|
|
43
|
-
if (eager) {
|
|
44
|
-
if (activeUploads + eagerQueued >= MAX_PARALLEL_UPLOADS) return null;
|
|
45
|
-
item.eagerQueued = true; eagerQueued++;
|
|
9
|
+
const $ = app.$, input = $("#msgInput"), list = $("#attachmentList"), tray = $("#attachmentTray"), picker = $("#attachmentPicker");
|
|
10
|
+
const drafts = new Map();
|
|
11
|
+
const statuses = new Map();
|
|
12
|
+
app.state.sendingRooms ||= new Set();
|
|
13
|
+
let limit = null, configRequest = null, activeUploads = 0, eagerQueued = 0;
|
|
14
|
+
const converting = new Set(), restoring = new Set(), uploadWaiters = new Map();
|
|
15
|
+
let editorLock = null, unloadGuard = false;
|
|
16
|
+
const roomId = () => app.state.room?.id || "";
|
|
17
|
+
const filesFor = (id) => drafts.get(id) || [];
|
|
18
|
+
const markers = (items) => items.filter((item) => item.resource).map((item) => `[[resource:${item.resource.id}]]`);
|
|
19
|
+
const validResource = (resource, id) => /^[\da-f]{8}-[\da-f]{4}-[1-8][\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i.test(resource?.id) && resource.roomID === id;
|
|
20
|
+
// crypto.randomUUID needs a secure context; the chat also runs on plain-HTTP LANs.
|
|
21
|
+
function newUploadID() {
|
|
22
|
+
const bytes = crypto.getRandomValues(new Uint8Array(16));
|
|
23
|
+
bytes[6] = (bytes[6] & 0x0f) | 0x40;
|
|
24
|
+
bytes[8] = (bytes[8] & 0x3f) | 0x80;
|
|
25
|
+
const hex = [...bytes].map((byte) => byte.toString(16).padStart(2, "0")).join("");
|
|
26
|
+
return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
|
|
46
27
|
}
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
//
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
return { text: parts.join("\n\n"), ids: filesFor(id).filter((item) => item.resource).map((item) => item.resource.id) };
|
|
57
|
-
};
|
|
58
|
-
function formatSize(size) {
|
|
59
|
-
if (size < 1024) return `${size} B`;
|
|
60
|
-
const units = ["KiB", "MiB", "GiB"];
|
|
61
|
-
let value = size / 1024, index = 0;
|
|
62
|
-
while (value >= 1024 && index < units.length - 1) { value /= 1024; index++; }
|
|
63
|
-
return `${value < 10 ? value.toFixed(1) : Math.round(value)} ${units[index]}`;
|
|
64
|
-
}
|
|
65
|
-
function preserveLayout(change) {
|
|
66
|
-
const thread = $("#thread");
|
|
67
|
-
// A follower can sit a few lines above the edge while a restored draft grows the composer.
|
|
68
|
-
const atBottom = Boolean(roomId() && followsBottom(app, 0));
|
|
69
|
-
if (atBottom) { change(); thread.scrollTop = thread.scrollHeight; }
|
|
70
|
-
else if (roomId() && app.preserveReadingLayout) void app.preserveReadingLayout(change).catch(() => {});
|
|
71
|
-
else change();
|
|
72
|
-
}
|
|
73
|
-
function setStatus(key = "", error = false, id = roomId(), values = {}) {
|
|
74
|
-
if (id) statuses.set(id, { key, error, values });
|
|
75
|
-
if (id === roomId()) preserveLayout(() => {
|
|
76
|
-
const node = $("#attachmentStatus"); node.textContent = key ? app.t(key, values) : ""; node.classList.toggle("danger-text", error); if (key) tray.hidden = false;
|
|
77
|
-
});
|
|
78
|
-
}
|
|
79
|
-
function prepareMessage(id, caption) {
|
|
80
|
-
const items = filesFor(id), composed = textFor(id, caption), body = String(caption || "");
|
|
81
|
-
const overLimit = composed.text.length > TEXT_LIMIT, question = Boolean(app.replyTargetFor?.(id)?.isQuestion);
|
|
82
|
-
// A prior attempt can already carry this text; reusing it avoids a second file.
|
|
83
|
-
const conversion = body.length > TEXT_LIMIT ? items.find((item) => item.textSource === body) : undefined;
|
|
84
|
-
const markerText = textFor(id, "").text, effective = conversion ? markerText : composed.text;
|
|
85
|
-
// Converting moves the draft into a file; the message then carries only resource markers.
|
|
86
|
-
const canConvert = overLimit && body.length > TEXT_LIMIT && markerText.length <= TEXT_LIMIT && !question && items.every((item) => item.status !== "failed");
|
|
87
|
-
return { ...composed, overLimit, conversion, canConvert, ready: Boolean(composed.text) && effective.length <= TEXT_LIMIT && items.every((item) => item.status === "uploaded") };
|
|
88
|
-
}
|
|
89
|
-
const pastedTextName = () => `pasted-text-${new Date().toISOString().slice(0, 19).replace(/\D/g, "")}.txt`;
|
|
90
|
-
// Mentions are stored as editor tokens; the file gets the visible text instead.
|
|
91
|
-
const plainText = (text) => String(text).replace(/<at>@([^<]+)<\/at>/g, "@$1");
|
|
92
|
-
const textFile = (text) => new File([text], pastedTextName(), { type: "text/plain" });
|
|
93
|
-
function persistItem(item, id) {
|
|
94
|
-
if (!item.pasted) return;
|
|
95
|
-
void persist(item, id).then((ok) => { if (!ok) persistenceFailed(id); });
|
|
96
|
-
}
|
|
97
|
-
function persistenceFailed(id) {
|
|
98
|
-
updateDurability();
|
|
99
|
-
setStatus("attachmentNotPersisted", true, id);
|
|
100
|
-
}
|
|
101
|
-
function warnUnload(event) { event.preventDefault(); event.returnValue = ""; }
|
|
102
|
-
function updateDurability() {
|
|
103
|
-
const unsafe = [...drafts.values()].flat().some((item) => item.durable === false);
|
|
104
|
-
if (unsafe && !unloadGuard) { window.onbeforeunload = warnUnload; unloadGuard = true; }
|
|
105
|
-
else if (!unsafe && unloadGuard) { window.onbeforeunload = null; unloadGuard = false; }
|
|
106
|
-
const id = roomId(), hint = $("#attachmentVolatile"), volatile = filesFor(id).some((item) => item.durable === false);
|
|
107
|
-
hint.textContent = app.t(volatile ? "attachmentNotPersisted" : "attachmentVolatile");
|
|
108
|
-
hint.classList.toggle("danger-text", volatile);
|
|
109
|
-
}
|
|
110
|
-
async function restoreRoom(id) {
|
|
111
|
-
if (restoring.has(id)) return;
|
|
112
|
-
restoring.add(id);
|
|
113
|
-
try {
|
|
114
|
-
const restored = await recover(id, app.state.drafts.get(id) || "");
|
|
115
|
-
const existing = filesFor(id), keys = new Set(existing.map((item) => item.uploadID)), items = [...existing];
|
|
116
|
-
for (const record of restored) {
|
|
117
|
-
if (keys.has(record.uploadID)) continue;
|
|
118
|
-
keys.add(record.uploadID);
|
|
119
|
-
items.push({ ...record, pasted: true, status: "queued", buffer: undefined, read: undefined, retried: false, loaded: 0, percent: 0, cancelled: false, durable: true });
|
|
120
|
-
}
|
|
121
|
-
if (items.length === existing.length) return;
|
|
122
|
-
drafts.set(id, items);
|
|
123
|
-
if (roomId() === id) { render(); pump(); }
|
|
124
|
-
} finally {
|
|
125
|
-
restoring.delete(id);
|
|
126
|
-
if (roomId() === id) app.updateSendState();
|
|
28
|
+
// Pasted files are read at paste time so a handle the browser cannot read fails
|
|
29
|
+
// as a read error, not later as a misleading network error. Eager reads only take
|
|
30
|
+
// the free upload slots; the rest read when they start uploading, so at most
|
|
31
|
+
// MAX_PARALLEL_UPLOADS buffers are held.
|
|
32
|
+
function releaseEager(item) {
|
|
33
|
+
if (item.eagerQueued) {
|
|
34
|
+
item.eagerQueued = false;
|
|
35
|
+
eagerQueued--;
|
|
36
|
+
}
|
|
127
37
|
}
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
}
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
const
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
if (roomId() === id) render();
|
|
222
|
-
settleUploads(id);
|
|
223
|
-
}
|
|
224
|
-
function clearRoom(id) {
|
|
225
|
-
for (const item of [...filesFor(id)]) removeItem(id, item, false);
|
|
226
|
-
drafts.delete(id); statuses.delete(id);
|
|
227
|
-
settleUploads(id);
|
|
228
|
-
}
|
|
229
|
-
app.disposeRoomAttachments = clearRoom;
|
|
230
|
-
function getLimit(refresh = false) {
|
|
231
|
-
if (refresh) limit = null;
|
|
232
|
-
if (limit !== null) return Promise.resolve(limit);
|
|
233
|
-
if (!configRequest || refresh) {
|
|
234
|
-
const request = app.api("/resources/config").then((data) => {
|
|
235
|
-
if (!Number.isSafeInteger(data.maxFileSizeBytes) || data.maxFileSizeBytes < 1) throw new Error("Invalid upload limit");
|
|
236
|
-
if (configRequest === request) limit = data.maxFileSizeBytes;
|
|
237
|
-
return data.maxFileSizeBytes;
|
|
238
|
-
}).finally(() => { if (configRequest === request) configRequest = null; });
|
|
239
|
-
configRequest = request;
|
|
38
|
+
function releaseBuffer(item) {
|
|
39
|
+
item.buffer = null;
|
|
40
|
+
if (item.readPending)
|
|
41
|
+
item.released = true;
|
|
42
|
+
else {
|
|
43
|
+
item.read = null;
|
|
44
|
+
releaseEager(item);
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
function startRead(item, eager = false) {
|
|
48
|
+
if (!item.pasted || item.file.size > MAX_BUFFERED_BYTES)
|
|
49
|
+
return null;
|
|
50
|
+
if (eager) {
|
|
51
|
+
if (activeUploads + eagerQueued >= MAX_PARALLEL_UPLOADS)
|
|
52
|
+
return null;
|
|
53
|
+
item.eagerQueued = true;
|
|
54
|
+
eagerQueued++;
|
|
55
|
+
}
|
|
56
|
+
const read = Promise.resolve().then(() => item.file.arrayBuffer());
|
|
57
|
+
item.read = read;
|
|
58
|
+
item.readPending = true;
|
|
59
|
+
item.released = false;
|
|
60
|
+
// Hold the eager slot until the read settles, even if the item is removed meanwhile.
|
|
61
|
+
const settle = () => { item.readPending = false; if (item.released) {
|
|
62
|
+
item.read = null;
|
|
63
|
+
releaseEager(item);
|
|
64
|
+
} };
|
|
65
|
+
void read.then(settle, settle);
|
|
66
|
+
return read;
|
|
67
|
+
}
|
|
68
|
+
const textFor = (id, caption) => {
|
|
69
|
+
const parts = [String(caption || "").trim(), ...markers(filesFor(id))].filter(Boolean);
|
|
70
|
+
return { text: parts.join("\n\n"), ids: filesFor(id).filter((item) => item.resource).map((item) => item.resource.id) };
|
|
71
|
+
};
|
|
72
|
+
function formatSize(size) {
|
|
73
|
+
if (size < 1024)
|
|
74
|
+
return `${size} B`;
|
|
75
|
+
const units = ["KiB", "MiB", "GiB"];
|
|
76
|
+
let value = size / 1024, index = 0;
|
|
77
|
+
while (value >= 1024 && index < units.length - 1) {
|
|
78
|
+
value /= 1024;
|
|
79
|
+
index++;
|
|
80
|
+
}
|
|
81
|
+
return `${value < 10 ? value.toFixed(1) : Math.round(value)} ${units[index]}`;
|
|
82
|
+
}
|
|
83
|
+
function preserveLayout(change) {
|
|
84
|
+
const thread = $("#thread");
|
|
85
|
+
// A follower can sit a few lines above the edge while a restored draft grows the composer.
|
|
86
|
+
const atBottom = Boolean(roomId() && followsBottom(app, 0));
|
|
87
|
+
if (atBottom) {
|
|
88
|
+
change();
|
|
89
|
+
thread.scrollTop = thread.scrollHeight;
|
|
90
|
+
}
|
|
91
|
+
else if (roomId() && app.preserveReadingLayout)
|
|
92
|
+
void app.preserveReadingLayout(change).catch(() => { });
|
|
93
|
+
else
|
|
94
|
+
change();
|
|
95
|
+
}
|
|
96
|
+
function setStatus(key = "", error = false, id = roomId(), values = {}) {
|
|
97
|
+
if (id)
|
|
98
|
+
statuses.set(id, { key, error, values });
|
|
99
|
+
if (id === roomId())
|
|
100
|
+
preserveLayout(() => {
|
|
101
|
+
const node = $("#attachmentStatus");
|
|
102
|
+
node.textContent = key ? app.t(key, values) : "";
|
|
103
|
+
node.classList.toggle("danger-text", error);
|
|
104
|
+
if (key)
|
|
105
|
+
tray.hidden = false;
|
|
106
|
+
});
|
|
107
|
+
}
|
|
108
|
+
function prepareMessage(id, caption) {
|
|
109
|
+
const items = filesFor(id), composed = textFor(id, caption), body = String(caption || "");
|
|
110
|
+
const overLimit = composed.text.length > TEXT_LIMIT, question = Boolean(app.replyTargetFor?.(id)?.isQuestion);
|
|
111
|
+
// A prior attempt can already carry this text; reusing it avoids a second file.
|
|
112
|
+
const conversion = body.length > TEXT_LIMIT ? items.find((item) => item.textSource === body) : undefined;
|
|
113
|
+
const markerText = textFor(id, "").text, effective = conversion ? markerText : composed.text;
|
|
114
|
+
// Converting moves the draft into a file; the message then carries only resource markers.
|
|
115
|
+
const canConvert = overLimit && body.length > TEXT_LIMIT && markerText.length <= TEXT_LIMIT && !question && items.every((item) => item.status !== "failed");
|
|
116
|
+
return { ...composed, overLimit, conversion, canConvert, ready: Boolean(composed.text) && effective.length <= TEXT_LIMIT && items.every((item) => item.status === "uploaded") };
|
|
117
|
+
}
|
|
118
|
+
const pastedTextName = () => `pasted-text-${new Date().toISOString().slice(0, 19).replace(/\D/g, "")}.txt`;
|
|
119
|
+
// Mentions are stored as editor tokens; the file gets the visible text instead.
|
|
120
|
+
const plainText = (text) => String(text).replace(/<at>@([^<]+)<\/at>/g, "@$1");
|
|
121
|
+
const textFile = (text) => new File([text], pastedTextName(), { type: "text/plain" });
|
|
122
|
+
function persistItem(item, id) {
|
|
123
|
+
if (!item.pasted)
|
|
124
|
+
return;
|
|
125
|
+
void persist(item, id).then((ok) => { if (!ok)
|
|
126
|
+
persistenceFailed(id); });
|
|
127
|
+
}
|
|
128
|
+
function persistenceFailed(id) {
|
|
129
|
+
updateDurability();
|
|
130
|
+
setStatus("attachmentNotPersisted", true, id);
|
|
240
131
|
}
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
132
|
+
function warnUnload(event) { event.preventDefault(); event.returnValue = ""; }
|
|
133
|
+
function updateDurability() {
|
|
134
|
+
const unsafe = [...drafts.values()].flat().some((item) => item.durable === false);
|
|
135
|
+
if (unsafe && !unloadGuard) {
|
|
136
|
+
window.onbeforeunload = warnUnload;
|
|
137
|
+
unloadGuard = true;
|
|
138
|
+
}
|
|
139
|
+
else if (!unsafe && unloadGuard) {
|
|
140
|
+
window.onbeforeunload = null;
|
|
141
|
+
unloadGuard = false;
|
|
142
|
+
}
|
|
143
|
+
const id = roomId(), hint = $("#attachmentVolatile"), volatile = filesFor(id).some((item) => item.durable === false);
|
|
144
|
+
hint.textContent = app.t(volatile ? "attachmentNotPersisted" : "attachmentVolatile");
|
|
145
|
+
hint.classList.toggle("danger-text", volatile);
|
|
250
146
|
}
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
try { max = await getLimit(item.refreshLimit); } catch {}
|
|
256
|
-
item.refreshLimit = false;
|
|
257
|
-
if (item.cancelled) return;
|
|
258
|
-
if (max !== null && item.file.size > max) { releaseBuffer(item); item.errorKey = "fileTooLarge"; item.status = "failed"; if (roomId() === id) setStatus(item.errorKey, true, id); return; }
|
|
259
|
-
if (item.pasted && item.file.size <= MAX_BUFFERED_BYTES) {
|
|
147
|
+
async function restoreRoom(id) {
|
|
148
|
+
if (restoring.has(id))
|
|
149
|
+
return;
|
|
150
|
+
restoring.add(id);
|
|
260
151
|
try {
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
152
|
+
const restored = await recover(id, app.state.drafts.get(id) || "");
|
|
153
|
+
const existing = filesFor(id), keys = new Set(existing.map((item) => item.uploadID)), items = [...existing];
|
|
154
|
+
for (const record of restored) {
|
|
155
|
+
if (keys.has(record.uploadID))
|
|
156
|
+
continue;
|
|
157
|
+
keys.add(record.uploadID);
|
|
158
|
+
items.push({ ...record, pasted: true, status: "queued", buffer: undefined, read: undefined, retried: false, loaded: 0, percent: 0, cancelled: false, durable: true });
|
|
159
|
+
}
|
|
160
|
+
if (items.length === existing.length)
|
|
161
|
+
return;
|
|
162
|
+
drafts.set(id, items);
|
|
163
|
+
if (roomId() === id) {
|
|
164
|
+
render();
|
|
165
|
+
pump();
|
|
166
|
+
}
|
|
270
167
|
}
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
}
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
} finally {
|
|
285
|
-
activeUploads--;
|
|
286
|
-
if (roomId() === id) render();
|
|
287
|
-
pump();
|
|
288
|
-
settleUploads(id);
|
|
168
|
+
finally {
|
|
169
|
+
restoring.delete(id);
|
|
170
|
+
if (roomId() === id)
|
|
171
|
+
app.updateSendState();
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
function lockComposer() {
|
|
175
|
+
if (editorLock)
|
|
176
|
+
return;
|
|
177
|
+
editorLock = { editable: input.contentEditable, disabled: input.getAttribute("aria-disabled"), busy: input.getAttribute("aria-busy"), selection: input.getSelectionOffsets?.() || null };
|
|
178
|
+
input.contentEditable = "false";
|
|
179
|
+
input.setAttribute("aria-disabled", "true");
|
|
180
|
+
input.setAttribute("aria-busy", "true");
|
|
289
181
|
}
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
catch { if (item.cancelled) throw error; throw Object.assign(new Error("Upload unreadable"), { unreadable: true }); }
|
|
304
|
-
}
|
|
305
|
-
if (item.cancelled || !item.buffer) throw error;
|
|
306
|
-
return upload(id, item);
|
|
182
|
+
function unlockComposer() {
|
|
183
|
+
if (!editorLock)
|
|
184
|
+
return;
|
|
185
|
+
input.contentEditable = "true";
|
|
186
|
+
input.setAttribute("aria-disabled", editorLock.disabled ?? "false");
|
|
187
|
+
if (editorLock.busy === null)
|
|
188
|
+
input.removeAttribute("aria-busy");
|
|
189
|
+
else
|
|
190
|
+
input.setAttribute("aria-busy", editorLock.busy);
|
|
191
|
+
const selection = editorLock.selection;
|
|
192
|
+
editorLock = null;
|
|
193
|
+
if (selection)
|
|
194
|
+
input.setSelectionRange?.(selection[0], selection[1]);
|
|
307
195
|
}
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
return validResource(resource, id) && resource.name === item.file.name && resource.uploaderSessionID === LS.sessionID ? resource : undefined;
|
|
315
|
-
} catch { return undefined; }
|
|
316
|
-
}
|
|
317
|
-
function upload(id, item) {
|
|
318
|
-
return new Promise((resolve, reject) => {
|
|
319
|
-
const xhr = new XMLHttpRequest(); item.xhr = xhr;
|
|
320
|
-
xhr.open("POST", `/rooms/${encodeURIComponent(id)}/resources`);
|
|
321
|
-
xhr.setRequestHeader("Content-Type", "application/octet-stream");
|
|
322
|
-
xhr.setRequestHeader("X-Session-ID", LS.sessionID);
|
|
323
|
-
xhr.setRequestHeader("X-File-Name", encodeURIComponent(item.file.name));
|
|
324
|
-
xhr.setRequestHeader("X-Resource-ID", item.uploadID);
|
|
325
|
-
if (LS.token) xhr.setRequestHeader("Authorization", `Bearer ${LS.token}`);
|
|
326
|
-
xhr.timeout = 1800000;
|
|
327
|
-
xhr.upload.onprogress = (event) => {
|
|
328
|
-
item.loaded = event.loaded; item.percent = Math.min(100, event.lengthComputable ? Math.floor(event.loaded / event.total * 100) : item.file.size ? Math.floor(event.loaded / item.file.size * 100) : 100);
|
|
329
|
-
if (roomId() === id) {
|
|
330
|
-
if (item.progressNode) { item.progressNode.value = item.loaded; item.progressNode.max = item.file.size || 1; item.progressNode.setAttribute("aria-valuetext", app.t("uploadPercent", { percent: item.percent })); }
|
|
331
|
-
if (item.detailNode) item.detailNode.textContent = `${formatSize(item.file.size)} · ${app.t("uploadPercent", { percent: item.percent })}`;
|
|
196
|
+
app.prepareMessage = prepareMessage;
|
|
197
|
+
const baseDraftCount = app.updateDraftCount;
|
|
198
|
+
app.updateDraftCount = () => {
|
|
199
|
+
if (!roomId()) {
|
|
200
|
+
$("#draftCount").classList.remove("over-limit");
|
|
201
|
+
return baseDraftCount();
|
|
332
202
|
}
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
203
|
+
const count = textFor(roomId(), input.value).text.length;
|
|
204
|
+
app.setText($("#draftCount"), "messageCount", { count });
|
|
205
|
+
$("#draftCount").classList.toggle("over-limit", count > TEXT_LIMIT);
|
|
206
|
+
};
|
|
207
|
+
app.updateSendState = () => {
|
|
208
|
+
const id = roomId(), message = id && prepareMessage(id, input.value);
|
|
209
|
+
$("#btnSend").disabled = !id || !(message?.ready || message?.canConvert) || app.state.sendingRooms.has(id) || converting.has(id) || restoring.has(id);
|
|
210
|
+
};
|
|
211
|
+
app.completeAttachments = (id, resourceIDs) => {
|
|
212
|
+
const used = new Set(resourceIDs), items = filesFor(id), removed = items.filter((item) => used.has(item.resource?.id));
|
|
213
|
+
for (const item of removed) {
|
|
214
|
+
forget(item);
|
|
215
|
+
if (item.previewUrl)
|
|
216
|
+
URL.revokeObjectURL(item.previewUrl);
|
|
217
|
+
}
|
|
218
|
+
const remaining = items.filter((item) => !used.has(item.resource?.id));
|
|
219
|
+
if (remaining.length)
|
|
220
|
+
drafts.set(id, remaining);
|
|
221
|
+
else {
|
|
222
|
+
drafts.delete(id);
|
|
223
|
+
statuses.delete(id);
|
|
224
|
+
}
|
|
225
|
+
if (roomId() === id)
|
|
226
|
+
render();
|
|
227
|
+
};
|
|
228
|
+
app.completeAttachmentsFromText = (id, text) => app.completeAttachments(id, [...String(text).matchAll(/\[\[resource:([\da-f-]{36})\]\]/gi)].map((match) => match[1]));
|
|
229
|
+
const applyLocale = app.applyLocale;
|
|
230
|
+
app.applyLocale = () => { applyLocale(); updateLocale(); };
|
|
231
|
+
function updateLocale() {
|
|
232
|
+
const id = roomId(), items = filesFor(id);
|
|
233
|
+
items.forEach((item, index) => {
|
|
234
|
+
const row = list.children[index];
|
|
235
|
+
if (!row)
|
|
236
|
+
return;
|
|
237
|
+
const detail = row.querySelector(".attachment-detail"), progress = row.querySelector("progress");
|
|
238
|
+
detail.textContent = `${formatSize(item.file.size)} · ${item.status === "failed" ? app.t(item.errorKey, item.errorValues || {}) : item.status === "uploaded" ? app.t("uploadReady") : item.status === "uploading" ? app.t("uploadPercent", { percent: item.percent || 0 }) : app.t("uploadQueued")}`;
|
|
239
|
+
const retry = row.querySelector('[data-upload-action="retry"]');
|
|
240
|
+
if (retry) {
|
|
241
|
+
retry.textContent = app.t("retryUpload");
|
|
242
|
+
retry.setAttribute("aria-label", retry.textContent);
|
|
243
|
+
}
|
|
244
|
+
const remove = row.querySelector('[data-upload-action="remove"]');
|
|
245
|
+
if (remove) {
|
|
246
|
+
remove.textContent = app.t("removeFile");
|
|
247
|
+
remove.setAttribute("aria-label", remove.textContent);
|
|
248
|
+
}
|
|
249
|
+
progress.setAttribute("aria-label", app.t("uploadPercent", { percent: item.percent || 0 }));
|
|
250
|
+
progress.setAttribute("aria-valuetext", app.t("uploadPercent", { percent: item.percent || 0 }));
|
|
251
|
+
});
|
|
252
|
+
const status = statuses.get(id);
|
|
253
|
+
$("#attachmentStatus").textContent = status?.key ? app.t(status.key, status.values) : "";
|
|
254
|
+
if (status?.key)
|
|
255
|
+
tray.hidden = false;
|
|
256
|
+
updateDurability();
|
|
257
|
+
}
|
|
258
|
+
function render() {
|
|
259
|
+
preserveLayout(() => {
|
|
260
|
+
const id = roomId(), items = filesFor(id), savedStatus = statuses.get(id);
|
|
261
|
+
tray.hidden = !items.length && !savedStatus?.key;
|
|
262
|
+
$("#attachmentVolatile").hidden = !items.length;
|
|
263
|
+
$("#attachmentStatus").textContent = savedStatus?.key ? app.t(savedStatus.key, savedStatus.values) : "";
|
|
264
|
+
$("#attachmentStatus").classList.toggle("danger-text", Boolean(savedStatus?.error));
|
|
265
|
+
list.replaceChildren();
|
|
266
|
+
items.forEach((item, index) => { const row = renderItem(item); row.dataset.index = String(index); list.append(row); });
|
|
267
|
+
updateDurability();
|
|
268
|
+
app.updateDraftCount();
|
|
269
|
+
app.updateSendState();
|
|
270
|
+
});
|
|
271
|
+
}
|
|
272
|
+
app.renderAttachments = render;
|
|
273
|
+
function renderItem(item) {
|
|
274
|
+
const row = document.createElement("li"), preview = document.createElement("span"), info = document.createElement("div"), name = document.createElement("p"), detail = document.createElement("p"), progress = document.createElement("progress"), actions = document.createElement("div");
|
|
275
|
+
row.className = "attachment-item";
|
|
276
|
+
preview.className = "attachment-preview";
|
|
277
|
+
if (previewTypes.has(item.file.type) && item.errorKey !== "fileUnreadable") {
|
|
278
|
+
item.previewUrl ||= URL.createObjectURL(item.file);
|
|
279
|
+
const image = document.createElement("img");
|
|
280
|
+
image.src = item.previewUrl;
|
|
281
|
+
image.alt = "";
|
|
282
|
+
preview.append(image);
|
|
283
|
+
}
|
|
284
|
+
else
|
|
285
|
+
preview.textContent = item.file.name.split(".").at(-1)?.slice(0, 4).toUpperCase() || "FILE";
|
|
286
|
+
info.className = "attachment-file";
|
|
287
|
+
name.className = "attachment-name";
|
|
288
|
+
name.textContent = item.file.name;
|
|
289
|
+
detail.className = `attachment-detail${item.status === "failed" ? " attachment-over-limit" : ""}`;
|
|
290
|
+
detail.textContent = `${formatSize(item.file.size)} · ${item.status === "failed" ? app.t(item.errorKey, item.errorValues || {}) : item.status === "uploaded" ? app.t("uploadReady") : item.status === "uploading" ? app.t("uploadPercent", { percent: item.percent || 0 }) : app.t("uploadQueued")}`;
|
|
291
|
+
progress.max = item.file.size || 1;
|
|
292
|
+
progress.value = item.loaded || 0;
|
|
293
|
+
progress.hidden = item.status !== "uploading";
|
|
294
|
+
progress.setAttribute("aria-label", app.t("uploadPercent", { percent: item.percent || 0 }));
|
|
295
|
+
item.progressNode = progress;
|
|
296
|
+
item.detailNode = detail;
|
|
297
|
+
info.append(name, detail, progress);
|
|
298
|
+
actions.className = "attachment-actions";
|
|
299
|
+
if (item.status === "failed")
|
|
300
|
+
actions.append(action("retry", app.t("retryUpload")));
|
|
301
|
+
actions.append(action("remove", app.t("removeFile")));
|
|
302
|
+
row.append(preview, info, actions);
|
|
303
|
+
return row;
|
|
304
|
+
}
|
|
305
|
+
function action(kind, label) {
|
|
306
|
+
const button = document.createElement("button");
|
|
307
|
+
button.type = "button";
|
|
308
|
+
button.dataset.uploadAction = kind;
|
|
309
|
+
button.textContent = label;
|
|
310
|
+
button.setAttribute("aria-label", label);
|
|
311
|
+
return button;
|
|
312
|
+
}
|
|
313
|
+
function removeItem(id, item, purge = true) {
|
|
314
|
+
item.cancelled = true;
|
|
315
|
+
item.xhr?.abort();
|
|
316
|
+
releaseBuffer(item);
|
|
317
|
+
if (purge)
|
|
318
|
+
forget(item);
|
|
319
|
+
if (item.previewUrl)
|
|
320
|
+
URL.revokeObjectURL(item.previewUrl);
|
|
321
|
+
const remaining = filesFor(id).filter((entry) => entry !== item);
|
|
322
|
+
if (remaining.length) {
|
|
323
|
+
drafts.set(id, remaining);
|
|
324
|
+
if (statuses.get(id)?.error && !remaining.some((entry) => entry.status === "failed"))
|
|
325
|
+
statuses.delete(id);
|
|
326
|
+
}
|
|
327
|
+
else {
|
|
328
|
+
drafts.delete(id);
|
|
329
|
+
statuses.delete(id);
|
|
330
|
+
}
|
|
331
|
+
if (roomId() === id)
|
|
332
|
+
render();
|
|
333
|
+
settleUploads(id);
|
|
334
|
+
}
|
|
335
|
+
function clearRoom(id) {
|
|
336
|
+
for (const item of [...filesFor(id)])
|
|
337
|
+
removeItem(id, item, false);
|
|
338
|
+
drafts.delete(id);
|
|
339
|
+
statuses.delete(id);
|
|
340
|
+
settleUploads(id);
|
|
341
|
+
}
|
|
342
|
+
app.disposeRoomAttachments = clearRoom;
|
|
343
|
+
function getLimit(refresh = false) {
|
|
344
|
+
if (refresh)
|
|
345
|
+
limit = null;
|
|
346
|
+
if (limit !== null)
|
|
347
|
+
return Promise.resolve(limit);
|
|
348
|
+
if (!configRequest || refresh) {
|
|
349
|
+
const request = app.api("/resources/config").then((data) => {
|
|
350
|
+
if (!Number.isSafeInteger(data.maxFileSizeBytes) || data.maxFileSizeBytes < 1)
|
|
351
|
+
throw new Error("Invalid upload limit");
|
|
352
|
+
if (configRequest === request)
|
|
353
|
+
limit = data.maxFileSizeBytes;
|
|
354
|
+
return data.maxFileSizeBytes;
|
|
355
|
+
}).finally(() => { if (configRequest === request)
|
|
356
|
+
configRequest = null; });
|
|
357
|
+
configRequest = request;
|
|
358
|
+
}
|
|
359
|
+
return configRequest;
|
|
360
|
+
}
|
|
361
|
+
function pump() {
|
|
362
|
+
while (activeUploads < MAX_PARALLEL_UPLOADS) {
|
|
363
|
+
const next = [...drafts].flatMap(([id, items]) => items.map((item) => ({ id, item }))).find(({ item }) => item.status === "queued");
|
|
364
|
+
if (!next)
|
|
365
|
+
return;
|
|
366
|
+
activeUploads++;
|
|
367
|
+
releaseEager(next.item);
|
|
368
|
+
next.item.status = "uploading";
|
|
369
|
+
next.item.percent = 0;
|
|
370
|
+
if (roomId() === next.id)
|
|
371
|
+
render();
|
|
372
|
+
void uploadItem(next.id, next.item);
|
|
373
|
+
}
|
|
374
|
+
}
|
|
375
|
+
async function uploadItem(id, item) {
|
|
337
376
|
try {
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
377
|
+
let max = null;
|
|
378
|
+
try {
|
|
379
|
+
max = await getLimit(item.refreshLimit);
|
|
380
|
+
}
|
|
381
|
+
catch { }
|
|
382
|
+
item.refreshLimit = false;
|
|
383
|
+
if (item.cancelled)
|
|
384
|
+
return;
|
|
385
|
+
if (max !== null && item.file.size > max) {
|
|
386
|
+
releaseBuffer(item);
|
|
387
|
+
item.errorKey = "fileTooLarge";
|
|
388
|
+
item.status = "failed";
|
|
389
|
+
if (roomId() === id)
|
|
390
|
+
setStatus(item.errorKey, true, id);
|
|
391
|
+
return;
|
|
392
|
+
}
|
|
393
|
+
if (item.pasted && item.file.size <= MAX_BUFFERED_BYTES) {
|
|
394
|
+
try {
|
|
395
|
+
const buffer = await (item.read ?? startRead(item));
|
|
396
|
+
if (item.cancelled)
|
|
397
|
+
return;
|
|
398
|
+
item.buffer = buffer;
|
|
399
|
+
}
|
|
400
|
+
catch {
|
|
401
|
+
releaseBuffer(item);
|
|
402
|
+
if (item.cancelled)
|
|
403
|
+
return;
|
|
404
|
+
item.errorKey = "fileUnreadable";
|
|
405
|
+
item.errorValues = null;
|
|
406
|
+
item.status = "failed";
|
|
407
|
+
if (roomId() === id)
|
|
408
|
+
setStatus("fileUnreadable", true, id);
|
|
409
|
+
return;
|
|
410
|
+
}
|
|
411
|
+
}
|
|
412
|
+
item.resource = await sendUpload(id, item);
|
|
413
|
+
if (item.cancelled)
|
|
414
|
+
return;
|
|
415
|
+
item.status = "uploaded";
|
|
416
|
+
item.loaded = item.file.size;
|
|
417
|
+
item.percent = 100;
|
|
418
|
+
releaseBuffer(item);
|
|
419
|
+
if (roomId() === id && filesFor(id).every((entry) => entry.status === "uploaded"))
|
|
420
|
+
setStatus(filesFor(id).some((entry) => entry.durable === false) ? "attachmentNotPersisted" : "uploadReady");
|
|
421
|
+
}
|
|
422
|
+
catch (error) {
|
|
423
|
+
releaseBuffer(item);
|
|
424
|
+
if (item.cancelled)
|
|
425
|
+
return;
|
|
426
|
+
if (error.status === 413) {
|
|
427
|
+
limit = null;
|
|
428
|
+
item.errorKey = "fileTooLarge";
|
|
429
|
+
}
|
|
430
|
+
else if (error.unreadable)
|
|
431
|
+
item.errorKey = "fileUnreadable";
|
|
432
|
+
else {
|
|
433
|
+
item.errorKey = "uploadFailed";
|
|
434
|
+
item.errorValues = { reason: error.status ? `HTTP ${error.status}` : error.timeout ? "timeout" : error.network ? "network" : error.message };
|
|
435
|
+
}
|
|
436
|
+
item.status = "failed";
|
|
437
|
+
if (roomId() === id)
|
|
438
|
+
setStatus(item.errorKey, true, id, item.errorValues || {});
|
|
439
|
+
}
|
|
440
|
+
finally {
|
|
441
|
+
activeUploads--;
|
|
442
|
+
if (roomId() === id)
|
|
443
|
+
render();
|
|
444
|
+
pump();
|
|
445
|
+
settleUploads(id);
|
|
400
446
|
}
|
|
401
|
-
return false;
|
|
402
|
-
}
|
|
403
|
-
if (roomId() !== id) return false;
|
|
404
|
-
const changed = (app.state.draftRevision.get(id) || 0) !== revision || app.replyTargetFor?.(id)?.id !== replyId;
|
|
405
|
-
if (changed) { setStatus("uploadReady"); return false; }
|
|
406
|
-
// The composer stayed locked, so clearing it now cannot drop text typed during the upload.
|
|
407
|
-
unlockComposer();
|
|
408
|
-
input.value = "";
|
|
409
|
-
app.clearDraft(id);
|
|
410
|
-
const sent = await baseSend();
|
|
411
|
-
if (sent) forgetTextSource(id, requested);
|
|
412
|
-
return sent;
|
|
413
|
-
} finally {
|
|
414
|
-
converting.delete(id);
|
|
415
|
-
if (roomId() === id) { unlockComposer(); app.updateDraftCount(); app.updateSendState(); }
|
|
416
|
-
else editorLock = null;
|
|
417
447
|
}
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
addFiles([textFile(text), ...files], true, { textSource: text, textContent: text });
|
|
450
|
-
setStatus("pasteAsFile", false, roomId(), { count: text.length });
|
|
451
|
-
return;
|
|
448
|
+
// One fallback after a network failure: a lost response is recovered by ID, and a
|
|
449
|
+
// file the XHR could not send is retried once from bytes read into memory.
|
|
450
|
+
async function sendUpload(id, item) {
|
|
451
|
+
try {
|
|
452
|
+
return await upload(id, item);
|
|
453
|
+
}
|
|
454
|
+
catch (error) {
|
|
455
|
+
if (!error.network || item.cancelled || item.retried)
|
|
456
|
+
throw error;
|
|
457
|
+
item.retried = true;
|
|
458
|
+
item.loaded = 0;
|
|
459
|
+
item.percent = 0;
|
|
460
|
+
const existing = await findUploaded(id, item);
|
|
461
|
+
if (item.cancelled)
|
|
462
|
+
throw error;
|
|
463
|
+
if (existing)
|
|
464
|
+
return existing;
|
|
465
|
+
if (item.buffer === undefined && item.file.size <= MAX_BUFFERED_BYTES) {
|
|
466
|
+
try {
|
|
467
|
+
item.buffer = await item.file.arrayBuffer();
|
|
468
|
+
}
|
|
469
|
+
catch {
|
|
470
|
+
if (item.cancelled)
|
|
471
|
+
throw error;
|
|
472
|
+
throw Object.assign(new Error("Upload unreadable"), { unreadable: true });
|
|
473
|
+
}
|
|
474
|
+
}
|
|
475
|
+
if (item.cancelled || !item.buffer)
|
|
476
|
+
throw error;
|
|
477
|
+
return upload(id, item);
|
|
478
|
+
}
|
|
452
479
|
}
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
480
|
+
async function findUploaded(id, item) {
|
|
481
|
+
try {
|
|
482
|
+
const response = await fetch(`/rooms/${encodeURIComponent(id)}/resources/${item.uploadID}`, { headers: LS.token ? { Authorization: `Bearer ${LS.token}` } : {} });
|
|
483
|
+
if (!response.ok)
|
|
484
|
+
return undefined;
|
|
485
|
+
const resource = (await response.json()).resource;
|
|
486
|
+
return validResource(resource, id) && resource.name === item.file.name && resource.uploaderSessionID === LS.sessionID ? resource : undefined;
|
|
487
|
+
}
|
|
488
|
+
catch {
|
|
489
|
+
return undefined;
|
|
490
|
+
}
|
|
491
|
+
}
|
|
492
|
+
function upload(id, item) {
|
|
493
|
+
return new Promise((resolve, reject) => {
|
|
494
|
+
const xhr = new XMLHttpRequest();
|
|
495
|
+
item.xhr = xhr;
|
|
496
|
+
xhr.open("POST", `/rooms/${encodeURIComponent(id)}/resources`);
|
|
497
|
+
xhr.setRequestHeader("Content-Type", "application/octet-stream");
|
|
498
|
+
xhr.setRequestHeader("X-Session-ID", LS.sessionID);
|
|
499
|
+
xhr.setRequestHeader("X-File-Name", encodeURIComponent(item.file.name));
|
|
500
|
+
xhr.setRequestHeader("X-Resource-ID", item.uploadID);
|
|
501
|
+
if (LS.token)
|
|
502
|
+
xhr.setRequestHeader("Authorization", `Bearer ${LS.token}`);
|
|
503
|
+
xhr.timeout = 1800000;
|
|
504
|
+
xhr.upload.onprogress = (event) => {
|
|
505
|
+
item.loaded = event.loaded;
|
|
506
|
+
item.percent = Math.min(100, event.lengthComputable ? Math.floor(event.loaded / event.total * 100) : item.file.size ? Math.floor(event.loaded / item.file.size * 100) : 100);
|
|
507
|
+
if (roomId() === id) {
|
|
508
|
+
if (item.progressNode) {
|
|
509
|
+
item.progressNode.value = item.loaded;
|
|
510
|
+
item.progressNode.max = item.file.size || 1;
|
|
511
|
+
item.progressNode.setAttribute("aria-valuetext", app.t("uploadPercent", { percent: item.percent }));
|
|
512
|
+
}
|
|
513
|
+
if (item.detailNode)
|
|
514
|
+
item.detailNode.textContent = `${formatSize(item.file.size)} · ${app.t("uploadPercent", { percent: item.percent })}`;
|
|
515
|
+
}
|
|
516
|
+
};
|
|
517
|
+
xhr.onload = () => {
|
|
518
|
+
item.xhr = null;
|
|
519
|
+
if (xhr.status !== 201)
|
|
520
|
+
return reject(Object.assign(new Error("Upload failed"), { status: xhr.status }));
|
|
521
|
+
try {
|
|
522
|
+
const resource = JSON.parse(xhr.responseText).resource;
|
|
523
|
+
if (!validResource(resource, id))
|
|
524
|
+
throw new Error("Invalid resource response");
|
|
525
|
+
resolve(resource);
|
|
526
|
+
}
|
|
527
|
+
catch {
|
|
528
|
+
reject(new Error("Invalid resource response"));
|
|
529
|
+
}
|
|
530
|
+
};
|
|
531
|
+
// A browser can surface a file handle it cannot read (cloud placeholder, network
|
|
532
|
+
// drive, cleaned temp file) as a bare network error; XHR exposes no finer cause.
|
|
533
|
+
xhr.onerror = () => { item.xhr = null; reject(Object.assign(new Error("Upload failed"), { network: true })); };
|
|
534
|
+
xhr.ontimeout = () => { item.xhr = null; reject(Object.assign(new Error("Upload timed out"), { timeout: true })); };
|
|
535
|
+
xhr.onabort = () => { item.xhr = null; reject(Object.assign(new Error("Upload cancelled"), { aborted: true })); };
|
|
536
|
+
xhr.send(item.buffer ?? item.file);
|
|
537
|
+
});
|
|
538
|
+
}
|
|
539
|
+
function addFiles(files, pasted = false, meta = {}) {
|
|
540
|
+
const id = roomId();
|
|
541
|
+
if (!id)
|
|
542
|
+
return;
|
|
543
|
+
const accepted = [...files].filter((file) => file instanceof File);
|
|
544
|
+
if (!accepted.length)
|
|
545
|
+
return;
|
|
546
|
+
const items = filesFor(id);
|
|
547
|
+
accepted.forEach((file, index) => {
|
|
548
|
+
const item = { file, uploadID: newUploadID(), pasted, buffer: undefined, read: undefined, retried: false, status: "queued", loaded: 0, percent: 0, cancelled: false, ...(index ? {} : meta) };
|
|
549
|
+
items.push(item);
|
|
550
|
+
if (pasted) {
|
|
551
|
+
startRead(item, true);
|
|
552
|
+
persistItem(item, id);
|
|
553
|
+
}
|
|
554
|
+
});
|
|
555
|
+
drafts.set(id, items);
|
|
556
|
+
setStatus("");
|
|
557
|
+
render();
|
|
558
|
+
pump();
|
|
559
|
+
}
|
|
560
|
+
function settleUploads(id) {
|
|
561
|
+
const waiters = uploadWaiters.get(id);
|
|
562
|
+
if (!waiters)
|
|
563
|
+
return;
|
|
564
|
+
const items = filesFor(id);
|
|
565
|
+
if (items.some((item) => item.status === "queued" || item.status === "uploading"))
|
|
566
|
+
return;
|
|
567
|
+
uploadWaiters.delete(id);
|
|
568
|
+
const uploaded = items.length > 0 && items.every((item) => item.status === "uploaded");
|
|
569
|
+
for (const resolve of waiters)
|
|
570
|
+
resolve(uploaded);
|
|
571
|
+
}
|
|
572
|
+
function waitForUploads(id) {
|
|
573
|
+
return new Promise((resolve) => {
|
|
574
|
+
uploadWaiters.set(id, [...(uploadWaiters.get(id) || []), resolve]);
|
|
575
|
+
settleUploads(id);
|
|
576
|
+
});
|
|
577
|
+
}
|
|
578
|
+
const baseSend = app.send;
|
|
579
|
+
app.send = async () => {
|
|
580
|
+
const id = roomId();
|
|
581
|
+
if (!id || converting.has(id) || restoring.has(id) || app.state.sendingRooms.has(id))
|
|
582
|
+
return false;
|
|
583
|
+
const message = prepareMessage(id, input.value);
|
|
584
|
+
if (!message.canConvert)
|
|
585
|
+
return baseSend();
|
|
586
|
+
const requested = input.value, revision = app.state.draftRevision.get(id) || 0, replyId = app.replyTargetFor?.(id)?.id;
|
|
587
|
+
converting.add(id);
|
|
588
|
+
lockComposer();
|
|
589
|
+
app.saveDraft(id, input.draftValue);
|
|
590
|
+
let item = message.conversion;
|
|
591
|
+
try {
|
|
592
|
+
if (!item) {
|
|
593
|
+
const content = plainText(requested), attachment = textFile(content);
|
|
594
|
+
addFiles([attachment], true, { textSource: requested, textContent: content });
|
|
595
|
+
item = filesFor(id).find((entry) => entry.file === attachment);
|
|
596
|
+
}
|
|
597
|
+
setStatus("sendAsFile", false, id, { count: requested.length });
|
|
598
|
+
if (!(await waitForUploads(id))) {
|
|
599
|
+
if (roomId() === id) {
|
|
600
|
+
if (item?.status === "failed")
|
|
601
|
+
setStatus("sendAsFileFailed", true, id);
|
|
602
|
+
else if (!item)
|
|
603
|
+
setStatus("");
|
|
604
|
+
}
|
|
605
|
+
return false;
|
|
606
|
+
}
|
|
607
|
+
if (roomId() !== id)
|
|
608
|
+
return false;
|
|
609
|
+
const changed = (app.state.draftRevision.get(id) || 0) !== revision || app.replyTargetFor?.(id)?.id !== replyId;
|
|
610
|
+
if (changed) {
|
|
611
|
+
setStatus("uploadReady");
|
|
612
|
+
return false;
|
|
613
|
+
}
|
|
614
|
+
// The composer stayed locked, so clearing it now cannot drop text typed during the upload.
|
|
615
|
+
unlockComposer();
|
|
616
|
+
input.value = "";
|
|
617
|
+
app.clearDraft(id);
|
|
618
|
+
const sent = await baseSend();
|
|
619
|
+
if (sent)
|
|
620
|
+
forgetTextSource(id, requested);
|
|
621
|
+
return sent;
|
|
622
|
+
}
|
|
623
|
+
finally {
|
|
624
|
+
converting.delete(id);
|
|
625
|
+
if (roomId() === id) {
|
|
626
|
+
unlockComposer();
|
|
627
|
+
app.updateDraftCount();
|
|
628
|
+
app.updateSendState();
|
|
629
|
+
}
|
|
630
|
+
else
|
|
631
|
+
editorLock = null;
|
|
632
|
+
}
|
|
633
|
+
};
|
|
634
|
+
function retryItem(item) {
|
|
635
|
+
if (item.status !== "failed")
|
|
636
|
+
return;
|
|
637
|
+
if (item.errorKey === "fileUnreadable")
|
|
638
|
+
item.read = null;
|
|
639
|
+
item.refreshLimit = item.errorKey === "fileTooLarge";
|
|
640
|
+
item.status = "queued";
|
|
641
|
+
item.errorKey = "";
|
|
642
|
+
item.errorValues = null;
|
|
643
|
+
item.loaded = 0;
|
|
644
|
+
item.percent = 0;
|
|
645
|
+
item.retried = false;
|
|
646
|
+
if (item.pasted && !item.readPending)
|
|
647
|
+
startRead(item, true);
|
|
648
|
+
if (roomId())
|
|
649
|
+
setStatus("");
|
|
650
|
+
render();
|
|
651
|
+
pump();
|
|
652
|
+
}
|
|
653
|
+
$("#btnAddAttachments").addEventListener("click", () => picker.click());
|
|
654
|
+
picker.addEventListener("change", () => { addFiles(picker.files || []); picker.value = ""; });
|
|
655
|
+
list.addEventListener("click", (event) => {
|
|
656
|
+
const button = event.target.closest?.("[data-upload-action]");
|
|
657
|
+
if (!button)
|
|
658
|
+
return;
|
|
659
|
+
const id = roomId(), index = Number(button.closest(".attachment-item")?.dataset.index), item = filesFor(id)[index];
|
|
660
|
+
if (!item)
|
|
661
|
+
return;
|
|
662
|
+
if (button.dataset.uploadAction === "retry") {
|
|
663
|
+
retryItem(item);
|
|
664
|
+
$("#btnAddAttachments").focus();
|
|
665
|
+
}
|
|
666
|
+
else {
|
|
667
|
+
removeItem(id, item);
|
|
668
|
+
(list.querySelector(`[data-index="${Math.min(index, filesFor(id).length - 1)}"] [data-upload-action=remove]`) || $("#btnAddAttachments")).focus();
|
|
669
|
+
}
|
|
670
|
+
});
|
|
671
|
+
const chatView = $("#chatView"), overlay = $("#attachmentDropOverlay");
|
|
672
|
+
const hasFiles = (event) => Array.from(event.dataTransfer?.types || []).includes("Files");
|
|
673
|
+
const showDrop = () => { chatView.classList.add("drag-over"); overlay.hidden = false; };
|
|
674
|
+
const clearDrop = () => { chatView.classList.remove("drag-over"); overlay.hidden = true; };
|
|
675
|
+
chatView.addEventListener("dragenter", (event) => { if (!hasFiles(event))
|
|
676
|
+
return; event.preventDefault(); showDrop(); });
|
|
677
|
+
chatView.addEventListener("dragover", (event) => { if (!hasFiles(event))
|
|
678
|
+
return; event.preventDefault(); event.dataTransfer.dropEffect = "copy"; showDrop(); });
|
|
679
|
+
chatView.addEventListener("dragleave", (event) => { if (hasFiles(event) && !chatView.contains(event.relatedTarget))
|
|
680
|
+
clearDrop(); });
|
|
681
|
+
chatView.addEventListener("drop", (event) => { if (!hasFiles(event))
|
|
682
|
+
return; event.preventDefault(); clearDrop(); addFiles(event.dataTransfer.files); });
|
|
683
|
+
// Capture before the editor's paste handler: an oversized paste never enters the DOM.
|
|
684
|
+
input.addEventListener("paste", (event) => {
|
|
685
|
+
const text = event.clipboardData?.getData("text/plain") || "";
|
|
686
|
+
if (text.length > TEXT_LIMIT && roomId() && input.contentEditable === "true") {
|
|
687
|
+
event.preventDefault();
|
|
688
|
+
const files = Array.from(event.clipboardData?.items || []).filter((item) => item.kind === "file").map((item) => item.getAsFile()).filter(Boolean);
|
|
689
|
+
addFiles([textFile(text), ...files], true, { textSource: text, textContent: text });
|
|
690
|
+
setStatus("pasteAsFile", false, roomId(), { count: text.length });
|
|
691
|
+
return;
|
|
692
|
+
}
|
|
693
|
+
const images = Array.from(event.clipboardData?.items || []).filter((item) => item.kind === "file" && item.type.startsWith("image/")).map((item) => item.getAsFile()).filter(Boolean);
|
|
694
|
+
if (!images.length)
|
|
695
|
+
return;
|
|
696
|
+
if (!event.clipboardData.getData("text/plain"))
|
|
697
|
+
event.preventDefault();
|
|
698
|
+
addFiles(images, true);
|
|
699
|
+
}, true);
|
|
700
|
+
document.addEventListener("chat-room-activated", (event) => {
|
|
701
|
+
render();
|
|
702
|
+
const id = event.detail;
|
|
703
|
+
$("#btnAddAttachments").disabled = !id;
|
|
704
|
+
void restoreRoom(id);
|
|
705
|
+
void getLimit().catch(() => { });
|
|
706
|
+
});
|
|
707
|
+
render();
|
|
463
708
|
}
|