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
profile.py · 15.1 KB · 358 lines
| 1 | """Public creator profile: bio/skills/experience + follow button + moderated |
| 2 | guestbook -- a faithful port of the source system's public profile page. |
| 3 | |
| 4 | Served through a site route like /u/{username} -> site_profile -- documented |
| 5 | here, not seeded, same precedent as app-notes' /notes/{note_id:uuid} and |
| 6 | app-forum's /forum/topics/{topic_id:uuid}. One difference from those: the |
| 7 | pattern segment here is plain {username}, NOT {username:uuid}. profiles.id is |
| 8 | the id of the account the profile belongs to (schemas/profiles.json: "one |
| 9 | profile per user"), and account ids in this codebase are not guaranteed to be |
| 10 | UUID-shaped (docs/permissions-model.md's own examples use plain ids like |
| 11 | "7") -- unlike most record ids here, which default to UUIDv4. So the route |
| 12 | pattern must accept any single path segment, not just a UUID one. There is |
| 13 | no separate "username" field or accounts collection in this codebase; the |
| 14 | path segment IS the account/profile id. Calling the route param "username" |
| 15 | matches the source system's URL shape even though what it captures is the |
| 16 | account id. |
| 17 | |
| 18 | The page is public read (see permissions/rules.json): anonymous visitors see |
| 19 | the profile and its approved guestbook comments. Only a signed-in visitor |
| 20 | gets the follow button, and only a signed-in visitor who is not the profile |
| 21 | owner gets one that does anything (following your own profile is not a |
| 22 | concept this package builds). The add-comment form is signed-in v1 only -- |
| 23 | see schemas/profile_comments.json and dbbasic-package.json for why anonymous |
| 24 | guestbook posting is deferred. |
| 25 | |
| 26 | Aggregation of the profile owner's other public content (articles, links, |
| 27 | notes, files, templates in the source) is a nice-to-have per the package |
| 28 | brief, not the core of this port. This page includes ONE such aggregation -- |
| 29 | recent public articles by this user, fetched opportunistically from |
| 30 | app-articles' collection -- and nothing else. It is opportunistic, not a |
| 31 | dependency: this package declares no dependency on app-articles in |
| 32 | dbbasic-package.json, and the fetch below fails silently (the section is |
| 33 | simply omitted) if that collection doesn't exist in this install. Notes, |
| 34 | links, files, and templates aggregation are left for a later slice -- see |
| 35 | dbbasic-package.json's deferred list. |
| 36 | |
| 37 | Followers/following (59): before this, the follow button above was the |
| 38 | whole story -- a visitor could follow someone but never SEE the social |
| 39 | graph (the audit's "profile drops the follow graph" finding). This is an |
| 40 | ordinary 59 `related` block over `follows` in each direction -- |
| 41 | `{collection: "follows", fk_field: "following_id"}` for followers, |
| 42 | `{collection: "follows", fk_field: "follower_id"}` for following, both |
| 43 | matched against PROFILE_ID -- mounted directly with window.dbbasicList's |
| 44 | `where` option (list.py) rather than through the views/site_routes system, |
| 45 | because this page is a bespoke object (see the routing note above), not a |
| 46 | `views` record; the compilation target is identical either way, a 58 |
| 47 | filtered read, just called straight from this page's own script instead |
| 48 | of through view_render.py's `related` block. |
| 49 | """ |
| 50 | |
| 51 | import re |
| 52 | |
| 53 | _RECORD_ID_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9_-]{0,127}$") |
| 54 | |
| 55 | _STYLE = """ |
| 56 | h1#name { font-size: 1.6rem; margin: 0 0 0.25rem; } |
| 57 | #meta { color: var(--muted); font-size: 0.85rem; margin-bottom: 1rem; } |
| 58 | .field-row { margin: 0.35rem 0; } |
| 59 | .field-row .label { color: var(--muted); font-size: 0.75rem; text-transform: uppercase; letter-spacing: 0.03em; } |
| 60 | .field-row .value { white-space: pre-wrap; word-break: break-word; } |
| 61 | #social a { display: inline-block; margin: 0.15rem 0.5rem 0.15rem 0; } |
| 62 | .owner-tools { margin: 1rem 0; display: none; gap: 0.5rem; flex-wrap: wrap; } |
| 63 | #follow-area { margin: 1rem 0; } |
| 64 | .follow-graph { display: grid; grid-template-columns: 1fr 1fr; gap: 1rem; margin: 1rem 0; } |
| 65 | .follow-graph-col h3 { font-size: 0.85rem; color: var(--muted); margin: 0 0 0.4rem; } |
| 66 | @media (max-width: 560px) { .follow-graph { grid-template-columns: 1fr; } } |
| 67 | .guestbook { margin-top: 2rem; } |
| 68 | .comment { border-top: 1px solid var(--line, #38384a); padding: 0.75rem 0; } |
| 69 | .comment .body { white-space: pre-wrap; word-break: break-word; } |
| 70 | .comment .meta { color: var(--muted); font-size: 0.75rem; margin-top: 0.25rem; } |
| 71 | .comment .pending-note { color: var(--muted); font-size: 0.75rem; font-style: italic; } |
| 72 | #commentformpanel { margin-top: 1rem; } |
| 73 | .articles-section { margin-top: 2rem; } |
| 74 | .articles-section ul { padding-left: 1.25rem; } |
| 75 | """ |
| 76 | |
| 77 | _SCRIPT = """ |
| 78 | const esc = (s) => String(s ?? "").replace(/[&<>"']/g, |
| 79 | (c) => ({"&": "&", "<": "<", ">": ">", '"': """, "'": "'"}[c])); |
| 80 | const el = (id) => document.getElementById(id); |
| 81 | let profile = null; |
| 82 | |
| 83 | function socialLinksHtml(raw) { |
| 84 | if (!raw) return ""; |
| 85 | let urls = []; |
| 86 | const trimmed = String(raw).trim(); |
| 87 | if (trimmed.startsWith("[")) { |
| 88 | try { urls = JSON.parse(trimmed); } catch (e) { urls = []; } |
| 89 | } |
| 90 | if (!urls.length) urls = trimmed.split(/\\r?\\n/).map((s) => s.trim()).filter(Boolean); |
| 91 | if (!urls.length) return ""; |
| 92 | return urls.map((u) => '<a href="' + esc(u) + '" target="_blank" rel="noopener noreferrer">' + esc(u) + '</a>').join(""); |
| 93 | } |
| 94 | |
| 95 | function renderProfile() { |
| 96 | el("name").textContent = profile.display_name || PROFILE_ID; |
| 97 | document.title = profile.display_name || PROFILE_ID; |
| 98 | el("bio").textContent = profile.bio || ""; |
| 99 | el("bio-row").style.display = profile.bio ? "block" : "none"; |
| 100 | |
| 101 | const rows = [ |
| 102 | ["skills", "Skills"], ["experience", "Experience"], ["location", "Location"], |
| 103 | ["education", "Education"], ["website", "Website"], |
| 104 | ]; |
| 105 | for (const [field, label] of rows) { |
| 106 | const row = el("row-" + field); |
| 107 | if (!row) continue; |
| 108 | const value = profile[field] || ""; |
| 109 | row.style.display = value ? "block" : "none"; |
| 110 | const valueEl = row.querySelector(".value"); |
| 111 | if (valueEl) valueEl.textContent = value; |
| 112 | } |
| 113 | |
| 114 | const social = socialLinksHtml(profile.social_links); |
| 115 | el("social-row").style.display = social ? "block" : "none"; |
| 116 | el("social").innerHTML = social; |
| 117 | |
| 118 | const mine = VIEWER_ID && profile.owner_id === VIEWER_ID; |
| 119 | el("owner-tools").style.display = mine ? "flex" : "none"; |
| 120 | } |
| 121 | |
| 122 | async function loadProfile() { |
| 123 | const res = await fetch(`/collections/profiles/records/${encodeURIComponent(PROFILE_ID)}`, |
| 124 | {credentials: "same-origin", headers: {accept: "application/json"}}); |
| 125 | if (!res.ok) { |
| 126 | el("body").innerHTML = '<p class="hint">No profile at this address.</p>'; |
| 127 | el("follow-area").style.display = "none"; |
| 128 | el("guestbook").style.display = "none"; |
| 129 | el("articles-section").style.display = "none"; |
| 130 | return; |
| 131 | } |
| 132 | const body = await res.json(); |
| 133 | profile = body.record || body; |
| 134 | renderProfile(); |
| 135 | loadFollowState(); |
| 136 | loadFollowGraph(); |
| 137 | loadComments(); |
| 138 | loadArticles(); |
| 139 | } |
| 140 | |
| 141 | // --- Follow / unfollow ----------------------------------------------- |
| 142 | let myFollowEdgeId = null; |
| 143 | |
| 144 | async function loadFollowState() { |
| 145 | if (!VIEWER_ID || VIEWER_ID === PROFILE_ID) { el("follow-area").style.display = "none"; return; } |
| 146 | const res = await fetch("/collections/follows/records?limit=500", |
| 147 | {credentials: "same-origin", headers: {accept: "application/json"}}); |
| 148 | if (!res.ok) return; |
| 149 | const body = await res.json(); |
| 150 | const mine = (body.records || []).find( |
| 151 | (r) => r.follower_id === VIEWER_ID && r.following_id === PROFILE_ID); |
| 152 | myFollowEdgeId = mine ? mine.id : null; |
| 153 | renderFollowButton(); |
| 154 | } |
| 155 | |
| 156 | function renderFollowButton() { |
| 157 | el("follow-area").style.display = "block"; |
| 158 | el("follow-btn").textContent = myFollowEdgeId ? "Unfollow" : "Follow"; |
| 159 | } |
| 160 | |
| 161 | // 59 related blocks over `follows`, one per direction, both matched |
| 162 | // against PROFILE_ID -- see the module docstring's Followers/following |
| 163 | // note. window.dbbasicList's `where` option is 58's real server-side |
| 164 | // filter (list.py), the exact compilation `related` uses in view_render.py. |
| 165 | function loadFollowGraph() { |
| 166 | if (!window.dbbasicList) return; |
| 167 | window.dbbasicList("follows", { |
| 168 | mount: "#followers-list", |
| 169 | where: {following_id: PROFILE_ID}, |
| 170 | title: (r) => r.follower_id, |
| 171 | }); |
| 172 | window.dbbasicList("follows", { |
| 173 | mount: "#following-list", |
| 174 | where: {follower_id: PROFILE_ID}, |
| 175 | title: (r) => r.following_id, |
| 176 | }); |
| 177 | } |
| 178 | |
| 179 | el("follow-btn").addEventListener("click", async () => { |
| 180 | if (myFollowEdgeId) { |
| 181 | await fetch(`/collections/follows/records/${encodeURIComponent(myFollowEdgeId)}`, |
| 182 | {method: "DELETE", credentials: "same-origin", headers: {accept: "application/json"}}); |
| 183 | myFollowEdgeId = null; |
| 184 | } else { |
| 185 | const res = await fetch("/collections/follows/records", { |
| 186 | method: "POST", credentials: "same-origin", |
| 187 | headers: {"content-type": "application/json", accept: "application/json"}, |
| 188 | body: JSON.stringify({follower_id: VIEWER_ID, following_id: PROFILE_ID}), |
| 189 | }); |
| 190 | const body = await res.json(); |
| 191 | if (res.ok) myFollowEdgeId = (body.record || body).id; |
| 192 | } |
| 193 | renderFollowButton(); |
| 194 | }); |
| 195 | |
| 196 | // --- Guestbook ---------------------------------------------------------- |
| 197 | function commentNode(c) { |
| 198 | const mine = VIEWER_ID && c.owner_id === VIEWER_ID; |
| 199 | const pendingNote = (mine && c.status !== "approved") |
| 200 | ? '<div class="pending-note">' + esc(c.status) + " -- only you can see this until it is approved</div>" |
| 201 | : ""; |
| 202 | return '<div class="comment">' |
| 203 | + '<div class="body">' + esc(c.content) + '</div>' |
| 204 | + '<div class="meta">' + esc(c.author_name || (mine ? "you" : "")) + " · " + esc(c.created_at || "") + '</div>' |
| 205 | + pendingNote |
| 206 | + '</div>'; |
| 207 | } |
| 208 | |
| 209 | async function loadComments() { |
| 210 | const res = await fetch("/collections/profile_comments/records?limit=500", |
| 211 | {credentials: "same-origin", headers: {accept: "application/json"}}); |
| 212 | if (!res.ok) return; |
| 213 | const body = await res.json(); |
| 214 | const mine = (body.records || []).filter((c) => c.profile_id === PROFILE_ID); |
| 215 | const visible = mine.filter((c) => c.status === "approved" || (VIEWER_ID && c.owner_id === VIEWER_ID)); |
| 216 | el("comments").innerHTML = visible.length |
| 217 | ? visible.map(commentNode).join("") |
| 218 | : '<p class="hint">No guestbook comments yet.</p>'; |
| 219 | } |
| 220 | |
| 221 | async function initCommentForm() { |
| 222 | await window.dbbasicForm("profile_comments", { |
| 223 | mount: "#commentformmount", owner: VIEWER_ID, |
| 224 | onSaved: () => { |
| 225 | const box = document.querySelector('#commentformmount textarea[name="content"]'); |
| 226 | if (box) box.value = ""; |
| 227 | loadComments(); |
| 228 | }, |
| 229 | }); |
| 230 | // profile_id is a required relation field on profile_comments; the generic |
| 231 | // form generator has no "prefill and lock a field to the page context" |
| 232 | // hook, so this page sets and hides it after render instead of building a |
| 233 | // bespoke create form for one field -- same trade-off app-forum's |
| 234 | // forum_topic.py makes for forum_replies.topic_id. |
| 235 | const profileField = document.querySelector('#commentformmount select[name="profile_id"]'); |
| 236 | if (profileField) { |
| 237 | profileField.value = PROFILE_ID; |
| 238 | const wrapper = profileField.closest(".field"); |
| 239 | if (wrapper) wrapper.dataset.hidden = "true"; |
| 240 | } |
| 241 | } |
| 242 | |
| 243 | // --- Recent public articles (opportunistic, no hard dependency) -------- |
| 244 | async function loadArticles() { |
| 245 | let res; |
| 246 | try { |
| 247 | res = await fetch("/collections/articles/records?limit=500", |
| 248 | {credentials: "same-origin", headers: {accept: "application/json"}}); |
| 249 | } catch (e) { el("articles-section").style.display = "none"; return; } |
| 250 | if (!res.ok) { el("articles-section").style.display = "none"; return; } |
| 251 | const body = await res.json(); |
| 252 | const mine = (body.records || []).filter( |
| 253 | (a) => a.owner_id === PROFILE_ID && a.is_public === "true"); |
| 254 | if (!mine.length) { el("articles-section").style.display = "none"; return; } |
| 255 | el("articles-section").style.display = "block"; |
| 256 | el("articles-list").innerHTML = mine.slice(0, 10) |
| 257 | .map((a) => '<li><a href="/articles/' + esc(a.id) + '">' + esc(a.title) + '</a></li>') |
| 258 | .join(""); |
| 259 | } |
| 260 | |
| 261 | loadProfile(); |
| 262 | if (VIEWER_ID) initCommentForm(); |
| 263 | |
| 264 | // Realtime: auto-refresh when any of these collections change. |
| 265 | (function () { |
| 266 | let _lt = null; |
| 267 | const reload = () => { clearTimeout(_lt); _lt = setTimeout(loadProfile, 150); }; |
| 268 | (function wait() { |
| 269 | if (window.dbbasicSubscribe) { |
| 270 | window.dbbasicSubscribe("profiles", reload); |
| 271 | window.dbbasicSubscribe("follows", reload); |
| 272 | window.dbbasicSubscribe("profile_comments", reload); |
| 273 | } else setTimeout(wait, 300); |
| 274 | })(); |
| 275 | })(); |
| 276 | """ |
| 277 | |
| 278 | |
| 279 | def GET(request): |
| 280 | username = str(request.get("username") or "").strip() |
| 281 | if username and not _RECORD_ID_RE.fullmatch(username): |
| 282 | username = "" |
| 283 | identity = request.get("_identity", {}) |
| 284 | user_id = identity.get("user_id") |
| 285 | _logger.info("site_profile served", username=username or "missing", |
| 286 | user_id=user_id or "anonymous") |
| 287 | |
| 288 | if not username: |
| 289 | return { |
| 290 | "content_type": "text/html; charset=utf-8", |
| 291 | "body": "<p>Profile not found.</p>", |
| 292 | "status": 404, |
| 293 | } |
| 294 | |
| 295 | who = ( |
| 296 | f"signed in as <strong>{user_id}</strong>" |
| 297 | if user_id |
| 298 | else f'<a href="/login?next=/u/{username}">sign in</a>' |
| 299 | ) |
| 300 | comment_form_html = ( |
| 301 | '<div id="commentformmount"></div>' |
| 302 | if user_id |
| 303 | else f'<p class="hint"><a href="/login?next=/u/{username}">Sign in</a> to leave a guestbook comment.</p>' |
| 304 | ) |
| 305 | html = f"""<!doctype html> |
| 306 | <html lang="en"> |
| 307 | <head> |
| 308 | <meta charset="utf-8"> |
| 309 | <meta name="viewport" content="width=device-width, initial-scale=1"> |
| 310 | <title>Profile</title> |
| 311 | <link rel="stylesheet" href="/style"> |
| 312 | <style>{_STYLE}</style> |
| 313 | </head> |
| 314 | <body> |
| 315 | <div class="wrap narrow"> |
| 316 | <header class="app"><a href="/">DBBASIC</a><div class="who">{who}</div></header> |
| 317 | <div id="body"> |
| 318 | <h1 id="name">loading…</h1> |
| 319 | <div class="owner-tools" id="owner-tools"> |
| 320 | <a class="btn" href="/profile/edit">Edit Profile</a> |
| 321 | </div> |
| 322 | <div class="field-row" id="bio-row" style="display:none"> |
| 323 | <div id="bio"></div> |
| 324 | </div> |
| 325 | <div class="field-row" id="row-skills" style="display:none"><div class="label">Skills</div><div class="value"></div></div> |
| 326 | <div class="field-row" id="row-experience" style="display:none"><div class="label">Experience</div><div class="value"></div></div> |
| 327 | <div class="field-row" id="row-location" style="display:none"><div class="label">Location</div><div class="value"></div></div> |
| 328 | <div class="field-row" id="row-education" style="display:none"><div class="label">Education</div><div class="value"></div></div> |
| 329 | <div class="field-row" id="row-website" style="display:none"><div class="label">Website</div><div class="value"></div></div> |
| 330 | <div class="field-row" id="social-row" style="display:none"><div class="label">Links</div><div id="social"></div></div> |
| 331 | </div> |
| 332 | <div id="follow-area" style="display:none"> |
| 333 | <button class="btn primary" id="follow-btn">Follow</button> |
| 334 | </div> |
| 335 | <div class="follow-graph"> |
| 336 | <div class="follow-graph-col"><h3>Followers</h3><div id="followers-list"></div></div> |
| 337 | <div class="follow-graph-col"><h3>Following</h3><div id="following-list"></div></div> |
| 338 | </div> |
| 339 | <div class="articles-section" id="articles-section" style="display:none"> |
| 340 | <h3>Recent Public Articles</h3> |
| 341 | <ul id="articles-list"></ul> |
| 342 | </div> |
| 343 | <div class="guestbook" id="guestbook"> |
| 344 | <h3>Guestbook</h3> |
| 345 | <div id="comments"><div class="state">loading…</div></div> |
| 346 | <div id="commentformpanel"> |
| 347 | {comment_form_html} |
| 348 | </div> |
| 349 | </div> |
| 350 | </div> |
| 351 | <script>const PROFILE_ID = {username!r}; const VIEWER_ID = {(user_id or "")!r};</script> |
| 352 | <script src="/list"></script> |
| 353 | <script src="/form"></script> |
| 354 | <script>{_SCRIPT}</script> |
| 355 | <script src="/nav"></script> |
| 356 | </body> |
| 357 | </html>""" |
| 358 | return {"content_type": "text/html; charset=utf-8", "body": html} |