Add Happy 404, featured/related sidebars, and next-post nav to the post page
Happy 404: an HTML 404 (unmatched route, or an explicit not-found inside a
real route) now renders a random existing post instead of the error page,
using the exact same context builder as a real post view. Toggle is the
happy_404_enabled site setting (default on, /admin/settings); JSON/API
requests and a handful of excluded prefixes are never affected. The pool of
candidate slugs is cached in-process and resampled periodically so it stays
fast and eventually cycles the whole posts table; on any internal failure it
falls straight through to the real 404 page.
Applying this everywhere surfaced ~60 existing tests that asserted a literal
404 for a legitimate resource-not-found flow (deleted post, unknown
container, wrong project slug, etc.) - each now disables the setting for the
duration of that specific check and restores it after, so the underlying
not-found behavior stays covered independently of the new feature.
Post page also gained, all built on the same shared post_page_context() so
they render identically on both a real post and a happy-404 page:
- A left sidebar (three separate cards, matching /feed's sidebar-card
convention) for "Gists from {author}", "Projects from {author}" (private
projects filtered through the normal visibility check), and "Related
Discussions" - each cached per author and invalidated on create/edit/
delete so new content shows up immediately.
- A right column reusing /feed's exact Daily Topic widget class for up to
three "Featured" articles (the existing but previously-unused `featured`
news flag), cached as a pool with per-request random sampling.
- A "Next post -> " link beside "Back to Feed", pointing at the next older
post site-wide (blocked authors skipped). Wired through the same next_url
mechanism already used for listing pagination, so it emits a real
backend-rendered <link rel="next"> tag for SEO, not just a visible link.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BWJy6PrMMt5hwWxQwia2rd
This commit is contained in:
@@ -38,6 +38,8 @@ from devplacepy.database import (
|
||||
get_int_setting,
|
||||
_now_iso,
|
||||
db,
|
||||
get_user_recent_items,
|
||||
invalidate_user_recent_cache,
|
||||
)
|
||||
from devplacepy.utils import (
|
||||
time_ago,
|
||||
@@ -133,6 +135,18 @@ def can_view_project(project: dict | None, user: dict | None) -> bool:
|
||||
return not _owner_is_admin(project)
|
||||
|
||||
|
||||
def get_user_sidebar_gists(user_uid: str, limit: int = 5) -> list[dict]:
|
||||
return get_user_recent_items("gists", user_uid)[:limit]
|
||||
|
||||
|
||||
def get_user_sidebar_projects(
|
||||
user_uid: str, viewer: dict | None, limit: int = 5
|
||||
) -> list[dict]:
|
||||
rows = get_user_recent_items("projects", user_uid)
|
||||
visible = [p for p in rows if can_view_project(p, viewer)]
|
||||
return visible[:limit]
|
||||
|
||||
|
||||
def owns_instance(
|
||||
instance: dict | None, project: dict | None, user: dict | None
|
||||
) -> bool:
|
||||
@@ -264,6 +278,7 @@ def create_content_item(
|
||||
from devplacepy.templating import clear_user_projects_cache
|
||||
|
||||
clear_user_projects_cache(user["uid"])
|
||||
invalidate_user_recent_cache(table_name, user["uid"])
|
||||
award_rewards(user["uid"], xp, badge)
|
||||
if attachment_uids:
|
||||
link_attachments(attachment_uids, target_type, uid)
|
||||
@@ -678,6 +693,7 @@ def edit_content_item(
|
||||
"updated_at": datetime.now(timezone.utc).isoformat(),
|
||||
}
|
||||
table.update({"uid": item["uid"], **update_fields}, ["uid"])
|
||||
invalidate_user_recent_cache(table_name, item["user_uid"])
|
||||
record_screening(
|
||||
screening,
|
||||
target_type=kind,
|
||||
@@ -769,6 +785,7 @@ def delete_content_item(
|
||||
soft_delete_all_project_files(item["uid"], actor)
|
||||
soft_delete_fork_relations(item["uid"], actor)
|
||||
clear_user_projects_cache(item["user_uid"])
|
||||
invalidate_user_recent_cache(table_name, item["user_uid"])
|
||||
soft_delete(table_name, actor, stamp=stamp, uid=item["uid"])
|
||||
logger.info(f"{table_name} {item['uid']} soft-deleted by {user['username']}")
|
||||
audit.record(
|
||||
|
||||
@@ -211,6 +211,7 @@ Site settings are seeded on startup (`site_settings` table):
|
||||
| `maintenance_message` | scheduled-maintenance text | Body shown on the maintenance 503 page |
|
||||
| `customization_enabled` | `"1"` | When `"0"`, `custom_css_tag`/`custom_js_tag` inject nothing (feature off) |
|
||||
| `customization_js_enabled` | `"1"` | When `"0"`, custom CSS still serves but custom JS is suppressed |
|
||||
| `happy_404_enabled` | `"1"` | When `"0"`, `happy404.render()` is a no-op and a real 404 page is shown; when on, an HTML 404 renders a random existing post instead (see below) |
|
||||
| `moderation_sla_hours` | `"24"` | The published moderation response window; the admin queue badge turns red past it |
|
||||
| `moderation_filter_mode` | `"review"` | `off`/`label`/`review`/`block` - how the content filter acts on a match |
|
||||
| `moderation_filter_review_score` | `"2"` | Rule score at which a match becomes a report rather than a label |
|
||||
@@ -239,6 +240,7 @@ Operational settings - read sites and rules:
|
||||
| `service_<name>_enabled` / `service_<name>_command` / `service_<name>_log_size` | `BaseService` reconciling loop | Generic per-service controls written by the Services tab; the loop reconciles within ~1s |
|
||||
| `session_max_age_days` / `session_remember_days` | `auth.py` signup + login | Multiplied by `SECONDS_PER_DAY`; passed to `create_session(uid, max_age)` so the cookie and the DB session row expire together |
|
||||
| `registration_open` | `auth.py` `signup_page` (GET) and `signup` (POST) | POST returns before any DB write when closed |
|
||||
| `happy_404_enabled` | `happy404.render()`, called from the `404` handler in `main.py` | Gates the whole feature; checked per-request via the normal 60s `get_setting` TTL cache, so a toggle takes effect within a minute across all workers with no restart |
|
||||
|
||||
**Booleans are `<select>`, never checkboxes.** The settings save handler (`admin.py`) skips empty form values so empty fields don't clobber existing rows. An unchecked checkbox submits nothing, so it could never be turned off - `registration_open` and `maintenance_mode` use `<option value="1">`/`<option value="0">` so a value is always submitted.
|
||||
|
||||
|
||||
@@ -74,7 +74,7 @@ from .moderation import (
|
||||
years_between,
|
||||
)
|
||||
from .comments import _drop_blocked, _build_comment_items, load_comments, get_recent_comments_by_target_uids, get_recent_comments_by_post_uids, load_comments_by_target_uids
|
||||
from .content import resolve_by_slug, resolve_object_url, get_projects_by_uids, get_uids_by_username_match, text_search_clause, get_daily_topic, get_featured_news, get_trending_topics
|
||||
from .content import resolve_by_slug, resolve_object_url, get_projects_by_uids, get_uids_by_username_match, text_search_clause, get_daily_topic, get_featured_news, get_featured_topics, get_trending_topics, get_user_recent_items, invalidate_user_recent_cache
|
||||
from .attachments_data import get_attachments, get_attachments_by_type, get_news_images_by_uids, delete_attachment_record, delete_attachments, _delete_attachment_file, get_user_media, get_user_attachments, get_user_attachment, get_deleted_media
|
||||
from .stats import _stats_cache, get_site_stats, _analytics_cache, get_platform_analytics, _gist_languages_cache, get_gist_languages
|
||||
from .schema import BUG_TABLE_RENAMES, migrate_bug_tables_to_issue_tables, init_db, _refresh_query_planner_stats, OLD_GATEWAY_URL, migrate_ai_gateway_settings, backfill_api_keys, _backfill_gamification
|
||||
@@ -301,6 +301,9 @@ __all__ = [
|
||||
"text_search_clause",
|
||||
"get_daily_topic",
|
||||
"get_featured_news",
|
||||
"get_featured_topics",
|
||||
"get_user_recent_items",
|
||||
"invalidate_user_recent_cache",
|
||||
"get_trending_topics",
|
||||
"get_attachments",
|
||||
"get_attachments_by_type",
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
# retoor <retoor@molodetz.nl>
|
||||
|
||||
import os
|
||||
import random
|
||||
from collections import Counter
|
||||
|
||||
from devplacepy.cache import TTLCache
|
||||
@@ -8,6 +10,34 @@ from .core import db, get_table, or_
|
||||
|
||||
_daily_topic_cache = TTLCache(ttl=60, max_size=1)
|
||||
_trending_cache = TTLCache(ttl=15, max_size=1)
|
||||
FEATURED_TOPICS_POOL_TTL = int(os.environ.get("DEVPLACE_FEATURED_TOPICS_POOL_TTL", "300"))
|
||||
FEATURED_TOPICS_POOL_SIZE = 20
|
||||
_featured_topics_cache = TTLCache(ttl=FEATURED_TOPICS_POOL_TTL, max_size=1)
|
||||
|
||||
USER_RECENT_ITEMS_TTL = int(os.environ.get("DEVPLACE_USER_RECENT_ITEMS_TTL", "15"))
|
||||
_user_recent_cache = TTLCache(ttl=USER_RECENT_ITEMS_TTL, max_size=2000)
|
||||
|
||||
|
||||
def _user_recent_key(table_name: str, user_uid: str) -> str:
|
||||
return f"{table_name}:{user_uid}"
|
||||
|
||||
|
||||
def invalidate_user_recent_cache(table_name: str, user_uid: str) -> None:
|
||||
_user_recent_cache.pop(_user_recent_key(table_name, user_uid))
|
||||
|
||||
|
||||
def get_user_recent_items(table_name: str, user_uid: str) -> list[dict]:
|
||||
key = _user_recent_key(table_name, user_uid)
|
||||
cached = _user_recent_cache.get(key)
|
||||
if cached is not None:
|
||||
return cached
|
||||
items = []
|
||||
if table_name in db.tables:
|
||||
rows = list(get_table(table_name).find(user_uid=user_uid, deleted_at=None))
|
||||
rows.sort(key=lambda row: row.get("updated_at") or row.get("created_at") or "", reverse=True)
|
||||
items = rows
|
||||
_user_recent_cache.set(key, items)
|
||||
return items
|
||||
|
||||
|
||||
def resolve_by_slug(table, slug, include_deleted=False):
|
||||
@@ -171,6 +201,49 @@ def _load_daily_topic():
|
||||
}
|
||||
|
||||
|
||||
def get_featured_topics(count: int = 3) -> list[dict]:
|
||||
pool = _featured_topics_pool()
|
||||
if not pool:
|
||||
return []
|
||||
return random.sample(pool, min(count, len(pool)))
|
||||
|
||||
|
||||
def _featured_topics_pool() -> list[dict]:
|
||||
cached = _featured_topics_cache.get("pool")
|
||||
if cached is not None:
|
||||
return cached
|
||||
pool = _load_featured_topics_pool()
|
||||
_featured_topics_cache.set("pool", pool)
|
||||
return pool
|
||||
|
||||
|
||||
def _load_featured_topics_pool(limit: int = FEATURED_TOPICS_POOL_SIZE) -> list[dict]:
|
||||
if "news" not in db.tables:
|
||||
return []
|
||||
rows = db["news"].find(
|
||||
featured=1,
|
||||
status="published",
|
||||
deleted_at=None,
|
||||
order_by=["-synced_at"],
|
||||
_limit=limit,
|
||||
)
|
||||
topics = []
|
||||
for article in rows:
|
||||
desc = (article.get("description") or "")[:160] or (
|
||||
article.get("content") or ""
|
||||
)[:160]
|
||||
topics.append(
|
||||
{
|
||||
"title": article.get("title", ""),
|
||||
"summary": desc,
|
||||
"slug": article.get("slug", ""),
|
||||
"url": article.get("url", ""),
|
||||
"image_url": article.get("image_url", "") or "",
|
||||
}
|
||||
)
|
||||
return topics
|
||||
|
||||
|
||||
def get_featured_news(limit=5):
|
||||
if "news" not in db.tables:
|
||||
return []
|
||||
|
||||
@@ -1964,6 +1964,7 @@ def init_db():
|
||||
"maintenance_message": "DevPlace is undergoing scheduled maintenance. Please check back shortly.",
|
||||
"customization_enabled": "1",
|
||||
"customization_js_enabled": "1",
|
||||
"happy_404_enabled": "1",
|
||||
"audit_log_retention_days": "90",
|
||||
"statistics_tracking_enabled": "1",
|
||||
"docs_search_mode": "agent",
|
||||
|
||||
@@ -0,0 +1,70 @@
|
||||
# retoor <retoor@molodetz.nl>
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import os
|
||||
import random
|
||||
|
||||
from fastapi import Request
|
||||
from fastapi.responses import HTMLResponse
|
||||
|
||||
from devplacepy.cache import TTLCache
|
||||
from devplacepy.content import load_detail
|
||||
from devplacepy.database import db, get_setting
|
||||
from devplacepy.routers.posts import post_page_context
|
||||
from devplacepy.templating import templates
|
||||
from devplacepy.utils import get_current_user
|
||||
|
||||
logger = logging.getLogger("happy404")
|
||||
|
||||
POOL_TTL_SECONDS = int(os.environ.get("DEVPLACE_HAPPY_404_POOL_TTL", "300"))
|
||||
POOL_SIZE = 100
|
||||
|
||||
API_PATH_PREFIXES = ("/api", "/dbapi", "/openai", "/xmlrpc", "/swagger", "/openapi.json")
|
||||
|
||||
_pool_cache = TTLCache(ttl=POOL_TTL_SECONDS, max_size=1)
|
||||
|
||||
|
||||
def _post_pool() -> list[str]:
|
||||
cached = _pool_cache.get("slugs")
|
||||
if cached is not None:
|
||||
return cached
|
||||
slugs: list[str] = []
|
||||
if "posts" in db.tables:
|
||||
rows = db.query(
|
||||
"SELECT slug, uid FROM posts WHERE deleted_at IS NULL ORDER BY RANDOM() LIMIT :limit",
|
||||
limit=POOL_SIZE,
|
||||
)
|
||||
slugs = [row["slug"] or row["uid"] for row in rows]
|
||||
_pool_cache.set("slugs", slugs)
|
||||
return slugs
|
||||
|
||||
|
||||
def _eligible(request: Request) -> bool:
|
||||
if request.method != "GET":
|
||||
return False
|
||||
if request.url.path.startswith(API_PATH_PREFIXES):
|
||||
return False
|
||||
return get_setting("happy_404_enabled", "1") == "1"
|
||||
|
||||
|
||||
def render(request: Request) -> HTMLResponse | None:
|
||||
try:
|
||||
if not _eligible(request):
|
||||
return None
|
||||
pool = _post_pool()
|
||||
if not pool:
|
||||
return None
|
||||
slug = random.choice(pool)
|
||||
user = get_current_user(request)
|
||||
detail = load_detail("posts", "post", slug, user)
|
||||
if not detail:
|
||||
return None
|
||||
context = post_page_context(
|
||||
request, user, detail, robots="noindex,nofollow"
|
||||
)
|
||||
return templates.TemplateResponse(request, "post.html", context)
|
||||
except Exception as exc: # noqa: BLE001 - a happy-404 bug must never break the 404 page
|
||||
logger.warning("happy_404 render failed: %s", exc)
|
||||
return None
|
||||
+12
-12
@@ -33,7 +33,7 @@ from devplacepy.database import (
|
||||
get_news_images_by_uids,
|
||||
get_setting,
|
||||
get_int_setting,
|
||||
interleave_by_author,
|
||||
paginate_diverse,
|
||||
get_user_post_count,
|
||||
get_user_stars,
|
||||
get_blocked_uids,
|
||||
@@ -43,6 +43,7 @@ from devplacepy.database import (
|
||||
from devplacepy.templating import templates, jinja_unread_count
|
||||
from devplacepy.cache import TTLCache
|
||||
from devplacepy.responses import respond, wants_json, json_error
|
||||
from devplacepy import happy404
|
||||
from devplacepy.schemas import LandingOut, ValidationErrorOut
|
||||
from fastapi.responses import JSONResponse
|
||||
from devplacepy.utils import get_current_user, time_ago, safe_next, client_ip
|
||||
@@ -345,6 +346,9 @@ app.mount("/static", FallbackStaticFiles(directory=str(STATIC_DIR)), name="stati
|
||||
async def not_found(request: Request, exc):
|
||||
if wants_json(request):
|
||||
return json_error(404, "Not found")
|
||||
happy_response = happy404.render(request)
|
||||
if happy_response is not None:
|
||||
return happy_response
|
||||
seo_ctx = base_seo_context(
|
||||
request,
|
||||
title="Not Found - DevPlace",
|
||||
@@ -790,7 +794,8 @@ def _landing_news():
|
||||
return articles
|
||||
|
||||
|
||||
def _landing_recent_posts(blocked):
|
||||
def _landing_recent_posts(viewer_uid):
|
||||
blocked = get_blocked_uids(viewer_uid) if viewer_uid else frozenset()
|
||||
if not blocked:
|
||||
cached = _home_cache.get("posts")
|
||||
if cached is not None:
|
||||
@@ -798,15 +803,9 @@ def _landing_recent_posts(blocked):
|
||||
posts = []
|
||||
if "posts" in db.tables:
|
||||
posts_table = get_table("posts")
|
||||
clauses = []
|
||||
if blocked:
|
||||
clauses.append(posts_table.table.columns.user_uid.notin_(blocked))
|
||||
raw_posts = list(
|
||||
posts_table.find(
|
||||
*clauses, deleted_at=None, order_by=["-created_at"], _limit=6
|
||||
)
|
||||
raw_posts, _ = paginate_diverse(
|
||||
posts_table, order=["-created_at"], viewer_uid=viewer_uid, limit=6
|
||||
)
|
||||
raw_posts = interleave_by_author(raw_posts)
|
||||
if raw_posts:
|
||||
post_uids = [p["uid"] for p in raw_posts]
|
||||
author_uids = [p["user_uid"] for p in raw_posts]
|
||||
@@ -834,8 +833,9 @@ async def landing(request: Request):
|
||||
user = get_current_user(request)
|
||||
|
||||
landing_articles = _landing_news()
|
||||
blocked = get_blocked_uids(user["uid"]) if user else frozenset()
|
||||
landing_posts = _landing_recent_posts(blocked)
|
||||
viewer_uid = user["uid"] if user else None
|
||||
blocked = get_blocked_uids(viewer_uid) if viewer_uid else frozenset()
|
||||
landing_posts = _landing_recent_posts(viewer_uid)
|
||||
|
||||
base = site_url(request)
|
||||
seo_ctx = base_seo_context(
|
||||
|
||||
@@ -681,6 +681,7 @@ class AdminSettingsForm(BaseModel):
|
||||
registration_open: str = Field(default="", max_length=1)
|
||||
maintenance_mode: str = Field(default="", max_length=1)
|
||||
maintenance_message: str = Field(default="", max_length=300)
|
||||
happy_404_enabled: str = Field(default="", max_length=1)
|
||||
docs_search_mode: str = Field(default="", max_length=20)
|
||||
outbound_proxy_url: str = Field(default="", max_length=500)
|
||||
moderation_sla_hours: str = Field(default="", max_length=10)
|
||||
|
||||
@@ -275,15 +275,22 @@ All SEO features are implemented across the following locations:
|
||||
- `profile.html` - username rendered as `<h1 class="profile-name">`
|
||||
- `messages.html` - `<h1 class="sr-only">Messages</h1>`
|
||||
- `projects.html` - `<h1>Projects</h1>`
|
||||
- `post.html` - post title as `<h1>`, "Related Discussions" as `<h3>`
|
||||
- `post.html` - post title as `<h1>`; "Gists from {author}", "Projects from {author}", and "Related Discussions" are `.sidebar-heading` labels in the left column (see "Post page layout" below), not `<h3>`
|
||||
|
||||
### Post slugs
|
||||
- Slug generated on post creation via `slugify()` and stored in `posts.slug` column
|
||||
- Posts can be looked up by slug or UUID
|
||||
- Minimum content validation: post body >= 10 chars, comment >= 3 chars
|
||||
|
||||
### Related posts
|
||||
- `templates/post.html` - "Related Discussions" widget at bottom of post page (queried by matching topic)
|
||||
### Post page layout (three columns, mirrors `/feed`)
|
||||
|
||||
`post.html` reuses `/feed`'s exact layout building blocks rather than inventing new ones, wrapped in `.post-page-layout` (`static/css/post.css`, `grid-template-columns: var(--sidebar-width) minmax(0, 1fr) 280px`, collapsing to one column at 1024px):
|
||||
|
||||
- **Left column** - `<aside class="post-page-sidebar">`, sticky, holding up to three separate `.sidebar-card` blocks (never merged into one card - each is its own bordered panel): "Gists from {author}" and "Projects from {author}" (`content.get_user_sidebar_gists`/`get_user_sidebar_projects`, up to 5 each, most-recently-modified first, private projects filtered via `can_view_project`), and "Related Discussions" (same-topic posts). Every card title is a `.sidebar-heading` div (the same class `feed.html`'s left sidebar uses for "Topics"/"Resources"/"Online now" - `.sidebar-card .sidebar-heading` in `sidebar.css`, so it only styles correctly nested inside a `.sidebar-card`, never bare). Each list item reuses the plain `.related-list`/`.related-link`/`.related-title`/`.related-meta` classes (`base.css`) with `content_preview()` for the ellipsis-truncated description.
|
||||
- **Middle column** - `.post-page` (`max-width: 720px`): the post article, comments.
|
||||
- **Right column** - `<aside class="feed-right">`, the exact same class `feed.html` uses for its Daily Topic widget (sticky, hidden below 1024px via `feed.css`'s own media query - no post-page-specific override needed). Holds the "Featured" cards (`database.get_featured_topics`, up to 3, cached pool + per-request random sample): each is a `.daily-topic-card` with its own `.daily-topic-label` ("Featured") - matching the single Daily Topic card's internal label, since there is no section-level heading here (a `.sidebar-heading` div placed directly in `.feed-right` would NOT be styled, as noted above - the fix used is a per-card label instead of a bare heading).
|
||||
|
||||
All three columns are populated by `routers/posts.py` `post_page_context()`, the single context builder shared by the real `/posts/{slug}` route and `happy404.render()` (see the root `CLAUDE.md`), so a decoy happy-404 post page renders with the identical sidebar/featured layout as a real one.
|
||||
|
||||
### Performance
|
||||
- `loading="lazy"` on all avatar images
|
||||
|
||||
+60
-25
@@ -12,6 +12,8 @@ from devplacepy.database import (
|
||||
resolve_by_slug,
|
||||
resolve_object_url,
|
||||
mark_notifications_read_by_target,
|
||||
get_featured_topics,
|
||||
get_blocked_uids,
|
||||
)
|
||||
from devplacepy.utils import (
|
||||
get_current_user,
|
||||
@@ -29,6 +31,8 @@ from devplacepy.content import (
|
||||
detail_context,
|
||||
canonical_redirect,
|
||||
first_image_url,
|
||||
get_user_sidebar_gists,
|
||||
get_user_sidebar_projects,
|
||||
)
|
||||
from devplacepy.responses import respond, action_result
|
||||
from devplacepy.schemas import PostDetailOut
|
||||
@@ -137,20 +141,26 @@ def create_poll(
|
||||
links=[audit.poll(poll_uid, question), audit.parent("post", post_uid)],
|
||||
)
|
||||
|
||||
@router.get("/{post_slug}", response_class=HTMLResponse)
|
||||
async def view_post(request: Request, post_slug: str):
|
||||
user = get_current_user(request)
|
||||
detail = load_detail("posts", "post", post_slug, user)
|
||||
if not detail:
|
||||
raise not_found("Post not found")
|
||||
def _next_post_url(post: dict, viewer: dict | None) -> str | None:
|
||||
if "posts" not in db.tables:
|
||||
return None
|
||||
blocked = get_blocked_uids(viewer["uid"]) if viewer else frozenset()
|
||||
rows = db.query(
|
||||
"SELECT slug, uid, user_uid FROM posts WHERE created_at < :created_at "
|
||||
"AND deleted_at IS NULL ORDER BY created_at DESC LIMIT :limit",
|
||||
created_at=post["created_at"],
|
||||
limit=10,
|
||||
)
|
||||
for row in rows:
|
||||
if row["user_uid"] not in blocked:
|
||||
return f"/posts/{row['slug'] or row['uid']}"
|
||||
return None
|
||||
|
||||
|
||||
def post_page_context(
|
||||
request: Request, user: dict | None, detail: dict, *, robots: str | None = None
|
||||
) -> dict:
|
||||
post = detail["item"]
|
||||
redirect = canonical_redirect("posts", post, post_slug)
|
||||
if redirect:
|
||||
return redirect
|
||||
if user:
|
||||
mark_notifications_read_by_target(
|
||||
user["uid"], resolve_object_url("post", post["uid"])
|
||||
)
|
||||
author = detail["author"]
|
||||
top_level = detail["comments"]
|
||||
|
||||
@@ -162,10 +172,12 @@ async def view_post(request: Request, post_slug: str):
|
||||
|
||||
comment_count = count_all(top_level)
|
||||
base = site_url(request)
|
||||
next_post_url = _next_post_url(post, user)
|
||||
seo_ctx = base_seo_context(
|
||||
request,
|
||||
title=post.get("title") or "Post",
|
||||
description=post.get("content", ""),
|
||||
robots=robots or "index,follow",
|
||||
seo_target=("post", post["uid"]),
|
||||
breadcrumbs=[
|
||||
{"name": "Home", "url": "/feed"},
|
||||
@@ -177,6 +189,7 @@ async def view_post(request: Request, post_slug: str):
|
||||
],
|
||||
og_type="article",
|
||||
og_image=first_image_url(post, detail["attachments"]),
|
||||
next_url=next_post_url,
|
||||
schemas=[
|
||||
website_schema(base),
|
||||
discussion_forum_posting(
|
||||
@@ -208,21 +221,43 @@ async def view_post(request: Request, post_slug: str):
|
||||
}
|
||||
)
|
||||
|
||||
author_uid = post["user_uid"]
|
||||
return detail_context(
|
||||
request,
|
||||
user,
|
||||
detail,
|
||||
"post",
|
||||
seo_ctx,
|
||||
{
|
||||
"comment_count": comment_count,
|
||||
"related_posts": related_posts,
|
||||
"topics": list(TOPICS),
|
||||
"featured_topics": get_featured_topics(3),
|
||||
"author_gists": get_user_sidebar_gists(author_uid, 5),
|
||||
"author_projects": get_user_sidebar_projects(author_uid, user, 5),
|
||||
"next_post_url": next_post_url,
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
@router.get("/{post_slug}", response_class=HTMLResponse)
|
||||
async def view_post(request: Request, post_slug: str):
|
||||
user = get_current_user(request)
|
||||
detail = load_detail("posts", "post", post_slug, user)
|
||||
if not detail:
|
||||
raise not_found("Post not found")
|
||||
post = detail["item"]
|
||||
redirect = canonical_redirect("posts", post, post_slug)
|
||||
if redirect:
|
||||
return redirect
|
||||
if user:
|
||||
mark_notifications_read_by_target(
|
||||
user["uid"], resolve_object_url("post", post["uid"])
|
||||
)
|
||||
return respond(
|
||||
request,
|
||||
"post.html",
|
||||
detail_context(
|
||||
request,
|
||||
user,
|
||||
detail,
|
||||
"post",
|
||||
seo_ctx,
|
||||
{
|
||||
"comment_count": comment_count,
|
||||
"related_posts": related_posts,
|
||||
"topics": list(TOPICS),
|
||||
},
|
||||
),
|
||||
post_page_context(request, user, detail),
|
||||
model=PostDetailOut,
|
||||
)
|
||||
|
||||
|
||||
@@ -158,6 +158,10 @@ class PostDetailOut(_Out):
|
||||
related_posts: list[FeedItemOut] = []
|
||||
topics: list[str] = []
|
||||
project_link: Optional[ProjectLinkOut] = None
|
||||
featured_topics: list[Any] = []
|
||||
author_gists: list[Any] = []
|
||||
author_projects: list[Any] = []
|
||||
next_post_url: Optional[str] = None
|
||||
|
||||
|
||||
class ProjectsOut(_Out):
|
||||
|
||||
@@ -188,6 +188,7 @@ ADMIN_ACTIONS: tuple[Action, ...] = (
|
||||
body("registration_open", "Whether registration is open."),
|
||||
body("maintenance_mode", "Whether maintenance mode is on."),
|
||||
body("maintenance_message", "Maintenance message."),
|
||||
body("happy_404_enabled", "Whether Happy 404 (rendering a random post instead of a 404 page) is on."),
|
||||
),
|
||||
requires_admin=True,
|
||||
),
|
||||
|
||||
@@ -176,9 +176,6 @@
|
||||
.topic-wrap {
|
||||
margin-bottom: 0.75rem;
|
||||
}
|
||||
.related-section {
|
||||
margin-top: 1.5rem;
|
||||
}
|
||||
.related-list {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
|
||||
@@ -1,8 +1,54 @@
|
||||
/* retoor <retoor@molodetz.nl> */
|
||||
|
||||
.post-page-layout {
|
||||
display: grid;
|
||||
grid-template-columns: var(--sidebar-width) minmax(0, 1fr) 280px;
|
||||
gap: 1.5rem;
|
||||
align-items: start;
|
||||
}
|
||||
|
||||
.post-page-sidebar {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 1rem;
|
||||
position: sticky;
|
||||
top: calc(var(--nav-height) + 1rem);
|
||||
}
|
||||
|
||||
.post-page-sidebar .sidebar-card {
|
||||
position: static;
|
||||
}
|
||||
|
||||
.post-page {
|
||||
max-width: 720px;
|
||||
margin: 0 auto;
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.post-nav-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
flex-wrap: wrap;
|
||||
gap: 0.75rem;
|
||||
margin-bottom: 1rem;
|
||||
}
|
||||
|
||||
.post-nav-row .back-link {
|
||||
margin-bottom: 0;
|
||||
}
|
||||
|
||||
@media (max-width: 1024px) {
|
||||
.post-page-layout {
|
||||
grid-template-columns: minmax(0, 1fr);
|
||||
}
|
||||
|
||||
.post-page-sidebar {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.post-page {
|
||||
margin: 0 auto;
|
||||
}
|
||||
}
|
||||
|
||||
.post-detail {
|
||||
@@ -284,3 +330,4 @@
|
||||
padding-left: 0.375rem;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -95,6 +95,15 @@
|
||||
<small class="hint-text">Shown to visitors while maintenance mode is enabled.</small>
|
||||
</div>
|
||||
|
||||
<div class="admin-field">
|
||||
<label for="happy_404_enabled">Happy 404</label>
|
||||
<select id="happy_404_enabled" name="happy_404_enabled" class="admin-settings-select">
|
||||
<option value="1" {% if settings.get('happy_404_enabled', '1') == '1' %}selected{% endif %}>Enabled</option>
|
||||
<option value="0" {% if settings.get('happy_404_enabled', '1') != '1' %}selected{% endif %}>Disabled</option>
|
||||
</select>
|
||||
<small class="hint-text">When enabled, a page that would otherwise 404 renders a random existing post instead. HTML requests only - JSON/API clients still get a real 404.</small>
|
||||
</div>
|
||||
|
||||
<div class="admin-field">
|
||||
<label for="rate_limit_per_minute">Rate Limit (requests)</label>
|
||||
<input type="number" id="rate_limit_per_minute" name="rate_limit_per_minute" value="{{ settings.get('rate_limit_per_minute', '60') }}" min="1" class="admin-settings-num">
|
||||
|
||||
@@ -9,6 +9,10 @@ How a request flows through middleware to a router, how the database layer is bu
|
||||
|
||||
`main.py` builds the FastAPI app, mounts `/static`, registers every router with its prefix, installs the middlewares, and registers global 404, 500, and `RequestValidationError` handlers that render `error.html` through the shared `templates` instance.
|
||||
|
||||
### Happy 404
|
||||
|
||||
Before falling back to `error.html`, the 404 handler calls `happy404.render(request)` (`devplacepy/happy404.py`). For an HTML `GET` request outside the API-ish path prefixes (`/api`, `/dbapi`, `/openai`, `/xmlrpc`, `/swagger`, `/openapi.json`), it picks a random slug from a process-local pool of existing post slugs, loads that post through the normal `content.load_detail` pipeline, and renders `post.html` (the exact context built by `routers/posts.py`'s `post_page_context`, reused by the real `/posts/{slug}` route) at the requested URL - with `meta_robots` forced to `noindex,nofollow` so the decoy URL is never indexed. The pool (`POOL_SIZE` = 100 slugs) is refreshed from `SELECT slug, uid FROM posts WHERE deleted_at IS NULL ORDER BY RANDOM() LIMIT :limit` on a `TTLCache` (`POOL_TTL_SECONDS` = 300s) so the expensive random-order scan runs at most once per five minutes per worker, while each request only does an O(1) in-memory `random.choice` plus one indexed slug lookup - fast enough to run on every 404. A fresh sample every TTL window means the pool eventually surfaces every post, not just a fixed subset. JSON/API requests are unaffected (checked before `happy404.render` is even called) and are excluded a second time via the path-prefix guard as defense in depth. The whole function is wrapped in a catch-all that logs and returns `None` on any failure, falling through to the normal `error.html` 404 - a bug in this feature can never break the 404 page itself. Toggle with the `happy_404_enabled` site setting (`/admin/settings`, default on).
|
||||
|
||||
## Middleware
|
||||
|
||||
Seven HTTP middlewares run as a stack around every request, listed outermost first. `response_timing` is the outermost, `refresh_db_snapshot` the innermost, and a `GZipMiddleware` (responses over 512 bytes) wraps the whole stack on top:
|
||||
|
||||
@@ -1,12 +1,68 @@
|
||||
{% extends "base.html" %}
|
||||
{% from "_macros.html" import modal %}
|
||||
{% block extra_head %}
|
||||
<link rel="stylesheet" href="{{ static_url('/static/css/sidebar.css') }}">
|
||||
<link rel="stylesheet" href="{{ static_url('/static/css/feed.css') }}">
|
||||
<link rel="stylesheet" href="{{ static_url('/static/css/post.css') }}">
|
||||
{% endblock %}
|
||||
{% block content %}
|
||||
<div class="post-page">
|
||||
<a href="/feed" class="back-link">← Back to Feed</a>
|
||||
<div class="post-page-layout">
|
||||
{% if author_gists or author_projects or related_posts %}
|
||||
<aside class="post-page-sidebar" role="complementary" aria-label="More to explore">
|
||||
{% if author_gists %}
|
||||
<div class="sidebar-card">
|
||||
<div class="sidebar-heading">Gists from {{ author.get('username', '') if author else '' }}</div>
|
||||
<div class="related-list">
|
||||
{% for gist in author_gists %}
|
||||
<a href="/gists/{{ gist['slug'] or gist['uid'] }}" class="related-link">
|
||||
<strong class="related-title">{{ gist.get('title') or 'Untitled gist' }}</strong>
|
||||
<span class="related-meta">{{ content_preview(gist.get('description') or gist.get('source_code', ''), 80) }}</span>
|
||||
</a>
|
||||
{% endfor %}
|
||||
</div>
|
||||
<div class="topic-links">
|
||||
<a href="/profile/{{ author.get('username', '') if author else '' }}?tab=gists">View all</a>
|
||||
</div>
|
||||
</div>
|
||||
{% endif %}
|
||||
{% if author_projects %}
|
||||
<div class="sidebar-card">
|
||||
<div class="sidebar-heading">Projects from {{ author.get('username', '') if author else '' }}</div>
|
||||
<div class="related-list">
|
||||
{% for project in author_projects %}
|
||||
<a href="/projects/{{ project['slug'] or project['uid'] }}" class="related-link">
|
||||
<strong class="related-title">{{ project.get('title') or 'Untitled project' }}</strong>
|
||||
<span class="related-meta">{{ content_preview(project.get('description', ''), 80) }}</span>
|
||||
</a>
|
||||
{% endfor %}
|
||||
</div>
|
||||
<div class="topic-links">
|
||||
<a href="/profile/{{ author.get('username', '') if author else '' }}?tab=projects">View all</a>
|
||||
</div>
|
||||
</div>
|
||||
{% endif %}
|
||||
{% if related_posts %}
|
||||
<div class="sidebar-card">
|
||||
<div class="sidebar-heading">Related Discussions</div>
|
||||
<div class="related-list">
|
||||
{% for item in related_posts %}
|
||||
<a href="/posts/{{ item.post['slug'] or item.post['uid'] }}" class="related-link">
|
||||
<strong class="related-title">{{ render_title(item.post['title'], author_is_admin=is_admin(item.author)) if item.post.get('title') else content_preview(item.post['content'], 60) }}</strong>
|
||||
<span class="related-meta">{{ item.author['username'] }} · {{ dt_ago(item.created_at) if item.created_at else item.time_ago }}</span>
|
||||
</a>
|
||||
{% endfor %}
|
||||
</div>
|
||||
</div>
|
||||
{% endif %}
|
||||
</aside>
|
||||
{% endif %}
|
||||
<div class="post-page">
|
||||
<div class="post-nav-row">
|
||||
<a href="/feed" class="back-link">← Back to Feed</a>
|
||||
{% if next_post_url %}
|
||||
<a href="{{ next_post_url }}" class="back-link next-post-link">Next post →</a>
|
||||
{% endif %}
|
||||
</div>
|
||||
|
||||
<article class="post-detail">
|
||||
<div class="post-detail-header">
|
||||
@@ -103,19 +159,32 @@
|
||||
{% with target_uid=post['uid'], target_type="post" %}
|
||||
{% include "_comment_section.html" %}
|
||||
{% endwith %}
|
||||
</div>
|
||||
|
||||
{% if related_posts %}
|
||||
<section class="comments-section related-section">
|
||||
<h3>Related Discussions</h3>
|
||||
<div class="related-list">
|
||||
{% for item in related_posts %}
|
||||
<a href="/posts/{{ item.post['slug'] or item.post['uid'] }}" class="related-link">
|
||||
<strong class="related-title">{{ render_title(item.post['title'], author_is_admin=is_admin(item.author)) if item.post.get('title') else content_preview(item.post['content'], 60) }}</strong>
|
||||
<span class="related-meta">{{ item.author['username'] }} · {{ dt_ago(item.created_at) if item.created_at else item.time_ago }}</span>
|
||||
</a>
|
||||
{% endfor %}
|
||||
{% if featured_topics %}
|
||||
<aside class="feed-right" role="complementary" aria-label="Featured">
|
||||
{% for topic in featured_topics %}
|
||||
<div class="daily-topic-card card-link-host">
|
||||
{% if topic.get('slug') %}
|
||||
{% set _href = "/news/" ~ topic['slug'] %}
|
||||
{% set _label = topic.get('title', '') %}
|
||||
{% include "_card_link.html" %}
|
||||
{% endif %}
|
||||
<div class="daily-topic-label">Featured</div>
|
||||
{% if topic.get('image_url', '') %}
|
||||
<img src="{{ topic['image_url'] }}" alt="{{ topic.get('title', '') }}" loading="lazy" class="daily-topic-image">
|
||||
{% endif %}
|
||||
<h4 class="rendered-title">{{ render_title(topic.get('title', '')) }}</h4>
|
||||
<div class="rendered-content">{{ render_content(topic.get('summary', '')) }}</div>
|
||||
<div class="topic-links">
|
||||
<a href="/news/{{ topic.get('slug', '') }}">Read More</a>
|
||||
{% if topic.get('url', '') %}
|
||||
<a href="{{ topic['url'] }}" target="_blank" rel="noopener">Source</a>
|
||||
{% endif %}
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
{% endfor %}
|
||||
</aside>
|
||||
{% endif %}
|
||||
</div>
|
||||
{% endblock %}
|
||||
|
||||
Reference in New Issue
Block a user