Spaces:
Running
Running
Deploy msgboard demo
Browse files- src/msgboard/client.py +4 -0
- src/msgboard/dashboard.html +16 -1
- src/msgboard/db.py +8 -1
- src/msgboard/server.py +12 -0
- src/msgboard/store.py +37 -7
src/msgboard/client.py
CHANGED
|
@@ -196,6 +196,10 @@ class Client:
|
|
| 196 |
"""Change `name`, `description` (admins and the creator) or `archived` (admins)."""
|
| 197 |
return self._request("PATCH", f"/channels/{channel_id}", json=changes).json()
|
| 198 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 199 |
def members(self, channel_id: int) -> list[dict]:
|
| 200 |
return self._request("GET", f"/channels/{channel_id}/members").json()["members"]
|
| 201 |
|
|
|
|
| 196 |
"""Change `name`, `description` (admins and the creator) or `archived` (admins)."""
|
| 197 |
return self._request("PATCH", f"/channels/{channel_id}", json=changes).json()
|
| 198 |
|
| 199 |
+
def delete_channel(self, channel_id: int, confirm: str) -> dict:
|
| 200 |
+
"""Delete a channel and everything in it, for good (admins). `confirm` is the channel's name."""
|
| 201 |
+
return self._request("DELETE", f"/channels/{channel_id}", params={"confirm": confirm}).json()
|
| 202 |
+
|
| 203 |
def members(self, channel_id: int) -> list[dict]:
|
| 204 |
return self._request("GET", f"/channels/{channel_id}/members").json()["members"]
|
| 205 |
|
src/msgboard/dashboard.html
CHANGED
|
@@ -221,6 +221,8 @@ body.resizing iframe { pointer-events: none; }
|
|
| 221 |
.info-pop .isec .linkish { margin-top: 8px; display: inline-block; }
|
| 222 |
.info-pop .ifoot { display: flex; gap: 10px; align-items: center; }
|
| 223 |
.info-pop .ifoot .btn { white-space: nowrap; flex: none; }
|
|
|
|
|
|
|
| 224 |
.topbar .close { margin-left: auto; background: none; border: 0; font: 18px/1 var(--mono); color: var(--ink-3); padding: 0 2px; }
|
| 225 |
.topbar .close:hover { color: var(--ink); }
|
| 226 |
#menu { display: none; background: none; border: 1px solid var(--rule-2); padding: 2px 8px; font-family: var(--mono); }
|
|
@@ -2411,7 +2413,9 @@ async function openInfo(editing = false) {
|
|
| 2411 |
<div class="isec"><div class="label">Added as members · ${info.members.length}</div>${who(info.members)}
|
| 2412 |
<button class="linkish" id="info-members">${canWriteHere() ? "manage members" : "see members"}</button></div>`}
|
| 2413 |
${info.can_archive ? `<div class="ifoot"><button class="btn ghost small" id="info-archive">${info.archived ? "Unarchive channel" : "Archive channel"}</button>
|
| 2414 |
-
<span class="small">${info.archived ? "Archived: history is read-only." : "Keeps the history, stops new messages."}</span></div>` : ""}
|
|
|
|
|
|
|
| 2415 |
hydrate(infoPop);
|
| 2416 |
const after = async () => { // refresh everything that shows the channel's name or state
|
| 2417 |
await refreshChannels();
|
|
@@ -2427,6 +2431,17 @@ async function openInfo(editing = false) {
|
|
| 2427 |
try { await api("PATCH", `/channels/${c.id}`, { body: { archived: !info.archived } }); await after(); }
|
| 2428 |
catch (e) { alert(e.message); }
|
| 2429 |
});
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2430 |
const form = infoPop.querySelector("#info-form");
|
| 2431 |
if (form) {
|
| 2432 |
const name = $("info-name"); name.focus(); name.select();
|
|
|
|
| 221 |
.info-pop .isec .linkish { margin-top: 8px; display: inline-block; }
|
| 222 |
.info-pop .ifoot { display: flex; gap: 10px; align-items: center; }
|
| 223 |
.info-pop .ifoot .btn { white-space: nowrap; flex: none; }
|
| 224 |
+
.info-pop .ifoot.danger .btn { border-color: var(--ink); }
|
| 225 |
+
.info-pop .ifoot.danger .btn:hover { background: var(--ink); color: var(--bg); }
|
| 226 |
.topbar .close { margin-left: auto; background: none; border: 0; font: 18px/1 var(--mono); color: var(--ink-3); padding: 0 2px; }
|
| 227 |
.topbar .close:hover { color: var(--ink); }
|
| 228 |
#menu { display: none; background: none; border: 1px solid var(--rule-2); padding: 2px 8px; font-family: var(--mono); }
|
|
|
|
| 2413 |
<div class="isec"><div class="label">Added as members · ${info.members.length}</div>${who(info.members)}
|
| 2414 |
<button class="linkish" id="info-members">${canWriteHere() ? "manage members" : "see members"}</button></div>`}
|
| 2415 |
${info.can_archive ? `<div class="ifoot"><button class="btn ghost small" id="info-archive">${info.archived ? "Unarchive channel" : "Archive channel"}</button>
|
| 2416 |
+
<span class="small">${info.archived ? "Archived: history is read-only." : "Keeps the history, stops new messages."}</span></div>` : ""}
|
| 2417 |
+
${info.can_delete ? `<div class="ifoot danger"><button class="btn ghost small" id="info-delete">Delete channel…</button>
|
| 2418 |
+
<span class="small">Removes it and everything in it, for good.</span></div>` : ""}`;
|
| 2419 |
hydrate(infoPop);
|
| 2420 |
const after = async () => { // refresh everything that shows the channel's name or state
|
| 2421 |
await refreshChannels();
|
|
|
|
| 2431 |
try { await api("PATCH", `/channels/${c.id}`, { body: { archived: !info.archived } }); await after(); }
|
| 2432 |
catch (e) { alert(e.message); }
|
| 2433 |
});
|
| 2434 |
+
on("info-delete", async () => {
|
| 2435 |
+
const typed = prompt(`Delete #${info.name} for everyone? Its ${info.messages} messages, threads, reactions, ${info.files} files and doc are removed and cannot be recovered.\n\nType the channel name to confirm:`);
|
| 2436 |
+
if (typed === null) return;
|
| 2437 |
+
if (typed.trim() !== info.name) { alert("The name did not match; nothing was deleted."); return; }
|
| 2438 |
+
try {
|
| 2439 |
+
await api("DELETE", `/channels/${c.id}?confirm=${encodeURIComponent(info.name)}`);
|
| 2440 |
+
closeInfo(); await refreshChannels();
|
| 2441 |
+
const next = state.channels.find((x) => x.kind !== "dm") || state.channels[0];
|
| 2442 |
+
if (next) openChannel(next.id); else showNoChannels();
|
| 2443 |
+
} catch (e) { alert("Not deleted: " + e.message); }
|
| 2444 |
+
});
|
| 2445 |
const form = infoPop.querySelector("#info-form");
|
| 2446 |
if (form) {
|
| 2447 |
const name = $("info-name"); name.focus(); name.select();
|
src/msgboard/db.py
CHANGED
|
@@ -358,9 +358,16 @@ ALTER TABLE invites ADD COLUMN agent_name TEXT;
|
|
| 358 |
ALTER TABLE invites ADD COLUMN agent_display TEXT;
|
| 359 |
"""
|
| 360 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 361 |
# Index i holds the SQL that moves the schema from version i to i + 1.
|
| 362 |
MIGRATIONS = [SCHEMA_V1, SCHEMA_V2, SCHEMA_V3, SCHEMA_V4, SCHEMA_V5, SCHEMA_V6, SCHEMA_V7, SCHEMA_V8, SCHEMA_V9,
|
| 363 |
-
SCHEMA_V10, SCHEMA_V11, SCHEMA_V12, SCHEMA_V13, SCHEMA_V14, SCHEMA_V15]
|
| 364 |
SCHEMA_VERSION = len(MIGRATIONS)
|
| 365 |
|
| 366 |
|
|
|
|
| 358 |
ALTER TABLE invites ADD COLUMN agent_display TEXT;
|
| 359 |
"""
|
| 360 |
|
| 361 |
+
# v16: channels can be deleted (admins); the search index forgets deleted messages.
|
| 362 |
+
SCHEMA_V16 = """
|
| 363 |
+
CREATE TRIGGER messages_fts_delete AFTER DELETE ON messages BEGIN
|
| 364 |
+
INSERT INTO messages_fts(messages_fts, rowid, body) VALUES ('delete', old.id, old.body);
|
| 365 |
+
END;
|
| 366 |
+
"""
|
| 367 |
+
|
| 368 |
# Index i holds the SQL that moves the schema from version i to i + 1.
|
| 369 |
MIGRATIONS = [SCHEMA_V1, SCHEMA_V2, SCHEMA_V3, SCHEMA_V4, SCHEMA_V5, SCHEMA_V6, SCHEMA_V7, SCHEMA_V8, SCHEMA_V9,
|
| 370 |
+
SCHEMA_V10, SCHEMA_V11, SCHEMA_V12, SCHEMA_V13, SCHEMA_V14, SCHEMA_V15, SCHEMA_V16]
|
| 371 |
SCHEMA_VERSION = len(MIGRATIONS)
|
| 372 |
|
| 373 |
|
src/msgboard/server.py
CHANGED
|
@@ -421,6 +421,18 @@ def create_app(board: Board, dashboard: bool = True) -> FastAPI:
|
|
| 421 |
p = await authn(request)
|
| 422 |
return await db.read(store.doc_version, p, channel_id, version)
|
| 423 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 424 |
@app.get("/v1/channels/{channel_id}/info")
|
| 425 |
async def channel_info(channel_id: int, request: Request):
|
| 426 |
p = await authn(request)
|
|
|
|
| 421 |
p = await authn(request)
|
| 422 |
return await db.read(store.doc_version, p, channel_id, version)
|
| 423 |
|
| 424 |
+
@app.delete("/v1/channels/{channel_id}")
|
| 425 |
+
async def delete_channel(channel_id: int, request: Request, confirm: str = ""):
|
| 426 |
+
p = await authn(request)
|
| 427 |
+
result = await db.write(store.delete_channel, p, channel_id, confirm, time.time())
|
| 428 |
+
for key in result.pop("storage_keys"): # the rows are gone; now the files
|
| 429 |
+
try:
|
| 430 |
+
board.blobs.path_for(key).unlink()
|
| 431 |
+
except FileNotFoundError:
|
| 432 |
+
pass
|
| 433 |
+
board.notifier.notify(channel_id)
|
| 434 |
+
return result
|
| 435 |
+
|
| 436 |
@app.get("/v1/channels/{channel_id}/info")
|
| 437 |
async def channel_info(channel_id: int, request: Request):
|
| 438 |
p = await authn(request)
|
src/msgboard/store.py
CHANGED
|
@@ -485,11 +485,11 @@ def create_channel(conn, p: Principal, name, description, private, now: float) -
|
|
| 485 |
|
| 486 |
|
| 487 |
def archive_channel(conn, p: Principal, channel_id: int, now: float) -> dict:
|
| 488 |
-
if not p.is_admin:
|
| 489 |
-
raise forbidden("only admins can archive channels")
|
| 490 |
row = conn.execute("SELECT * FROM channels WHERE id = ?", (channel_id,)).fetchone()
|
| 491 |
if row is None:
|
| 492 |
raise not_found("channel not found")
|
|
|
|
|
|
|
| 493 |
conn.execute("UPDATE channels SET archived = 1 WHERE id = ?", (channel_id,))
|
| 494 |
audit(conn, p.id, "channel.archive", f"channel:{channel_id}", None, now)
|
| 495 |
return _channel_json(conn, conn.execute("SELECT * FROM channels WHERE id = ?", (channel_id,)).fetchone())
|
|
@@ -518,14 +518,14 @@ def channel_info(conn, p: Principal, channel_id: int) -> dict:
|
|
| 518 |
"""SELECT sender_id, COUNT(*), MAX(created_at) FROM messages WHERE channel_id = ?
|
| 519 |
GROUP BY sender_id ORDER BY COUNT(*) DESC LIMIT 50""", (channel_id,))],
|
| 520 |
"can_edit": row["kind"] != "dm" and _may_manage_channel(conn, p, row),
|
| 521 |
-
"can_archive": row["kind"] != "dm" and p
|
|
|
|
| 522 |
})
|
| 523 |
return out
|
| 524 |
|
| 525 |
|
| 526 |
def update_channel(conn, p: Principal, channel_id: int, changes: Any, now: float) -> dict:
|
| 527 |
-
"""Rename, describe, archive or unarchive a channel
|
| 528 |
-
archiving: admins."""
|
| 529 |
row = channel_for(conn, p, channel_id)
|
| 530 |
if not isinstance(changes, dict) or not changes or set(changes) - {"name", "description", "archived"}:
|
| 531 |
raise bad_request("supported fields: name, description, archived")
|
|
@@ -533,8 +533,8 @@ def update_channel(conn, p: Principal, channel_id: int, changes: Any, now: float
|
|
| 533 |
raise bad_request("direct messages cannot be renamed or archived")
|
| 534 |
if ("name" in changes or "description" in changes) and not _may_manage_channel(conn, p, row):
|
| 535 |
raise forbidden("only admins and the channel's creator can rename it")
|
| 536 |
-
if "archived" in changes and not p
|
| 537 |
-
raise forbidden("only admins can archive
|
| 538 |
if "name" in changes:
|
| 539 |
name = changes["name"]
|
| 540 |
if not isinstance(name, str) or not CHANNEL_NAME.match(name):
|
|
@@ -1967,3 +1967,33 @@ def get_message(conn, p: Principal, message_id: int) -> dict:
|
|
| 1967 |
c = _channel_json(conn, channel)
|
| 1968 |
out["channel"] = {k: c[k] for k in ("id", "name", "kind")} | ({"members": c["members"]} if c["kind"] == "dm" else {})
|
| 1969 |
return out
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 485 |
|
| 486 |
|
| 487 |
def archive_channel(conn, p: Principal, channel_id: int, now: float) -> dict:
|
|
|
|
|
|
|
| 488 |
row = conn.execute("SELECT * FROM channels WHERE id = ?", (channel_id,)).fetchone()
|
| 489 |
if row is None:
|
| 490 |
raise not_found("channel not found")
|
| 491 |
+
if not _may_manage_channel(conn, p, row):
|
| 492 |
+
raise forbidden("only admins and the channel's creator can archive it")
|
| 493 |
conn.execute("UPDATE channels SET archived = 1 WHERE id = ?", (channel_id,))
|
| 494 |
audit(conn, p.id, "channel.archive", f"channel:{channel_id}", None, now)
|
| 495 |
return _channel_json(conn, conn.execute("SELECT * FROM channels WHERE id = ?", (channel_id,)).fetchone())
|
|
|
|
| 518 |
"""SELECT sender_id, COUNT(*), MAX(created_at) FROM messages WHERE channel_id = ?
|
| 519 |
GROUP BY sender_id ORDER BY COUNT(*) DESC LIMIT 50""", (channel_id,))],
|
| 520 |
"can_edit": row["kind"] != "dm" and _may_manage_channel(conn, p, row),
|
| 521 |
+
"can_archive": row["kind"] != "dm" and _may_manage_channel(conn, p, row),
|
| 522 |
+
"can_delete": row["kind"] != "dm" and p.is_admin,
|
| 523 |
})
|
| 524 |
return out
|
| 525 |
|
| 526 |
|
| 527 |
def update_channel(conn, p: Principal, channel_id: int, changes: Any, now: float) -> dict:
|
| 528 |
+
"""Rename, describe, archive or unarchive a channel (admins and the channel's creator)."""
|
|
|
|
| 529 |
row = channel_for(conn, p, channel_id)
|
| 530 |
if not isinstance(changes, dict) or not changes or set(changes) - {"name", "description", "archived"}:
|
| 531 |
raise bad_request("supported fields: name, description, archived")
|
|
|
|
| 533 |
raise bad_request("direct messages cannot be renamed or archived")
|
| 534 |
if ("name" in changes or "description" in changes) and not _may_manage_channel(conn, p, row):
|
| 535 |
raise forbidden("only admins and the channel's creator can rename it")
|
| 536 |
+
if "archived" in changes and not _may_manage_channel(conn, p, row):
|
| 537 |
+
raise forbidden("only admins and the channel's creator can archive it")
|
| 538 |
if "name" in changes:
|
| 539 |
name = changes["name"]
|
| 540 |
if not isinstance(name, str) or not CHANNEL_NAME.match(name):
|
|
|
|
| 1967 |
c = _channel_json(conn, channel)
|
| 1968 |
out["channel"] = {k: c[k] for k in ("id", "name", "kind")} | ({"members": c["members"]} if c["kind"] == "dm" else {})
|
| 1969 |
return out
|
| 1970 |
+
|
| 1971 |
+
|
| 1972 |
+
def delete_channel(conn, p: Principal, channel_id: int, confirm, now: float) -> dict:
|
| 1973 |
+
"""Delete a channel for good (admins): its messages, threads, reactions, files, doc and members.
|
| 1974 |
+
`confirm` must repeat the channel's name. Returns what went, plus the file keys to remove from disk."""
|
| 1975 |
+
if not p.is_admin:
|
| 1976 |
+
raise forbidden("only admins can delete channels")
|
| 1977 |
+
row = conn.execute("SELECT * FROM channels WHERE id = ?", (channel_id,)).fetchone()
|
| 1978 |
+
if row is None:
|
| 1979 |
+
raise not_found("channel not found")
|
| 1980 |
+
if row["kind"] == "dm":
|
| 1981 |
+
raise bad_request("direct messages cannot be deleted")
|
| 1982 |
+
if confirm != row["name"]:
|
| 1983 |
+
raise bad_request(f"to delete it, confirm with the channel's name ({row['name']!r})")
|
| 1984 |
+
in_channel = "SELECT id FROM messages WHERE channel_id = ?"
|
| 1985 |
+
counts = {"messages": conn.execute("SELECT COUNT(*) FROM messages WHERE channel_id = ?", (channel_id,)).fetchone()[0]}
|
| 1986 |
+
keys = [r[0] for r in conn.execute("SELECT storage_key FROM attachments WHERE channel_id = ?", (channel_id,))]
|
| 1987 |
+
counts["files"] = len(keys)
|
| 1988 |
+
for table in ("message_reactions", "message_mentions", "message_revisions"):
|
| 1989 |
+
conn.execute(f"DELETE FROM {table} WHERE message_id IN ({in_channel})", (channel_id,))
|
| 1990 |
+
conn.execute("UPDATE messages SET reply_to = NULL, thread_id = NULL WHERE channel_id = ?", (channel_id,))
|
| 1991 |
+
conn.execute("DELETE FROM messages WHERE channel_id = ?", (channel_id,))
|
| 1992 |
+
for table in ("attachments", "channel_doc_versions", "channel_members", "channel_reads"):
|
| 1993 |
+
conn.execute(f"DELETE FROM {table} WHERE channel_id = ?", (channel_id,))
|
| 1994 |
+
for inv in conn.execute("SELECT id, channel_ids FROM invites WHERE channel_ids IS NOT NULL").fetchall():
|
| 1995 |
+
ids = [i for i in json.loads(inv["channel_ids"]) if i != channel_id]
|
| 1996 |
+
conn.execute("UPDATE invites SET channel_ids = ? WHERE id = ?", (json.dumps(ids) if ids else None, inv["id"]))
|
| 1997 |
+
conn.execute("DELETE FROM channels WHERE id = ?", (channel_id,))
|
| 1998 |
+
audit(conn, p.id, "channel.delete", f"channel:{channel_id}", {"name": row["name"], **counts}, now)
|
| 1999 |
+
return {"deleted": row["name"], **counts, "storage_keys": keys}
|