askrobots / dbbasic-object-server
Public
Runs live, versioned Python application objects on one VM, with a suite of apps: projects, notes, tasks, files and more.
danq9
signup: the person chooses the password and name on the confirm page
83c7aa6
2 weeks, 5 days ago
History
files.py · 4.9 KB · 135 lines
| 1 | """Files page: upload, list, share, download, delete. |
| 2 | |
| 3 | Uploads post multipart to /api/files; downloads hit /api/files/{id}, which |
| 4 | authorizes against the file's metadata record — so the share toggle here |
| 5 | is just a record update, and a public file's URL works for anyone. |
| 6 | """ |
| 7 | |
| 8 | _SCRIPT = """ |
| 9 | const esc = (s) => String(s ?? "").replace(/[&<>"']/g, |
| 10 | (c) => ({"&": "&", "<": "<", ">": ">", '"': """, "'": "'"}[c])); |
| 11 | |
| 12 | function fmtSize(n) { |
| 13 | const size = Number(n) || 0; |
| 14 | if (size > 1048576) return (size / 1048576).toFixed(1) + " MB"; |
| 15 | if (size > 1024) return (size / 1024).toFixed(1) + " KB"; |
| 16 | return size + " B"; |
| 17 | } |
| 18 | |
| 19 | function render(records) { |
| 20 | const rows = records.slice().reverse().map((f) => { |
| 21 | const mine = f.owner_id === OWNER_ID; |
| 22 | const pub = f.is_public === "true" ? '<span class="badge positive">public</span>' : ""; |
| 23 | const actions = mine |
| 24 | ? `<button class="btn ghost sm" data-id="${esc(f.id)}" data-act="share">` + |
| 25 | `${f.is_public === "true" ? "make private" : "make public"}</button>` + |
| 26 | `<button class="btn danger sm" data-id="${esc(f.id)}" data-act="delete">delete</button>` |
| 27 | : ""; |
| 28 | return `<tr><td><a href="/api/files/${esc(f.id)}">${esc(f.filename)}</a> ${pub}</td>` + |
| 29 | `<td class="num">${fmtSize(f.size)}</td><td>${esc(f.content_type)}</td>` + |
| 30 | `<td>${actions}</td></tr>`; |
| 31 | }); |
| 32 | document.getElementById("rows").innerHTML = |
| 33 | rows.join("") || '<tr><td colspan="4">No files yet.</td></tr>'; |
| 34 | } |
| 35 | |
| 36 | async function load() { |
| 37 | const res = await fetch("/collections/files/records?limit=500", |
| 38 | {credentials: "same-origin", headers: {accept: "application/json"}}); |
| 39 | const body = await res.json(); |
| 40 | render(body.records || []); |
| 41 | } |
| 42 | |
| 43 | document.getElementById("upload-form").addEventListener("submit", async (event) => { |
| 44 | event.preventDefault(); |
| 45 | const input = event.target.elements["file"]; |
| 46 | if (!input.files.length) return; |
| 47 | const data = new FormData(); |
| 48 | data.append("file", input.files[0]); |
| 49 | const res = await fetch("/api/files", {method: "POST", credentials: "same-origin", body: data}); |
| 50 | const body = await res.json(); |
| 51 | document.getElementById("form-error").textContent = res.ok ? "" : (body.error || "Upload failed"); |
| 52 | if (res.ok) { event.target.reset(); load(); } |
| 53 | }); |
| 54 | |
| 55 | document.getElementById("rows").addEventListener("click", async (event) => { |
| 56 | const button = event.target.closest("button"); |
| 57 | if (!button) return; |
| 58 | const id = button.dataset.id; |
| 59 | if (button.dataset.act === "delete") { |
| 60 | if (!confirm("Delete this file?")) return; |
| 61 | await fetch(`/api/files/${id}`, {method: "DELETE", credentials: "same-origin", |
| 62 | headers: {accept: "application/json"}}); |
| 63 | load(); |
| 64 | return; |
| 65 | } |
| 66 | const res = await fetch(`/collections/files/records/${id}`, |
| 67 | {credentials: "same-origin", headers: {accept: "application/json"}}); |
| 68 | const body = await res.json(); |
| 69 | const current = (body.record || {}).is_public === "true"; |
| 70 | await fetch(`/collections/files/records/${id}`, { |
| 71 | method: "PUT", credentials: "same-origin", |
| 72 | headers: {"content-type": "application/json", accept: "application/json"}, |
| 73 | body: JSON.stringify({is_public: current ? "false" : "true"}), |
| 74 | }); |
| 75 | load(); |
| 76 | }); |
| 77 | load(); |
| 78 | |
| 79 | // Realtime: auto-refresh when this collection changes (another tab, user, or agent). |
| 80 | (function () { |
| 81 | let _lt = null; |
| 82 | const reload = () => { clearTimeout(_lt); _lt = setTimeout(load, 150); }; |
| 83 | (function wait() { |
| 84 | if (window.dbbasicSubscribe) window.dbbasicSubscribe("files", reload); |
| 85 | else setTimeout(wait, 300); |
| 86 | })(); |
| 87 | })(); |
| 88 | """ |
| 89 | |
| 90 | |
| 91 | def GET(request): |
| 92 | identity = request.get("_identity", {}) |
| 93 | user_id = identity.get("user_id") |
| 94 | _logger.info("site_files served", user_id=user_id or "anonymous") |
| 95 | |
| 96 | if not user_id: |
| 97 | body = '<p class="hint"><a href="/login?next=/files">Sign in</a> to see your files.</p>' |
| 98 | script = "" |
| 99 | else: |
| 100 | body = """ |
| 101 | <form class="toolbar" id="upload-form"> |
| 102 | <input type="file" name="file" required class="grow"> |
| 103 | <button type="submit" class="btn primary">Upload</button> |
| 104 | <div class="error" id="form-error"></div> |
| 105 | </form> |
| 106 | <table> |
| 107 | <thead><tr><th>File</th><th class="num">Size</th><th>Type</th><th></th></tr></thead> |
| 108 | <tbody id="rows"><tr><td colspan="4">loading…</td></tr></tbody> |
| 109 | </table> |
| 110 | """ |
| 111 | script = f"<script>const OWNER_ID = {user_id!r};{_SCRIPT}</script>" |
| 112 | |
| 113 | who = ( |
| 114 | f"signed in as <strong>{user_id}</strong>" |
| 115 | if user_id |
| 116 | else '<a href="/login?next=/files">sign in</a>' |
| 117 | ) |
| 118 | html = f"""<!doctype html> |
| 119 | <html lang="en"> |
| 120 | <head> |
| 121 | <meta charset="utf-8"> |
| 122 | <meta name="viewport" content="width=device-width, initial-scale=1"> |
| 123 | <title>Files</title> |
| 124 | <link rel="stylesheet" href="/style"> |
| 125 | </head> |
| 126 | <body> |
| 127 | <div class="wrap"> |
| 128 | <header class="app"><h1>Files</h1><div class="who">{who}</div></header> |
| 129 | {body} |
| 130 | </div> |
| 131 | {script} |
| 132 | <script src="/nav"></script> |
| 133 | </body> |
| 134 | </html>""" |
| 135 | return {"content_type": "text/html; charset=utf-8", "body": html} |