Runs live, versioned Python application objects on one VM, with a suite of apps: projects, notes, tasks, files and more.

0 downloads

Download zip
Clone
Clone with git
git clone https://gitstable.com/git/askrobots/dbbasic-object-server.git
HTTPS
https://gitstable.com/git/askrobots/dbbasic-object-server.git
SSH
ssh://git@gitstable.com:2222/askrobots/dbbasic-object-server.git

Cloning needs no sign-in. Pushing over HTTPS asks for your username and an access token. SSH needs your key under SSH keys.

danq9 signup: the person chooses the password and name on the confirm page 83c7aa6 2 weeks, 5 days ago History
attachments.py · 5.5 KB · 117 lines
1"""Attachment widget, served at /attachments as window.dbbasicAttachments.
2
3The files sibling of app-thread's comment widget: what a collection's
4`capabilities.attachments` flag mounts under a detail page. It lists the
5files attached to one record via the polymorphic (parent_collection,
6parent_id) pair, uploads new ones (multipart to /api/files, which owns
7owner_id/size/content-type and saves the blob), links to download, and lets
8the owner delete (blob-aware, via /api/files/{id}). One widget, any
9collection -- no per-collection FK column on `files`.
10"""
11
12_JS = r"""
13(function () {
14 const esc = (s) => String(s == null ? "" : s).replace(/[&<>"']/g,
15 (c) => ({"&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;"}[c]));
16 const qs = (m) => typeof m === "string" ? document.querySelector(m) : m;
17
18 function fmtSize(n) {
19 const size = Number(n) || 0;
20 if (size >= 1048576) return (size / 1048576).toFixed(1) + " MB";
21 if (size >= 1024) return (size / 1024).toFixed(1) + " KB";
22 return size + " B";
23 }
24
25 async function jget(path) {
26 const res = await fetch(path, {credentials: "same-origin", headers: {accept: "application/json"}});
27 let data = null; try { data = await res.json(); } catch (e) {}
28 return [res.ok, data];
29 }
30
31 window.dbbasicAttachments = {
32 mount: async function (mountEl, opts) {
33 mountEl = qs(mountEl); opts = opts || {};
34 const pc = opts.parent_collection, pid = opts.parent_id;
35 const viewer = opts.viewer_id
36 || (typeof VIEWER_ID !== "undefined" ? VIEWER_ID : "") || "";
37 if (!mountEl) return;
38 if (!pc || !pid) {
39 mountEl.innerHTML = '<div class="viewblock-error">attachments need a parent_collection and parent_id</div>';
40 return;
41 }
42
43 mountEl.innerHTML =
44 '<div class="attachments"><h3 class="threadhead">Attachments</h3>'
45 + '<div class="attachlist"><div class="state">loading&hellip;</div></div>'
46 + (viewer
47 ? '<form class="attachupload"><input type="file" name="file" required>'
48 + '<button type="submit" class="btn primary">Upload</button>'
49 + '<span class="error" data-err></span></form>'
50 : '<div class="state"><a href="/login">Sign in</a> to attach files.</div>')
51 + '</div>';
52 const listEl = mountEl.querySelector(".attachlist");
53 const form = mountEl.querySelector(".attachupload");
54
55 function fileRow(f) {
56 const mine = viewer && f.owner_id && f.owner_id === viewer;
57 const del = mine
58 ? '<button class="rowbtn danger" data-del="' + esc(f.id) + '" title="Delete">✕</button>' : "";
59 const meta = [fmtSize(f.size), f.content_type].filter(Boolean).join(" · ");
60 return '<div class="attachrow"><div class="attachicon">📎</div>'
61 + '<div class="attachbody"><a class="attachname" href="/api/files/' + esc(f.id) + '">'
62 + esc(f.filename || "file") + '</a>'
63 + '<div class="attachmeta">' + esc(meta) + '</div></div>'
64 + '<div class="attachactions">' + del + '</div></div>';
65 }
66
67 async function load() {
68 const [ok, body] = await jget("/collections/files/records?limit=500"
69 + "&parent_collection=" + encodeURIComponent(pc) + "&parent_id=" + encodeURIComponent(pid));
70 if (!ok) { listEl.innerHTML = '<div class="state">Could not load attachments.</div>'; return; }
71 const rows = (body.records || []).filter((f) => f.parent_collection === pc && f.parent_id === pid);
72 rows.sort((a, b) => String(a.created_at || "").localeCompare(String(b.created_at || "")));
73 listEl.innerHTML = rows.length ? rows.map(fileRow).join("") : '<div class="state">No attachments yet.</div>';
74 }
75
76 if (form) {
77 form.addEventListener("submit", async (e) => {
78 e.preventDefault();
79 const input = form.elements["file"];
80 const errEl = form.querySelector("[data-err]"); if (errEl) errEl.textContent = "";
81 if (!input.files || !input.files.length) return;
82 // Multipart to /api/files: the server owns owner_id/size/content_type
83 // and saves the blob; we pass the polymorphic parent so it lands on
84 // this record's attachment list.
85 const data = new FormData();
86 data.append("file", input.files[0]);
87 data.append("parent_collection", pc);
88 data.append("parent_id", pid);
89 const res = await fetch("/api/files", {method: "POST", credentials: "same-origin", body: data});
90 let resp = null; try { resp = await res.json(); } catch (x) {}
91 if (!res.ok) { if (errEl) errEl.textContent = (resp && resp.error) || "Upload failed"; return; }
92 form.reset(); load();
93 });
94 }
95 listEl.addEventListener("click", async (e) => {
96 const del = e.target.closest("[data-del]"); if (!del) return;
97 if (!window.confirm("Delete this attachment?")) return;
98 // Blob-aware delete: /api/files/{id} removes the file bytes AND the
99 // metadata record (a plain record delete would orphan the blob).
100 await fetch("/api/files/" + encodeURIComponent(del.getAttribute("data-del")),
101 {method: "DELETE", credentials: "same-origin", headers: {accept: "application/json"}});
102 load();
103 });
104
105 (function sub() {
106 if (window.dbbasicSubscribe) window.dbbasicSubscribe("files", load);
107 else setTimeout(sub, 400);
108 })();
109 load();
110 },
111 };
112})();
113"""
114
115
116def GET(request):
117 return {"content_type": "application/javascript; charset=utf-8", "body": _JS}