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

9 downloads

Install on DigitalOcean 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.

Daniel Quellhorst Changelog for this batch. 65ef78d 3 hours, 49 minutes ago History
profile.py · 15.4 KB · 361 lines
1"""Public creator profile: bio/skills/experience + follow button + moderated
2guestbook -- a faithful port of the source system's public profile page.
3
4Served through a site route like /u/{username} -> site_profile -- documented
5here, not seeded, same precedent as app-notes' /notes/{note_id:uuid} and
6app-forum's /forum/topics/{topic_id:uuid}. One difference from those: the
7pattern segment here is plain {username}, NOT {username:uuid}. profiles.id is
8the id of the account the profile belongs to (schemas/profiles.json: "one
9profile per user"), and account ids in this codebase are not guaranteed to be
10UUID-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
12pattern must accept any single path segment, not just a UUID one. There is
13no separate "username" field or accounts collection in this codebase; the
14path segment IS the account/profile id. Calling the route param "username"
15matches the source system's URL shape even though what it captures is the
16account id.
17
18The page is public read (see permissions/rules.json): anonymous visitors see
19the profile and its approved guestbook comments. Only a signed-in visitor
20gets the follow button, and only a signed-in visitor who is not the profile
21owner gets one that does anything (following your own profile is not a
22concept this package builds). The add-comment form is signed-in v1 only --
23see schemas/profile_comments.json and dbbasic-package.json for why anonymous
24guestbook posting is deferred.
25
26Aggregation of the profile owner's other public content (articles, links,
27notes, files, templates in the source) is a nice-to-have per the package
28brief, not the core of this port. This page includes ONE such aggregation --
29recent public articles by this user, fetched opportunistically from
30app-articles' collection -- and nothing else. It is opportunistic, not a
31dependency: this package declares no dependency on app-articles in
32dbbasic-package.json, and the fetch below fails silently (the section is
33simply omitted) if that collection doesn't exist in this install. Notes,
34links, files, and templates aggregation are left for a later slice -- see
35dbbasic-package.json's deferred list.
36
37Followers/following (59): before this, the follow button above was the
38whole story -- a visitor could follow someone but never SEE the social
39graph (the audit's "profile drops the follow graph" finding). This is an
40ordinary 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
43matched against PROFILE_ID -- mounted directly with window.dbbasicList's
44`where` option (list.py) rather than through the views/site_routes system,
45because 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
47filtered read, just called straight from this page's own script instead
48of through view_render.py's `related` block.
49"""
50
51import re
52
53_RECORD_ID_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9_-]{0,127}$")
54
55_STYLE = """
56h1#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 = """
78const esc = (s) => String(s ?? "").replace(/[&<>"']/g,
79 (c) => ({"&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;"}[c]));
80const el = (id) => document.getElementById(id);
81let profile = null;
82
83function 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
95function 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
122async 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 -----------------------------------------------
142let myFollowEdgeId = null;
143
144async 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
156function 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.
165function 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
179el("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 ----------------------------------------------------------
197function 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" : "")) + " &middot; " + esc(c.created_at || "") + '</div>'
205 + pendingNote
206 + '</div>';
207}
208
209async 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 // The server decides which comments come back (public reads are approved
216 // rows only) and hides `status` from everyone but a comment's author, so a
217 // row without it is one the rules already let this viewer see.
218 const visible = mine.filter((c) => !("status" in c) || c.status === "approved" || (VIEWER_ID && c.owner_id === VIEWER_ID));
219 el("comments").innerHTML = visible.length
220 ? visible.map(commentNode).join("")
221 : '<p class="hint">No guestbook comments yet.</p>';
222}
223
224async function initCommentForm() {
225 await window.dbbasicForm("profile_comments", {
226 mount: "#commentformmount", owner: VIEWER_ID,
227 onSaved: () => {
228 const box = document.querySelector('#commentformmount textarea[name="content"]');
229 if (box) box.value = "";
230 loadComments();
231 },
232 });
233 // profile_id is a required relation field on profile_comments; the generic
234 // form generator has no "prefill and lock a field to the page context"
235 // hook, so this page sets and hides it after render instead of building a
236 // bespoke create form for one field -- same trade-off app-forum's
237 // forum_topic.py makes for forum_replies.topic_id.
238 const profileField = document.querySelector('#commentformmount select[name="profile_id"]');
239 if (profileField) {
240 profileField.value = PROFILE_ID;
241 const wrapper = profileField.closest(".field");
242 if (wrapper) wrapper.dataset.hidden = "true";
243 }
244}
245
246// --- Recent public articles (opportunistic, no hard dependency) --------
247async function loadArticles() {
248 let res;
249 try {
250 res = await fetch("/collections/articles/records?limit=500",
251 {credentials: "same-origin", headers: {accept: "application/json"}});
252 } catch (e) { el("articles-section").style.display = "none"; return; }
253 if (!res.ok) { el("articles-section").style.display = "none"; return; }
254 const body = await res.json();
255 const mine = (body.records || []).filter(
256 (a) => a.owner_id === PROFILE_ID && a.is_public === "true");
257 if (!mine.length) { el("articles-section").style.display = "none"; return; }
258 el("articles-section").style.display = "block";
259 el("articles-list").innerHTML = mine.slice(0, 10)
260 .map((a) => '<li><a href="/articles/' + esc(a.id) + '">' + esc(a.title) + '</a></li>')
261 .join("");
262}
263
264loadProfile();
265if (VIEWER_ID) initCommentForm();
266
267// Realtime: auto-refresh when any of these collections change.
268(function () {
269 let _lt = null;
270 const reload = () => { clearTimeout(_lt); _lt = setTimeout(loadProfile, 150); };
271 (function wait() {
272 if (window.dbbasicSubscribe) {
273 window.dbbasicSubscribe("profiles", reload);
274 window.dbbasicSubscribe("follows", reload);
275 window.dbbasicSubscribe("profile_comments", reload);
276 } else setTimeout(wait, 300);
277 })();
278})();
279"""
280
281
282def GET(request):
283 username = str(request.get("username") or "").strip()
284 if username and not _RECORD_ID_RE.fullmatch(username):
285 username = ""
286 identity = request.get("_identity", {})
287 user_id = identity.get("user_id")
288 _logger.info("site_profile served", username=username or "missing",
289 user_id=user_id or "anonymous")
290
291 if not username:
292 return {
293 "content_type": "text/html; charset=utf-8",
294 "body": "<p>Profile not found.</p>",
295 "status": 404,
296 }
297
298 who = (
299 f"signed in as <strong>{user_id}</strong>"
300 if user_id
301 else f'<a href="/login?next=/u/{username}">sign in</a>'
302 )
303 comment_form_html = (
304 '<div id="commentformmount"></div>'
305 if user_id
306 else f'<p class="hint"><a href="/login?next=/u/{username}">Sign in</a> to leave a guestbook comment.</p>'
307 )
308 html = f"""<!doctype html>
309<html lang="en">
310<head>
311<meta charset="utf-8">
312<meta name="viewport" content="width=device-width, initial-scale=1">
313<title>Profile</title>
314<link rel="stylesheet" href="/style">
315<style>{_STYLE}</style>
316</head>
317<body>
318<div class="wrap narrow">
319<header class="app"><a href="/">DBBASIC</a><div class="who">{who}</div></header>
320<div id="body">
321<h1 id="name">loading&hellip;</h1>
322<div class="owner-tools" id="owner-tools">
323<a class="btn" href="/profile/edit">Edit Profile</a>
324</div>
325<div class="field-row" id="bio-row" style="display:none">
326<div id="bio"></div>
327</div>
328<div class="field-row" id="row-skills" style="display:none"><div class="label">Skills</div><div class="value"></div></div>
329<div class="field-row" id="row-experience" style="display:none"><div class="label">Experience</div><div class="value"></div></div>
330<div class="field-row" id="row-location" style="display:none"><div class="label">Location</div><div class="value"></div></div>
331<div class="field-row" id="row-education" style="display:none"><div class="label">Education</div><div class="value"></div></div>
332<div class="field-row" id="row-website" style="display:none"><div class="label">Website</div><div class="value"></div></div>
333<div class="field-row" id="social-row" style="display:none"><div class="label">Links</div><div id="social"></div></div>
334</div>
335<div id="follow-area" style="display:none">
336<button class="btn primary" id="follow-btn">Follow</button>
337</div>
338<div class="follow-graph">
339<div class="follow-graph-col"><h3>Followers</h3><div id="followers-list"></div></div>
340<div class="follow-graph-col"><h3>Following</h3><div id="following-list"></div></div>
341</div>
342<div class="articles-section" id="articles-section" style="display:none">
343<h3>Recent Public Articles</h3>
344<ul id="articles-list"></ul>
345</div>
346<div class="guestbook" id="guestbook">
347<h3>Guestbook</h3>
348<div id="comments"><div class="state">loading&hellip;</div></div>
349<div id="commentformpanel">
350{comment_form_html}
351</div>
352</div>
353</div>
354<script>const PROFILE_ID = {username!r}; const VIEWER_ID = {(user_id or "")!r};</script>
355<script src="/list"></script>
356<script src="/form"></script>
357<script>{_SCRIPT}</script>
358<script src="/nav"></script>
359</body>
360</html>"""
361 return {"content_type": "text/html; charset=utf-8", "body": html}