@alexsun-top/opencode-chat-room 0.5.0 → 0.5.2
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 +26 -0
- package/README.md +23 -7
- package/README.zh-CN.md +23 -7
- package/docs/administrator-rooms.md +51 -0
- package/package.json +11 -2
- package/plugin.ts +29 -12
- package/server/admin-auth.ts +16 -0
- package/server/admin-plan-routes.ts +79 -0
- package/server/admin-routes.ts +154 -0
- package/server/admin-scheduler.ts +42 -0
- package/server/admin-state.ts +61 -0
- package/server/admin-task-routes.ts +182 -0
- package/server/assets/base.css +55 -43
- package/server/assets/chat/admin.js +223 -0
- package/server/assets/chat/attachments.js +240 -0
- package/server/assets/chat/editor.js +211 -0
- package/server/assets/chat/events.js +34 -10
- package/server/assets/chat/index.js +8 -0
- package/server/assets/chat/markdown.js +1 -12
- package/server/assets/chat/members.js +1 -1
- package/server/assets/chat/mentions.js +38 -28
- package/server/assets/chat/message-window.js +18 -0
- package/server/assets/chat/messages.js +64 -46
- package/server/assets/chat/questions.js +113 -41
- package/server/assets/chat/receipts.js +0 -1
- package/server/assets/chat/reminders.js +101 -0
- package/server/assets/chat/replies.js +149 -0
- package/server/assets/chat/rooms.js +30 -10
- package/server/assets/chat/state.js +68 -18
- package/server/assets/conversation.css +111 -45
- package/server/assets/responsive.css +83 -28
- package/server/chat-server.ts +23 -6
- package/server/chat.html +82 -31
- package/server/inbox.ts +5 -1
- package/server/newrooms.ts +27 -10
- package/server/resource-routes.ts +3 -0
- package/server/room-reminders.ts +212 -0
- package/server/wake.ts +11 -15
- package/skills/chatroom/SKILL.md +21 -1
- package/src/admin-client.ts +130 -0
- package/src/admin-credentials.ts +58 -0
- package/src/agent-receipts.ts +13 -18
- package/src/center-client.ts +1 -1
- package/src/center-inbox.ts +2 -0
- package/src/plugin-notifications.ts +4 -0
- package/src/queue.ts +7 -2
- package/src/reminder-client.ts +50 -0
- package/src/resource-read.ts +118 -0
- package/src/resources.ts +1 -1
- package/src/sqlite-state.ts +89 -21
- package/src/store.ts +22 -8
- package/src/supervision-inbox.ts +62 -0
- package/src/v1-plugin.ts +13 -3
- package/src/v2-plugin.ts +24 -7
|
@@ -0,0 +1,223 @@
|
|
|
1
|
+
import { LS } from "./state.js";
|
|
2
|
+
|
|
3
|
+
export function initAdmin(app) {
|
|
4
|
+
const $ = app.$, dialog = $("#adminDialog");
|
|
5
|
+
let rooms = [], bindings = [], agents = [], taskAgents = [], viewGeneration = 0, designationGeneration = 0, taskGeneration = 0, tokenGeneration = 0;
|
|
6
|
+
const status = (text, error = false) => { $("#adminStatus").textContent = text; $("#adminStatus").classList.toggle("danger-text", error); };
|
|
7
|
+
const json = (body) => JSON.stringify(body);
|
|
8
|
+
const select = (node, values, label, id = (item) => item.id) => {
|
|
9
|
+
node.replaceChildren(new Option(label, ""), ...values.map((item) => new Option(item.name, id(item))));
|
|
10
|
+
};
|
|
11
|
+
app.state.adminRoomIds = new Set();
|
|
12
|
+
const renderRoomOptions = app.renderRoomOptions;
|
|
13
|
+
app.renderRoomOptions = (list, available) => {
|
|
14
|
+
renderRoomOptions(list, available);
|
|
15
|
+
for (const button of list?.querySelectorAll(".room-row[data-room-id]") || []) {
|
|
16
|
+
if (!app.state.adminRoomIds.has(button.dataset.roomId)) continue;
|
|
17
|
+
const badge = document.createElement("span"); badge.className = "room-admin-badge"; badge.textContent = app.t("adminRoomBadge");
|
|
18
|
+
button.querySelector(".r-name")?.after(badge);
|
|
19
|
+
}
|
|
20
|
+
};
|
|
21
|
+
const renderHead = app.renderHead;
|
|
22
|
+
app.renderHead = () => {
|
|
23
|
+
renderHead();
|
|
24
|
+
const badge = $("#activeAdminBadge");
|
|
25
|
+
if (badge) badge.hidden = !app.state.adminRoomIds.has(app.state.room?.id);
|
|
26
|
+
};
|
|
27
|
+
function setAdminRooms(items) {
|
|
28
|
+
app.state.adminRoomIds = new Set(items.map((item) => item.roomId));
|
|
29
|
+
app.renderRoomOptions($("#roomList"), app.state.availableRooms || []);
|
|
30
|
+
app.renderRoomOptions($("#roomListChat"), app.state.availableRooms || []);
|
|
31
|
+
if (app.state.room) app.renderHead();
|
|
32
|
+
}
|
|
33
|
+
function renderAdminRooms() {
|
|
34
|
+
$("#adminRoomSelect").replaceChildren(new Option(app.t("chooseAdminRoom"), ""), ...rooms.map((room) => new Option(`${room.name}${bindings.some((item) => item.roomId === room.id) ? ` · ${app.t("adminRoomBadge")}` : ""}`, room.id)));
|
|
35
|
+
}
|
|
36
|
+
const clearEnrollment = () => { $("#adminEnrollment").replaceChildren(); $("#adminEnrollment").hidden = true; };
|
|
37
|
+
async function verifyToken() {
|
|
38
|
+
const generation = ++tokenGeneration, token = LS.adminToken, error = $("#adminAccessError"), button = $("#btnOpenAdmin");
|
|
39
|
+
error.hidden = true; button.hidden = true;
|
|
40
|
+
if (!token) { setAdminRooms([]); return; }
|
|
41
|
+
try {
|
|
42
|
+
const result = await app.adminApi("/admin/rooms");
|
|
43
|
+
if (generation !== tokenGeneration || token !== LS.adminToken) return;
|
|
44
|
+
setAdminRooms(result.rooms || []); button.hidden = false;
|
|
45
|
+
} catch (failure) {
|
|
46
|
+
if (generation === tokenGeneration && token === LS.adminToken) { setAdminRooms([]); error.textContent = failure.message; error.hidden = false; }
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
async function open() {
|
|
50
|
+
const generation = ++viewGeneration;
|
|
51
|
+
clearEnrollment(); $("#adminOverview").replaceChildren(); $("#adminTaskList").replaceChildren(); $("#adminPlanList").replaceChildren();
|
|
52
|
+
dialog.showModal(); status(app.t("adminLoading"));
|
|
53
|
+
$("#adminRoomSelect").disabled = $("#adminTargetRoom").disabled = $("#adminTargetAgent").disabled = true;
|
|
54
|
+
$("#adminTaskRoom").disabled = $("#adminTaskAgent").disabled = true;
|
|
55
|
+
$("#btnRevokeAdmin").hidden = $("#adminTaskForm").hidden = $("#adminPlanForm").hidden = true;
|
|
56
|
+
try {
|
|
57
|
+
const [adminResult, roomResult] = await Promise.all([app.adminApi("/admin/rooms"), app.api(`/rooms?sessionID=${encodeURIComponent(LS.sessionID)}`)]);
|
|
58
|
+
if (generation !== viewGeneration || !dialog.open) return;
|
|
59
|
+
bindings = adminResult.rooms || []; setAdminRooms(bindings); rooms = roomResult || [];
|
|
60
|
+
renderAdminRooms();
|
|
61
|
+
$("#adminRoomSelect").value = bindings[0]?.roomId || rooms[0]?.id || "";
|
|
62
|
+
select($("#adminTargetRoom"), rooms, app.t("chooseTargetRoom"), (room) => room.id);
|
|
63
|
+
select($("#adminTaskRoom"), rooms, app.t("chooseTargetRoom"), (room) => room.id);
|
|
64
|
+
if (rooms.length) $("#adminTargetRoom").value = rooms[0].id;
|
|
65
|
+
if (rooms.length) $("#adminTaskRoom").value = rooms[0].id;
|
|
66
|
+
status(rooms.length ? "" : app.t("createAdminRoomFirst"));
|
|
67
|
+
await Promise.all([loadDesignationAgents(), loadTaskAgents()]); await loadBinding(generation);
|
|
68
|
+
} catch (error) { if (generation === viewGeneration) { setAdminRooms([]); status(error.message, true); } }
|
|
69
|
+
finally { if (generation === viewGeneration) { $("#adminRoomSelect").disabled = $("#adminTargetRoom").disabled = $("#adminTargetAgent").disabled = false; $("#adminTaskRoom").disabled = $("#adminTaskAgent").disabled = false; } }
|
|
70
|
+
}
|
|
71
|
+
async function registryAgents(roomId) {
|
|
72
|
+
return roomId ? Object.entries(await app.api(`/rooms/${encodeURIComponent(roomId)}/registry`)).map(([sessionID, value]) => ({ sessionID, ...value })).filter((agent) => agent.membershipID) : [];
|
|
73
|
+
}
|
|
74
|
+
async function loadDesignationAgents() {
|
|
75
|
+
const generation = ++designationGeneration, roomId = $("#adminTargetRoom").value;
|
|
76
|
+
agents = []; $("#adminTargetAgent").disabled = true; select($("#adminTargetAgent"), [], app.t("chooseAgent"), (agent) => agent.sessionID);
|
|
77
|
+
try {
|
|
78
|
+
const found = await registryAgents(roomId);
|
|
79
|
+
if (generation !== designationGeneration || roomId !== $("#adminTargetRoom").value) return;
|
|
80
|
+
agents = found; select($("#adminTargetAgent"), agents.map((agent) => ({ ...agent, name: `${agent.name} · ${agent.sessionID.slice(0, 8)}` })), app.t("chooseAgent"), (agent) => agent.sessionID); $("#adminTargetAgent").disabled = false;
|
|
81
|
+
} catch (error) { if (generation === designationGeneration) status(error.message, true); }
|
|
82
|
+
}
|
|
83
|
+
async function loadTaskAgents() {
|
|
84
|
+
const generation = ++taskGeneration, roomId = $("#adminTaskRoom").value;
|
|
85
|
+
taskAgents = []; $("#adminTaskAgent").disabled = true; select($("#adminTaskAgent"), [], app.t("chooseAgent"), (agent) => agent.sessionID);
|
|
86
|
+
try {
|
|
87
|
+
const found = await registryAgents(roomId);
|
|
88
|
+
if (generation !== taskGeneration || roomId !== $("#adminTaskRoom").value) return;
|
|
89
|
+
taskAgents = found; select($("#adminTaskAgent"), taskAgents.map((agent) => ({ ...agent, name: `${agent.name} · ${agent.sessionID.slice(0, 8)}` })), app.t("chooseAgent"), (agent) => agent.sessionID); $("#adminTaskAgent").disabled = false;
|
|
90
|
+
} catch (error) { if (generation === taskGeneration) status(error.message, true); }
|
|
91
|
+
}
|
|
92
|
+
async function loadBinding(generation = ++viewGeneration) {
|
|
93
|
+
const id = $("#adminRoomSelect").value;
|
|
94
|
+
const binding = bindings.find((item) => item.roomId === id);
|
|
95
|
+
$("#adminOverview").replaceChildren(); $("#adminTaskList").replaceChildren(); $("#adminPlanList").replaceChildren();
|
|
96
|
+
$("#adminTaskForm").hidden = $("#adminPlanForm").hidden = true;
|
|
97
|
+
$("#btnRevokeAdmin").hidden = !binding;
|
|
98
|
+
if (!id || !binding) return renderData({}, id);
|
|
99
|
+
$("#adminTargetRoom").value = binding.targetRoomId;
|
|
100
|
+
const targetRoomId = binding.targetRoomId;
|
|
101
|
+
await loadDesignationAgents();
|
|
102
|
+
if (generation !== viewGeneration || id !== $("#adminRoomSelect").value || targetRoomId !== $("#adminTargetRoom").value || !dialog.open) return;
|
|
103
|
+
$("#adminTargetAgent").value = binding.sessionID;
|
|
104
|
+
try {
|
|
105
|
+
const base = `/admin/rooms/${encodeURIComponent(id)}`;
|
|
106
|
+
const [overview, tasks, plans] = await Promise.all([app.adminApi(`${base}/overview`), app.adminApi(`${base}/tasks`), app.adminApi(`${base}/plans`)]);
|
|
107
|
+
if (generation !== viewGeneration || id !== $("#adminRoomSelect").value || !dialog.open) return;
|
|
108
|
+
renderData({ overview, tasks: tasks.tasks, plans: plans.plans }, id);
|
|
109
|
+
} catch (error) { if (generation === viewGeneration) status(error.message, true); }
|
|
110
|
+
}
|
|
111
|
+
function renderData(data, id) {
|
|
112
|
+
const overview = $("#adminOverview"); overview.replaceChildren();
|
|
113
|
+
for (const room of data.overview?.rooms || []) {
|
|
114
|
+
const item = document.createElement("p");
|
|
115
|
+
item.textContent = `${room.name}: ${(room.members || []).map((member) => `${member.name} (${member.workState || "unknown"})`).join(", ") || app.t("noAgents")}`;
|
|
116
|
+
overview.append(item);
|
|
117
|
+
}
|
|
118
|
+
const binding = bindings.find((item) => item.roomId === id);
|
|
119
|
+
$("#adminTaskForm").hidden = !binding; $("#adminPlanForm").hidden = !binding;
|
|
120
|
+
renderTasks(data.tasks || [], id); renderPlans(data.plans || [], id);
|
|
121
|
+
}
|
|
122
|
+
function renderTasks(tasks, roomId) {
|
|
123
|
+
const list = $("#adminTaskList"); list.replaceChildren();
|
|
124
|
+
for (const task of tasks) {
|
|
125
|
+
const row = document.createElement("li"), title = document.createElement("p"), state = document.createElement("select"), progress = document.createElement("textarea"), save = document.createElement("button");
|
|
126
|
+
title.textContent = task.text; state.className = "admin-select";
|
|
127
|
+
for (const value of ["pending", "working", "blocked", "completed", "cancelled"]) state.add(new Option(app.t(`task_${value}`), value));
|
|
128
|
+
state.value = task.status; progress.className = "input"; progress.rows = 2; progress.value = task.progress || "";
|
|
129
|
+
save.className = "btn ghost small"; save.type = "button"; save.textContent = app.t("updateTask");
|
|
130
|
+
save.addEventListener("click", async () => {
|
|
131
|
+
const generation = viewGeneration, nextStatus = state.value, nextProgress = progress.value; save.disabled = true;
|
|
132
|
+
try { await app.adminApi(`/admin/rooms/${encodeURIComponent(roomId)}/tasks/${encodeURIComponent(task.id)}`, { method: "PATCH", body: json({ status: nextStatus, progress: nextProgress }) }); if (generation === viewGeneration && roomId === $("#adminRoomSelect").value && state.value === nextStatus && progress.value === nextProgress) await loadBinding(); }
|
|
133
|
+
catch (error) { if (generation === viewGeneration) status(error.message, true); }
|
|
134
|
+
finally { save.disabled = false; }
|
|
135
|
+
});
|
|
136
|
+
row.append(title, state, progress, save); list.append(row);
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
function renderPlans(plans, roomId) {
|
|
140
|
+
const list = $("#adminPlanList"); list.replaceChildren();
|
|
141
|
+
for (const plan of plans) {
|
|
142
|
+
const row = document.createElement("li"), text = document.createElement("p"), toggle = document.createElement("button"), remove = document.createElement("button");
|
|
143
|
+
text.textContent = `${plan.name} · ${app.t(plan.paused ? "paused" : "nextRun", { time: new Date(plan.nextRunAt).toLocaleString(), minutes: Math.round(plan.intervalSeconds / 60) })}`;
|
|
144
|
+
toggle.className = remove.className = "btn ghost small"; toggle.type = remove.type = "button";
|
|
145
|
+
toggle.textContent = app.t(plan.paused ? "resumeTimer" : "pauseTimer"); remove.textContent = app.t("deleteTimer");
|
|
146
|
+
toggle.addEventListener("click", () => changePlan(roomId, plan.id, { paused: !plan.paused }, toggle));
|
|
147
|
+
remove.addEventListener("click", async () => { if (confirm(app.t("deleteTimerConfirm", { name: plan.name }))) await changePlan(roomId, plan.id, null, remove); });
|
|
148
|
+
row.append(text, toggle, remove); list.append(row);
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
async function changePlan(roomId, planId, update, button) {
|
|
152
|
+
const generation = viewGeneration; button.disabled = true;
|
|
153
|
+
try { await app.adminApi(`/admin/rooms/${encodeURIComponent(roomId)}/plans/${encodeURIComponent(planId)}`, update ? { method: "PATCH", body: json(update) } : { method: "DELETE", body: json({}) }); if (generation === viewGeneration && roomId === $("#adminRoomSelect").value) await loadBinding(); }
|
|
154
|
+
catch (error) { if (generation === viewGeneration) status(error.message, true); }
|
|
155
|
+
finally { button.disabled = false; }
|
|
156
|
+
}
|
|
157
|
+
$("#btnSaveAdminToken").addEventListener("click", async () => { ++viewGeneration; ++designationGeneration; ++taskGeneration; clearEnrollment(); setAdminRooms([]); LS.adminToken = $("#inAdminToken").value.trim(); $("#inAdminToken").value = LS.adminToken; await verifyToken(); });
|
|
158
|
+
$("#btnOpenAdmin").addEventListener("click", () => { app.closePanels(); void open(); });
|
|
159
|
+
$("#btnRefreshAdmin").addEventListener("click", async () => {
|
|
160
|
+
const id = $("#adminRoomSelect").value;
|
|
161
|
+
const generation = ++viewGeneration;
|
|
162
|
+
try { const result = await app.adminApi("/admin/rooms"); if (generation !== viewGeneration || !dialog.open) return; bindings = result.rooms || []; setAdminRooms(bindings); renderAdminRooms(); $("#adminRoomSelect").value = id; await loadBinding(generation); }
|
|
163
|
+
catch (error) { if (generation === viewGeneration) { setAdminRooms([]); status(error.message, true); } }
|
|
164
|
+
});
|
|
165
|
+
$("#btnCloseAdmin").addEventListener("click", () => dialog.close());
|
|
166
|
+
dialog.addEventListener("close", () => { ++viewGeneration; ++designationGeneration; ++taskGeneration; clearEnrollment(); });
|
|
167
|
+
dialog.addEventListener("click", (event) => { if (event.target === dialog) dialog.close(); });
|
|
168
|
+
$("#adminRoomSelect").addEventListener("change", () => { clearEnrollment(); void loadBinding(); });
|
|
169
|
+
$("#adminTargetRoom").addEventListener("change", () => { clearEnrollment(); void loadDesignationAgents(); });
|
|
170
|
+
$("#adminTargetAgent").addEventListener("change", clearEnrollment);
|
|
171
|
+
$("#adminTaskRoom").addEventListener("change", () => void loadTaskAgents());
|
|
172
|
+
$("#btnDesignateAgent").addEventListener("click", async () => {
|
|
173
|
+
const roomId = $("#adminRoomSelect").value, agent = agents.find((item) => item.sessionID === $("#adminTargetAgent").value);
|
|
174
|
+
if (!roomId || !agent || !agent.membershipID) return status(app.t("selectAdminAgent"), true);
|
|
175
|
+
const body = { targetRoomId: $("#adminTargetRoom").value, sessionID: agent.sessionID, receiverOwnerID: agent.receiverOwnerID || "", membershipID: agent.membershipID };
|
|
176
|
+
const generation = viewGeneration, button = $("#btnDesignateAgent"); button.disabled = true;
|
|
177
|
+
try {
|
|
178
|
+
const existing = bindings.some((item) => item.roomId === roomId);
|
|
179
|
+
const result = await app.adminApi(existing ? `/admin/rooms/${encodeURIComponent(roomId)}` : "/admin/rooms", { method: existing ? "PUT" : "POST", body: json(existing ? body : { roomId, ...body }) });
|
|
180
|
+
if (generation !== viewGeneration || !dialog.open || roomId !== $("#adminRoomSelect").value || body.targetRoomId !== $("#adminTargetRoom").value || agent.sessionID !== $("#adminTargetAgent").value) return;
|
|
181
|
+
if (!existing) bindings.push(result.adminRoom); else bindings = bindings.map((item) => item.roomId === roomId ? result.adminRoom : item);
|
|
182
|
+
setAdminRooms(bindings); renderAdminRooms(); $("#adminRoomSelect").value = roomId;
|
|
183
|
+
await loadBinding(generation);
|
|
184
|
+
if (generation !== viewGeneration || roomId !== $("#adminRoomSelect").value || body.targetRoomId !== $("#adminTargetRoom").value) return;
|
|
185
|
+
const box = $("#adminEnrollment"), instruction = document.createElement("code"), copy = document.createElement("button"), warning = document.createElement("p");
|
|
186
|
+
instruction.textContent = `admin(action='admin_claim',roomId='${roomId}',enrollmentKey='${result.enrollmentKey}')`;
|
|
187
|
+
warning.textContent = app.t("privateEnrollment", { expires: new Date(result.expiresAt).toLocaleString() });
|
|
188
|
+
copy.className = "btn ghost small"; copy.type = "button"; copy.textContent = app.t("copyEnrollment");
|
|
189
|
+
copy.addEventListener("click", async () => { try { await navigator.clipboard.writeText(instruction.textContent); status(app.t("enrollmentCopied")); } catch (error) { status(error.message, true); } });
|
|
190
|
+
box.replaceChildren(warning, instruction, copy); box.hidden = false; $("#btnRevokeAdmin").hidden = false; status("");
|
|
191
|
+
} catch (error) { if (generation === viewGeneration) status(error.message, true); }
|
|
192
|
+
finally { button.disabled = false; }
|
|
193
|
+
});
|
|
194
|
+
$("#btnRevokeAdmin").addEventListener("click", async () => {
|
|
195
|
+
const id = $("#adminRoomSelect").value;
|
|
196
|
+
if (!id || !confirm(app.t("revokeConfirm"))) return;
|
|
197
|
+
const generation = viewGeneration, button = $("#btnRevokeAdmin"); button.disabled = true;
|
|
198
|
+
try { await app.adminApi(`/admin/rooms/${encodeURIComponent(id)}`, { method: "DELETE", body: json({}) }); if (generation !== viewGeneration || id !== $("#adminRoomSelect").value) return; bindings = bindings.filter((item) => item.roomId !== id); setAdminRooms(bindings); renderAdminRooms(); $("#adminRoomSelect").value = id; clearEnrollment(); await loadBinding(generation); }
|
|
199
|
+
catch (error) { if (generation === viewGeneration) status(error.message, true); }
|
|
200
|
+
finally { button.disabled = false; }
|
|
201
|
+
});
|
|
202
|
+
$("#adminTaskForm").addEventListener("submit", async (event) => {
|
|
203
|
+
event.preventDefault(); const roomId = $("#adminRoomSelect").value, binding = bindings.find((item) => item.roomId === roomId), targetRoomId = $("#adminTaskRoom").value, targetSessionID = $("#adminTaskAgent").value, target = taskAgents.find((item) => item.sessionID === targetSessionID && item.membershipID), input = $("#adminTaskText"), text = input.value, button = $("#adminTaskForm button[type=submit]");
|
|
204
|
+
if (!binding) return status(app.t("selectAdminAgent"), true);
|
|
205
|
+
if (!target || !text.trim()) return status(app.t("chooseAgent"), true);
|
|
206
|
+
const generation = viewGeneration; button.disabled = true;
|
|
207
|
+
try {
|
|
208
|
+
await app.adminApi(`/admin/rooms/${encodeURIComponent(roomId)}/tasks`, { method: "POST", body: json({ targetRoomId, targetSessionID, text }) });
|
|
209
|
+
if (generation !== viewGeneration || !dialog.open || roomId !== $("#adminRoomSelect").value) return;
|
|
210
|
+
if (input.value === text && targetRoomId === $("#adminTaskRoom").value && targetSessionID === $("#adminTaskAgent").value) input.value = "";
|
|
211
|
+
await loadBinding(generation);
|
|
212
|
+
} catch (error) { if (generation === viewGeneration) status(error.message, true); }
|
|
213
|
+
finally { button.disabled = false; }
|
|
214
|
+
});
|
|
215
|
+
$("#adminPlanForm").addEventListener("submit", async (event) => {
|
|
216
|
+
event.preventDefault(); const roomId = $("#adminRoomSelect").value, generation = viewGeneration, form = $("#adminPlanForm"), button = form.querySelector("button[type=submit]"), name = $("#adminPlanName").value, interval = $("#adminPlanInterval").value, text = $("#adminPlanText").value; button.disabled = true;
|
|
217
|
+
try { await app.adminApi(`/admin/rooms/${encodeURIComponent(roomId)}/plans`, { method: "POST", body: json({ name, intervalSeconds: Number(interval), text }) }); if (generation !== viewGeneration || roomId !== $("#adminRoomSelect").value || !dialog.open) return; if ($("#adminPlanName").value === name && $("#adminPlanInterval").value === interval && $("#adminPlanText").value === text) { form.reset(); $("#adminPlanInterval").value = "3600"; } await loadBinding(generation); }
|
|
218
|
+
catch (error) { if (generation === viewGeneration) status(error.message, true); }
|
|
219
|
+
finally { button.disabled = false; }
|
|
220
|
+
});
|
|
221
|
+
$("#inAdminToken").value = LS.adminToken;
|
|
222
|
+
void verifyToken();
|
|
223
|
+
}
|
|
@@ -0,0 +1,240 @@
|
|
|
1
|
+
import { LS } from "./state.js";
|
|
2
|
+
|
|
3
|
+
const MAX_PARALLEL_UPLOADS = 2;
|
|
4
|
+
const TEXT_LIMIT = 2000;
|
|
5
|
+
const previewTypes = new Set(["image/png", "image/jpeg", "image/gif", "image/webp", "image/avif", "image/bmp"]);
|
|
6
|
+
|
|
7
|
+
export function initAttachments(app) {
|
|
8
|
+
const $ = app.$, input = $("#msgInput"), list = $("#attachmentList"), tray = $("#attachmentTray"), picker = $("#attachmentPicker");
|
|
9
|
+
const drafts = new Map();
|
|
10
|
+
const statuses = new Map();
|
|
11
|
+
app.state.sendingRooms ||= new Set();
|
|
12
|
+
let limit = null, configRequest = null, activeUploads = 0;
|
|
13
|
+
const roomId = () => app.state.room?.id || "";
|
|
14
|
+
const filesFor = (id) => drafts.get(id) || [];
|
|
15
|
+
const markers = (items) => items.filter((item) => item.resource).map((item) => `[[resource:${item.resource.id}]]`);
|
|
16
|
+
const textFor = (id, caption) => {
|
|
17
|
+
const parts = [String(caption || "").trim(), ...markers(filesFor(id))].filter(Boolean);
|
|
18
|
+
return { text: parts.join("\n\n"), ids: filesFor(id).filter((item) => item.resource).map((item) => item.resource.id) };
|
|
19
|
+
};
|
|
20
|
+
function formatSize(size) {
|
|
21
|
+
if (size < 1024) return `${size} B`;
|
|
22
|
+
const units = ["KiB", "MiB", "GiB"];
|
|
23
|
+
let value = size / 1024, index = 0;
|
|
24
|
+
while (value >= 1024 && index < units.length - 1) { value /= 1024; index++; }
|
|
25
|
+
return `${value < 10 ? value.toFixed(1) : Math.round(value)} ${units[index]}`;
|
|
26
|
+
}
|
|
27
|
+
function preserveLayout(change) {
|
|
28
|
+
const thread = $("#thread"), atBottom = Boolean(roomId() && Math.abs(thread.scrollHeight - thread.clientHeight - thread.scrollTop) < 1);
|
|
29
|
+
if (atBottom) { change(); thread.scrollTop = thread.scrollHeight; }
|
|
30
|
+
else if (roomId() && app.preserveReadingLayout) void app.preserveReadingLayout(change).catch(() => {});
|
|
31
|
+
else change();
|
|
32
|
+
}
|
|
33
|
+
function setStatus(key = "", error = false, id = roomId(), values = {}) {
|
|
34
|
+
if (id) statuses.set(id, { key, error, values });
|
|
35
|
+
if (id === roomId()) preserveLayout(() => {
|
|
36
|
+
const node = $("#attachmentStatus"); node.textContent = key ? app.t(key, values) : ""; node.classList.toggle("danger-text", error); if (key) tray.hidden = false;
|
|
37
|
+
});
|
|
38
|
+
}
|
|
39
|
+
function prepareMessage(id, caption) {
|
|
40
|
+
const items = filesFor(id), composed = textFor(id, caption);
|
|
41
|
+
return { ...composed, ready: Boolean(composed.text) && composed.text.length <= TEXT_LIMIT && items.every((item) => item.status === "uploaded") };
|
|
42
|
+
}
|
|
43
|
+
app.prepareMessage = prepareMessage;
|
|
44
|
+
const baseDraftCount = app.updateDraftCount;
|
|
45
|
+
app.updateDraftCount = () => {
|
|
46
|
+
if (!roomId()) { $("#draftCount").classList.remove("over-limit"); return baseDraftCount(); }
|
|
47
|
+
const count = textFor(roomId(), input.value).text.length;
|
|
48
|
+
app.setText($("#draftCount"), "messageCount", { count });
|
|
49
|
+
$("#draftCount").classList.toggle("over-limit", count > TEXT_LIMIT);
|
|
50
|
+
};
|
|
51
|
+
app.updateSendState = () => {
|
|
52
|
+
const id = roomId(), message = id && prepareMessage(id, input.value);
|
|
53
|
+
$("#btnSend").disabled = !id || !message?.ready || app.state.sendingRooms.has(id);
|
|
54
|
+
};
|
|
55
|
+
app.completeAttachments = (id, resourceIDs) => {
|
|
56
|
+
const used = new Set(resourceIDs), items = filesFor(id), removed = items.filter((item) => used.has(item.resource?.id));
|
|
57
|
+
for (const item of removed) if (item.previewUrl) URL.revokeObjectURL(item.previewUrl);
|
|
58
|
+
const remaining = items.filter((item) => !used.has(item.resource?.id));
|
|
59
|
+
if (remaining.length) drafts.set(id, remaining); else { drafts.delete(id); statuses.delete(id); }
|
|
60
|
+
if (roomId() === id) render();
|
|
61
|
+
};
|
|
62
|
+
app.completeAttachmentsFromText = (id, text) => app.completeAttachments(id, [...String(text).matchAll(/\[\[resource:([\da-f-]{36})\]\]/gi)].map((match) => match[1]));
|
|
63
|
+
const applyLocale = app.applyLocale;
|
|
64
|
+
app.applyLocale = () => { applyLocale(); updateLocale(); };
|
|
65
|
+
function updateLocale() {
|
|
66
|
+
const id = roomId(), items = filesFor(id);
|
|
67
|
+
items.forEach((item, index) => {
|
|
68
|
+
const row = list.children[index]; if (!row) return;
|
|
69
|
+
const detail = row.querySelector(".attachment-detail"), progress = row.querySelector("progress");
|
|
70
|
+
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")}`;
|
|
71
|
+
const retry = row.querySelector('[data-upload-action="retry"]'); if (retry) { retry.textContent = app.t("retryUpload"); retry.setAttribute("aria-label", retry.textContent); }
|
|
72
|
+
const remove = row.querySelector('[data-upload-action="remove"]'); if (remove) { remove.textContent = app.t("removeFile"); remove.setAttribute("aria-label", remove.textContent); }
|
|
73
|
+
progress.setAttribute("aria-label", app.t("uploadPercent", { percent: item.percent || 0 }));
|
|
74
|
+
progress.setAttribute("aria-valuetext", app.t("uploadPercent", { percent: item.percent || 0 }));
|
|
75
|
+
});
|
|
76
|
+
const status = statuses.get(id); $("#attachmentStatus").textContent = status?.key ? app.t(status.key, status.values) : "";
|
|
77
|
+
if (status?.key) tray.hidden = false;
|
|
78
|
+
}
|
|
79
|
+
function render() {
|
|
80
|
+
preserveLayout(() => {
|
|
81
|
+
const id = roomId(), items = filesFor(id), savedStatus = statuses.get(id);
|
|
82
|
+
tray.hidden = !items.length && !savedStatus?.key; $("#attachmentVolatile").hidden = !items.length;
|
|
83
|
+
$("#attachmentStatus").textContent = savedStatus?.key ? app.t(savedStatus.key, savedStatus.values) : ""; $("#attachmentStatus").classList.toggle("danger-text", Boolean(savedStatus?.error));
|
|
84
|
+
list.replaceChildren();
|
|
85
|
+
items.forEach((item, index) => { const row = renderItem(item); row.dataset.index = String(index); list.append(row); });
|
|
86
|
+
app.updateDraftCount(); app.updateSendState();
|
|
87
|
+
});
|
|
88
|
+
}
|
|
89
|
+
app.renderAttachments = render;
|
|
90
|
+
function renderItem(item) {
|
|
91
|
+
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");
|
|
92
|
+
row.className = "attachment-item"; preview.className = "attachment-preview";
|
|
93
|
+
if (previewTypes.has(item.file.type)) {
|
|
94
|
+
item.previewUrl ||= URL.createObjectURL(item.file);
|
|
95
|
+
const image = document.createElement("img"); image.src = item.previewUrl; image.alt = ""; preview.append(image);
|
|
96
|
+
} else preview.textContent = item.file.name.split(".").at(-1)?.slice(0, 4).toUpperCase() || "FILE";
|
|
97
|
+
info.className = "attachment-file"; name.className = "attachment-name"; name.textContent = item.file.name;
|
|
98
|
+
detail.className = `attachment-detail${item.status === "failed" ? " attachment-over-limit" : ""}`;
|
|
99
|
+
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")}`;
|
|
100
|
+
progress.max = item.file.size || 1; progress.value = item.loaded || 0; progress.hidden = item.status !== "uploading";
|
|
101
|
+
progress.setAttribute("aria-label", app.t("uploadPercent", { percent: item.percent || 0 }));
|
|
102
|
+
item.progressNode = progress; item.detailNode = detail;
|
|
103
|
+
info.append(name, detail, progress); actions.className = "attachment-actions";
|
|
104
|
+
if (item.status === "failed") actions.append(action("retry", app.t("retryUpload")));
|
|
105
|
+
actions.append(action("remove", app.t("removeFile"))); row.append(preview, info, actions);
|
|
106
|
+
return row;
|
|
107
|
+
}
|
|
108
|
+
function action(kind, label) {
|
|
109
|
+
const button = document.createElement("button"); button.type = "button"; button.dataset.uploadAction = kind; button.textContent = label; button.setAttribute("aria-label", label); return button;
|
|
110
|
+
}
|
|
111
|
+
function removeItem(id, item) {
|
|
112
|
+
item.cancelled = true; item.xhr?.abort();
|
|
113
|
+
if (item.previewUrl) URL.revokeObjectURL(item.previewUrl);
|
|
114
|
+
const remaining = filesFor(id).filter((entry) => entry !== item);
|
|
115
|
+
if (remaining.length) drafts.set(id, remaining); else { drafts.delete(id); statuses.delete(id); }
|
|
116
|
+
if (roomId() === id) render();
|
|
117
|
+
}
|
|
118
|
+
function clearRoom(id) {
|
|
119
|
+
for (const item of [...filesFor(id)]) removeItem(id, item);
|
|
120
|
+
drafts.delete(id); statuses.delete(id);
|
|
121
|
+
}
|
|
122
|
+
app.disposeRoomAttachments = clearRoom;
|
|
123
|
+
function getLimit(refresh = false) {
|
|
124
|
+
if (refresh) limit = null;
|
|
125
|
+
if (limit !== null) return Promise.resolve(limit);
|
|
126
|
+
if (!configRequest || refresh) {
|
|
127
|
+
const request = app.api("/resources/config").then((data) => {
|
|
128
|
+
if (!Number.isSafeInteger(data.maxFileSizeBytes) || data.maxFileSizeBytes < 1) throw new Error("Invalid upload limit");
|
|
129
|
+
if (configRequest === request) limit = data.maxFileSizeBytes;
|
|
130
|
+
return data.maxFileSizeBytes;
|
|
131
|
+
}).finally(() => { if (configRequest === request) configRequest = null; });
|
|
132
|
+
configRequest = request;
|
|
133
|
+
}
|
|
134
|
+
return configRequest;
|
|
135
|
+
}
|
|
136
|
+
function pump() {
|
|
137
|
+
while (activeUploads < MAX_PARALLEL_UPLOADS) {
|
|
138
|
+
const next = [...drafts].flatMap(([id, items]) => items.map((item) => ({ id, item }))).find(({ item }) => item.status === "queued");
|
|
139
|
+
if (!next) return;
|
|
140
|
+
activeUploads++; next.item.status = "uploading"; next.item.percent = 0;
|
|
141
|
+
if (roomId() === next.id) render();
|
|
142
|
+
void uploadItem(next.id, next.item);
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
async function uploadItem(id, item) {
|
|
146
|
+
try {
|
|
147
|
+
let max = null;
|
|
148
|
+
try { max = await getLimit(item.refreshLimit); } catch {}
|
|
149
|
+
item.refreshLimit = false;
|
|
150
|
+
if (item.cancelled) return;
|
|
151
|
+
if (max !== null && item.file.size > max) { item.errorKey = "fileTooLarge"; item.status = "failed"; if (roomId() === id) setStatus(item.errorKey, true, id); return; }
|
|
152
|
+
item.resource = await upload(id, item);
|
|
153
|
+
if (item.cancelled) return;
|
|
154
|
+
item.status = "uploaded"; item.loaded = item.file.size; item.percent = 100;
|
|
155
|
+
if (roomId() === id && filesFor(id).every((entry) => entry.status === "uploaded")) setStatus("uploadReady");
|
|
156
|
+
} catch (error) {
|
|
157
|
+
if (item.cancelled) return;
|
|
158
|
+
if (error.status === 413) { limit = null; item.errorKey = "fileTooLarge"; }
|
|
159
|
+
else item.errorKey = "uploadFailed";
|
|
160
|
+
item.status = "failed";
|
|
161
|
+
if (roomId() === id) setStatus(item.errorKey, true, id, item.errorValues || {});
|
|
162
|
+
} finally {
|
|
163
|
+
activeUploads--;
|
|
164
|
+
if (roomId() === id) render();
|
|
165
|
+
pump();
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
function upload(id, item) {
|
|
169
|
+
return new Promise((resolve, reject) => {
|
|
170
|
+
const xhr = new XMLHttpRequest(); item.xhr = xhr;
|
|
171
|
+
xhr.open("POST", `/rooms/${encodeURIComponent(id)}/resources`);
|
|
172
|
+
xhr.setRequestHeader("Content-Type", "application/octet-stream");
|
|
173
|
+
xhr.setRequestHeader("X-Session-ID", LS.sessionID);
|
|
174
|
+
xhr.setRequestHeader("X-File-Name", encodeURIComponent(item.file.name));
|
|
175
|
+
if (LS.token) xhr.setRequestHeader("Authorization", `Bearer ${LS.token}`);
|
|
176
|
+
xhr.timeout = 1800000;
|
|
177
|
+
xhr.upload.onprogress = (event) => {
|
|
178
|
+
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);
|
|
179
|
+
if (roomId() === id) {
|
|
180
|
+
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 })); }
|
|
181
|
+
if (item.detailNode) item.detailNode.textContent = `${formatSize(item.file.size)} · ${app.t("uploadPercent", { percent: item.percent })}`;
|
|
182
|
+
}
|
|
183
|
+
};
|
|
184
|
+
xhr.onload = () => {
|
|
185
|
+
item.xhr = null;
|
|
186
|
+
if (xhr.status !== 201) return reject(Object.assign(new Error("Upload failed"), { status: xhr.status }));
|
|
187
|
+
try {
|
|
188
|
+
const resource = JSON.parse(xhr.responseText).resource;
|
|
189
|
+
if (!/^[\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) throw new Error("Invalid resource response");
|
|
190
|
+
resolve(resource);
|
|
191
|
+
} catch { reject(new Error("Invalid resource response")); }
|
|
192
|
+
};
|
|
193
|
+
xhr.onerror = () => { item.xhr = null; reject(Object.assign(new Error("Upload failed"), { network: true })); };
|
|
194
|
+
xhr.ontimeout = () => { item.xhr = null; reject(Object.assign(new Error("Upload timed out"), { timeout: true })); };
|
|
195
|
+
xhr.onabort = () => { item.xhr = null; reject(Object.assign(new Error("Upload cancelled"), { aborted: true })); };
|
|
196
|
+
xhr.send(item.file);
|
|
197
|
+
});
|
|
198
|
+
}
|
|
199
|
+
function addFiles(files) {
|
|
200
|
+
const id = roomId(); if (!id) return;
|
|
201
|
+
const accepted = [...files].filter((file) => file instanceof File);
|
|
202
|
+
if (!accepted.length) return;
|
|
203
|
+
const items = filesFor(id);
|
|
204
|
+
for (const file of accepted) items.push({ file, status: "queued", loaded: 0, percent: 0, cancelled: false });
|
|
205
|
+
drafts.set(id, items); setStatus(""); render(); pump();
|
|
206
|
+
}
|
|
207
|
+
function retryItem(item) {
|
|
208
|
+
if (item.status !== "failed") return;
|
|
209
|
+
item.refreshLimit = item.errorKey === "fileTooLarge"; item.status = "queued"; item.errorKey = ""; item.errorValues = null; item.loaded = 0; item.percent = 0;
|
|
210
|
+
if (roomId()) setStatus(""); render(); pump();
|
|
211
|
+
}
|
|
212
|
+
$("#btnAddAttachments").addEventListener("click", () => picker.click());
|
|
213
|
+
picker.addEventListener("change", () => { addFiles(picker.files || []); picker.value = ""; });
|
|
214
|
+
list.addEventListener("click", (event) => {
|
|
215
|
+
const button = event.target.closest?.("[data-upload-action]"); if (!button) return;
|
|
216
|
+
const id = roomId(), index = Number(button.closest(".attachment-item")?.dataset.index), item = filesFor(id)[index];
|
|
217
|
+
if (!item) return;
|
|
218
|
+
if (button.dataset.uploadAction === "retry") { retryItem(item); $("#btnAddAttachments").focus(); }
|
|
219
|
+
else { removeItem(id, item); (list.querySelector(`[data-index="${Math.min(index, filesFor(id).length - 1)}"] [data-upload-action=remove]`) || $("#btnAddAttachments")).focus(); }
|
|
220
|
+
});
|
|
221
|
+
const chatView = $("#chatView"), overlay = $("#attachmentDropOverlay");
|
|
222
|
+
const hasFiles = (event) => Array.from(event.dataTransfer?.types || []).includes("Files");
|
|
223
|
+
const showDrop = () => { chatView.classList.add("drag-over"); overlay.hidden = false; };
|
|
224
|
+
const clearDrop = () => { chatView.classList.remove("drag-over"); overlay.hidden = true; };
|
|
225
|
+
chatView.addEventListener("dragenter", (event) => { if (!hasFiles(event)) return; event.preventDefault(); showDrop(); });
|
|
226
|
+
chatView.addEventListener("dragover", (event) => { if (!hasFiles(event)) return; event.preventDefault(); event.dataTransfer.dropEffect = "copy"; showDrop(); });
|
|
227
|
+
chatView.addEventListener("dragleave", (event) => { if (hasFiles(event) && !chatView.contains(event.relatedTarget)) clearDrop(); });
|
|
228
|
+
chatView.addEventListener("drop", (event) => { if (!hasFiles(event)) return; event.preventDefault(); clearDrop(); addFiles(event.dataTransfer.files); });
|
|
229
|
+
input.addEventListener("paste", (event) => {
|
|
230
|
+
const images = Array.from(event.clipboardData?.items || []).filter((item) => item.kind === "file" && item.type.startsWith("image/")).map((item) => item.getAsFile()).filter(Boolean);
|
|
231
|
+
if (!images.length) return;
|
|
232
|
+
if (!event.clipboardData.getData("text/plain")) event.preventDefault();
|
|
233
|
+
addFiles(images);
|
|
234
|
+
});
|
|
235
|
+
document.addEventListener("chat-room-activated", (event) => {
|
|
236
|
+
render(); const id = event.detail; $("#btnAddAttachments").disabled = !id;
|
|
237
|
+
void getLimit().catch(() => {});
|
|
238
|
+
});
|
|
239
|
+
render();
|
|
240
|
+
}
|