From 31c4580da4cbdf7b7cbb758fad586cc936e66dbd Mon Sep 17 00:00:00 2001 From: Brian Hursey Date: Sat, 14 Nov 2026 17:05:01 +0000 Subject: [PATCH] Initial commit: simpleblog --- .dockerignore | 11 + .gitignore | 18 + Dockerfile | 35 + README.md | 0 blog/__init__.py | 397 + blog/admin.py | 1514 + blog/analytics.py | 518 + blog/auth.py | 388 + blog/db.py | 508 + blog/images.py | 62 + blog/manage.py | 290 + blog/markdown.py | 71 + blog/notify.py | 169 + blog/public.py | 871 + blog/wxr_export.py | 168 + blog/wxr_import.py | 193 + docker-compose.yml | 66 + .../specs/2026-11-05-photo-gallery-design.md | 73 + ntfy/server.yml | 22 + requirements.txt | 4 + run.py | 17 + static/css/admin.css | 512 + static/css/custom.css | 14 + static/css/style.css | 877 + static/js/admin_analytics.js | 268 + static/js/gallery_lightbox.js | 114 + static/js/icons/default/icons.min.js | 1 + static/js/lightbox.js | 134 + static/js/models/dom/model.min.js | 1 + static/js/plugins/anchor/plugin.min.js | 1 + static/js/plugins/autolink/plugin.min.js | 1 + static/js/plugins/charmap/plugin.min.js | 1 + static/js/plugins/codesample/plugin.min.js | 9 + static/js/plugins/emoticons/js/emojis.min.js | 1 + static/js/plugins/emoticons/plugin.min.js | 1 + static/js/plugins/image/plugin.min.js | 1 + static/js/plugins/link/plugin.min.js | 1 + static/js/plugins/lists/plugin.min.js | 1 + static/js/plugins/media/plugin.min.js | 1 + static/js/plugins/searchreplace/plugin.min.js | 1 + static/js/plugins/table/plugin.min.js | 1 + static/js/plugins/visualblocks/plugin.min.js | 1 + static/js/plugins/wordcount/plugin.min.js | 1 + static/js/skins/ui/oxide/content.min.css | 10 + static/js/skins/ui/oxide/skin.min.css | 1 + static/js/skins/ui/oxide/skin.min.js | 7 + static/js/themes/silver/theme.min.js | 3 + static/js/tinymce.min.js | 43095 ++++++++++++++++ .../08b60281391446ea80e4ea766cd2a91d.png | 3 + .../0e1a2b71bf3c4eec8bd48dc030d358fe.png | 3 + .../546046aa86454100a0240878fd9fdcd6.png | 3 + .../5b3b4c3fc1094746a54fb85ba5fb606f.png | 3 + .../789748f37a2b4a97aa4e2b9a2e16eb16.png | 3 + .../c7c2b91dc3114ca3aa211a3fc5ff6514.png | 3 + .../eda5dcf9fa1a42fda5e6efb76ce00458.png | 3 + .../f2ae5d14a7324e5492fbb62a5e8eee5d.png | 3 + static/vendor/leaflet/images/layers-2x.png | Bin 0 -> 1259 bytes static/vendor/leaflet/images/layers.png | Bin 0 -> 696 bytes .../vendor/leaflet/images/marker-icon-2x.png | Bin 0 -> 2464 bytes static/vendor/leaflet/images/marker-icon.png | Bin 0 -> 1466 bytes .../vendor/leaflet/images/marker-shadow.png | Bin 0 -> 618 bytes static/vendor/leaflet/leaflet.css | 661 + static/vendor/leaflet/leaflet.js | 6 + templates/_pagination.html | 11 + templates/admin/albums.html | 141 + templates/admin/analytics.html | 187 + templates/admin/appearance.html | 447 + templates/admin/base.html | 103 + templates/admin/categories.html | 51 + templates/admin/comments.html | 99 + templates/admin/dashboard.html | 61 + templates/admin/import_export.html | 31 + templates/admin/links.html | 53 + templates/admin/media.html | 124 + templates/admin/page_edit.html | 84 + templates/admin/pages.html | 36 + templates/admin/password.html | 36 + templates/admin/post_edit.html | 179 + templates/admin/posts.html | 42 + templates/admin/visit_history.html | 38 + templates/admin/visitors.html | 86 + templates/base.html | 76 + templates/comments.html | 59 + templates/home.html | 135 + templates/login.html | 26 + templates/page.html | 25 + templates/photos.html | 44 + templates/post.html | 79 + templates/public/albums.html | 36 + templates/search.html | 37 + templates/tags.html | 23 + 91 files changed, 53494 insertions(+) create mode 100644 .dockerignore create mode 100644 .gitignore create mode 100644 Dockerfile create mode 100644 README.md create mode 100644 blog/__init__.py create mode 100644 blog/admin.py create mode 100644 blog/analytics.py create mode 100644 blog/auth.py create mode 100644 blog/db.py create mode 100644 blog/images.py create mode 100644 blog/manage.py create mode 100644 blog/markdown.py create mode 100644 blog/notify.py create mode 100644 blog/public.py create mode 100644 blog/wxr_export.py create mode 100644 blog/wxr_import.py create mode 100644 docker-compose.yml create mode 100644 docs/superpowers/specs/2026-11-05-photo-gallery-design.md create mode 100644 ntfy/server.yml create mode 100644 requirements.txt create mode 100644 run.py create mode 100644 static/css/admin.css create mode 100644 static/css/custom.css create mode 100644 static/css/style.css create mode 100644 static/js/admin_analytics.js create mode 100644 static/js/gallery_lightbox.js create mode 100644 static/js/icons/default/icons.min.js create mode 100644 static/js/lightbox.js create mode 100644 static/js/models/dom/model.min.js create mode 100644 static/js/plugins/anchor/plugin.min.js create mode 100644 static/js/plugins/autolink/plugin.min.js create mode 100644 static/js/plugins/charmap/plugin.min.js create mode 100644 static/js/plugins/codesample/plugin.min.js create mode 100644 static/js/plugins/emoticons/js/emojis.min.js create mode 100644 static/js/plugins/emoticons/plugin.min.js create mode 100644 static/js/plugins/image/plugin.min.js create mode 100644 static/js/plugins/link/plugin.min.js create mode 100644 static/js/plugins/lists/plugin.min.js create mode 100644 static/js/plugins/media/plugin.min.js create mode 100644 static/js/plugins/searchreplace/plugin.min.js create mode 100644 static/js/plugins/table/plugin.min.js create mode 100644 static/js/plugins/visualblocks/plugin.min.js create mode 100644 static/js/plugins/wordcount/plugin.min.js create mode 100644 static/js/skins/ui/oxide/content.min.css create mode 100644 static/js/skins/ui/oxide/skin.min.css create mode 100644 static/js/skins/ui/oxide/skin.min.js create mode 100644 static/js/themes/silver/theme.min.js create mode 100644 static/js/tinymce.min.js create mode 100644 static/uploads/08b60281391446ea80e4ea766cd2a91d.png create mode 100644 static/uploads/0e1a2b71bf3c4eec8bd48dc030d358fe.png create mode 100644 static/uploads/546046aa86454100a0240878fd9fdcd6.png create mode 100644 static/uploads/5b3b4c3fc1094746a54fb85ba5fb606f.png create mode 100644 static/uploads/789748f37a2b4a97aa4e2b9a2e16eb16.png create mode 100644 static/uploads/c7c2b91dc3114ca3aa211a3fc5ff6514.png create mode 100644 static/uploads/eda5dcf9fa1a42fda5e6efb76ce00458.png create mode 100644 static/uploads/f2ae5d14a7324e5492fbb62a5e8eee5d.png create mode 100644 static/vendor/leaflet/images/layers-2x.png create mode 100644 static/vendor/leaflet/images/layers.png create mode 100644 static/vendor/leaflet/images/marker-icon-2x.png create mode 100644 static/vendor/leaflet/images/marker-icon.png create mode 100644 static/vendor/leaflet/images/marker-shadow.png create mode 100644 static/vendor/leaflet/leaflet.css create mode 100644 static/vendor/leaflet/leaflet.js create mode 100644 templates/_pagination.html create mode 100644 templates/admin/albums.html create mode 100644 templates/admin/analytics.html create mode 100644 templates/admin/appearance.html create mode 100644 templates/admin/base.html create mode 100644 templates/admin/categories.html create mode 100644 templates/admin/comments.html create mode 100644 templates/admin/dashboard.html create mode 100644 templates/admin/import_export.html create mode 100644 templates/admin/links.html create mode 100644 templates/admin/media.html create mode 100644 templates/admin/page_edit.html create mode 100644 templates/admin/pages.html create mode 100644 templates/admin/password.html create mode 100644 templates/admin/post_edit.html create mode 100644 templates/admin/posts.html create mode 100644 templates/admin/visit_history.html create mode 100644 templates/admin/visitors.html create mode 100644 templates/base.html create mode 100644 templates/comments.html create mode 100644 templates/home.html create mode 100644 templates/login.html create mode 100644 templates/page.html create mode 100644 templates/photos.html create mode 100644 templates/post.html create mode 100644 templates/public/albums.html create mode 100644 templates/search.html create mode 100644 templates/tags.html diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..73b4abb --- /dev/null +++ b/.dockerignore @@ -0,0 +1,11 @@ +__pycache__/ +*.pyc +.venv/ +venv/ +.git/ +.gitignore +.env +data/ +build/ +dist/ +*.log diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..67a3afd --- /dev/null +++ b/.gitignore @@ -0,0 +1,18 @@ +# Secrets / local env +.env +.env.* + +# Python +__pycache__/ +*.py[cod] +.venv/ + +# Local agent config (never push) +.pi/ + +# Throwaway dev / verification scripts +appearance_test.py +proxy_test.py +verify_gallery.py +verify_upload.py +pw_cmd.txt diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..aaca28f --- /dev/null +++ b/Dockerfile @@ -0,0 +1,35 @@ +# Simple Blog — single-container image +# Built from this directory. No external services required. +FROM python:3.11-slim + +# Keep Python warnings out of stdout/stderr +ENV PYTHONUNBUFFERED=1 \ + PYTHONDONTWRITEBYTECODE=1 \ + PIP_NO_CACHE_DIR=1 + +WORKDIR /app + +# Install dependencies first (better layer caching) +COPY requirements.txt . +RUN pip install --upgrade pip && pip install -r requirements.txt + +# Copy the application +COPY blog/ ./blog/ +COPY templates/ ./templates/ +COPY static/ ./static/ +COPY run.py ./ + +# Create the data directory for the SQLite database +RUN mkdir -p /app/data + +# The app listens on all interfaces on port 5000 +EXPOSE 5000 + +# Default environment (override with -e or docker-compose). No password or +# session secret is baked in: without them the app generates strong ones on +# first boot (the temporary password is printed once to the logs). +ENV PORT=5000 \ + BLOG_DATA_DIR=/app/data + +# Run the application +CMD ["python", "run.py"] diff --git a/README.md b/README.md new file mode 100644 index 0000000..e69de29 diff --git a/blog/__init__.py b/blog/__init__.py new file mode 100644 index 0000000..00344b3 --- /dev/null +++ b/blog/__init__.py @@ -0,0 +1,397 @@ +"""Application factory for the Simple Blog CMS.""" + +import os +import secrets +import tempfile +import time +from datetime import datetime, timedelta + +from flask import ( + Flask, + abort, + current_app, + flash, + g, + redirect, + render_template, + request, + session, + url_for, +) +from itsdangerous import URLSafeTimedSerializer +from . import auth +from .db import _slugify, get_db, init_db, parse_date, split_tags +from .markdown import render_markdown +from .analytics import ( + classify_source, + client_ip, + country_flag, + is_bot, + parse_user_agent, + record_visit, +) + + +APP_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) + + +def _env_flag(name, default=False): + """Read a boolean environment flag (1/true/yes/on).""" + value = os.environ.get(name) + if value is None: + return default + return value.strip().lower() in ("1", "true", "yes", "on") + + +def _title_for_path(path): + """Return a human-friendly page title for tracking, looked up from the DB.""" + db = get_db() + slug = path.split("/", 2)[-1] if "/" in path else "" + if path == "/": + row = db.execute("SELECT value FROM settings WHERE key='site_title'").fetchone() + return (row[0] if row else "") or "Home" + if not slug: + return "" + if path.startswith("/post/"): + row = db.execute("SELECT title FROM posts WHERE slug=?", (slug,)).fetchone() + return row[0] if row else "" + if path.startswith("/p/"): + row = db.execute("SELECT title FROM pages WHERE slug=?", (slug,)).fetchone() + return row[0] if row else "" + if path.startswith("/category/"): + row = db.execute("SELECT name FROM categories WHERE slug=?", (slug,)).fetchone() + return row[0] if row else "" + if path.startswith("/tag/"): + return slug.replace("-", " ").title() + if path == "/search": + return "Search" + return "" + + +def create_app(): + app = Flask(__name__) + # The real key is resolved in _load_auth_bootstrap(): an env-provided secret + # is used when it is long and not a known placeholder, otherwise a random + # secret is generated once and stored in the DB. Sessions are therefore + # never signed with a publicly known key. + app.config["SECRET_KEY"] = None + # Flag emoji for country codes, used by the analytics dashboards. + app.jinja_env.filters["country_flag"] = country_flag + # Turn the stored comma-separated tags into (name, slug) pairs so templates + # can link every tag to its public tag page. + app.jinja_env.filters["tag_list"] = lambda raw: [ + {"name": name, "slug": _slugify(name)} for name in split_tags(raw) + ] + app.config["MAX_CONTENT_LENGTH"] = 64 * 1024 * 1024 # 64 MB (raised: image uploads were hitting werkzeug's 413 REQUEST ENTITY TOO LARGE at the old 8 MB cap) + + # --- Session cookie hardening --------------------------------------- + # HttpOnly keeps the session cookie away from JavaScript; SameSite=Lax + # blocks cross-site POSTs (CSRF) while keeping normal navigation working. + # Cookies are marked Secure when the site is served over HTTPS; set + # BLOG_SECURE_COOKIES=1 behind a TLS-terminating reverse proxy. + app.config["SESSION_COOKIE_HTTPONLY"] = True + app.config["SESSION_COOKIE_SAMESITE"] = "Lax" + app.config["SESSION_COOKIE_SECURE"] = _env_flag("BLOG_SECURE_COOKIES") + app.config["PERMANENT_SESSION_LIFETIME"] = timedelta( + seconds=auth.session_absolute_seconds() + ) + app.config["SESSION_REFRESH_EACH_REQUEST"] = True + + # --- Login management ------------------------------------------------- + # Templates and static assets live at the project root (sibling of the blog + # package), so point both folders there explicitly. + app.template_folder = os.path.join(APP_ROOT, "templates") + app.static_folder = os.path.join(APP_ROOT, "static") + + # Opt-in proxy awareness: behind a TLS-terminating reverse proxy set + # BLOG_TRUST_PROXY=1 so request.remote_addr, request.is_secure and the + # URLs Flask generates reflect the client/protocol instead of the proxy. + if _env_flag("BLOG_TRUST_PROXY"): + from werkzeug.middleware.proxy_fix import ProxyFix + + app.wsgi_app = ProxyFix(app.wsgi_app, x_for=1, x_proto=1, x_host=1) + + @app.teardown_appcontext + def close_db(_exc=None): + db = g.pop("db", None) + if db is not None: + db.close() + + with app.app_context(): + init_db() + _seed_defaults() + auth.ensure_session_secret(app) + auth.ensure_admin_credentials(app) + + from .public import bp as public_bp + from .admin import bp as admin_bp + + app.register_blueprint(public_bp) + app.register_blueprint(admin_bp, url_prefix="/admin") + + # --- Session lifetime ------------------------------------------------- + # Expire idle/absolute-timeout sessions and invalidate them when the admin + # password has changed since the login. Registered first so every later + # hook (and every view) sees an already-validated session. + @app.before_request + def _enforce_session_lifetime(): + auth.refresh_session() + + @app.before_request + def _sync_custom_css(): + # Keep the served custom.css in sync with the saved DB settings. The + # appearance editor writes this file on save, but a container/image + # rebuild restores the committed default template (losing your colors). + # Regenerating from the DB on every request guarantees your theme always + # applies -- even after a rebuild wipes this generated file. Only writes + # when a saved theme exists so we never clobber an existing file. + try: + custom_css = get_db().execute( + "SELECT value FROM settings WHERE key='custom_css'" + ).fetchone()[0] or "" + except Exception: + return + if not custom_css: + return + css_dir = os.path.join(APP_ROOT, "static", "css") + css_path = os.path.join(css_dir, "custom.css") + try: + # Read with newline="" so a CRLF-saved theme stays distinct, then + # compare after normalising both sides. Text-mode reads turn CRLF + # into LF, so a theme saved with Windows line endings never matched: + # the file was rewritten on EVERY request, and a concurrent /static/ + # read could catch it truncated. That dropped the theme's + # `.posts-grid` rule and the layout fell back to the default 2 + # columns (intermittently, depending on navigation timing). + with open(css_path, "r", encoding="utf-8", newline="") as handle: + current = handle.read() + if current == custom_css or ( + current.replace("\r\n", "\n") == custom_css.replace("\r\n", "\n") + ): + return + except OSError: + pass + try: + os.makedirs(css_dir, exist_ok=True) + # Write then atomically replace: readers see either the old CSS or + # the new CSS, never a half-written stylesheet. + fd, tmp_path = tempfile.mkstemp( + dir=css_dir, prefix=".custom-", suffix=".css" + ) + try: + with os.fdopen(fd, "w", encoding="utf-8") as handle: + handle.write(custom_css) + os.replace(tmp_path, css_path) + finally: + if os.path.exists(tmp_path): + os.remove(tmp_path) + except Exception: + return + + # --- Visitor analytics (tracking) ------------------------------------- + # Capture an anonymous visitor identity on first contact and record a visit + # for every public content page. Only the opaque `visitor_id` cookie is used; + # no personal data is stored. Admin pages and static assets are never tracked. + VISITOR_COOKIE_AGE = 60 * 60 * 24 * 365 # 1 year + + class _Tracking: + def __init__(self, request): + self.request = request + self.is_new = True + cookie_val = request.cookies.get("visitor_id") + if cookie_val: + self.visitor_id = cookie_val + self.is_new = False + else: + self.visitor_id = secrets.token_hex(16) + browser, os_name, device = parse_user_agent( + request.headers.get("User-Agent", "") + ) + referer, referrer_domain, source = classify_source( + request.headers.get("Referer", "") + ) + self.visitor = { + "visitor_id": self.visitor_id, + "browser": browser, + "os": os_name, + "device": device, + "referrer": referer, + "referrer_domain": referrer_domain, + "source": source, + } + self.page_path = request.path + self.title = _title_for_path(request.path) + # Used once to resolve the visitor's approximate location (the IP + # itself is never persisted). ProxyFix supplies the real client + # address when BLOG_TRUST_PROXY is enabled. + # Behind Docker's port mapping / a LAN reverse proxy the peer is a + # private address, so the forwarding headers supply the real one. + self.ip = client_ip( + request.remote_addr, + request.headers, + _env_flag("BLOG_TRUST_PROXY"), + ) + + @app.before_request + def _tracking_before(): + if getattr(g, "_track", None) is not None: + return + path = request.path + # Track only public content; never the admin area or static assets. + if path.startswith("/admin/") or path.startswith("/static/"): + return + if request.method != "GET": + return + # Crawlers, monitors and CLI fetchers would otherwise dominate the + # analytics tables. + if is_bot(request.headers.get("User-Agent", "")): + return + g._track = _Tracking(request) + + @app.after_request + def _tracking_after(resp): + track = getattr(g, "_track", None) + if track is None: + return resp + # Only successful page loads count: 404s from link scanners used to + # create a visitor row for every bogus URL they probed. + if resp.status_code != 200: + return resp + record_visit(track.visitor, track.page_path, track.title, ip=track.ip) + if track.is_new: + resp.set_cookie( + "visitor_id", + track.visitor_id, + max_age=VISITOR_COOKIE_AGE, + path="/", + httponly=True, + ) + return resp + + # --- Static asset caching -------------------------------------------- + # This app is a subpath (/admin/*) and serves large JS bundles. Flask's default + # static route uses ETag-based conditional requests, so the browser revalidates + # (HTTP 304) and can serve a STALE cached copy that never loads the real file. + # Force no-store on every /static/ response so assets are always downloaded fresh; + # combined with a one-time cache clear this removes stale-editor problems permanently. + @app.after_request + def force_no_static_cache(resp): + if request.path.startswith("/static/"): + resp.headers["Cache-Control"] = "no-store" + # Authenticated pages must never be cached by a shared cache or the + # browser back button after logout. + elif request.path.startswith("/admin/"): + resp.headers["Cache-Control"] = "no-store, private" + return resp + + # --- Security headers ------------------------------------------------- + @app.after_request + def _security_headers(resp): + resp.headers.setdefault("X-Content-Type-Options", "nosniff") + resp.headers.setdefault("X-Frame-Options", "SAMEORIGIN") + # strict-origin-when-cross-origin is the browser default: cross-origin + # requests still get the site origin. "same-origin" stripped the Referer + # entirely, which OpenStreetMap's tile usage policy forbids — its tile + # servers answered the analytics map with a 403 "Access blocked" tile. + resp.headers.setdefault( + "Referrer-Policy", "strict-origin-when-cross-origin" + ) + if request.is_secure: + resp.headers.setdefault( + "Strict-Transport-Security", "max-age=31536000; includeSubDomains" + ) + return resp + + @app.context_processor + def expose_helpers(): + session.setdefault("csrf_token", secrets.token_hex(16)) + db = get_db() + # One query for every setting the templates need (this was five + # separate round trips per request) plus one for the nav pages. + settings = { + row["key"]: row["value"] or "" + for row in db.execute("SELECT key, value FROM settings").fetchall() + } + pages = db.execute( + "SELECT id, slug, title FROM pages WHERE published = 1 " + "ORDER BY position, id" + ).fetchall() + # Defensive against a missing row so an un-seeded DB still renders. + try: + comments_enabled = bool(int(settings.get("comments_enabled") or "1")) + except ValueError: + comments_enabled = True + + # Badge count for the admin nav: comments waiting for moderation. Kept + # defensive so a not-yet-migrated DB still renders every page. + try: + pending_comments = db.execute( + "SELECT COUNT(*) FROM comments WHERE status = 'pending'" + ).fetchone()[0] + except Exception: + pending_comments = 0 + + def preview_url(post): + """Signed, expiring link to view an unpublished post.""" + token = URLSafeTimedSerializer( + current_app.config["SECRET_KEY"], salt="post-preview" + ).dumps(int(post["id"])) + return url_for("public.preview", pid=post["id"], token=token) + + return { + # Real year (this was hardcoded to 2026 in the footer). + "current_year": lambda: datetime.now().year, + # Render time of this page, used by the comment form's bot traps. + "now_ts": int(time.time()), + "csrf_token": session.get("csrf_token"), + "parse_date": parse_date, + "render_markdown": render_markdown, + # Exposed so public templates (base.html) can render the admin-uploaded + # header image and load custom CSS without each route passing them. + "header_image": settings.get("header_image", ""), + "custom_css": settings.get("custom_css", ""), + # Published content pages, in display order — drives the top nav and + # is what the admin Pages manager edits. + "pages": pages, + "site_title": settings.get("site_title") or "My Blog", + "site_tagline": settings.get("site_tagline", ""), + # Default search/social description, editable from Appearance. Pages + # can override it with a meta_description template block. + "meta_description": settings.get("meta_description", ""), + "pending_comments": pending_comments, + "preview_url": preview_url, + # Whether the public comment system is switched on (toggleable from + # the admin Appearance page) and whether an admin is signed in (used + # to let logged-in users delete their own comments). + "comments_enabled": comments_enabled, + "logged_in": auth.is_logged_in(), + } + + return app + + +def _seed_defaults(): + from .db import _utcnow + + db = get_db() + db.execute( + "INSERT OR IGNORE INTO settings (key, value) VALUES (?, ?)", + ("site_title", "My Blog"), + ) + db.execute( + "INSERT OR IGNORE INTO settings (key, value) VALUES (?, ?)", + ("site_tagline", "Thoughts on tech, self-hosting and life."), + ) + db.execute( + "INSERT OR IGNORE INTO settings (key, value) VALUES (?, ?)", + ("meta_description", ""), + ) + db.execute( + "INSERT OR IGNORE INTO settings (key, value) VALUES (?, ?)", + ("header_image", ""), + ) + db.execute( + "INSERT OR IGNORE INTO settings (key, value) VALUES (?, ?)", + ("custom_css", ""), + ) + db.commit() diff --git a/blog/admin.py b/blog/admin.py new file mode 100644 index 0000000..ad8b639 --- /dev/null +++ b/blog/admin.py @@ -0,0 +1,1514 @@ +"""Admin (CMS) routes — password protected, custom UI (no Flask-Admin).""" + +import functools +import hmac +import os +import re +import uuid +from datetime import datetime, timedelta, timezone +from urllib.parse import urlsplit + +from flask import ( + Blueprint, + abort, + flash, + jsonify, + redirect, + render_template, + request, + session, + url_for, +) + +from . import auth +from .db import ( + _all_albums, + _album_by_id, + _album_by_slug, + _album_media, + _comment_by_id, + _comment_counts, + _pending_comments, + _slugify, + _ungrouped_media, + _media_by_id, + _utcnow, + get_db, + parse_date, +) +from .markdown import render_markdown, to_html +from .images import make_thumbnail +from . import wxr_export, wxr_import + +bp = Blueprint("admin", __name__, url_prefix="/admin") + +# Project root (this file lives in blog/admin.py, so climb up twice). +APP_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +UPLOAD_DIR = os.path.join(APP_ROOT, "static", "uploads") +# Created eagerly so uploaded images are served even before the first upload. +os.makedirs(UPLOAD_DIR, exist_ok=True) + +# CSS lives here; the constant must be defined before _default_font_stack() +# runs (it used to sit 200 lines further down the module). +CSS_DIR = os.path.join(APP_ROOT, "static", "css") +os.makedirs(CSS_DIR, exist_ok=True) + + +# Read the default font stack straight from static/css/style.css so the editor's +# "System (default)" preset always matches the built-in theme, no hardcoding. +@functools.lru_cache(maxsize=1) +def _default_font_stack(): + try: + with open(os.path.join(CSS_DIR, "style.css"), "r", encoding="utf-8") as handle: + for line in handle: + if line.startswith("--font-stack"): + return line.split(":", 1)[1].strip().rstrip("}").strip() + except OSError: + pass + return "Inter, Roboto, sans-serif" + + +def _admin_username(): + return os.environ.get("BLOG_ADMIN_NAME", "admin") + + +def _valid_status(value): + """Only the statuses the editor offers are ever stored.""" + return value if value in ("published", "draft") else "published" + + +def _post_timestamp(date_value, current=""): + """Combine a YYYY-MM-DD form date with the post's existing time of day. + + Returns "" when the field is blank or not a real date, so callers can keep + the stored value (a new post then simply uses the current time). Keeping the + old clock time means backdating a post does not reshuffle posts made on the + same day, and it avoids every backdated post landing at midnight. + """ + value = (date_value or "").strip() + if not value: + return "" + try: + chosen = datetime.strptime(value, "%Y-%m-%d") + except ValueError: + return "" + current = str(current or "") + clock = current[11:19] if len(current) >= 19 else "" + if len(clock) != 8: + clock = datetime.now(timezone.utc).strftime("%H:%M:%S") + return chosen.strftime("%Y-%m-%d") + " " + clock + + +def _csrf(): + """Per-session CSRF token (rotated on sign-in).""" + return session.get("csrf_token") + + +def _check_csrf(): + """Constant-time CSRF check; the token may arrive as a form field or a header.""" + expected = _csrf() + if not expected: + flash("Invalid request.", "error") + return False + token = request.form.get("csrf_token") or request.headers.get("X-CSRFToken") + if not token or not hmac.compare_digest(str(token), str(expected)): + flash("Invalid CSRF token.", "error") + return False + return True + + +# --------------------------------------------------------------------------- # +# Auth +# --------------------------------------------------------------------------- # +def _login_required(fn): + """Require an active admin session (see session['logged_in']).""" + @functools.wraps(fn) + def wrapper(*args, **kwargs): + if not auth.is_logged_in(): + return redirect(url_for("admin.admin_login")) + return fn(*args, **kwargs) + return wrapper + + +@bp.route("/") +@_login_required +def index(): + """/admin (no trailing path) used to 404; send it to the dashboard.""" + return redirect(url_for("admin.dashboard")) + + +# Image uploads ------------------------------------------------------------- +# Accepted image types and their leading magic bytes (used to reject non-images +# and format-spoofing). Maps extension -> (signature, min_length). +_IMAGE_SIGNATURES = { + "png": (b"\x89PNG\r\n\x1a\n", 8), + "jpg": (b"\xff\xd8\xff", 4), + "jpeg": (b"\xff\xd8\xff", 4), + "gif": (b"GIF8", 4), + "webp": (b"RIFF\x00\x00\x00\x14WEBP", 12), +} + + +@bp.route("/upload", methods=["POST"]) +@_login_required +def upload(): + """Store uploaded image(s) and return their public URLs. + + Accepts one or more ``file`` parts. When a single image is uploaded the + response keeps the legacy shape ``{"url": ...}`` (so the inline post/page + rich editor still works). When several are uploaded at once it returns a + JSON list of ``{"url": ..., "id": ..., "album_id": ...}`` objects. + + Each image may be attached to an album via the optional ``album`` slug. If + an album slug is supplied we validate it up front (so no file is written for + a bad album); without one we keep the old behaviour and just return the URL. + Deleting an album later only uncouples photos; it never deletes the file on + disk. + """ + if not _check_csrf(): + flash("Invalid request.", "error"); abort(400) + files = list(request.files.getlist("file")) if request.files else [] + if not files: + flash("No image selected.", "error"); abort(400) + db = get_db() + album_slug = (request.form.get("album") or "").strip() + if album_slug: + album = _album_by_slug(album_slug) + if not album: + flash("Album not found.", "error"); abort(400) + results = [] + for file in files: + filename = file.filename + if not filename or filename.startswith("("): + flash("Invalid file.", "error"); abort(400) + ext = os.path.splitext(filename)[1].lower().lstrip(".") + if ext not in _IMAGE_SIGNATURES: + flash("Unsupported image type.", "error"); abort(400) + data = file.read() + signature, min_len = _IMAGE_SIGNATURES[ext] + if len(data) < min_len or data[:len(signature)] != signature: + flash("That doesn't look like a valid image.", "error"); abort(400) + new_filename = "%s.%s" % (uuid.uuid4().hex, ext) + try: + with open(os.path.join(UPLOAD_DIR, new_filename), "wb") as handle: + handle.write(data) + except OSError: + flash("Could not store the image.", "error"); abort(500) + # Downscaled copy for galleries/lists; empty when the format can't be + # thumbnailed (e.g. animated GIF), in which case the UI uses the original. + thumb = make_thumbnail(os.path.join(UPLOAD_DIR, new_filename)) + url = url_for("static", filename="uploads/" + new_filename) + thumb_url = url_for("static", filename="uploads/" + thumb) if thumb else "" + # NOTE: on this sqlite3 build, execute(...).fetchone() returns None + # for an INSERT (the row is still written), so we rely on lastrowid. + # We ALWAYS persist the photo (album_id NULL when ungrouped) so it shows + # in /photos and can later be grouped via media_assign. Previously only + # selecting an album created a row — otherwise the file was orphaned on + # disk and the upload silently never appeared. + cur = db.execute( + "INSERT INTO media (filename, url, thumb_url, album_id, position, created_at) " + "VALUES (?, ?, ?, ?, 0, ?)", + (new_filename, url, thumb_url, + album["id"] if album_slug else None, _utcnow()), + ) + db.commit() + results.append({"url": url, "thumb_url": thumb_url, "id": cur.lastrowid, + "album_id": album["id"] if album_slug else None}) + if len(results) == 1: + return jsonify(results[0]) + return jsonify(results) + + +# --------------------------------------------------------------------------- # +# Appearance (header image + custom CSS) +# --------------------------------------------------------------------------- # +@bp.route("/appearance", methods=["GET", "POST"]) +@_login_required +def appearance(): + """Set the site header image and custom CSS.""" + if request.method == "POST": + if not _check_csrf(): + return redirect(url_for("admin.appearance")) + db = get_db() + # NOTE: this page has TWO independent forms that both POST here — the + # "Site identity" form (site_title / site_tagline / comments_enabled) and + # the "Theme editor" form (custom_css, header_image). Each form only + # carries its own fields, so we must do a PARTIAL update: only write the + # keys that were actually submitted. Otherwise saving one section would + # clobber the other (e.g. saving the title wiped custom_css to ""). + if "site_title" in request.form: + site_title = (request.form.get("site_title") or "").strip() + db.execute("UPDATE settings SET value = ? WHERE key = 'site_title'", (site_title,)) + if "site_tagline" in request.form: + site_tagline = (request.form.get("site_tagline") or "").strip() + db.execute("UPDATE settings SET value = ? WHERE key = 'site_tagline'", (site_tagline,)) + # Fallback search/social description for pages without their own. + if "meta_description" in request.form: + meta_description = (request.form.get("meta_description") or "").strip() + db.execute( + "UPDATE settings SET value = ? WHERE key = 'meta_description'", + (meta_description,), + ) + # Comments toggle — stored as 0/1 in settings; the public comment form is + # gated on it so admins can switch engagement off without touching routes. + # Comments toggle — stored as 0/1 in settings; the public comment form is + # gated on it so admins can switch engagement off without touching routes. + # NOTE: "0" is a *truthy* Python string, so the old `if value.strip()` test + # treated an unchecked box's "0" as enabled. The form now uses radio buttons + # (explicit 1/0), and we compare against ("", "0") explicitly to be safe. + if "comments_enabled" in request.form: + comments_enabled = "1" if (request.form.get("comments_enabled") or "").strip() not in ("", "0") else "0" + db.execute( + "UPDATE settings SET value = ? WHERE key = 'comments_enabled'", + (comments_enabled,), + ) + # Custom CSS is stored verbatim in settings and mirrored to a static file + # so public pages can load it efficiently via a (browser-cached). + if "custom_css" in request.form: + custom_css = (request.form.get("custom_css") or "").strip() + db.execute("UPDATE settings SET value = ? WHERE key = 'custom_css'", (custom_css,)) + # Only rewrite the static file when the theme form is actually + # submitted. The identity form never carries custom_css, so we must + # NOT touch this file here — otherwise saving the title would wipe + # the saved theme off every public page. + css_path = os.path.join(CSS_DIR, "custom.css") + with open(css_path, "w") as handle: + handle.write(custom_css) + if not custom_css: + handle.write("\n/* (custom CSS) */\n") + # Header image reuses the same signature validation as /upload. + img_file = request.files.get("header_image") + if img_file and img_file.filename: + ext = os.path.splitext(img_file.filename)[1].lower().lstrip(".") + if ext not in _IMAGE_SIGNATURES: + flash("Unsupported image type.", "error") + return redirect(url_for("admin.appearance")) + data = img_file.read() + signature, min_len = _IMAGE_SIGNATURES[ext] + if len(data) < min_len or data[:len(signature)] != signature: + flash("That doesn't look like a valid image.", "error") + return redirect(url_for("admin.appearance")) + filename = "%s.%s" % (uuid.uuid4().hex, ext) + try: + with open(os.path.join(UPLOAD_DIR, filename), "wb") as handle: + handle.write(data) + except OSError: + flash("Could not store the header image.", "error") + return redirect(url_for("admin.appearance")) + url = url_for("static", filename="uploads/" + filename) + db.execute("UPDATE settings SET value = ? WHERE key = 'header_image'", (url,)) + elif request.form.get("remove_header"): + # No new file uploaded and removal requested: clear the setting. + db.execute("UPDATE settings SET value = '' WHERE key = 'header_image'") + db.commit() + flash("Appearance saved.", "success") + return redirect(url_for("admin.appearance")) + db = get_db() + header_image = db.execute( + "SELECT value FROM settings WHERE key = 'header_image'").fetchone()[0] or "" + custom_css = db.execute( + "SELECT value FROM settings WHERE key = 'custom_css'").fetchone()[0] or "" + + # --- Build the theme state for the GUI editor. Values are parsed out of the + # stored custom CSS (so a saved theme round-trips); anything missing falls + # back to the built-in defaults so a fresh site looks unchanged. + def pick(var, default): + # Match the value up to the end of its line (or a ';'); buildVars emits + # newline-separated declarations without trailing ';', so require only that + # the value is terminated by a newline or semicolon (handles both formats). + m = re.search(r"--" + re.escape(var) + r"\s*:\s*([^;\n]+)", custom_css) + return m.group(1).strip() if m else default + + def has_dark(): + # Detect dark mode via the explicit marker buildTheme() emits, not a + # literal background colour (which can be user-chosen), so dark mode + # round-trips reliably even with a custom background. + return "theme-dark" in custom_css + + m_posts = re.search(r"\.posts-grid \{[^}]*grid-template-columns:\s*repeat\((\d+),[^}]*\}", custom_css) + + theme = { + "accent": pick("color-accent", "#00a0d1"), + "background": pick("color-bg", "#ffffff"), + "text": pick("color-text", "#1e1e1e"), + "sidebar": pick("color-sidebar-bg", "#f2f2f2"), + "font": pick("font-stack", _default_font_stack()), + "posts": int(m_posts.group(1)) if m_posts else 1, + "header": "stacked" if "flex-direction: column" in custom_css else "side", + "radius": int(re.search(r"border-radius:\s*(\d+)px", custom_css).group(1)) if re.search(r"border-radius:\s*\d+px", custom_css) else 6, + "dark": has_dark(), + "fonts": [ + {"value": _default_font_stack(), "label": "System (default)"}, + {"value": '"Inter", "Segoe UI", system-ui, sans-serif', "label": "Inter / Modern"}, + {"value": 'Georgia, "Times New Roman", serif', "label": "Serif (Georgia)"}, + {"value": '"SFMono-Regular", Consolas, "Liberation Mono", Menlo, monospace', "label": "Mono (code)"}, + {"value": '"Verdana", "Trebuchet MS", sans-serif', "label": "Rounded (Verdana)"} + ], + "post_columns": [ + {"value": 1, "label": "1 column"}, + {"value": 2, "label": "2 columns"}, + {"value": 3, "label": "3 columns"} + ], + "header_layouts": [ + {"value": "side", "label": "Logo + nav side by side"}, + {"value": "stacked", "label": "Logo above nav"} + ] + } + return render_template( + "admin/appearance.html", + header_image=header_image, + custom_css=custom_css, + theme=theme, + active_page="appearance", + ) + + +# --------------------------------------------------------------------------- # +# Auth +# --------------------------------------------------------------------------- # +def _lockout_message(seconds): + """Human-readable backoff message without confirming any credentials.""" + if seconds >= 60: + minutes = (seconds + 59) // 60 + return "Too many failed sign-in attempts. Try again in %d minute%s." % ( + minutes, "" if minutes == 1 else "s") + return "Too many failed sign-in attempts. Try again in %d seconds." % max(1, seconds) + + +@bp.route("/login", methods=["GET", "POST"]) +def admin_login(): + if auth.is_logged_in(): + return redirect(url_for("admin.dashboard")) + if request.method == "POST": + if not _check_csrf(): + return render_template("login.html", title="Sign in"), 400 + # Throttle by client address before touching the password hash, so a + # brute-force loop cannot keep the CPU busy either. + ip = request.remote_addr + remaining = auth.lockout_remaining(ip) + if remaining: + flash(_lockout_message(remaining), "error") + return render_template("login.html", title="Sign in"), 429 + password = request.form.get("password", "") + if auth.verify_admin_password(password): + # login_admin() clears the session and rotates the CSRF token + # (session-fixation defence) and remembers the display name used + # for comment ownership. + auth.login_admin(_admin_username()) + flash("Welcome back.", "success") + return redirect(url_for("admin.dashboard")) + locked = auth.record_failed_login(ip) + if locked: + flash(_lockout_message(locked), "error") + else: + flash("Invalid password. Please try again.", "error") + return render_template("login.html", title="Sign in") + + +@bp.route("/logout", methods=["POST"]) +@_login_required +def admin_logout(): + # POST + CSRF so a third-party page cannot sign the admin out; a GET link + # would be triggerable from any tag. + if not _check_csrf(): + abort(400) + auth.logout_admin() + flash("You have been signed out.", "info") + return redirect(url_for("public.index")) + + +@bp.route("/password", methods=["GET", "POST"]) +@_login_required +def admin_password(): + """Let a signed-in admin change the admin password from the browser. + + The current password is required even though the session is already + authenticated: otherwise anyone who got hold of an unlocked browser could + lock the real owner out. Changing the password invalidates every existing + session (they carry the old password stamp), so this session is signed in + again afterwards to keep the person who just changed it logged in. + """ + if request.method == "POST": + if not _check_csrf(): + return redirect(url_for("admin.admin_password")) + current = request.form.get("current_password", "") + new = request.form.get("new_password", "") + confirm = request.form.get("confirm_password", "") + if not auth.verify_admin_password(current): + flash("Current password is incorrect.", "error") + elif new != confirm: + flash("The new passwords do not match.", "error") + else: + problem = auth.password_problem(new) + if problem: + flash("Password rejected: %s." % problem, "error") + else: + auth.set_admin_password(new) + # set_admin_password() bumped the stamp, which invalidated this + # session too; re-establish it so the admin is not kicked out. + auth.login_admin(_admin_username()) + flash( + "Password updated. Any other signed-in sessions have been " + "signed out.", + "success", + ) + return redirect(url_for("admin.admin_password")) + return render_template( + "admin/password.html", + min_length=auth.MIN_PASSWORD_LENGTH, + active_page="password", + ) + + +# --------------------------------------------------------------------------- # +# Media galleries (albums) +# --------------------------------------------------------------------------- # +@bp.route("/albums") +@_login_required +def albums(): + db = get_db() + albums_list = _all_albums() + ungrouped_count = len(_ungrouped_media()) + album_counts = {a["id"]: len(_album_media(a["id"])) for a in albums_list} + return render_template( + "admin/albums.html", + albums=albums_list, + ungrouped_count=ungrouped_count, + album_counts=album_counts, + active_page="albums", + ) + + +@bp.route("/albums/new", methods=["GET", "POST"]) +@_login_required +def album_new(): + db = get_db() + if request.method == "POST": + if not _check_csrf(): + flash("Invalid request.", "error") + return redirect(url_for("admin.albums")) + name = (request.form.get("name") or "").strip() + if not name: + flash("Name is required.", "error") + return redirect(url_for("admin.albums")) + slug = _slugify(name) + base, n = slug, 1 + while db.execute("SELECT 1 FROM media_albums WHERE slug = ?", (slug,)).fetchone(): + slug = f"{base}-{n}" + n += 1 + db.execute( + "INSERT INTO media_albums (name, slug, description, created_at) VALUES (?, ?, ?, ?)", + (name, slug, (request.form.get("description") or "").strip(), _utcnow()), + ) + db.commit() + flash(f"Album '{name}' created.", "success") + return redirect(url_for("admin.albums")) + return render_template( + "admin/albums.html", + albums=_all_albums(), + ungrouped_count=len(_ungrouped_media()), + # The template reads album_counts.get(...), so a missing value made the + # "new album" page fail with an UndefinedError (HTTP 500). + album_counts={}, + active_page="albums", + ) + + +@bp.route("/albums//edit", methods=["GET", "POST"]) +@_login_required +def album_edit(slug): + db = get_db() + album = _album_by_slug(slug) + if not album: + abort(404) + if request.method == "POST": + if not _check_csrf(): + flash("Invalid request.", "error") + return redirect(url_for("admin.albums")) + name = (request.form.get("name") or "").strip() + if not name: + flash("Name is required.", "error") + return redirect(url_for("admin.albums")) + # The slug is the album's public URL (/photos/), so a rename must + # not silently break existing links: only the name and description are + # updated here. + db.execute( + "UPDATE media_albums SET name = ?, description = ? WHERE id = ?", + (name, (request.form.get("description") or "").strip(), album["id"]), + ) + db.commit() + flash("Album updated.", "success") + return redirect(url_for("admin.albums")) + return render_template( + "admin/albums.html", + albums=_all_albums(), + editing=album, + ungrouped_count=len(_ungrouped_media()), + album_counts={album["id"]: len(_album_media(album["id"]))}, + active_page="albums", + ) + + +@bp.route("/albums//delete", methods=["POST"]) +@_login_required +def album_delete(slug): + db = get_db() + album = _album_by_slug(slug) + if not album: + abort(404) + if not _check_csrf(): + flash("Invalid request.", "error") + return redirect(url_for("admin.albums")) + # Uncouple, don't delete: photos stay in /uploads and become ungrouped. + db.execute("UPDATE media SET album_id = NULL WHERE album_id = ?", (album["id"],)) + db.execute("DELETE FROM media_albums WHERE id = ?", (album["id"],)) + db.commit() + flash(f"Album '{album['name']}' deleted.", "success") + return redirect(url_for("admin.albums")) + + +# --------------------------------------------------------------------------- # +# Media management (assign / remove photos from albums) +# --------------------------------------------------------------------------- # +@bp.route("/media") +@_login_required +def media_list(): + db = get_db() + albums = _all_albums() + album_names = {a["id"]: a["name"] for a in albums} + grouped, ungrouped = {}, [] + for row in db.execute( + "SELECT * FROM media ORDER BY COALESCE(album_id, 0) ASC, position ASC, id ASC" + ).fetchall(): + aid = row["album_id"] + (grouped.setdefault(aid, []) if aid is not None else ungrouped).append(row) + return render_template( + "admin/media.html", + albums=albums, + album_names=album_names, + grouped=grouped, + ungrouped=ungrouped, + active_page="media", + ) + + +@bp.route("/media//assign", methods=["POST"]) +@_login_required +def media_assign(mid): + db = get_db() + photo = _media_by_id(mid) + if not photo: + abort(404) + if not _check_csrf(): + flash("Invalid request.", "error") + return redirect(url_for("admin.media_list")) + try: + album_id = int(request.form.get("album_id") or 0) + except (TypeError, ValueError): + album_id = 0 + if album_id <= 0 or not _album_by_id(album_id): + # A missing/non-numeric album_id raised ValueError (HTTP 500), and a + # stale form could point at an album that no longer exists. + flash("Please choose a valid album.", "error") + return redirect(url_for("admin.media_list")) + db.execute( + "UPDATE media SET album_id = ?, position = (SELECT COALESCE(MAX(position), 0) + 1 FROM media WHERE album_id = ?) WHERE id = ?", + (album_id, album_id, mid), + ) + db.commit() + flash("Photo added to album.", "success") + return redirect(url_for("admin.media_list")) + + +@bp.route("/media//remove", methods=["POST"]) +@_login_required +def media_remove(mid): + db = get_db() + photo = _media_by_id(mid) + if not photo: + abort(404) + if not _check_csrf(): + flash("Invalid request.", "error") + return redirect(url_for("admin.media_list")) + # Delete the photo entirely: remove the file on disk and the DB row. + try: + os.remove(os.path.join(UPLOAD_DIR, photo["filename"])) + except OSError: + pass + # The generated thumbnail lives next to the original; remove it too so + # deleted photos don't leave files behind. + thumb_name = os.path.basename((photo["thumb_url"] or "").strip()) + if thumb_name: + try: + os.remove(os.path.join(UPLOAD_DIR, thumb_name)) + except OSError: + pass + db.execute("DELETE FROM media WHERE id = ?", (mid,)) + db.commit() + flash("Photo removed.", "success") + return redirect(url_for("admin.media_list")) + + +# --------------------------------------------------------------------------- # +# Dashboard +# --------------------------------------------------------------------------- # + +@bp.route("/dashboard") +@_login_required +def dashboard(): + db = get_db() + count = db.execute("SELECT COUNT(*) FROM posts").fetchone()[0] + published = db.execute("SELECT COUNT(*) FROM posts WHERE status = 'published'").fetchone()[0] + drafts = db.execute("SELECT COUNT(*) FROM posts WHERE status = 'draft'").fetchone()[0] + posts = db.execute("SELECT * FROM posts ORDER BY created_at DESC").fetchall() + return render_template( + "admin/dashboard.html", + count=count, + published=published, + drafts=drafts, + posts=posts, + pending=_pending_comments()[:5], + active_page="dashboard", + ) + + +# --------------------------------------------------------------------------- # +# Posts CRUD +# --------------------------------------------------------------------------- # +@bp.route("/posts") +@_login_required +def posts(): + db = get_db() + posts = db.execute("SELECT * FROM posts ORDER BY created_at DESC").fetchall() + return render_template("admin/posts.html", posts=posts) + + +@bp.route("/posts/new", methods=["GET", "POST"]) +@_login_required +def post_new(): + body_html = "" + if request.method == "POST": + if not _check_csrf(): + return render_template("admin/post_edit.html", post=None, categories=[], body_html=body_html, active_page="posts") + db = get_db() + title = (request.form.get("title") or "").strip() + if not title: + flash("Title is required.", "error") + return render_template("admin/post_edit.html", post=None, categories=[], body_html=body_html, active_page="posts") + slug = _slugify(request.form.get("slug") or title) + base, n = slug, 1 + while db.execute("SELECT 1 FROM posts WHERE slug = ?", (slug,)).fetchone(): + slug = f"{base}-{n}" + n += 1 + now = _utcnow() + # An optional backdate: the public site displays and orders posts by + # created_at, so that is the field a "post date" really controls. + created_at = _post_timestamp(request.form.get("post_date"), now) or now + db.execute( + """ + INSERT INTO posts + (title, slug, body, excerpt, author, category, tags, status, + created_at, updated_at, published_at) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) + """, + (title, slug, request.form.get("body", ""), request.form.get("excerpt", ""), + request.form.get("author") or "editor", request.form.get("category") or "General", + request.form.get("tags") or "", _valid_status(request.form.get("status")), + created_at, now, now), + ) + db.commit() + flash("Post created.", "success") + return redirect(url_for("admin.posts")) + return render_template("admin/post_edit.html", post=None, categories=[], body_html=body_html, active_page="posts") + + +@bp.route("/posts//edit", methods=["GET", "POST"]) +@_login_required +def post_edit(pid): + db = get_db() + row = db.execute("SELECT * FROM posts WHERE id = ?", (pid,)).fetchone() + post = dict(row) if row else None + if not post: + abort(404) + cats = db.execute("SELECT slug, name FROM categories ORDER BY name").fetchall() + if request.method == "POST": + if not _check_csrf(): + return render_template("admin/post_edit.html", post=post, categories=cats, body_html=to_html(post["body"]), active_page="posts") + new_slug = _slugify(request.form.get("slug") or request.form.get("title") or "") + base, n = new_slug, 1 + while db.execute("SELECT 1 FROM posts WHERE slug = ? AND id != ?", (new_slug, pid,)).fetchone(): + new_slug = f"{base}-{n}" + n += 1 + now = _utcnow() + status = _valid_status(request.form.get("status")) + # Keep an existing publish time (so a scheduled post stays scheduled); + # stamp one the first time the post actually goes live. + published_at = post.get("published_at") or "" + if status == "published" and not published_at: + published_at = now + # Blank/invalid date input keeps the stored date; a real one backdates + # the post (created_at drives display, ordering and archive months). + created_at = ( + _post_timestamp( + request.form.get("post_date"), post.get("created_at") or now + ) + or post.get("created_at") + or now + ) + db.execute( + """ + UPDATE posts + SET title = ?, slug = ?, body = ?, excerpt = ?, author = ?, + category = ?, tags = ?, status = ?, updated_at = ?, published_at = ?, + created_at = ? + WHERE id = ? + """, + (request.form.get("title") or "", new_slug, + request.form.get("body", ""), request.form.get("excerpt", ""), + request.form.get("author") or "editor", request.form.get("category") or "General", + request.form.get("tags") or "", status, now, published_at, created_at, pid), + ) + db.commit() + flash("Post updated.", "success") + return redirect(url_for("admin.post_edit", pid=pid)) + return render_template("admin/post_edit.html", post=post, categories=cats, body_html=to_html(post["body"]), active_page="posts") + + +@bp.route("/posts//delete", methods=["POST"]) +@_login_required +def post_delete(pid): + if not _check_csrf(): + return redirect(url_for("admin.posts")) + db = get_db() + if db.execute("SELECT 1 FROM posts WHERE id = ?", (pid,)).fetchone(): + # Delete the post's comments too; they used to linger forever and kept + # showing up in moderation counts. + db.execute( + "DELETE FROM comments WHERE object_type = 'post' AND object_id = ?", (pid,) + ) + db.execute("DELETE FROM posts WHERE id = ?", (pid,)) + db.commit() + flash("Post deleted.", "info") + return redirect(url_for("admin.posts")) + + +# --------------------------------------------------------------------------- # +# Categories CRUD +# --------------------------------------------------------------------------- # +@bp.route("/categories") +@_login_required +def categories(): + db = get_db() + cats = db.execute("SELECT slug, name FROM categories ORDER BY name").fetchall() + return render_template("admin/categories.html", categories=cats, active_page="categories") + + +@bp.route("/categories/new", methods=["GET", "POST"]) +@_login_required +def category_new(): + if request.method == "POST": + if not _check_csrf(): + return render_template("admin/categories.html", categories=None, active_page="posts") + db = get_db() + name = (request.form.get("name") or "").strip() + if not name: + flash("Name is required.", "error") + return render_template("admin/categories.html", categories=None, active_page="posts") + slug = _slugify(name) + base, n = slug, 1 + while db.execute("SELECT 1 FROM categories WHERE slug = ?", (slug,)).fetchone(): + slug = f"{base}-{n}" + n += 1 + db.execute("INSERT INTO categories (slug, name) VALUES (?, ?)", (slug, name)) + db.commit() + flash("Category created.", "success") + return redirect(url_for("admin.categories")) + return render_template("admin/categories.html", categories=None, active_page="categories") + + +@bp.route("/categories//delete", methods=["POST"]) +@_login_required +def category_delete(slug): + if not _check_csrf(): + return redirect(url_for("admin.categories")) + db = get_db() + if slug != "general": # never delete the default category + db.execute("DELETE FROM categories WHERE slug = ?", (slug,)) + db.commit() + flash("Category deleted.", "info") + return redirect(url_for("admin.categories")) + + +# --------------------------------------------------------------------------- # +# Sidebar link tree +# --------------------------------------------------------------------------- # +# Schemes a sidebar link may use. Anything else (notably javascript:) is +# rejected, so a mistyped/pasted URL can never become script on every page. +_LINK_SCHEMES = ("http", "https", "mailto") + + +def _link_url(raw): + """Normalise a submitted link URL; return "" when it is unusable. + + Bare domains ("example.com") get https:// so the common case works without + the admin having to type a scheme. Site-relative targets (/p/about, #top) + are kept as-is. + """ + url = (raw or "").strip() + if not url or any(ch.isspace() for ch in url): + return "" + lowered = url.lower() + if lowered.startswith(("/", "#", "?")): + return url + if "://" not in url and not lowered.startswith("mailto:"): + # Reject a non-allowlisted scheme outright (javascript:, data:, …) + # rather than turning it into a bogus https URL. A trailing port + # (example.com:8080) is not a scheme, hence the (?!\d) guard. + if re.match(r"^[a-z][a-z0-9+.\-]*:(?!\d)", lowered): + return "" + url = "https://" + url + parts = urlsplit(url) + scheme = parts.scheme.lower() + if scheme not in _LINK_SCHEMES: + return "" + if scheme in ("http", "https") and not parts.netloc: + return "" + return url + + +@bp.route("/links", methods=["GET", "POST"]) +@_login_required +def links(): + """Manage the sidebar link tree. The public panel is hidden while empty.""" + db = get_db() + if request.method == "POST": + if not _check_csrf(): + return redirect(url_for("admin.links")) + label = (request.form.get("label") or "").strip()[:80] + url = _link_url(request.form.get("url")) + if not label or not url: + flash("A label and a valid http(s) or mailto URL are required.", "error") + return redirect(url_for("admin.links")) + # Same pattern as pages: append after whatever is already listed. + position = db.execute( + "SELECT COALESCE(MAX(position), 0) + 1 FROM links" + ).fetchone()[0] + db.execute( + "INSERT INTO links (label, url, position, created_at) VALUES (?, ?, ?, ?)", + (label, url, position, _utcnow()), + ) + db.commit() + flash("Link added.", "success") + return redirect(url_for("admin.links")) + rows = db.execute("SELECT * FROM links ORDER BY position ASC, id ASC").fetchall() + return render_template("admin/links.html", links=rows, active_page="links") + + +@bp.route("/links//delete", methods=["POST"]) +@_login_required +def link_delete(lid): + if not _check_csrf(): + return redirect(url_for("admin.links")) + db = get_db() + db.execute("DELETE FROM links WHERE id = ?", (lid,)) + db.commit() + flash("Link removed.", "info") + return redirect(url_for("admin.links")) + + +# --------------------------------------------------------------------------- # +# Pages CRUD (content pages shown in the top nav) +# --------------------------------------------------------------------------- # +@bp.route("/pages") +@_login_required +def pages(): + db = get_db() + all_pages = db.execute( + "SELECT id, slug, title, content, position, published FROM pages " + "ORDER BY position, id" + ).fetchall() + return render_template("admin/pages.html", pages=all_pages, active_page="pages") + + +@bp.route("/pages/new", methods=["GET", "POST"]) +@_login_required +def page_new(): + if request.method == "POST": + if not _check_csrf(): + return render_template("admin/page_edit.html", page=None, categories=[], body_html="", active_page="pages") + db = get_db() + title = (request.form.get("title") or "").strip() + if not title: + flash("Title is required.", "error") + return render_template("admin/page_edit.html", page=None, categories=[], body_html="", active_page="pages") + slug = _slugify(request.form.get("slug") or title) + base, n = slug, 1 + while db.execute("SELECT 1 FROM pages WHERE slug = ?", (slug,)).fetchone(): + slug = f"{base}-{n}" + n += 1 + now = _utcnow() + # New pages are appended after existing ones. + position = db.execute("SELECT COALESCE(MAX(position), 0) + 1 FROM pages").fetchone()[0] + db.execute( + "INSERT INTO pages (slug, title, content, position, published, created_at, updated_at) " + "VALUES (?, ?, ?, ?, 1, ?, ?)", + (slug, title, request.form.get("content", ""), position, now, now), + ) + db.commit() + flash("Page created.", "success") + return redirect(url_for("admin.pages")) + return render_template("admin/page_edit.html", page=None, categories=[], body_html="", active_page="pages") + + +@bp.route("/pages//edit", methods=["GET", "POST"]) +@_login_required +def page_edit(pid): + db = get_db() + row = db.execute("SELECT * FROM pages WHERE id = ?", (pid,)).fetchone() + page = dict(row) if row else None + if not page: + abort(404) + if request.method == "POST": + if not _check_csrf(): + return render_template("admin/page_edit.html", page=page, categories=[], body_html=page["content"], active_page="pages") + new_slug = _slugify(request.form.get("slug") or request.form.get("title") or "") + base, n = new_slug, 1 + while db.execute("SELECT 1 FROM pages WHERE slug = ? AND id != ?", (new_slug, pid,)).fetchone(): + new_slug = f"{base}-{n}" + n += 1 + # Preserve display order unless the editor explicitly moved it. + position = request.form.get("position") + if position and position.strip().isdigit(): + try: + position = int(position.strip()) + except (ValueError, TypeError): + position = None + now = _utcnow() + db.execute( + "UPDATE pages SET title = ?, slug = ?, content = ?, position = ?, updated_at = ? WHERE id = ?", + (request.form.get("title") or "", new_slug, + request.form.get("content", ""), + position if position is not None else page["position"], now, pid), + ) + db.commit() + flash("Page updated.", "success") + return redirect(url_for("admin.page_edit", pid=pid)) + return render_template("admin/page_edit.html", page=page, categories=[], body_html=page["content"], active_page="pages") + + +@bp.route("/pages//delete", methods=["POST"]) +@_login_required +def page_delete(pid): + if not _check_csrf(): + return redirect(url_for("admin.pages")) + db = get_db() + if db.execute("SELECT 1 FROM pages WHERE id = ?", (pid,)).fetchone(): + db.execute( + "DELETE FROM comments WHERE object_type = 'page' AND object_id = ?", (pid,) + ) + db.execute("DELETE FROM pages WHERE id = ?", (pid,)) + db.commit() + flash("Page deleted.", "info") + return redirect(url_for("admin.pages")) + + +# --------------------------------------------------------------------------- # +# Visitor analytics (tracking) +# --------------------------------------------------------------------------- # +@bp.route("/analytics") +@_login_required +def analytics(): + """Overview: how many people visited, where they came from, what they saw.""" + db = get_db() + total_visitors = db.execute("SELECT COUNT(*) FROM visitors").fetchone()[0] + total_visits = db.execute("SELECT COUNT(*) FROM visits").fetchone()[0] + unique_pages = db.execute("SELECT COUNT(DISTINCT page_path) FROM visits").fetchone()[0] + total_countries = db.execute( + "SELECT COUNT(DISTINCT country_code) FROM visitors WHERE country_code <> ''" + ).fetchone()[0] + total_cities = db.execute( + "SELECT COUNT(DISTINCT city) FROM visitors WHERE city <> ''" + ).fetchone()[0] + + top_pages = db.execute( + """SELECT page_path, title, COUNT(*) AS c + FROM visits + GROUP BY page_path + ORDER BY c DESC, timestamp DESC + LIMIT 15""" + ).fetchall() + top_browsers = db.execute( + "SELECT browser, COUNT(*) AS c FROM visitors GROUP BY browser ORDER BY c DESC" + ).fetchall() + top_sources = db.execute( + "SELECT source, COUNT(*) AS c FROM visitors GROUP BY source ORDER BY c DESC" + ).fetchall() + top_domains = db.execute( + "SELECT referrer_domain, COUNT(*) AS c FROM visitors WHERE referrer_domain <> '' " + "GROUP BY referrer_domain ORDER BY c DESC LIMIT 15" + ).fetchall() + top_devices = db.execute( + "SELECT device, COUNT(*) AS c FROM visitors GROUP BY device ORDER BY c DESC" + ).fetchall() + + # --- Locations -------------------------------------------------------- # + top_countries = db.execute( + """ + SELECT v.country AS country, v.country_code AS country_code, + COUNT(DISTINCT v.visitor_id) AS visitors, COUNT(t.id) AS visits + FROM visitors v + LEFT JOIN visits t ON t.visitor_id = v.visitor_id + WHERE v.country <> '' + GROUP BY v.country, v.country_code + ORDER BY visits DESC, visitors DESC + LIMIT 15 + """ + ).fetchall() + + top_cities = db.execute( + """ + SELECT v.city AS city, v.region AS region, v.country AS country, + v.country_code AS country_code, + COUNT(DISTINCT v.visitor_id) AS visitors, COUNT(t.id) AS visits + FROM visitors v + LEFT JOIN visits t ON t.visitor_id = v.visitor_id + WHERE v.city <> '' + GROUP BY v.city, v.region, v.country, v.country_code + ORDER BY visits DESC, visitors DESC + LIMIT 15 + """ + ).fetchall() + + # One point per (rounded) city coordinate. Rounding collapses the tiny + # coordinate differences the geolocation API returns for the same city. + map_rows = db.execute( + """ + SELECT v.city AS city, v.region AS region, v.country AS country, + v.country_code AS country_code, + ROUND(v.latitude, 2) AS latitude, + ROUND(v.longitude, 2) AS longitude, + COUNT(DISTINCT v.visitor_id) AS visitors, COUNT(t.id) AS visits + FROM visitors v + LEFT JOIN visits t ON t.visitor_id = v.visitor_id + WHERE v.latitude IS NOT NULL AND v.longitude IS NOT NULL + GROUP BY city, region, country, country_code, latitude, longitude + ORDER BY visits DESC + LIMIT 500 + """ + ).fetchall() + map_points = [ + { + "city": row["city"], + "region": row["region"], + "country": row["country"], + "country_code": row["country_code"], + "lat": row["latitude"], + "lon": row["longitude"], + "visitors": row["visitors"], + "visits": row["visits"], + } + for row in map_rows + ] + + # --- Location trends (last 30 days) ---------------------------------- # + trend_days = 30 + today = datetime.now(timezone.utc).date() + day_labels = [ + (today - timedelta(days=trend_days - 1 - offset)).isoformat() + for offset in range(trend_days) + ] + trend_rows = db.execute( + """ + SELECT substr(t.timestamp, 1, 10) AS day, + CASE WHEN IFNULL(v.country, '') = '' THEN 'Unknown' + ELSE v.country END AS country, + COUNT(*) AS visits + FROM visits t + LEFT JOIN visitors v ON v.visitor_id = t.visitor_id + WHERE t.timestamp >= ? + GROUP BY day, country + """, + (day_labels[0],), + ).fetchall() + + country_totals = {} + for row in trend_rows: + country_totals[row["country"]] = ( + country_totals.get(row["country"], 0) + row["visits"] + ) + # The five busiest countries get their own line; the rest are grouped so the + # chart stays readable no matter how many countries show up. + top_names = [ + name + for name, _count in sorted( + country_totals.items(), key=lambda item: item[1], reverse=True + )[:5] + ] + series_values = {name: [0] * trend_days for name in top_names} + if len(country_totals) > len(top_names): + series_values["Other"] = [0] * trend_days + day_index = {day: index for index, day in enumerate(day_labels)} + for row in trend_rows: + name = row["country"] if row["country"] in series_values else "Other" + index = day_index.get(row["day"]) + if index is not None and name in series_values: + series_values[name][index] += row["visits"] + location_trend = { + "labels": day_labels, + "series": [ + {"name": name, "data": values} + for name, values in series_values.items() + ], + } + + # --- Where visitors to each page come from --------------------------- # + # Bounded to the 15 busiest pages so the dashboard stays fast on a large + # archive; each page then lists its five top countries. + page_location_rows = db.execute( + """ + WITH busiest AS ( + SELECT page_path, COUNT(*) AS total + FROM visits + GROUP BY page_path + ORDER BY total DESC + LIMIT 15 + ) + SELECT t.page_path AS page_path, + MAX(t.title) AS title, + CASE WHEN IFNULL(v.country, '') = '' THEN 'Unknown' + ELSE v.country END AS country, + IFNULL(v.country_code, '') AS country_code, + COUNT(DISTINCT v.visitor_id) AS visitors, + COUNT(*) AS visits + FROM visits t + JOIN busiest b ON b.page_path = t.page_path + LEFT JOIN visitors v ON v.visitor_id = t.visitor_id + GROUP BY t.page_path, country, v.country_code + """ + ).fetchall() + pages_by_path = {} + for row in page_location_rows: + page = pages_by_path.setdefault( + row["page_path"], + { + "path": row["page_path"], + "title": row["title"] or "", + "visits": 0, + "countries": {}, + }, + ) + page["visits"] += row["visits"] + key = (row["country"], row["country_code"]) + entry = page["countries"].setdefault( + key, + { + "country": row["country"], + "country_code": row["country_code"], + "visitors": 0, + "visits": 0, + }, + ) + entry["visitors"] += row["visitors"] + entry["visits"] += row["visits"] + page_locations = sorted( + pages_by_path.values(), key=lambda item: item["visits"], reverse=True + ) + for page in page_locations: + countries = sorted( + page["countries"].values(), + key=lambda item: (item["visits"], item["visitors"]), + reverse=True, + ) + page["countries"] = countries[:5] + page["more_countries"] = max(0, len(countries) - 5) + + return render_template( + "admin/analytics.html", + total_visitors=total_visitors, + total_visits=total_visits, + unique_pages=unique_pages, + total_countries=total_countries, + total_cities=total_cities, + top_pages=top_pages, + top_browsers=top_browsers, + top_sources=top_sources, + top_domains=top_domains, + top_devices=top_devices, + top_countries=top_countries, + top_cities=top_cities, + map_points=map_points, + location_trend=location_trend, + page_locations=page_locations, + active_page="analytics", + ) + + +@bp.route("/visitors") +@_login_required +def visitors(): + """List tracked visitors, optionally filtered by country or city.""" + db = get_db() + country = (request.args.get("country") or "").strip().upper() + city = (request.args.get("city") or "").strip() + + conditions = [] + params = [] + if country: + conditions.append("v.country_code = ?") + params.append(country) + if city: + conditions.append("v.city = ?") + params.append(city) + where = (" WHERE " + " AND ".join(conditions)) if conditions else "" + + rows = db.execute( + """ + SELECT v.visitor_id, v.browser, v.os, v.device, v.source, + v.referrer_domain, v.country, v.country_code, v.city, v.region, + v.first_seen, v.last_seen, + (SELECT COUNT(*) FROM visits WHERE visitor_id = v.visitor_id) AS visits + FROM visitors v + """ + + where + + """ + ORDER BY v.last_seen DESC, v.visitor_id DESC + LIMIT 300 + """, + params, + ).fetchall() + + countries = db.execute( + """ + SELECT country_code, country, COUNT(*) AS c + FROM visitors + WHERE country_code <> '' + GROUP BY country_code, country + ORDER BY country + """ + ).fetchall() + + # Cities are scoped to the selected country so the second dropdown never + # offers a place that cannot match. + if country: + city_rows = db.execute( + "SELECT DISTINCT city FROM visitors WHERE city <> '' " + "AND country_code = ? ORDER BY city", + (country,), + ).fetchall() + else: + city_rows = db.execute( + "SELECT DISTINCT city FROM visitors WHERE city <> '' ORDER BY city" + ).fetchall() + + return render_template( + "admin/visitors.html", + rows=rows, + countries=countries, + cities=[row["city"] for row in city_rows], + selected_country=country, + selected_city=city, + active_page="visitors", + ) + + +@bp.route("/visits/") +@_login_required +def visit_history(vid): + """Show every page a single visitor visited, most recent first.""" + v = get_db().execute("SELECT * FROM visitors WHERE visitor_id = ?", (vid,)).fetchone() + if not v: + abort(404) + visits = get_db().execute( + """SELECT page_path, title, timestamp FROM visits + WHERE visitor_id = ? ORDER BY timestamp DESC""", + (vid,), + ).fetchall() + return render_template( + "admin/visit_history.html", + visitor=v, + visits=visits, + active_page="visitors", + ) + + +# --------------------------------------------------------------------------- # +# Comments moderation +# --------------------------------------------------------------------------- # +@bp.route("/comments") +@_login_required +def comments(): + """Moderation dashboard: counts + every comment that needs a human eye. + + Pending comments get full action buttons (approve/reject/spam/delete). A + rejected or spam comment leaves the pending queue but is still rendered below + so an admin can review what they flagged and un-reject if they changed their + mind — otherwise the dashboard would only ever show the counts, never the text. + """ + counts = _comment_counts() + pending = _pending_comments() + db = get_db() + rejected = db.execute( + "SELECT * FROM comments WHERE status='rejected' ORDER BY created_at DESC, id DESC" + ).fetchall() + spam = db.execute( + "SELECT * FROM comments WHERE status='spam' ORDER BY created_at DESC, id DESC" + ).fetchall() + return render_template("admin/comments.html", counts=counts, comments=pending, rejected=rejected, spam=spam) + + +@bp.route("/comments//approve", methods=["POST"]) +@_login_required +def comment_approve(cid): + if not _check_csrf(): + return redirect(url_for("admin.comments")) + db = get_db() + row = _comment_by_id(cid) + if not row: + abort(404) + db.execute("UPDATE comments SET status='approved', updated_at=? WHERE id=?", (_utcnow(), cid)) + db.commit() + flash("Comment approved.", "success") + return redirect(url_for("admin.comments")) + + +@bp.route("/comments//reject", methods=["POST"]) +@_login_required +def comment_reject(cid): + if not _check_csrf(): + return redirect(url_for("admin.comments")) + db = get_db() + row = _comment_by_id(cid) + if not row: + abort(404) + # Rejected comments are hidden from the public but retained for review. + db.execute("UPDATE comments SET status='rejected', updated_at=? WHERE id=?", (_utcnow(), cid)) + db.commit() + flash("Comment rejected.", "info") + return redirect(url_for("admin.comments")) + + +@bp.route("/comments//unreject", methods=["POST"]) +@_login_required +def comment_unreject(cid): + """Move a rejected comment back to pending so it can be reviewed again.""" + if not _check_csrf(): + return redirect(url_for("admin.comments")) + db = get_db() + row = _comment_by_id(cid) + if not row: + abort(404) + db.execute("UPDATE comments SET status='pending', updated_at=? WHERE id=?", (_utcnow(), cid)) + db.commit() + flash("Comment returned to moderation.", "success") + return redirect(url_for("admin.comments")) + + +@bp.route("/comments//spam", methods=["POST"]) +@_login_required +def comment_spam(cid): + if not _check_csrf(): + return redirect(url_for("admin.comments")) + db = get_db() + row = _comment_by_id(cid) + if not row: + abort(404) + db.execute("UPDATE comments SET status='spam', updated_at=? WHERE id=?", (_utcnow(), cid)) + db.commit() + flash("Comment marked as spam.", "info") + return redirect(url_for("admin.comments")) + + +@bp.route("/comments//delete", methods=["POST"]) +@_login_required +def comment_delete(cid): + if not _check_csrf(): + return redirect(url_for("admin.comments")) + db = get_db() + row = _comment_by_id(cid) + if not row: + abort(404) + db.execute("DELETE FROM comments WHERE id=?", (cid,)) + db.commit() + flash("Comment deleted.", "info") + return redirect(url_for("admin.comments")) + + +# --------------------------------------------------------------------------- # +# Comments moderation +# --------------------------------------------------------------------------- # + + +# --------------------------------------------------------------------------- # +# Import / Export (WXR) — move content to and from a WordPress site. +# --------------------------------------------------------------------------- # +def _site_meta(db): + """Return (title, url, description) for the WXR channel. + + Each setting is optional; a missing row falls back to a sensible default so + an unconfigured blog still renders its admin pages instead of 500ing. + """ + title = db.execute("SELECT value FROM settings WHERE key = 'site_title'").fetchone() + tagline = db.execute("SELECT value FROM settings WHERE key = 'site_tagline'").fetchone() + meta = db.execute("SELECT value FROM settings WHERE key = 'meta_description'").fetchone() + title = title[0] if title else "My Blog" + tagline = tagline[0] if tagline else "" + desc = meta[0] if meta else tagline + url = os.environ.get("BLOG_URL", "http://localhost:8000") + return title, url, desc + + +@bp.route("/import-export", methods=["GET", "POST"]) +@_login_required +def import_export(): + """Page with an Export button and a WXR file-upload form.""" + if request.method == "POST" and "export" in request.form: + db = get_db() + title, url, desc = _site_meta(db) + wxr = wxr_export.build_wxr(db, title, url, desc) + from io import BytesIO + from flask import send_file + return send_file( + BytesIO(wxr.encode("utf-8")), + mimetype="application/xml", + as_attachment=True, + download_name="simple-blog-export.xml", + ) + # Only the title is displayed on this page. + title = _site_meta(get_db())[0] + return render_template("admin/import_export.html", site_title=title, active_page="import-export") + + +@bp.route("/import-wxr", methods=["POST"]) +@_login_required +def import_wxr_route(): + """Run a WXR import from an uploaded file and report the results.""" + if not _check_csrf(): + flash("Invalid CSRF token.", "error") + return redirect(url_for("admin.import_export")) + upload = request.files.get("file") + if not upload or not upload.filename.lower().endswith(".xml"): + flash("Please choose a .xml (WXR) file to import.", "error") + return redirect(url_for("admin.import_export")) + try: + import tempfile, os.path as _osp + with tempfile.NamedTemporaryFile("wb", delete=False) as tmp: + tmp.write(upload.read()) + tmp_path = tmp.name + try: + result = wxr_import.import_wxr(tmp_path) + finally: + _osp.unlink(tmp_path) + except Exception as exc: # pragma: no cover - defensive + flash(f"Import failed: {exc}", "error") + return redirect(url_for("admin.import_export")) + + for err in result.get("errors", []): + flash(f"Import error: {err}", "error") + flash( + f"Import done — {result['posts_imported']} post(s) added, " + f"{result['categories_added']} category(ies), " + f"{result['comments_imported']} comment(s). " + + (f"{result['posts_skipped']} skipped as duplicates." if result.get("posts_skipped") else ""), + "success", + ) + return redirect(url_for("admin.import_export")) diff --git a/blog/analytics.py b/blog/analytics.py new file mode 100644 index 0000000..26f22c9 --- /dev/null +++ b/blog/analytics.py @@ -0,0 +1,518 @@ +"""Visitor analytics — parse request metadata and persist visits/visitors. + +This module holds the pure logic behind the tracking middleware so it can be +unit-tested without spinning up Flask or faking HTTP headers. The app factory +(`blog/__init__.py`) wires `record_visit()` into the request cycle; the UA and +referrer parsing are deliberately dependency-free (stdlib only). + +What we capture for every public-page visit: + - browser / os / device -> from the User-Agent header + - referrer + source -> from the Referer header (where they found us) + - page path + title -> from the request URL + a lightweight lookup + - approximate location -> from the client IP (country/region/city + coords) + +Only an opaque `visitor_id` cookie is used to correlate visits. The IP address +itself is never stored: geolocation lookups are cached under a SHA-256 hash and +only the resolved place is kept. +""" + +import hashlib +import ipaddress +import json +import os +import re +import time +import urllib.request +from urllib.parse import quote, urlparse + +from .db import get_db + +# --- User-Agent parsing ----------------------------------------------------- # +# Ordered most-specific-first. Each entry is (token, browser-name); the first +# matching token wins. Chrome-on-iOS masquerades as Safari, so it is checked +# before the generic Safari rule. +_BROWSER_TOKENS = [ + ("Edg", "Edge"), # catches Edg / EdgE / EdgiOS / EdgA (Chromium-based Edge) + ("Firefox", "Firefox"), + ("Opera", "Opera"), + ("SamsungBrowser", "Samsung Internet"), + ("CriOS", "Safari"), # Chrome on iOS reports itself as Safari + ("Chrome", "Chrome"), + ("Vivaldi", "Vivaldi"), + ("Brave", "Brave"), + ("Edge", "Edge"), # legacy Edge (rare, pre-Chromium) + ("KaiaOS", "KaiaOS"), + ("Coast", "Firefox OS"), + ("Safari", "Safari"), +] + +# Ordered most-specific-first. iOS tokens MUST precede "Mac OS X"/"Darwin" +# because every Apple UA also contains "Mac OS X". +_OS_TOKENS = [ + ("iPhone", "iOS"), + ("iPad", "iOS"), + ("iPod", "iOS"), + ("Windows", "Windows"), + ("Mac OS X", "macOS"), + ("Darwin", "macOS"), + ("Android", "Android"), + ("Linux", "Linux"), +] + +_DEVICE_TOKENS = ( + "Mobile iPad Tablet XBOX ONE PLAYSTATION Vita PS4 PS5 Baidu" +) + + +def parse_user_agent(ua): + """Return a (browser, os, device) tuple from a User-Agent string. + + Any field we cannot confidently identify is returned as an empty string so + the stored row stays clean rather than falling back to a wrong default. + """ + ua = (ua or "").strip() + if not ua: + return "", "", "" + + browser = _first_match(ua, _BROWSER_TOKENS) + os_name = _first_match(ua, _OS_TOKENS) + device = "mobile" if any(tok in ua for tok in _DEVICE_TOKENS.split()) else "desktop" + + # iPad is frequently a desktop-class device; downgrade only when the UA is + # an iOS Safari build (real touch/iPhone-style browsing). + if os_name == "iOS" and "Mobile" not in ua: + device = "desktop" + return browser, os_name, device + + +def _first_match(ua, tokens): + for token, name in tokens: + if token in ua: + return name + return "" + + +# Substrings that mark an automated client. Analytics used to record crawlers, +# uptime monitors and CLI fetchers as if they were readers, which inflated every +# number on the dashboard. +_BOT_TOKENS = ( + "bot", "crawl", "spider", "slurp", "scrapy", "curl/", "wget", + "python-requests", "python-urllib", "httpx", "httpclient", "go-http-client", + "headlesschrome", "phantomjs", "monitor", "uptime", "pingdom", "feedfetcher", + "preview", "facebookexternalhit", "whatsapp", "telegrambot", +) + + +def is_bot(user_agent): + """True when the User-Agent looks automated (or is missing entirely).""" + ua = (user_agent or "").strip().lower() + if not ua: + return True + return any(token in ua for token in _BOT_TOKENS) + + +# --- Referrer / source classification --------------------------------------- # +# Where the visitor came from. The raw referrer and its domain are always kept +# (for detail); `source` is a coarse category shown prominently in the UI. +_SEARCH_DOMAINS = { + "google", "bing", "duckduckgo", "yahoo", "brave", "startpage", "mojeek", + "ecosia", "qwant", "yandex", "search.marginalia.nu", +} +_SOCIAL_DOMAINS = { + "twitter", "x.com", "facebook", "fb.com", "instagram", "linkedin", + "reddit", "pinterest", "tumblr", "youtube", "tiktok", "vimeo", "mastodon", +} + + +def _matches_any(host, domain_set): + """True if any label of `host` (excluding the TLD) is in `domain_set`.""" + host = host.lower() + if host in domain_set: + return True + for label in host.split(".")[:-1]: # drop the top-level domain + if label in domain_set: + return True + return False + + +def classify_source(referer): + """Return a (referrer, domain, source) tuple. + + `source` is one of: 'direct', 'search', 'social', 'referral', 'external'. + """ + if not referer: + return "", "", "direct" + + referer = referer.strip() + parsed = urlparse(referer) + domain = (parsed.netloc or "").lower() + host = domain.split(":")[0] # drop any port + + if not host: + return referer, "", "external" + + # Match on the bare domain name appearing as any label (so "www.google.com", + # "mobile.twitter.com" etc. are still recognised), then collapse a leading + # subdomain (www./m./mobile.) to the registrable domain for clean grouping. + host = host.lower() + if _matches_any(host, _SEARCH_DOMAINS): + source = "search" + elif _matches_any(host, _SOCIAL_DOMAINS): + source = "social" + else: + source = "referral" # any other known web origin + + labels = host.split(".") + domain = ".".join(labels[1:]) if len(labels) > 2 else host + return referer, domain, source + + +# --- Location (IP geolocation) ---------------------------------------------- # +# The dashboard shows where readers are, so each visitor's approximate location +# is resolved from their IP address: country/region/city plus map coordinates. +# +# Lookups are best-effort and cached per *hashed* IP (geo_cache), so repeat +# visits cost one indexed read and a flaky/unreachable service never blocks a +# page: the visit is still recorded, just without a location. Set BLOG_GEOIP=0 +# to turn all outbound lookups off. +GEO_API_TEMPLATE = os.environ.get("BLOG_GEOIP_URL", "https://ipwho.is/{ip}") +GEO_POSITIVE_TTL = 60 * 60 * 24 * 30 # re-check a resolved address after 30 days +GEO_NEGATIVE_TTL = 60 * 60 * 24 # retry a failed lookup after a day + + +def _env_float(name, default): + try: + return float(os.environ.get(name, default)) + except (TypeError, ValueError): + return default + + +def geo_enabled(): + """Geo lookups default to on; BLOG_GEOIP=0 opts out entirely.""" + return os.environ.get("BLOG_GEOIP", "1").strip().lower() not in ( + "0", "false", "no", "off", + ) + + +def _blank_location(): + return { + "country": "", + "country_code": "", + "region": "", + "city": "", + "latitude": None, + "longitude": None, + } + + +def hash_ip(ip): + """Stable pseudonymous cache key; the raw IP never reaches the database.""" + return hashlib.sha256((ip or "").strip().encode("utf-8", "replace")).hexdigest() + + +def _row_location(row): + return { + "country": row["country"] or "", + "country_code": row["country_code"] or "", + "region": row["region"] or "", + "city": row["city"] or "", + "latitude": row["latitude"], + "longitude": row["longitude"], + } + + +def _coordinate(value, limit): + try: + number = float(value) + except (TypeError, ValueError): + return None + if -limit <= number <= limit: + return round(number, 4) + return None + + +GEO_SELF_KEY = "__server__" # cache key for this host's own public location + + +def local_fallback_enabled(): + """Whether LAN/local visitors fall back to the server's own location.""" + return os.environ.get("BLOG_GEOIP_LOCAL", "1").strip().lower() not in ( + "0", "false", "no", "off", + ) + + +def _public_ip(value): + """Return `value` as a normalised public IP string, or ''.""" + try: + address = ipaddress.ip_address((value or "").strip()) + except ValueError: + return "" + return str(address) if address.is_global else "" + + +def client_ip(remote_addr, headers, trust_proxy=False): + """Resolve the reader's address, looking through a local proxy if needed. + + Docker's port publishing and LAN reverse proxies make every request appear + to come from a private address (172.20.0.1, 192.168.2.2, ...), which used to + switch geolocation off entirely. When the direct peer is private/loopback the + real address is only available in the forwarding headers, so the first public + address they name is used. Headers from a direct internet peer are ignored + (unless BLOG_TRUST_PROXY is set) so clients cannot spoof their own location. + """ + peer = (remote_addr or "").strip() + try: + peer_is_local = not ipaddress.ip_address(peer).is_global + except ValueError: + peer_is_local = True + if not (peer_is_local or trust_proxy): + return peer + + for name in ("CF-Connecting-IP", "True-Client-IP", "X-Real-IP"): + candidate = _public_ip(headers.get(name, "")) + if candidate: + return candidate + for part in (headers.get("X-Forwarded-For", "") or "").split(","): + candidate = _public_ip(part) + if candidate: + return candidate + return peer + + +def _cache_location(db, ip_hash, location, ok): + db.execute( + """ + INSERT INTO geo_cache + (ip_hash, ok, country, country_code, region, city, latitude, + longitude, checked_at) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?) + ON CONFLICT(ip_hash) DO UPDATE SET + ok = excluded.ok, + country = excluded.country, + country_code = excluded.country_code, + region = excluded.region, + city = excluded.city, + latitude = excluded.latitude, + longitude = excluded.longitude, + checked_at = excluded.checked_at + """, + ( + ip_hash, + 1 if ok else 0, + location["country"], + location["country_code"], + location["region"], + location["city"], + location["latitude"], + location["longitude"], + time.time(), + ), + ) + db.commit() + + +def lookup_location(ip): + """Return an approximate location dict for a visitor's IP address. + + Public addresses are resolved directly. Private/loopback addresses (LAN + readers, or every request behind Docker's port mapping when nothing forwards + the real address) have no location of their own, so they fall back to this + server's own public location — the closest sensible guess for a self-hosted + blog. Set BLOG_GEOIP_LOCAL=0 to disable that fallback. Any network/API + problem degrades to an empty location rather than an error. + """ + location = _blank_location() + if not geo_enabled(): + return location + + ip = (ip or "").strip() + if ip: + try: + if not ipaddress.ip_address(ip).is_global: + ip = "" + except ValueError: + return location + if not ip and not local_fallback_enabled(): + return location + + db = get_db() + key = hash_ip(ip or GEO_SELF_KEY) + row = db.execute("SELECT * FROM geo_cache WHERE ip_hash = ?", (key,)).fetchone() + if row is not None: + ttl = GEO_POSITIVE_TTL if row["ok"] else GEO_NEGATIVE_TTL + if time.time() - (row["checked_at"] or 0) < ttl: + return _row_location(row) + + try: + # An empty {ip} resolves the caller, i.e. this server's egress address. + api_request = urllib.request.Request( + GEO_API_TEMPLATE.format(ip=quote(ip)), + headers={"User-Agent": "SimpleBlogAnalytics/1.0"}, + ) + with urllib.request.urlopen( + api_request, timeout=_env_float("BLOG_GEOIP_TIMEOUT", 2.5) + ) as response: + payload = json.loads(response.read(65536).decode("utf-8", "replace")) + if not payload.get("success", True): + raise ValueError("geolocation lookup failed") + location = { + "country": (payload.get("country") or "").strip(), + "country_code": (payload.get("country_code") or "").strip().upper(), + "region": (payload.get("region") or "").strip(), + "city": (payload.get("city") or "").strip(), + "latitude": _coordinate(payload.get("latitude"), 90), + "longitude": _coordinate(payload.get("longitude"), 180), + } + except Exception: + # Offline, rate-limited or malformed: remember the failure for a day so + # every page view does not pay for another timeout. + try: + _cache_location(db, key, location, ok=False) + except Exception: + pass + return _blank_location() + + try: + _cache_location(db, key, location, ok=True) + except Exception: + pass + return location + + +def country_flag(code): + """Turn an ISO 3166-1 alpha-2 code into a flag emoji ('' when unknown).""" + code = (code or "").strip().upper() + if len(code) != 2 or not code.isalpha(): + return "" + return "".join(chr(0x1F1E6 + ord(ch) - ord("A")) for ch in code) + + +# --- Persistence ------------------------------------------------------------- # +def record_visit(visitor, page_path, title, ip=""): + """Upsert the visitor row and append a visit for `page_path`. + + `visitor` is a dict of the mutable fields (browser, os, device, referrer, + referrer_domain, source, country, ...). `ip` is used once to resolve the + visitor's approximate location when they are new or still have none. + Returns the visitor row. + """ + db = get_db() + + # Upsert: match on visitor_id, update the mutable fields + last_seen. + row = db.execute( + "SELECT * FROM visitors WHERE visitor_id = ?", (visitor["visitor_id"],) + ).fetchone() + + # Resolve the location only when it is still missing (cached per hashed IP), + # so returning readers never trigger another lookup. + visitor = dict(visitor) + if row is None or not (row["country"] or row["city"]): + visitor.update(lookup_location(ip)) + + if row is None: + now = _utcnow() + first_seen = now + db.execute( + """ + INSERT INTO visitors + (visitor_id, browser, os, device, referrer, referrer_domain, + source, country, country_code, region, city, latitude, + longitude, first_seen, last_seen, created_at) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) + """, + ( + visitor["visitor_id"], + visitor.get("browser") or "", + visitor.get("os") or "", + visitor.get("device") or "", + visitor.get("referrer") or "", + visitor.get("referrer_domain") or "", + visitor.get("source") or "direct", + visitor.get("country") or "", + visitor.get("country_code") or "", + visitor.get("region") or "", + visitor.get("city") or "", + visitor.get("latitude"), + visitor.get("longitude"), + first_seen, + first_seen, + now, + ), + ) + else: + # Keep the first-ever referrer/source (do not overwrite with a later + # empty/changed value), but always refresh last_seen. + keep_referrer = visitor.get("referrer") or row["referrer"] + keep_domain = visitor.get("referrer_domain") or row["referrer_domain"] + keep_source = visitor.get("source") or row["source"] + # Never erase a location we already resolved with a later empty lookup. + keep_country = visitor.get("country") or row["country"] + keep_code = visitor.get("country_code") or row["country_code"] + keep_region = visitor.get("region") or row["region"] + keep_city = visitor.get("city") or row["city"] + keep_lat = ( + visitor.get("latitude") + if visitor.get("latitude") is not None + else row["latitude"] + ) + keep_lon = ( + visitor.get("longitude") + if visitor.get("longitude") is not None + else row["longitude"] + ) + db.execute( + """ + UPDATE visitors + SET browser = COALESCE(?, browser), + os = COALESCE(? , os), + device = COALESCE(? , device), + referrer = COALESCE(? , referrer), + referrer_domain = COALESCE(? , referrer_domain), + source = COALESCE(? , source), + country = COALESCE(? , country), + country_code = COALESCE(? , country_code), + region = COALESCE(? , region), + city = COALESCE(? , city), + latitude = COALESCE(? , latitude), + longitude = COALESCE(? , longitude), + last_seen = ? + WHERE visitor_id = ? + """, + ( + visitor.get("browser") or "", + visitor.get("os") or "", + visitor.get("device") or "", + keep_referrer, + keep_domain, + keep_source, + keep_country, + keep_code, + keep_region, + keep_city, + keep_lat, + keep_lon, + _utcnow(), + visitor["visitor_id"], + ), + ) + + db.execute( + """ + INSERT INTO visits (visitor_id, page_path, title, timestamp) + VALUES (?, ?, ?, ?) + """, + ( + visitor["visitor_id"], + page_path, + title or "", + _utcnow(), + ), + ) + db.commit() + return row + + +def _utcnow(): + from datetime import datetime, timezone + + return datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M:%S") diff --git a/blog/auth.py b/blog/auth.py new file mode 100644 index 0000000..a3d7fe9 --- /dev/null +++ b/blog/auth.py @@ -0,0 +1,388 @@ +"""Admin authentication: credential storage, throttling and session lifecycle. + +There is a single admin account. Its password is stored as a salted hash in the +``settings`` table, so it can be rotated from a shell without rebuilding the +container or editing environment variables:: + + python -m blog.manage set-password + +``BLOG_ADMIN_PASSWORD`` is only a *bootstrap* value: on the first run (when no +hash is stored yet) it is hashed into the database. After that it is ignored; +use the CLI to change the password. Changing the password invalidates every +existing admin session, because sessions remember the password stamp. +""" + +import os +import secrets +import sys +import time + +from flask import session +from werkzeug.security import check_password_hash, generate_password_hash + +from .db import get_db + +PASSWORD_HASH_KEY = "admin_password_hash" +PASSWORD_SET_AT_KEY = "admin_password_set_at" +SESSION_SECRET_KEY = "session_secret" + +MIN_PASSWORD_LENGTH = 12 +# Anything longer than this is almost certainly a malicious payload, and running +# a deliberately slow KDF over megabytes is a cheap CPU-exhaustion vector. +MAX_PASSWORD_LENGTH = 1024 + +# Placeholder / well-known passwords that must never be accepted. The values on +# the right are matched case-insensitively. +WEAK_PASSWORDS = { + "admin", + "administrator", + "change-me", + "change-me-in-production", + "changeme", + "letmein", + "password", + "please-change-this-to-a-long-random-string", + "please-change-me", + "secret", + "test", + "welcome", + "123456", + "12345678", + "123456789", + "qwerty", +} + +# Secret-key values that used to ship with the project. They are public, so a +# session signed with one can be forged: never use them. +PLACEHOLDER_SECRETS = { + "please-change-me", + "dev-insecure-secret", + "please-change-this-to-a-long-random-string", + "change-me", + "changeme", + "secret", +} + +# --- Failed-login throttling ------------------------------------------------ # +# Exponential backoff per client IP: the first MAX_FAILED_ATTEMPTS attempts are +# free, then the lock doubles from LOCKOUT_BASE_SECONDS up to LOCKOUT_MAX_SECONDS. +MAX_FAILED_ATTEMPTS = 5 +LOCKOUT_BASE_SECONDS = 30 +LOCKOUT_MAX_SECONDS = 15 * 60 + + +# --------------------------------------------------------------------------- # +# settings table helpers +# --------------------------------------------------------------------------- # +def get_setting(key, default=""): + row = get_db().execute( + "SELECT value FROM settings WHERE key = ?", (key,) + ).fetchone() + if row is None or row[0] is None: + return default + return row[0] + + +def set_setting(key, value): + db = get_db() + db.execute( + "INSERT INTO settings (key, value) VALUES (?, ?) " + "ON CONFLICT(key) DO UPDATE SET value = excluded.value", + (key, value), + ) + db.commit() + + +# --------------------------------------------------------------------------- # +# Passwords +# --------------------------------------------------------------------------- # +def generate_temporary_password(): + """A random, hard-to-guess password shown once when none is configured.""" + return secrets.token_urlsafe(18) + + +def password_problem(password): + """Return a human-readable reason the password is unacceptable, or None.""" + if not password: + return "the password is empty" + if len(password) < MIN_PASSWORD_LENGTH: + return "the password must be at least %d characters" % MIN_PASSWORD_LENGTH + if len(password) > MAX_PASSWORD_LENGTH: + return "the password is too long" + if password.strip().lower() in WEAK_PASSWORDS: + return "that password is a well-known default" + return None + + +def set_admin_password(password): + """Hash and store a new admin password; returns its stamp. + + The returned stamp travels inside sessions so every active login becomes + invalid as soon as the password changes. + """ + problem = password_problem(password) + if problem: + raise ValueError(problem) + stamp = str(int(time.time())) + set_setting(PASSWORD_HASH_KEY, generate_password_hash(password)) + set_setting(PASSWORD_SET_AT_KEY, stamp) + clear_login_attempts() + return stamp + + +def password_stamp(): + """Identity of the current password (empty when none is configured).""" + return get_setting(PASSWORD_SET_AT_KEY, "") + + +def verify_admin_password(password): + """Check a candidate password against the stored hash. + + The hash comparison always runs (even for an empty/oversized input) so the + response time does not reveal whether a password was supplied. + """ + stored = get_setting(PASSWORD_HASH_KEY, "") + if not stored: + return False + if not isinstance(password, str) or not password or len(password) > MAX_PASSWORD_LENGTH: + # Burn the same KDF work a real comparison would do. + check_password_hash(stored, secrets.token_hex(16)) + return False + try: + return check_password_hash(stored, password) + except (ValueError, TypeError): + # A corrupt hash in the DB must fail closed, never raise. + return False + + +def ensure_admin_credentials(app): + """Seed the stored password from the environment on first run. + + - No stored hash + a strong ``BLOG_ADMIN_PASSWORD`` -> hash it into the DB. + - No stored hash + nothing usable -> generate a random password and print it + once, so the site never comes up with a guessable default. + - A stored hash always wins; the env var is only a bootstrap value. + """ + stored = get_setting(PASSWORD_HASH_KEY, "") + env_password = os.environ.get("BLOG_ADMIN_PASSWORD") or "" + + if not stored: + if not password_problem(env_password): + set_admin_password(env_password) + app.logger.info("Admin password initialised from BLOG_ADMIN_PASSWORD.") + return + temporary = generate_temporary_password() + set_admin_password(temporary) + if env_password: + print( + "WARNING: BLOG_ADMIN_PASSWORD is a weak/default value and was " + "rejected. Change the password with: python -m blog.manage " + "set-password", + file=sys.stderr, + ) + print( + "\n" + " ============================================================\n" + " No admin password was configured, so a temporary one was\n" + " generated. Sign in with it and change it right away:\n" + "\n" + " password: %s\n" + "\n" + " Change it with:\n" + " python -m blog.manage set-password\n" + " ============================================================\n" + % temporary, + file=sys.stderr, + flush=True, + ) + return + + # A hash is stored; warn if the environment still claims to control it. + if env_password and not verify_admin_password(env_password): + app.logger.warning( + "BLOG_ADMIN_PASSWORD is set but no longer controls the admin login " + "(a password is already stored in the database). Use " + "'python -m blog.manage set-password' to change it." + ) + + +# --------------------------------------------------------------------------- # +# Session secret +# --------------------------------------------------------------------------- # +def ensure_session_secret(app): + """Configure a strong SECRET_KEY, preferring the environment. + + A placeholder/absent ``BLOG_SESSION_SECRET`` falls back to a random secret + generated once and stored in the database, so sessions survive restarts but + are never signed with a publicly known key. + """ + env_secret = (os.environ.get("BLOG_SESSION_SECRET") or "").strip() + if ( + len(env_secret) >= 32 + and env_secret.lower() not in PLACEHOLDER_SECRETS + ): + app.config["SECRET_KEY"] = env_secret + return + + stored = get_setting(SESSION_SECRET_KEY, "") + if len(stored) < 32: + stored = secrets.token_hex(32) + set_setting(SESSION_SECRET_KEY, stored) + app.logger.warning( + "BLOG_SESSION_SECRET is missing or a known placeholder; generated " + "and stored a new session secret." + ) + app.config["SECRET_KEY"] = stored + + +# --------------------------------------------------------------------------- # +# Sessions +# --------------------------------------------------------------------------- # +def session_absolute_seconds(): + try: + hours = int(os.environ.get("BLOG_SESSION_HOURS", "12")) + except ValueError: + hours = 12 + return max(1, hours) * 3600 + + +def session_idle_seconds(): + try: + minutes = int(os.environ.get("BLOG_SESSION_IDLE_MINUTES", "120")) + except ValueError: + minutes = 120 + return max(1, minutes) * 60 + + +def is_logged_in(): + """True when the session is a live, current admin login.""" + if session.get("logged_in") is not True: + return False + login_at = session.get("login_at") + last_seen = session.get("last_seen") + if not isinstance(login_at, int) or not isinstance(last_seen, int): + # Pre-upgrade sessions had no timestamps: treat them as expired. + return False + now = int(time.time()) + if now - login_at > session_absolute_seconds(): + return False + if now - last_seen > session_idle_seconds(): + return False + if session.get("pwd_stamp") != password_stamp(): + return False + return True + + +def login_admin(username): + """Start a fresh admin session (clears anything already in the session).""" + session.clear() + now = int(time.time()) + session.permanent = True + session["logged_in"] = True + session["username"] = username + session["login_at"] = now + session["last_seen"] = now + session["pwd_stamp"] = password_stamp() + # Rotate the CSRF token on privilege change (session fixation defence). + session["csrf_token"] = secrets.token_hex(32) + + +def logout_admin(): + session.clear() + + +def refresh_session(): + """Expire stale sessions and slide the idle window. + + Called once per request. Writing ``last_seen`` on every asset request would + churn cookies, so it is only refreshed about once a minute. + """ + if session.get("logged_in") is None: + return + if not is_logged_in(): + session.clear() + return + now = int(time.time()) + if now - int(session.get("last_seen", 0)) >= 60: + session["last_seen"] = now + + +# --------------------------------------------------------------------------- # +# Login throttling +# --------------------------------------------------------------------------- # +def _attempt_key(ip): + return (ip or "unknown").strip() or "unknown" + + +def lockout_remaining(ip): + """Seconds the given client is still locked out for (0 when not locked).""" + row = get_db().execute( + "SELECT locked_until FROM login_attempts WHERE key = ?", + (_attempt_key(ip),), + ).fetchone() + if row is None or not row[0]: + return 0 + return max(0, int(float(row[0]) - time.time())) + + +def record_failed_login(ip): + """Count a failed attempt and apply exponential backoff. + + Returns the number of seconds the client is now locked out for (0 if it + still has attempts left). + """ + db = get_db() + key = _attempt_key(ip) + now = time.time() + row = db.execute( + "SELECT failures FROM login_attempts WHERE key = ?", (key,) + ).fetchone() + failures = (row[0] if row else 0) + 1 + + locked_until = 0.0 + if failures >= MAX_FAILED_ATTEMPTS: + overage = failures - MAX_FAILED_ATTEMPTS + delay = min(LOCKOUT_BASE_SECONDS * (2 ** overage), LOCKOUT_MAX_SECONDS) + locked_until = now + delay + + db.execute( + "INSERT INTO login_attempts (key, failures, last_failure, locked_until) " + "VALUES (?, ?, ?, ?) " + "ON CONFLICT(key) DO UPDATE SET failures = excluded.failures, " + "last_failure = excluded.last_failure, locked_until = excluded.locked_until", + (key, failures, now, locked_until), + ) + # Opportunistic cleanup so the table cannot grow without bound. + db.execute( + "DELETE FROM login_attempts WHERE locked_until = 0 AND last_failure < ?", + (now - 24 * 3600,), + ) + db.commit() + return max(0, int(locked_until - now)) + + +def clear_login_attempts(ip=None): + """Clear the failure history for one client, or for everyone.""" + db = get_db() + if ip is None: + cur = db.execute("DELETE FROM login_attempts") + else: + cur = db.execute( + "DELETE FROM login_attempts WHERE key = ?", (_attempt_key(ip),) + ) + db.commit() + return cur.rowcount if cur.rowcount and cur.rowcount > 0 else 0 + + +def locked_clients(): + """Currently locked-out client keys, for the CLI status command.""" + now = time.time() + rows = get_db().execute( + "SELECT key, failures, locked_until FROM login_attempts " + "WHERE locked_until > ? ORDER BY locked_until DESC", + (now,), + ).fetchall() + return [ + {"key": r[0], "failures": r[1], "remaining": int(float(r[2]) - now)} + for r in rows + ] diff --git a/blog/db.py b/blog/db.py new file mode 100644 index 0000000..59bbda7 --- /dev/null +++ b/blog/db.py @@ -0,0 +1,508 @@ +"""Database helpers for the Simple Blog CMS.""" + +import os +import random +import re +import sqlite3 +import threading +import time +import unicodedata +from datetime import datetime, timezone + +from flask import current_app, g + +DATA_DIR = os.environ.get("BLOG_DATA_DIR", "/app/data") +os.makedirs(DATA_DIR, exist_ok=True) +DB_PATH = os.path.join(DATA_DIR, "blog.db") + +_lock = threading.Lock() + + +def get_db(): + """Return a per-request SQLite connection.""" + db = getattr(g, "db", None) + if db is None: + # `timeout` plus the busy_timeout pragma let a waiting writer sit out + # the lock instead of failing with "database is locked"; WAL keeps + # readers from blocking the single writer. + db = g.db = sqlite3.connect(DB_PATH, timeout=10) + db.row_factory = sqlite3.Row + db.execute("PRAGMA foreign_keys = ON") + db.execute("PRAGMA busy_timeout = 10000") + db.execute("PRAGMA journal_mode = WAL") + db.execute("PRAGMA synchronous = NORMAL") + return db + + +def init_db(): + """Create the schema and seed defaults on first run.""" + with _lock: + db = get_db() + db.executescript( + """ + CREATE TABLE IF NOT EXISTS posts ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + title TEXT NOT NULL, + slug TEXT NOT NULL UNIQUE, + body TEXT NOT NULL, + excerpt TEXT NOT NULL DEFAULT '', + author TEXT NOT NULL DEFAULT 'editor', + category TEXT NOT NULL DEFAULT 'General', + tags TEXT NOT NULL DEFAULT '', + status TEXT NOT NULL DEFAULT 'published', + created_at TEXT NOT NULL, + updated_at TEXT NOT NULL, + published_at TEXT + ); + + CREATE TABLE IF NOT EXISTS categories ( + slug TEXT PRIMARY KEY, + name TEXT NOT NULL + ); + + -- Sidebar "Links" panel (a small link tree). Each row is one + -- label/URL pair; the public sidebar hides the panel entirely + -- while this table is empty. + CREATE TABLE IF NOT EXISTS links ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + label TEXT NOT NULL, + url TEXT NOT NULL, + position INTEGER NOT NULL DEFAULT 0, + created_at TEXT NOT NULL + ); + + CREATE TABLE IF NOT EXISTS pages ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + slug TEXT NOT NULL UNIQUE, + title TEXT NOT NULL, + content TEXT NOT NULL DEFAULT '', + position INTEGER NOT NULL DEFAULT 0, + published INTEGER NOT NULL DEFAULT 1, + created_at TEXT NOT NULL, + updated_at TEXT NOT NULL + ); + + CREATE TABLE IF NOT EXISTS settings ( + key TEXT PRIMARY KEY, + value TEXT + ); + + CREATE TABLE IF NOT EXISTS visitors ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + visitor_id TEXT NOT NULL UNIQUE, + browser TEXT NOT NULL DEFAULT '', + os TEXT NOT NULL DEFAULT '', + device TEXT NOT NULL DEFAULT '', + referrer TEXT NOT NULL DEFAULT '', + referrer_domain TEXT NOT NULL DEFAULT '', + source TEXT NOT NULL DEFAULT 'direct', + country TEXT NOT NULL DEFAULT '', + country_code TEXT NOT NULL DEFAULT '', + region TEXT NOT NULL DEFAULT '', + city TEXT NOT NULL DEFAULT '', + latitude REAL, + longitude REAL, + first_seen TEXT, + last_seen TEXT, + created_at TEXT NOT NULL + ); + + -- IP -> approximate location lookups, keyed by a hash of the + -- address (the raw IP is never stored). Caching keeps repeat + -- visits fast and keeps us inside the geolocation API's limits. + CREATE TABLE IF NOT EXISTS geo_cache ( + ip_hash TEXT PRIMARY KEY, + ok INTEGER NOT NULL DEFAULT 0, + country TEXT NOT NULL DEFAULT '', + country_code TEXT NOT NULL DEFAULT '', + region TEXT NOT NULL DEFAULT '', + city TEXT NOT NULL DEFAULT '', + latitude REAL, + longitude REAL, + checked_at REAL NOT NULL + ); + + CREATE TABLE IF NOT EXISTS visits ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + visitor_id TEXT NOT NULL, + page_path TEXT NOT NULL, + title TEXT NOT NULL DEFAULT '', + timestamp TEXT NOT NULL + ); + + CREATE TABLE IF NOT EXISTS media_albums ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + name TEXT NOT NULL, + slug TEXT NOT NULL UNIQUE, + description TEXT, + position INTEGER NOT NULL DEFAULT 0, + created_at TEXT NOT NULL + ); + + CREATE TABLE IF NOT EXISTS media ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + filename TEXT NOT NULL, + url TEXT NOT NULL, + thumb_url TEXT NOT NULL DEFAULT '', + album_id INTEGER REFERENCES media_albums(id) ON DELETE SET NULL, + position INTEGER NOT NULL DEFAULT 0, + created_at TEXT NOT NULL + ); + + CREATE TABLE IF NOT EXISTS comments ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + object_type TEXT NOT NULL DEFAULT 'post', + object_id INTEGER NOT NULL, + author TEXT NOT NULL, + email TEXT NOT NULL DEFAULT '', + body TEXT NOT NULL, + status TEXT NOT NULL DEFAULT 'pending', + created_at TEXT NOT NULL, + updated_at TEXT NOT NULL + ); + + -- Failed admin logins, one row per client IP. Drives the + -- exponential-backoff lockout in blog/auth.py. + CREATE TABLE IF NOT EXISTS login_attempts ( + key TEXT PRIMARY KEY, + failures INTEGER NOT NULL DEFAULT 0, + last_failure REAL NOT NULL DEFAULT 0, + locked_until REAL NOT NULL DEFAULT 0 + ); + + -- Accepted comment submissions, one row per attempt. Backs the + -- per-IP rate limit; the old counter lived in the signed session + -- cookie, so clearing cookies reset the limit. + CREATE TABLE IF NOT EXISTS comment_attempts ( + key TEXT NOT NULL, + ts REAL NOT NULL + ); + + -- Query indexes: without them every comment lookup, visit count + -- and album listing was a full table scan. + CREATE INDEX IF NOT EXISTS idx_comments_object + ON comments (object_type, object_id, status); + CREATE INDEX IF NOT EXISTS idx_comments_status + ON comments (status, created_at); + CREATE INDEX IF NOT EXISTS idx_visits_visitor + ON visits (visitor_id, timestamp); + CREATE INDEX IF NOT EXISTS idx_visits_timestamp + ON visits (timestamp); + CREATE INDEX IF NOT EXISTS idx_media_album + ON media (album_id, position); + CREATE INDEX IF NOT EXISTS idx_comment_attempts + ON comment_attempts (key, ts); + """ + ) + db.commit() + + # Migration: media_albums was created without a `position` column on + # earlier schema versions; add it (idempotent) so existing albums keep + # their natural order. Photos already have the column. + if not db.execute( + "SELECT 1 FROM pragma_table_info('media_albums') WHERE name = 'position'" + ).fetchone(): + db.execute("ALTER TABLE media_albums ADD COLUMN position INTEGER NOT NULL DEFAULT 0") + db.commit() + + # Migration: thumbnail URL for uploaded photos. Older databases have + # only the full-size URL, so the gallery falls back to it until + # `python -m blog.manage thumbs` (or a fresh upload) fills this in. + if not db.execute( + "SELECT 1 FROM pragma_table_info('media') WHERE name = 'thumb_url'" + ).fetchone(): + db.execute("ALTER TABLE media ADD COLUMN thumb_url TEXT NOT NULL DEFAULT ''") + db.commit() + + # Migration: visitor geolocation columns. Older databases only had a + # free-text `country`; add the structured place + map coordinates so + # existing installs can show the visitor map without a reset. + for column, decl in ( + ("country_code", "TEXT NOT NULL DEFAULT ''"), + ("region", "TEXT NOT NULL DEFAULT ''"), + ("city", "TEXT NOT NULL DEFAULT ''"), + ("latitude", "REAL"), + ("longitude", "REAL"), + ): + if not db.execute( + "SELECT 1 FROM pragma_table_info('visitors') WHERE name = ?", + (column,), + ).fetchone(): + db.execute( + "ALTER TABLE visitors ADD COLUMN %s %s" % (column, decl) + ) + db.commit() + # Only after the columns exist: creating this index inside the + # executescript above would crash on databases that predate location + # tracking (the table exists, but without these columns). + db.execute( + "CREATE INDEX IF NOT EXISTS idx_visitors_location " + "ON visitors (country_code, city)" + ) + db.commit() + + # Migration: `published_at` backs scheduled publishing (a post whose + # timestamp is in the future stays off the public site until then). + # Older databases get the column added and backfilled from created_at + # so no existing post disappears. + if not db.execute( + "SELECT 1 FROM pragma_table_info('posts') WHERE name = 'published_at'" + ).fetchone(): + db.execute("ALTER TABLE posts ADD COLUMN published_at TEXT") + db.execute("UPDATE posts SET published_at = created_at") + db.commit() + db.execute( + "CREATE INDEX IF NOT EXISTS idx_posts_status " + "ON posts (status, published_at)" + ) + + # Deleting a post/page used to leave its comments behind; clean up rows + # orphaned by older versions. + db.execute( + "DELETE FROM comments WHERE object_type = 'post' " + "AND object_id NOT IN (SELECT id FROM posts)" + ) + db.execute( + "DELETE FROM comments WHERE object_type = 'page' " + "AND object_id NOT IN (SELECT id FROM pages)" + ) + db.commit() + + # Seed default categories + db.execute( + "INSERT OR IGNORE INTO categories (slug, name) VALUES (?, ?)", + ("general", "General"), + ) + db.commit() + + # Seed the comments toggle (1 = enabled). Existing installs without a row + # get it on the next startup so expose_helpers() never queries a missing + # setting and crashes. + db.execute( + "INSERT OR IGNORE INTO settings (key, value) VALUES (?, ?)", + ("comments_enabled", "1"), + ) + db.commit() + + # Seed a welcome post if the table is empty + count = db.execute("SELECT COUNT(*) FROM posts").fetchone()[0] + if count == 0: + now = _utcnow() + db.execute( + """ + INSERT INTO posts + (title, slug, body, excerpt, author, category, tags, status, created_at, updated_at) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?) + """, + ( + "Welcome to my new blog", + "welcome-to-my-new-blog", + ( + "This is a **simple blog** with a lightweight content " + "management system. Everything — posts, categories, and " + "the admin panel — lives in this single container.\n\n" + "You can sign in to the admin area to create and manage " + "your own posts. Content is written in Markdown, so feel " + "free to add links, code blocks, and emphasis.\n\n" + "## Getting started\n\n" + "- Head to the **[admin login](%s/admin/login)** to start " + "writing.\n- Posts are published immediately when saved.\n" + "- Use the **categories** and **tags** fields to organise " + "your content.\n" + % os.environ.get("BLOG_URL", "http://localhost:5000") + ), + "Welcome to my new blog", + "editor", + "General", + "welcome,getting-started", + "published", + now, + now, + ), + ) + db.commit() + + # Seed the About page as the first content page (so it shows in the nav) + about_count = db.execute("SELECT COUNT(*) FROM pages").fetchone()[0] + if about_count == 0: + now = _utcnow() + db.execute( + """ + INSERT INTO pages (slug, title, content, position, published, created_at, updated_at) + VALUES (?, ?, ?, 0, 1, ?, ?) + """, + ( + "about", + "About", + ( + "Hello! I'm the author of this blog.\n" + "\n" + "Here I write about technology, self-hosting, AI, and the occasional thought\n" + "about life. The goal is to keep things simple, honest, and useful." + "\n" + "## What's here\n" + "\n" + "- Practical guides for building and running your own systems.\n" + "- Notes on emerging technology and how I'm learning it.\n" + "- Occasional musings and lessons learned the hard way.\n" + "\n" + "Thanks for stopping by. Feel free to browse, search, or reach out." + ), + now, + now, + ), + ) + db.commit() + + +_SLUG_STRIP = re.compile(r"[^a-z0-9]+") + + +def _slugify(value): + """Turn a title/name into a URL slug. + + The old helper only replaced spaces and slashes, so punctuation survived + ("Hello, World!" -> "hello,-world!") and accented text produced unusable + URLs. This strips accents, collapses every run of punctuation/whitespace + into one hyphen and caps the length. Only affects newly generated slugs; + existing URLs are never rewritten. + """ + text = unicodedata.normalize("NFKD", str(value or "").strip().lower()) + text = text.encode("ascii", "ignore").decode("ascii") + slug = _SLUG_STRIP.sub("-", text).strip("-") + return slug[:80].strip("-") or "item" + + +def split_tags(value): + """Split stored comma-separated tags into unique, trimmed names. + + Tags are stored as one TEXT column ("ai, selfhost, tips") by both the + editor and the WXR importer. Case-insensitive de-duplication keeps a post + from appearing twice under the same tag page. + """ + seen = set() + names = [] + for raw in str(value or "").split(","): + name = raw.strip() + key = name.lower() + if name and key not in seen: + seen.add(key) + names.append(name) + return names + + +def _all_albums(): + db = get_db() + return db.execute( + "SELECT * FROM media_albums ORDER BY position ASC, id ASC" + ).fetchall() + + +def _random_album_thumbs(): + """Return {album_id: url} by sampling one photo at random per album. + + Fetches every media row once and groups by album so the index page needs + a single query regardless of how many albums or photos exist. Albums with + no photos are omitted (they have nothing to preview). Prefers the small + thumbnail so album cards don't download full-size originals. + """ + db = get_db() + grouped = {} + for row in db.execute("SELECT album_id, url, thumb_url FROM media").fetchall(): + grouped.setdefault(row["album_id"], []).append( + row["thumb_url"] or row["url"] + ) + # Seed a fresh RNG per call so every page load features a different photo + # (the long-lived container's global random state can stay sticky across + # requests, which would make the preview look unchanged). + rng = random.Random(time.time_ns()) + return {aid: rng.choice(urls) for aid, urls in grouped.items()} + + +def _album_by_slug(slug): + db = get_db() + return db.execute("SELECT * FROM media_albums WHERE slug = ?", (slug,)).fetchone() + + +def _album_by_id(album_id): + db = get_db() + return db.execute("SELECT * FROM media_albums WHERE id = ?", (album_id,)).fetchone() + + +def _album_media(album_id): + db = get_db() + return db.execute( + "SELECT * FROM media WHERE album_id = ? ORDER BY position ASC, id ASC", + (album_id,), + ).fetchall() + + +def _ungrouped_media(): + db = get_db() + return db.execute( + "SELECT * FROM media WHERE album_id IS NULL ORDER BY position ASC, id ASC" + ).fetchall() + + +def _media_by_id(media_id): + db = get_db() + return db.execute("SELECT * FROM media WHERE id = ?", (media_id,)).fetchone() + + +def _utcnow(): + """Current UTC time in the DB's `YYYY-MM-DD HH:MM:SS` format.""" + return datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M:%S") + + +def parse_date(iso): + """Render an ISO timestamp as a human-friendly month name.""" + try: + dt = datetime.strptime(str(iso)[:10], "%Y-%m-%d") + # %e is a glibc extension; build the label portably instead. + return "%s %d, %d" % (dt.strftime("%B"), dt.day, dt.year) + except (ValueError, TypeError): + return str(iso or "") + + +# --------------------------------------------------------------------------- # +# Comments +# --------------------------------------------------------------------------- # +COMMENT_STATUSES = ("pending", "approved", "rejected", "spam") +MAX_COMMENT_BODY = 2000 + + +def _comment_counts(): + """Return a dict of comment counts keyed by status.""" + db = get_db() + counts = {s: 0 for s in COMMENT_STATUSES} + for row in db.execute("SELECT status FROM comments").fetchall(): + counts[row[0]] = counts.get(row[0], 0) + 1 + return counts + + +def _comments_for(object_type, object_id): + """Return the publicly-visible (approved) comments for one post/page. + + `object_type` is 'post' or 'page'; `object_id` is that row's primary key. + Only approved comments are returned, oldest first. + """ + db = get_db() + return db.execute( + "SELECT * FROM comments WHERE object_type = ? AND object_id = ? " + "AND status = 'approved' ORDER BY id ASC", + (object_type, object_id), + ).fetchall() + + +def _pending_comments(): + """Return every comment awaiting moderation, most recent first.""" + db = get_db() + return db.execute( + "SELECT * FROM comments WHERE status = 'pending' ORDER BY created_at DESC, id DESC" + ).fetchall() + + +def _comment_by_id(cid): + """Return a single comment by its id, or None.""" + db = get_db() + return db.execute("SELECT * FROM comments WHERE id = ?", (cid,)).fetchone() diff --git a/blog/images.py b/blog/images.py new file mode 100644 index 0000000..7f764c1 --- /dev/null +++ b/blog/images.py @@ -0,0 +1,62 @@ +"""Thumbnail generation for uploaded photos (Pillow). + +Uploads are stored at full size; galleries and admin lists ask for hundreds of +them at once, so each upload also gets a downscaled copy next to the original. +Thumbnails are best-effort: an unsupported/corrupt image simply has no +thumbnail and the UI falls back to the full-size URL. +""" + +import logging +import os + +from PIL import Image, ImageOps + +log = logging.getLogger(__name__) + +THUMB_MAX_PX = 640 +THUMB_QUALITY = 82 +# GIF is deliberately absent: Pillow would flatten an animation to one frame. +SUPPORTED_EXTENSIONS = {".jpg", ".jpeg", ".png", ".webp"} + + +def thumbnail_name(filename): + """Return the thumbnail filename for `filename` (same stem, _thumb suffix).""" + stem, ext = os.path.splitext(filename) + ext = ext.lower() + if ext in (".jpg", ".jpeg"): + ext = ".jpg" + return "%s_thumb%s" % (stem, ext) + + +def make_thumbnail(path, max_px=THUMB_MAX_PX): + """Write a downscaled copy next to `path`; return its filename. + + Returns "" when the image type is unsupported or the file can't be read, + so callers can store an empty thumb_url and fall back to the original. + """ + ext = os.path.splitext(path)[1].lower() + if ext not in SUPPORTED_EXTENSIONS: + return "" + out_name = thumbnail_name(os.path.basename(path)) + out_path = os.path.join(os.path.dirname(path), out_name) + try: + with Image.open(path) as img: + # Honour EXIF orientation so portrait phone photos aren't sideways. + img = ImageOps.exif_transpose(img) + img.thumbnail((max_px, max_px), Image.LANCZOS) + if ext in (".jpg", ".jpeg"): + img.convert("RGB").save( + out_path, "JPEG", quality=THUMB_QUALITY, optimize=True + ) + elif ext == ".webp": + img.save(out_path, "WEBP", quality=THUMB_QUALITY, method=4) + else: + img.save(out_path, "PNG", optimize=True) + return out_name + except Exception: + log.warning("thumbnail generation failed for %s", path, exc_info=True) + try: + os.remove(out_path) + except OSError: + pass + return "" diff --git a/blog/manage.py b/blog/manage.py new file mode 100644 index 0000000..3826bba --- /dev/null +++ b/blog/manage.py @@ -0,0 +1,290 @@ +"""Command-line maintenance for the blog (no web server needed). + +Run from the project root, or inside the running container:: + + docker compose exec blog python -m blog.manage set-password + docker compose exec blog python -m blog.manage status + docker compose exec blog python -m blog.manage unlock 203.0.113.7 + +``set-password`` is the supported password-recovery path: it does not need the +old password, works directly against the SQLite database, and signs out every +existing admin session. The new password is read from a prompt (or stdin when +non-interactive), never from the command line, so it stays out of shell history +and ``ps`` output. +""" + +import argparse +import datetime +import getpass +import os +import sqlite3 +import sys + +from . import auth, create_app +from .db import DB_PATH, _utcnow, get_db + + +def _prompt_password(): + """Read the new password (interactive double prompt, or one line of stdin).""" + if not sys.stdin.isatty(): + return sys.stdin.readline().rstrip("\r\n") + password = getpass.getpass("New admin password: ") + confirm = getpass.getpass("Repeat new admin password: ") + if password != confirm: + print("Passwords do not match.", file=sys.stderr) + return None + return password + + +def cmd_set_password(_args): + password = _prompt_password() + if password is None: + return 1 + problem = auth.password_problem(password) + if problem: + print("Password rejected: %s." % problem, file=sys.stderr) + print( + "Use at least %d characters and avoid default values." + % auth.MIN_PASSWORD_LENGTH, + file=sys.stderr, + ) + return 1 + auth.set_admin_password(password) + print("Admin password updated. Every existing admin session has been signed out.") + return 0 + + +def cmd_backup(args): + """Write a consistent snapshot of the SQLite database.""" + dest = os.path.abspath(args.out) if args.out else os.path.join( + os.path.dirname(DB_PATH), + "blog-backup-%s.db" % datetime.datetime.now().strftime("%Y%m%d-%H%M%S"), + ) + target = sqlite3.connect(dest) + try: + get_db().backup(target) + finally: + target.close() + print("Backup written to %s" % dest) + return 0 + + +def cmd_restore(args): + """Replace the live database with a backup (requires --yes).""" + if not args.yes: + print("Refusing to overwrite the live database without --yes.", file=sys.stderr) + return 1 + if not os.path.exists(args.file): + print("No such file: %s" % args.file, file=sys.stderr) + return 1 + source = sqlite3.connect(args.file) + try: + if not source.execute( + "SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'posts'" + ).fetchone(): + print("That file does not look like a blog database.", file=sys.stderr) + return 1 + source.backup(get_db()) + finally: + source.close() + print("Restored from %s. Restart any running server." % args.file) + return 0 + + +def cmd_vacuum(_args): + """Reclaim disk space (SQLite never shrinks the file on its own).""" + conn = sqlite3.connect(DB_PATH) + try: + conn.execute("VACUUM") + finally: + conn.close() + print("Database vacuumed.") + return 0 + + +def cmd_prune(args): + """Delete old visit history so the analytics tables stay bounded.""" + cutoff = ( + datetime.datetime.now(datetime.timezone.utc) + - datetime.timedelta(days=max(1, args.days)) + ).strftime("%Y-%m-%d %H:%M:%S") + db = get_db() + visits = db.execute("DELETE FROM visits WHERE timestamp < ?", (cutoff,)).rowcount + visitors = db.execute( + "DELETE FROM visitors WHERE last_seen < ? " + "AND visitor_id NOT IN (SELECT visitor_id FROM visits)", + (cutoff,), + ).rowcount + db.commit() + print( + "Removed %d visit(s) and %d stale visitor(s) older than %d day(s)." + % (visits, visitors, args.days) + ) + return 0 + + +def cmd_thumbs(_args): + """Backfill thumbnails for photos uploaded before thumbnails existed.""" + from .images import make_thumbnail + + root = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) + upload_dir = os.path.join(root, "static", "uploads") + db = get_db() + made = skipped = 0 + for row in db.execute("SELECT id, filename, thumb_url FROM media").fetchall(): + existing = os.path.basename((row["thumb_url"] or "").strip()) + if existing and os.path.exists(os.path.join(upload_dir, existing)): + skipped += 1 + continue + name = make_thumbnail(os.path.join(upload_dir, row["filename"])) + if not name: + skipped += 1 + continue + db.execute( + "UPDATE media SET thumb_url = ? WHERE id = ?", + ("/static/uploads/" + name, row["id"]), + ) + made += 1 + db.commit() + print("Generated %d thumbnail(s); skipped %d." % (made, skipped)) + return 0 + + +def cmd_schedule(args): + """Schedule a post (or publish it now) by slug.""" + db = get_db() + row = db.execute("SELECT id FROM posts WHERE slug = ?", (args.slug,)).fetchone() + if not row: + print("No post with slug %r." % args.slug, file=sys.stderr) + return 1 + if args.when: + try: + when = datetime.datetime.strptime(args.when, "%Y-%m-%d %H:%M") + except ValueError: + print("Use the format 'YYYY-MM-DD HH:MM' (UTC).", file=sys.stderr) + return 1 + stamp = when.strftime("%Y-%m-%d %H:%M:%S") + else: + stamp = _utcnow() + db.execute( + "UPDATE posts SET status = 'published', published_at = ? WHERE id = ?", + (stamp, row[0]), + ) + db.commit() + print("Post %r goes live at %s UTC." % (args.slug, stamp)) + return 0 + + +def _format_stamp(stamp): + try: + moment = datetime.datetime.fromtimestamp( + int(stamp), datetime.timezone.utc + ) + except (TypeError, ValueError): + return "unknown" + return moment.strftime("%Y-%m-%d %H:%M:%S UTC") + + +def cmd_status(_args): + stored = auth.get_setting(auth.PASSWORD_HASH_KEY, "") + print("Password set: %s" % ("yes" if stored else "no")) + if stored: + print( + "Password changed: %s" + % _format_stamp(auth.get_setting(auth.PASSWORD_SET_AT_KEY, "")) + ) + print( + "BLOG_ADMIN_PASSWORD: %s (bootstrap only; ignored once a password is stored)" + % ("set" if os.environ.get("BLOG_ADMIN_PASSWORD") else "not set") + ) + locked = auth.locked_clients() + if not locked: + print("Locked-out clients: none") + else: + print("Locked-out clients:") + for item in locked: + print( + " %s (%d failed attempts, %ds remaining)" + % (item["key"], item["failures"], item["remaining"]) + ) + return 0 + + +def cmd_unlock(args): + count = auth.clear_login_attempts(args.ip) + print("Cleared %d lockout record(s)." % count) + return 0 + + +def main(argv=None): + parser = argparse.ArgumentParser( + prog="python -m blog.manage", + description="Blog maintenance commands.", + ) + sub = parser.add_subparsers(dest="command", required=True) + + sub.add_parser( + "set-password", + help="Set a new admin password (prompted; signs out all sessions).", + ).set_defaults(func=cmd_set_password) + + sub.add_parser( + "status", + help="Show whether a password is configured and who is locked out.", + ).set_defaults(func=cmd_status) + + unlock = sub.add_parser( + "unlock", help="Clear failed-login lockouts (all clients, or one IP)." + ) + unlock.add_argument( + "ip", nargs="?", default=None, + help="Client IP to unlock; omit to clear every lockout.", + ) + unlock.set_defaults(func=cmd_unlock) + + backup = sub.add_parser("backup", help="Write a snapshot of the database.") + backup.add_argument( + "--out", default=None, + help="Destination path (default: a timestamped file next to the database).", + ) + backup.set_defaults(func=cmd_backup) + + restore = sub.add_parser("restore", help="Overwrite the database from a backup.") + restore.add_argument("file", help="Path to a database backup written by 'backup'.") + restore.add_argument( + "--yes", action="store_true", help="Confirm overwriting the live database." + ) + restore.set_defaults(func=cmd_restore) + + sub.add_parser( + "vacuum", help="Compact the database file after deletions." + ).set_defaults(func=cmd_vacuum) + + prune = sub.add_parser( + "prune-visits", help="Delete visit history older than N days." + ) + prune.add_argument("--days", type=int, default=365, help="Retention window (default 365).") + prune.set_defaults(func=cmd_prune) + + sub.add_parser( + "thumbs", help="Generate missing thumbnails for existing uploads." + ).set_defaults(func=cmd_thumbs) + + schedule = sub.add_parser( + "schedule", help="Schedule a post to go live (UTC), or publish it now." + ) + schedule.add_argument("slug", help="Post slug.") + schedule.add_argument( + "when", nargs="?", default=None, help="Publish time 'YYYY-MM-DD HH:MM' (UTC)." + ) + schedule.set_defaults(func=cmd_schedule) + + args = parser.parse_args(argv) + + app = create_app() + with app.app_context(): + return args.func(args) + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/blog/markdown.py b/blog/markdown.py new file mode 100644 index 0000000..b8d9e27 --- /dev/null +++ b/blog/markdown.py @@ -0,0 +1,71 @@ +"""Markdown rendering with XSS protection.""" + +import bleach +from markupsafe import Markup +from markdown import markdown + + +# Convert stored content to raw HTML for the editor (edit-load path). +# Rich-text editors store clean HTML; Markdown is converted on save. We detect +# which the caller stored and only run the Markdown parser on Markdown, so +# storing HTML never gets mangled. +# This is NOT bleach-sanitised — the editor receives the author's own content. +# Public rendering (render_markdown) is what applies XSS protection. +def _looks_like_html(text): + """True if `text` is clean HTML rather than Markdown source.""" + stripped = text.lstrip() + return bool(stripped) and stripped[0] == "<" + +def to_html(text): + if not text: + return "" + if _looks_like_html(text): + # Already clean HTML from the rich-text editor — hand it straight + # through so it reaches the editor un-mangled. + return Markup(text) + html = markdown(text, extensions=["fenced_code", "tables", "nl2br"]) + # The markdown library only ever emits its own known tags, so this is safe + # to hand to the editor. Wrap in Markup so Jinja does NOT HTML-escape the + # tags when the template renders this value into the Quill container. + return Markup(html) + + +# Tags we allow through. Markdown already produces safe HTML; bleach strips +# anything else to prevent stored XSS from editor input. +ALLOWED_TAGS = { + "a", "p", "br", "strong", "em", "b", "i", "code", "pre", "blockquote", + "h1", "h2", "h3", "h4", "h5", "h6", "ul", "ol", "li", "table", "thead", + "tbody", "tr", "th", "td", "hr", "img", "figure", "figcaption", +} +ALLOWED_ATTR = { + "a": ["href", "title", "target", "rel"], + "img": ["src", "alt", "title", "width", "height"], +} +ALLOWED_PROTOCOLS = ["http", "https", "mailto"] + + +def render_markdown(text): + """Render stored content to safely-sanitised HTML for public display. + + Handles both inputs: + * Markdown (the legacy Quill editor's format) -> markdown() + bleach. + * Clean HTML (the TipTap rich-text editor's format) -> bleach only, + so images/links render as-is instead of being mangled by the Markdown + parser. Either way, bleach strips anything outside ALLOWED_TAGS to + prevent stored XSS. + """ + if not text: + return "" + if _looks_like_html(text): + html = text + else: + html = markdown(text, extensions=["fenced_code", "tables", "nl2br"]) + safe = bleach.clean( + html, + tags=ALLOWED_TAGS, + attributes=ALLOWED_ATTR, + protocols=ALLOWED_PROTOCOLS, + ) + # bleach 6.x returns a plain str; wrap in Markup so Flask/Jinja does not + # HTML-escape the generated tags when the template renders this value. + return Markup(safe) diff --git a/blog/notify.py b/blog/notify.py new file mode 100644 index 0000000..8dbfc22 --- /dev/null +++ b/blog/notify.py @@ -0,0 +1,169 @@ +"""Best-effort notifications for new (moderated) comments. + +Two independent channels, both configured with env vars: + +* Email over plain SMTP, so any provider works (Postmark, SendGrid, Mailgun, + Fastmail, a self-hosted relay, ...). +* Push via ntfy (https://ntfy.sh) — by default the self-hosted ntfy service in + this project's docker-compose file, but any ntfy server works. + +When a channel is unconfigured it does nothing. Delivery runs on daemon threads +and never raises into the comment request: a mail or push outage must not lose a +visitor's comment. +""" + +import logging +import os +import smtplib +import ssl +import threading +import urllib.parse +import urllib.request +from email.message import EmailMessage + +log = logging.getLogger(__name__) + +NTFY_PRIORITIES = { + "min", "low", "default", "high", "urgent", "max", + "1", "2", "3", "4", "5", +} + + +def smtp_config(): + """Return SMTP settings from the environment, or None when unconfigured.""" + host = (os.environ.get("BLOG_SMTP_HOST") or "").strip() + recipient = (os.environ.get("BLOG_NOTIFY_EMAIL") or "").strip() + if not host or not recipient: + return None + try: + port = int(os.environ.get("BLOG_SMTP_PORT") or 587) + except ValueError: + port = 587 + user = (os.environ.get("BLOG_SMTP_USER") or "").strip() + sender = (os.environ.get("BLOG_SMTP_FROM") or "").strip() or user or recipient + tls = (os.environ.get("BLOG_SMTP_TLS") or "1").strip().lower() not in ( + "0", "false", "no", "off", + ) + return { + "host": host, + "port": port, + "user": user, + "password": os.environ.get("BLOG_SMTP_PASSWORD") or "", + "sender": sender, + "recipient": recipient, + "tls": tls, + } + + +def ntfy_config(): + """Return ntfy settings from the environment, or None when unconfigured.""" + base = (os.environ.get("BLOG_NTFY_URL") or "").strip().rstrip("/") + topic = (os.environ.get("BLOG_NTFY_TOPIC") or "").strip().strip("/") + if not base or not topic: + return None + priority = (os.environ.get("BLOG_NTFY_PRIORITY") or "").strip().lower() + if priority not in NTFY_PRIORITIES: + priority = "default" + return { + "url": "%s/%s" % (base, urllib.parse.quote(topic, safe="")), + "token": (os.environ.get("BLOG_NTFY_TOKEN") or "").strip(), + "priority": priority, + } + + +def notify_new_comment(comment_author, comment_body, comment_email, + target_title, target_url, moderation_url=""): + """Queue admin alerts about a pending comment. No-op when unconfigured. + + Returns True when at least one channel was configured and queued. + """ + queued = False + + email_config = smtp_config() + if email_config: + threading.Thread( + target=_send_email, + args=(email_config, comment_author, comment_body, comment_email, + target_title, target_url, moderation_url), + daemon=True, + ).start() + queued = True + + push_config = ntfy_config() + if push_config: + threading.Thread( + target=_send_ntfy, + args=(push_config, comment_author, comment_body, target_title, + target_url, moderation_url), + daemon=True, + ).start() + queued = True + + return queued + + +def _send_email(config, author, body, email, title, url, moderation_url): + try: + message = EmailMessage() + message["Subject"] = "New comment awaiting moderation: %s" % (title or "your blog") + message["From"] = config["sender"] + message["To"] = config["recipient"] + if email: + # Replying to the notification goes straight to the commenter. + message["Reply-To"] = email + excerpt = body if len(body) <= 2000 else body[:2000] + "..." + message.set_content( + "A new comment is waiting for moderation.\n\n" + "Post: %s\n" + "URL: %s\n" + "Author: %s\n" + "Email: %s\n\n" + "%s\n\n" + "Moderate: %s\n" + % (title or "", url or "", author or "", email or "not provided", + excerpt, moderation_url or "") + ) + with smtplib.SMTP(config["host"], config["port"], timeout=15) as smtp: + smtp.ehlo() + if config["tls"]: + smtp.starttls(context=ssl.create_default_context()) + smtp.ehlo() + if config["user"]: + smtp.login(config["user"], config["password"]) + smtp.send_message(message) + except Exception: + log.warning("comment notification email failed", exc_info=True) + + +def _send_ntfy(config, author, body, title, url, moderation_url): + try: + excerpt = body.strip() + if len(excerpt) > 1000: + excerpt = excerpt[:1000].rstrip() + "..." + lines = ["%s commented on %s" % (author or "Someone", title or "your blog")] + if url: + lines.append(url) + lines.extend(["", excerpt]) + headers = { + # ntfy shows this as the push title. Kept ASCII so urllib can always + # encode it; the post title is in the message body instead. + "Title": "New comment awaiting moderation", + "Priority": config["priority"], + "Tags": "speech_balloon", + "Content-Type": "text/plain; charset=utf-8", + } + if moderation_url and moderation_url.isascii(): + # Tapping the notification opens the moderation queue. + headers["Click"] = moderation_url + request = urllib.request.Request( + config["url"], + data="\n".join(lines).encode("utf-8"), + headers=headers, + method="POST", + ) + if config["token"]: + request.add_header("Authorization", "Bearer " + config["token"]) + with urllib.request.urlopen(request, timeout=10) as response: + response.read(1) + except Exception: + log.warning("ntfy notification failed", exc_info=True) diff --git a/blog/public.py b/blog/public.py new file mode 100644 index 0000000..16686bc --- /dev/null +++ b/blog/public.py @@ -0,0 +1,871 @@ +"""Public (front-end) routes.""" + +from flask import ( + Blueprint, + abort, + current_app, + flash, + make_response, + redirect, + render_template, + request, + session, + url_for, +) + +import datetime +import os +import re +import time +from xml.sax.saxutils import escape as xml_escape + +from itsdangerous import BadSignature, SignatureExpired, URLSafeTimedSerializer + +from . import auth, notify +from .admin import _check_csrf +from .db import ( + MAX_COMMENT_BODY, + _album_by_slug, + _album_media, + _all_albums, + _comment_by_id, + _comment_counts, + _comments_for, + _random_album_thumbs, + _slugify, + get_db, + parse_date, + split_tags, +) +from .markdown import render_markdown + +bp = Blueprint("public", __name__) + +POSTS_PER_PAGE = 10 +# Draft preview links are signed and expire, so a link shared by mistake stops +# working on its own. +PREVIEW_MAX_AGE = 60 * 60 * 24 * 7 + +_IMG_SRC_RE = re.compile(r']+src=["\']([^"\']+)["\']', re.IGNORECASE) + + +def _utcnow(): + """Current UTC time in the DB's timestamp format (comment + schedule times).""" + return datetime.datetime.now(datetime.timezone.utc).strftime("%Y-%m-%d %H:%M:%S") + + +@bp.route("/robots.txt") +def robots(): + """Serve robots.txt at the site root so search engines can crawl it. + + Flask's static route only covers /static/, so this explicit route exposes + the file at /robots.txt. The Sitemap directive must be an absolute URL + (the spec rejects a relative one), so it is built from BLOG_URL when set. + """ + base = (os.environ.get("BLOG_URL") or request.url_root).rstrip("/") + body = ( + "User-agent: *\n" + "Allow: /\n" + "\n" + "# Admin area and search results aren't useful to crawlers.\n" + "Disallow: /admin/\n" + "Disallow: /search\n" + "\n" + "Sitemap: %s/sitemap.xml\n" % base + ) + return body, 200, {"Content-Type": "text/plain; charset=utf-8"} + + +@bp.route("/sitemap.xml") +def sitemap(): + """Auto-generated XML sitemap so search engines can discover every page.""" + db = get_db() + now = _utcnow() + base = request.url_root.rstrip("/") + + # (path, lastmod). `/about` is deliberately absent: it redirects to + # `/p/about`, which is the canonical URL already listed below. + rows = [("", None), ("/photos", None)] + rows += [ + ("/post/" + r["slug"], r["updated_at"]) + for r in db.execute( + "SELECT slug, updated_at FROM posts " + "WHERE status = 'published' AND COALESCE(published_at, created_at) <= ? " + "ORDER BY created_at DESC", + (now,), + ).fetchall() + ] + rows += [ + ("/category/" + r["slug"], None) + for r in db.execute("SELECT slug FROM categories ORDER BY name").fetchall() + ] + # Tag browsing pages, matching the links rendered on posts and cards. + rows.append(("/tags", None)) + for tag in _tag_index(): + rows.append(("/tag/" + tag["slug"], None)) + rows += [ + ("/p/" + r["slug"], r["updated_at"]) + for r in db.execute( + "SELECT slug, updated_at FROM pages WHERE published = 1 " + "ORDER BY position, id" + ).fetchall() + ] + + out = ['', + ''] + for path, lastmod in rows: + out.append(" ") + loc = request.url_root if path == "" else (base + path) + out.append(" %s" % xml_escape(loc)) + # Real modification dates: this used to always be "today", telling + # crawlers every page changed on every crawl. + if lastmod: + out.append(" %s" % str(lastmod)[:10]) + out.append(" ") + out.append("") + return "\n".join(out), 200, { + "Content-Type": "application/xml", + "Cache-Control": "public, max-age=3600", + } + + +def _page_number(): + """Current ?page= as a positive integer (bad input falls back to 1).""" + try: + value = int(request.args.get("page", "1")) + except (TypeError, ValueError): + value = 1 + return max(1, value) + + +def _pagination(page_number, total): + """Template context for prev/next links, preserving query + path args.""" + pages = max(1, (total + POSTS_PER_PAGE - 1) // POSTS_PER_PAGE) + + def build(target): + args = request.args.to_dict() + args["page"] = target + return url_for(request.endpoint, **(request.view_args or {}), **args) + + return { + "page": page_number, + "pages": pages, + "total": total, + "has_prev": page_number > 1, + "has_next": page_number < pages, + "prev_url": build(page_number - 1) if page_number > 1 else "", + "next_url": build(page_number + 1) if page_number < pages else "", + } + + +def _first_image(body): + """Absolute URL of the first in a post body (for social previews).""" + match = _IMG_SRC_RE.search(str(body or "")) + if not match: + return "" + src = match.group(1).strip() + if src.startswith(("http://", "https://")): + return src + return request.url_root.rstrip("/") + "/" + src.lstrip("/") + + +def _published(page_number=1, per_page=POSTS_PER_PAGE): + """Published posts whose publish time has arrived (see scheduled posts).""" + db = get_db() + return db.execute( + """ + SELECT * FROM posts + WHERE status = 'published' + AND COALESCE(published_at, created_at) <= ? + ORDER BY created_at DESC, id DESC + LIMIT ? OFFSET ? + """, + (_utcnow(), per_page, (page_number - 1) * per_page), + ).fetchall() + + +def _published_count(): + db = get_db() + return db.execute( + "SELECT COUNT(*) FROM posts WHERE status = 'published' " + "AND COALESCE(published_at, created_at) <= ?", + (_utcnow(),), + ).fetchone()[0] + + +def _tag_index(): + """Every tag used by live posts: [{slug, name, count}], most used first.""" + db = get_db() + rows = db.execute( + "SELECT tags FROM posts WHERE status = 'published' " + "AND COALESCE(published_at, created_at) <= ?", + (_utcnow(),), + ).fetchall() + tags = {} + for row in rows: + for name in split_tags(row["tags"]): + slug = _slugify(name) + entry = tags.setdefault(slug, {"slug": slug, "name": name, "count": 0}) + entry["count"] += 1 + return sorted(tags.values(), key=lambda t: (-t["count"], t["name"].lower())) + + +def _live_posts(): + """Every published-and-due post, newest first (used for tag filtering).""" + db = get_db() + return db.execute( + "SELECT * FROM posts WHERE status = 'published' " + "AND COALESCE(published_at, created_at) <= ? " + "ORDER BY created_at DESC, id DESC", + (_utcnow(),), + ).fetchall() + + +def _tag_posts(slug): + """Return (display name, posts) for the tag whose slug matches `slug`.""" + name, matched = slug, [] + for row in _live_posts(): + names = {_slugify(tag): tag for tag in split_tags(row["tags"])} + if slug in names: + name = names[slug] + matched.append(row) + return name, matched + + +def _related_posts(post, limit=3): + """Posts most related to `post`, using shared tags then category. + + Shared tags score 2 each and a matching category scores 1, so a post with + two tags in common always outranks one that merely shares a category. Only + live posts are considered (drafts and scheduled posts never surface here). + """ + wanted = {_slugify(tag) for tag in split_tags(post["tags"])} + category = (post["category"] or "").strip().lower() + scored = [] + for row in _live_posts(): + if row["id"] == post["id"]: + continue + shared = len(wanted & {_slugify(tag) for tag in split_tags(row["tags"])}) + same_category = bool(category) and (row["category"] or "").strip().lower() == category + if not shared and not same_category: + continue + score = shared * 2 + (1 if same_category else 0) + scored.append((score, row["created_at"] or "", row)) + scored.sort(key=lambda item: (item[0], item[1]), reverse=True) + return [item[2] for item in scored[:limit]] + + +def _recent_other_posts(post, limit=3): + """Fallback when a post has no tag/category neighbours: newest other posts.""" + return [row for row in _live_posts() if row["id"] != post["id"]][:limit] + + +def _sidebar(): + """Shared sidebar data: recent posts, archive months and the tag cloud.""" + db = get_db() + recent = db.execute( + "SELECT title, slug, created_at FROM posts WHERE status = 'published' " + "AND COALESCE(published_at, created_at) <= ? " + "ORDER BY created_at DESC, id DESC LIMIT 5", + (_utcnow(),), + ).fetchall() + months = db.execute( + "SELECT substr(created_at, 1, 7) AS month FROM posts " + "WHERE status = 'published' AND COALESCE(published_at, created_at) <= ? " + "GROUP BY month ORDER BY month DESC", + (_utcnow(),), + ).fetchall() + # Admin-managed link tree; empty until the first link is added, which is + # what keeps the "Links" widget off the page entirely on a fresh site. + links = db.execute( + "SELECT label, url FROM links ORDER BY position ASC, id ASC" + ).fetchall() + return {"recent": recent, "months": months, "tags": _tag_index(), "links": links} + + +def _category_map(): + db = get_db() + return {r[0]: r[1] for r in db.execute("SELECT slug, name FROM categories").fetchall()} + + +@bp.route("/") +def index(): + page_number = _page_number() + total = _published_count() + posts = _published(page_number) + return render_template( + "home.html", + posts=posts, + category_map=_category_map(), + page="home", + pagination=_pagination(page_number, total), + sidebar=_sidebar(), + ) + + +def _posts_in_month(month, page_number=1): + """Return published posts whose created_at starts with `month` (e.g. '2026-11').""" + db = get_db() + return db.execute( + "SELECT * FROM posts WHERE status = 'published' " + "AND COALESCE(published_at, created_at) <= ? " + "AND substr(created_at, 1, 7) = ? " + "ORDER BY created_at DESC, id DESC LIMIT ? OFFSET ?", + (_utcnow(), month, POSTS_PER_PAGE, (page_number - 1) * POSTS_PER_PAGE), + ).fetchall() + + +def _month_count(month): + db = get_db() + return db.execute( + "SELECT COUNT(*) FROM posts WHERE status = 'published' " + "AND COALESCE(published_at, created_at) <= ? " + "AND substr(created_at, 1, 7) = ?", + (_utcnow(), month), + ).fetchone()[0] + + +@bp.route("/archive/") +def archive(month): + page_number = _page_number() + posts = _posts_in_month(month, page_number) + return render_template( + "home.html", + posts=posts, + category_map=_category_map(), + page="archive", + month=month, + pagination=_pagination(page_number, _month_count(month)), + sidebar=_sidebar(), + ) + + +@bp.route("/post/") +def post(slug): + db = get_db() + # Scheduled posts (publish time still in the future) must not be reachable + # by URL before they go live. + row = db.execute( + "SELECT * FROM posts WHERE slug = ? AND COALESCE(published_at, created_at) <= ?", + (slug, _utcnow()), + ).fetchone() + if not row: + abort(404) + cat_slug = _slugify(row["category"]) + # Approved comments for this post are rendered by the shared comments partial; + # `enabled`, `logged_in` and `csrf_token` come from expose_helpers(). + comments = _comments_for("post", row["id"]) + # Tag/category matches first; on a small blog with no overlap, fall back to + # the newest posts (labelled differently) instead of an empty section. + related = _related_posts(row) + related_fallback = False + if not related: + related = _recent_other_posts(row) + related_fallback = bool(related) + return render_template( + "post.html", + post=row, + category_map=_category_map(), + cat_slug=cat_slug, + page="post", + object_type="post", + slug=slug, + comments=comments, + comment_count=len(comments), + og_image=_first_image(row["body"]), + related=related, + related_fallback=related_fallback, + preview=False, + ) + + +@bp.route("/preview//") +def preview(pid, token): + """Signed preview of a draft or scheduled post (noindex, never public). + + The URL carries an itsdangerous token bound to the post id, so drafts are + not reachable by guessing an id and shared links expire after a week. + """ + serializer = URLSafeTimedSerializer( + current_app.config["SECRET_KEY"], salt="post-preview" + ) + try: + signed_pid = int(serializer.loads(token, max_age=PREVIEW_MAX_AGE)) + except (BadSignature, SignatureExpired, TypeError, ValueError): + abort(404) + if signed_pid != pid: + abort(404) + row = get_db().execute("SELECT * FROM posts WHERE id = ?", (pid,)).fetchone() + if not row: + abort(404) + related = _related_posts(row) + related_fallback = False + if not related: + related = _recent_other_posts(row) + related_fallback = bool(related) + response = make_response( + render_template( + "post.html", + post=row, + category_map=_category_map(), + cat_slug=_slugify(row["category"]), + page="post", + object_type="post", + slug=row["slug"], + comments=[], + comment_count=0, + # Drafts must not accept comments: the public comment route would + # otherwise happily attach one to an unpublished post. + comments_enabled=False, + og_image=_first_image(row["body"]), + related=related, + related_fallback=related_fallback, + preview=True, + ) + ) + response.headers["X-Robots-Tag"] = "noindex, nofollow" + response.headers["Cache-Control"] = "no-store, private" + return response + + +@bp.route("/category/") +def category(slug): + db = get_db() + cat = db.execute( + "SELECT name FROM categories WHERE slug = ?", (slug,) + ).fetchone() + if not cat: + abort(404) + # Posts store the category's display name, not its slug, so match the name + # (and tolerate a slug stored by an import). This used to fall back to + # "every published post" whenever the strings didn't match — so any category + # whose name differed from its slug showed the whole blog, and an empty + # category did too. + page_number = _page_number() + where = ( + "status = 'published' " + "AND COALESCE(published_at, created_at) <= ? " + "AND (lower(category) = lower(?) OR lower(category) = lower(?))" + ) + params = (_utcnow(), cat["name"], slug) + total = db.execute( + "SELECT COUNT(*) FROM posts WHERE " + where, params + ).fetchone()[0] + posts = db.execute( + "SELECT * FROM posts WHERE " + where + + " ORDER BY created_at DESC, id DESC LIMIT ? OFFSET ?", + params + (POSTS_PER_PAGE, (page_number - 1) * POSTS_PER_PAGE), + ).fetchall() + return render_template( + "home.html", + posts=posts, + category_map=_category_map(), + page="category", + category_name=cat["name"], + pagination=_pagination(page_number, total), + sidebar=_sidebar(), + ) + + +@bp.route("/tags") +def tags(): + """Browse every tag, most-used first.""" + return render_template("tags.html", tag_index=_tag_index(), page="tags") + + +@bp.route("/tag/") +def tag(slug): + name, matched = _tag_posts(slug) + if not matched: + abort(404) + page_number = _page_number() + start = (page_number - 1) * POSTS_PER_PAGE + return render_template( + "home.html", + posts=matched[start:start + POSTS_PER_PAGE], + category_map=_category_map(), + page="tag", + tag_name=name, + tag_slug=slug, + pagination=_pagination(page_number, len(matched)), + sidebar=_sidebar(), + ) + + +@bp.route("/tag//feed.xml") +def tag_feed(slug): + name, matched = _tag_posts(slug) + if not matched: + abort(404) + title = "%s — %s" % (_site_title(), name) + return _atom(matched[:FEED_LIMIT], title, url_for("public.tag_feed", slug=slug)), 200, { + "Content-Type": "application/atom+xml; charset=utf-8", + "Cache-Control": "public, max-age=600", + } + + +def _page_by_slug(slug): + db = get_db() + row = db.execute("SELECT * FROM pages WHERE slug = ?", (slug,)).fetchone() + if not row or int(row["published"]) != 1: + abort(404) + return row + + +@bp.route("/about") +def about(): + # Backwards-compatible alias: the About content now lives in the pages table, + # so redirect here to its canonical /p/about URL. + return redirect(url_for("public.page", slug="about")) + + +@bp.route("/p/") +def page(slug): + row = _page_by_slug(slug) + # Approved comments for this page are rendered by the shared comments partial. + comments = _comments_for("page", row["id"]) + return render_template( + "page.html", + page=row, + page_name="page", + object_type="page", + slug=slug, + comments=comments, + comment_count=len(comments), + ) + + +@bp.route("/photos") +def photos_index(): + """List every album so visitors can browse them (dynamically from the DB).""" + albums = _all_albums() + album_counts = {a["id"]: len(_album_media(a["id"])) for a in albums} + album_thumbs = _random_album_thumbs() + return render_template( + "public/albums.html", + albums=albums, + album_counts=album_counts, + album_thumbs=album_thumbs, + ) + + +@bp.route("/photos/") +def photos(slug): + album = _album_by_slug(slug) + if not album: + abort(404) + rows = _album_media(album["id"]) + return render_template("photos.html", album=album, media=rows) + + +EMAIL_RE = re.compile(r"^[^@\s]+@[^@\s]+\.[^@\s]+$") + + +# --------------------------------------------------------------------------- # +# Comments (public submission) +# --------------------------------------------------------------------------- # +# A lightweight, human-moderated commenting system. Every public submission is +# stored as 'pending' and only reaches visitors once an admin approves it, so a +# single bad-faith post can't spam the site. See blog/admin.py for moderation. +# --------------------------------------------------------------------------- # +COMMENT_RATE_LIMIT = 5 # max submissions per client per window +COMMENT_RATE_WINDOW = 60 # seconds +COMMENT_MIN_SECONDS = 3 # a human needs at least this long to write a comment + + +def _validate_comment_input(): + """Validate + sanitise the raw submit fields. Returns a cleaned dict, + or None if the input is invalid (caller flashes an error).""" + author = (request.form.get("author") or "").strip() + email = (request.form.get("email") or "").strip() + body = (request.form.get("body") or "").strip() + + if not author: + return None + if len(author) > 100: + return None + if email and not EMAIL_RE.match(email): + return None + # Body must be non-trivial: reject empty/whitespace and near-empty filler. + words = body.split() + if len(words) < 3: + return None + if len(body) > MAX_COMMENT_BODY: + return None + return {"author": author, "email": email, "body": body} + + +def _throttle_ok(): + """Allow at most COMMENT_RATE_LIMIT submissions per client per window. + + The counter lives in the database: the previous version stored it in the + signed session cookie, so clearing cookies (or changing the submitted + email address) reset the limit. + """ + now = time.time() + key = request.remote_addr or "unknown" + db = get_db() + db.execute( + "DELETE FROM comment_attempts WHERE ts < ?", (now - COMMENT_RATE_WINDOW,) + ) + recent = db.execute( + "SELECT COUNT(*) FROM comment_attempts WHERE key = ? AND ts >= ?", + (key, now - COMMENT_RATE_WINDOW), + ).fetchone()[0] + if recent >= COMMENT_RATE_LIMIT: + db.commit() + return False + db.execute("INSERT INTO comment_attempts (key, ts) VALUES (?, ?)", (key, now)) + db.commit() + return True + + +def _submit_comment(object_type, slug): + """Shared handler for the post/page comment forms. + + Validates CSRF, object existence and input; stores the comment as 'pending' + (awaiting admin approval). Redirects back to the object's public page. + """ + if not _check_csrf(): + flash("Invalid request.", "error") + abort(400) + + # Optional site-wide comments toggle. + enabled = get_db().execute( + "SELECT value FROM settings WHERE key = 'comments_enabled'" + ).fetchone() + if enabled is None or int(enabled[0]) != 1: + return redirect(url_for("public.page_comment", object_type=object_type, slug=slug)) + + # The comment must attach to a real post/page. + if object_type == "post": + row = get_db().execute("SELECT * FROM posts WHERE slug = ?", (slug,)).fetchone() + target_route = url_for("public.post", slug=slug) + else: + row = get_db().execute("SELECT * FROM pages WHERE slug = ?", (slug,)).fetchone() + target_route = url_for("public.page", slug=slug) + if not row: + abort(404) + + # --- Bot traps ------------------------------------------------------- + # `website` is a hidden field no human ever fills in: a value means an + # automated submission, so drop it silently (no error, no hint). + if (request.form.get("website") or "").strip(): + return redirect(target_route) + # The form carries its render timestamp; submissions arriving faster than a + # person can type — or replayed from a day-old page — are rejected. + try: + rendered_at = float(request.form.get("ts") or 0) + except (TypeError, ValueError): + rendered_at = 0.0 + elapsed = time.time() - rendered_at + if rendered_at and (elapsed < COMMENT_MIN_SECONDS or elapsed > 86400): + flash("Please take a moment to write your comment.", "error") + return redirect(target_route) + + validated = _validate_comment_input() + if validated is None: + flash("Please fill in your name and a genuine comment.", "error") + return redirect(target_route) + if not _throttle_ok(): + flash("Please wait a moment before submitting another comment.", "error") + return redirect(target_route) + + now = _utcnow() + db = get_db() + db.execute( + "INSERT INTO comments (object_type, object_id, author, email, body, status, created_at, updated_at) " + "VALUES (?, ?, ?, ?, ?, 'pending', ?, ?)", + (object_type, row["id"], validated["author"], validated["email"], + validated["body"], now, now), + ) + db.commit() + # Alert the admin by email and/or push (best-effort; unconfigured channels + # are a no-op). Runs on daemon threads, so a slow server never delays the + # visitor. + notify.notify_new_comment( + comment_author=validated["author"], + comment_body=validated["body"], + comment_email=validated["email"], + target_title=row["title"], + target_url=url_for( + "public.post" if object_type == "post" else "public.page", + slug=slug, + _external=True, + ), + moderation_url=url_for("admin.comments", _external=True), + ) + flash("Thanks! Your comment is awaiting moderation and will appear shortly.", "success") + return redirect(target_route) + + +@bp.route("/post//comment", methods=["POST"]) +def post_comment(slug): + return _submit_comment("post", slug) + + +@bp.route("/p//comment", methods=["POST"]) +def page_comment(slug): + return _submit_comment("page", slug) + + +@bp.route("/comment//delete", methods=["POST"]) +def public_comment_delete(cid): + """Let a logged-in user delete their own public comment.""" + if not _check_csrf(): + flash("Invalid request.", "error") + abort(400) + db = get_db() + row = _comment_by_id(cid) + if not row: + abort(404) + if not auth.is_logged_in(): + flash("You must be signed in to delete your comment.", "error") + return redirect(request.referrer or "/") + if row["author"] != session.get("username"): + flash("You can only delete your own comments.", "error") + return redirect(request.referrer or "/") + db.execute("DELETE FROM comments WHERE id=?", (cid,)) + db.commit() + flash("Your comment was deleted.", "success") + return redirect(request.referrer or "/") + + +# --- Search ------------------------------------------------------------------- +# Lightweight substring search over published posts (title / excerpt / body). +# Replaces the earlier SearXNG-backed route with a self-contained SQL LIKE query +# so results never depend on an external search service. +@bp.route("/search") +def search(): + q = request.args.get("q", "").strip() + db = get_db() + page_number = _page_number() + posts, total = [], 0 + if q: + # Escape the LIKE wildcards so "%" and "_" search for themselves + # instead of matching everything. + escaped = q.replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_") + like = "%" + escaped + "%" + # Scheduled posts are published-but-future; like every other listing + # they must stay out of results until their publish time arrives. + where = ( + "status = 'published' " + "AND COALESCE(published_at, created_at) <= ? " + "AND (title LIKE ? ESCAPE '\\' " + "OR excerpt LIKE ? ESCAPE '\\' " + "OR body LIKE ? ESCAPE '\\')" + ) + params = (_utcnow(), like, like, like) + total = db.execute( + "SELECT COUNT(*) FROM posts WHERE " + where, params + ).fetchone()[0] + posts = db.execute( + "SELECT * FROM posts WHERE " + where + + " ORDER BY created_at DESC, id DESC LIMIT ? OFFSET ?", + params + (POSTS_PER_PAGE, (page_number - 1) * POSTS_PER_PAGE), + ).fetchall() + return render_template( + "search.html", + query=q, + posts=posts, + category_map={}, + pagination=_pagination(page_number, total), + ) + + +# --------------------------------------------------------------------------- # +# Atom feed +# --------------------------------------------------------------------------- # +FEED_LIMIT = 20 + + +def _site_title(): + row = get_db().execute( + "SELECT value FROM settings WHERE key = 'site_title'" + ).fetchone() + return (row[0] if row else "") or "Blog" + + +def _rfc3339(value): + """Stored UTC timestamp -> RFC 3339 ("YYYY-MM-DD HH:MM:SS" -> "...T...Z").""" + if not value: + return "" + return str(value).replace(" ", "T") + "Z" + + +def _atom(posts, title, feed_path): + """Render an Atom 1.0 document for `posts` (shared by both feed routes).""" + base = request.url_root.rstrip("/") + self_url = base + feed_path + updated = ( + _rfc3339(posts[0]["updated_at"] or posts[0]["created_at"]) + if posts else _rfc3339(_utcnow()) + ) + out = [ + '', + '', + " %s" % xml_escape(title), + ' ' % xml_escape(base + "/"), + ' ' % xml_escape(self_url), + " %s" % xml_escape(self_url), + " %s" % updated, + " Simple Blog", + " %s" % xml_escape(_site_title()), + ] + for p in posts: + url = base + url_for("public.post", slug=p["slug"]) + out += [ + " ", + " %s" % xml_escape(p["title"] or ""), + ' ' % xml_escape(url), + " %s" % xml_escape(url), + " %s" % _rfc3339(p["created_at"]), + " %s" % _rfc3339(p["updated_at"] or p["created_at"]), + " %s" % xml_escape(p["author"] or "editor"), + ] + if p["category"]: + out.append(' ' % xml_escape(p["category"])) + out += [ + ' %s' + % xml_escape(str(render_markdown(p["body"]))), + " ", + ] + out.append("") + return "\n".join(out) + + +@bp.route("/feed.xml") +def feed(): + """Site-wide Atom feed of the most recent posts.""" + posts = get_db().execute( + "SELECT * FROM posts WHERE status = 'published' " + "AND COALESCE(published_at, created_at) <= ? " + "ORDER BY created_at DESC LIMIT ?", + (_utcnow(), FEED_LIMIT), + ).fetchall() + return _atom(posts, _site_title(), url_for("public.feed")), 200, { + "Content-Type": "application/atom+xml; charset=utf-8", + "Cache-Control": "public, max-age=600", + } + + +@bp.route("/category//feed.xml") +def category_feed(slug): + """Atom feed for a single category.""" + cat = get_db().execute( + "SELECT name FROM categories WHERE slug = ?", (slug,) + ).fetchone() + if not cat: + abort(404) + posts = get_db().execute( + "SELECT * FROM posts WHERE status = 'published' " + "AND COALESCE(published_at, created_at) <= ? " + "AND (lower(category) = lower(?) OR lower(category) = lower(?)) " + "ORDER BY created_at DESC LIMIT ?", + (_utcnow(), cat["name"], slug, FEED_LIMIT), + ).fetchall() + title = "%s — %s" % (_site_title(), cat["name"]) + return _atom(posts, title, url_for("public.category_feed", slug=slug)), 200, { + "Content-Type": "application/atom+xml; charset=utf-8", + "Cache-Control": "public, max-age=600", + } diff --git a/blog/wxr_export.py b/blog/wxr_export.py new file mode 100644 index 0000000..b4797a2 --- /dev/null +++ b/blog/wxr_export.py @@ -0,0 +1,168 @@ +"""Generate a WordPress eXtended RSS (WXR) export from this blog's data. + +The output is a standard WXR 1.2 feed — the same format WordPress's own +"Import" tool reads. Posts become elements; categories and tags are +expressed as / domain="post_tag">; comments appear +as blocks inside their post's item. + +Only published posts are exported (option a: text only, images left in place — +their URLs keep pointing at the source host). Pure logic, stdlib only, so it can +be unit-tested without an HTTP server or database. +""" + +import re +from datetime import datetime, timezone + +# Characters that are not legal in XML 1.0: a body pasted from another system +# could contain them and make the exported file unparseable. +_INVALID_XML = re.compile("[\x00-\x08\x0b\x0c\x0e-\x1f]") + + +# WXR namespaces. The order here controls prefix order in the emitted output. +NS = [ + ("excerpt", "http://wordpress.org/export/1.2/excerpt/"), + ("content", "http://purl.org/rss/1.0/modules/content/"), + ("wfw", "http://wellformedweb.org/CommentAPI/"), + ("dc", "http://purl.org/dc/elements/1.1/"), + ("wp", "http://wordpress.com/export/1.2/"), + ("slash", "http://slashworks.org/rss/1.0/"), +] + + +def _xml_escape(value): + """Escape a value for use as element text (not attributes).""" + if value is None: + return "" + return (_INVALID_XML.sub("", str(value)) + .replace("&", "&") + .replace("<", "<") + .replace(">", ">")) + + +def _attr_escape(value): + """Escape a value for use inside an attribute.""" + if value is None: + return "" + return (_INVALID_XML.sub("", str(value)) + .replace("&", "&") + .replace("<", "<") + .replace(">", ">") + .replace('"', """) + .replace("'", "'")) + + +def _rfc822(dt): + """Format a datetime as an RFC 822 date, as / expect.""" + return dt.strftime("%a, %d %b %Y %H:%M:%S +0000") + + +def _post_url(site_url, slug): + return f"{site_url.rstrip('/')}/post/{slug}" + + +def _comment_dt(comment): + """A comment's own timestamp. + + Every comment used to carry the *post's* date, which made the exported feed + claim all comments were written when the post was published. + """ + try: + return datetime.strptime(comment["created_at"], "%Y-%m-%d %H:%M:%S") + except (KeyError, ValueError, TypeError): + return datetime.now(timezone.utc).replace(tzinfo=None) + + +def build_wxr(db, site_title, site_url, site_description): + """Return the WXR document as a string. + + `db` must be an open sqlite3 connection; `site_title`, `site_url` and + `site_description` describe the channel (the WordPress importer needs them). + """ + posts = db.execute( + "SELECT * FROM posts WHERE status = 'published' ORDER BY created_at DESC" + ).fetchall() + # name -> slug, for turning WXR category names back into our category slugs. + cat_by_name = {slug: name for slug, name in + db.execute("SELECT slug, name FROM categories").fetchall()} + + # Channel metadata comes first (WordPress's importer needs it before any + # ), so build everything into one list in document order. + out = [] + out.append('') + out.append( + '' + ) + out.append(" ") + out.append(f" {_xml_escape(site_title)}") + out.append(f" {_xml_escape(site_url.rstrip('/'))}") + out.append(f" {_xml_escape(site_description)}") + out.append(' en_US') + out.append(' http://blogs.law.harvard.edu/tech/rss') + out.append(' Simple Blog WXR Export') + + for p in posts: + url = _post_url(site_url, p["slug"]) + created = datetime.strptime(p["created_at"], "%Y-%m-%d %H:%M:%S") + out.append(" ") + wxr_status = "publish" if p["status"] == "published" else "draft" + out.append(f' {_xml_escape(wxr_status)}') + out.append(f' {_xml_escape(p["slug"])}') + out.append(f" {_xml_escape(p['title'])}") + out.append(f" {_xml_escape(url)}") + out.append(f' {_xml_escape(url)}') + out.append( + f' {_xml_escape(p["author"] or "editor")}' + ) + out.append(f" {_rfc822(created)}") + out.append(f" {_rfc822(created)}") + + categories, tags = [], [] + for cat in (p["category"] or "").split(","): + cat = cat.strip() + if not cat: + continue + slug_ = cat_by_name.get(cat, cat) + categories.append(slug_) + for tag in (p["tags"] or "").split(","): + tag = tag.strip() + if tag: + tags.append(tag) + for slug_ in categories: + out.append( + f' {_xml_escape(slug_)}' + ) + for tag in tags: + out.append( + f' {_xml_escape(tag)}' + ) + + # Comments attached to this post. + comments = db.execute( + "SELECT * FROM comments WHERE object_type = 'post' AND object_id = ? " + "ORDER BY created_at", (p["id"],)).fetchall() + for c in comments: + comment_link = url + f"#c{c['id']}" + attrs = [ + f'ID="{c["id"]}"', + f'author="{_attr_escape(c["author"] or "")}"', + f'author_email="{_attr_escape(c["email"] or "")}"', + 'author_url=""', + f'date_time_gmt="{_rfc822(_comment_dt(c))}"', + 'comment_type=""', + 'status="approved"', + f'permalink="{_attr_escape(comment_link)}"', + ] + out.append(' ') + out.append(f" {_xml_escape(c['body'])}") + out.append(" ") + + out.append(f' {_xml_escape(url + "#comments")}') + out.append(f" {len(comments)}") + out.append(f" {_xml_escape(p['body'])}") + out.append(" ") + + out.append(" ") + out.append("") + return "\n".join(out) diff --git a/blog/wxr_import.py b/blog/wxr_import.py new file mode 100644 index 0000000..84e2b94 --- /dev/null +++ b/blog/wxr_import.py @@ -0,0 +1,193 @@ +"""Parse a WXR (WordPress export) feed and load it into this blog. + +Reads posts (), categories/tags (), and comments +() from a WXR 1.2 document and writes them into the same tables +this blog already uses. Pure logic, stdlib only, so it can be unit-tested +without an HTTP server or database. + +Mapping decisions (option a): + - Posts only are imported (no Pages). + - WordPress post_status -> our status: "publish" -> published, everything else -> draft. + - Categories are matched by name against existing rows; unknown names are created. + The slug is stored in posts.category (comma-joined for multiple categories). + - Tags are stored comma-joined in posts.tags. + - Comments are attached to their post by object_id; only approved ones are kept, + mapped to our status="approved" (the value the public view shows). + +On import we never overwrite existing rows: a post with a slug that already +exists is skipped (reported in the result) so re-importing is safe. +""" + +from email.utils import parsedate_to_datetime +from datetime import datetime, timezone + +import xml.etree.ElementTree as ET + +from .db import _slugify, get_db + + +# Qualified names of the elements we read. WordPress stores them with these URI +# prefixes; matching on the URI (not the prefix) means a different prefix in the +# file still resolves correctly. +_N = { + "post_name": "{http://wordpress.com/export/1.2/}post_name", + "encoded": "{http://purl.org/rss/1.0/modules/content/}encoded", + "excerpt": "{http://wordpress.org/export/1.2/excerpt/}excerpt", + "creator": "{http://purl.org/dc/elements/1.1/}creator", + "date": "{http://purl.org/dc/elements/1.1/}date", + "status": "{http://wordpress.com/export/1.2/}status", + "comment": "{http://wellformedweb.org/CommentAPI/}comment", +} + + +def _text(el): + return (el.text or "").strip() if el is not None else "" + + +def _attr(el, name): + if el is None: + return "" + val = el.get(name) + return val if val is not None else "" + + +def _to_db_date(value): + """Parse an RFC 822 date (WXR pubDate/dc:date) into our DB timestamp format.""" + if not value.strip(): + return "" + try: + dt = parsedate_to_datetime(value.strip()) + except (TypeError, ValueError): + return "" + if dt.tzinfo is not None: + dt = dt.astimezone(timezone.utc).replace(tzinfo=None) + return dt.strftime("%Y-%m-%d %H:%M:%S") + + +def _comment_datetime(el): + """A comment's own timestamp (WXR stores it per comment, not per post).""" + if el is None: + return "" + raw = (el.get("date_time_gmt") or el.get("comment_date_gmt") or "").strip() + if not raw: + return "" + if len(raw) >= 19 and raw[4] == "-" and raw[7] == "-": + return raw[:19] # already "YYYY-MM-DD HH:MM:SS" + return _to_db_date(raw) + + +def import_wxr(path, db=None): + """Parse the WXR file at `path` and insert rows into the DB. + + Returns a result dict: posts_imported, posts_skipped (duplicate slug), + categories_added, comments_imported, errors (list of strings). + + `db` defaults to the app's live database; tests may pass their own sqlite3 + connection so an import can be exercised against throwaway data. + """ + if db is None: + db = get_db() + + try: + tree = ET.parse(path) + except ET.ParseError as exc: + return {"posts_imported": 0, "posts_skipped": 0, "categories_added": 0, + "comments_imported": 0, "errors": [f"Could not parse the WXR file: {exc}"]} + + root = tree.getroot() + channel = root.find("channel") + if channel is None: + return {"posts_imported": 0, "posts_skipped": 0, "categories_added": 0, + "comments_imported": 0, "errors": ["No found in the WXR file."] } + + # name -> slug for categories that already exist. + cat_by_name = {} + for slug_, name_ in db.execute("SELECT slug, name FROM categories").fetchall(): + cat_by_name.setdefault(name_, slug_) + + # First pass: collect every category name referenced by any post, then make + # sure each one exists so we can resolve its slug. + referenced = set() + items = channel.findall("item") + for item in items: + for cat in item.findall("category"): + # Only real categories (domain="category") need ensuring to exist; + # tags are stored on the post, never as their own category row. + if cat.get("domain") == "post_tag": + continue + name = _text(cat) + if name: + referenced.add(name) + + counts = {"posts_imported": 0, "posts_skipped": 0, "categories_added": 0, + "comments_imported": 0, "errors": []} + + for name in sorted(referenced): + if name not in cat_by_name: + slug_ = _slugify(name) + if not db.execute("SELECT 1 FROM categories WHERE slug = ?", (slug_,)).fetchone(): + db.execute("INSERT INTO categories (slug, name) VALUES (?, ?)", (slug_, name)) + counts["categories_added"] += 1 + cat_by_name[name] = slug_ + + for item in items: + title = _text(item.find("title")) + if not title: + continue + + slug = _text(item.find(_N["post_name"])) or _slugify(title) + + status_raw = _text(item.find(_N["status"])).lower() + status = "published" if status_raw == "publish" else "draft" + + body = _text(item.find(_N["encoded"])) + excerpt = _text(item.find(_N["excerpt"])) + author = _text(item.find(_N["creator"])) or "editor" + created_at = _to_db_date(_text(item.find(_N["date"]))) or _to_db_date(_text(item.find("pubDate"))) + + categories, tags = [], [] + for cat in item.findall("category"): + domain = cat.get("domain", "category") + name = _text(cat) + if not name: + continue + if domain == "post_tag": + tags.append(name) + else: + categories.append(cat_by_name.get(name, name)) + + # A is nested inside this post's , so it belongs to + # this post. Insert the post first, then attach each comment to its id. + if db.execute("SELECT 1 FROM posts WHERE slug = ?", (slug,)).fetchone(): + counts["posts_skipped"] += 1 + continue + + db.execute( + "INSERT INTO posts (title, slug, body, excerpt, author, category, tags, status, " + "created_at, updated_at, published_at) " + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + (title, slug, body, excerpt, author, ",".join(categories), ",".join(tags), + status, created_at, created_at, created_at), + ) + post_id = db.execute("SELECT id FROM posts WHERE slug = ?", (slug,)).fetchone()[0] + + for c in item.findall(_N["comment"]): + body_c = _text(c) + if not body_c: + continue + email = _attr(c, "author_email") or "" + # Imported comments start as 'pending': auto-approving arbitrary + # text from an uploaded file published whatever it contained. + comment_at = _comment_datetime(c) or created_at + db.execute( + "INSERT INTO comments (object_type, object_id, author, email, body, status, created_at, updated_at) " + "VALUES (?, ?, ?, ?, ?, ?, ?, ?)", + ("post", post_id, _attr(c, "author") or author, email, body_c, + "pending", comment_at, comment_at), + ) + counts["comments_imported"] += 1 + + counts["posts_imported"] += 1 + + db.commit() + return counts diff --git a/docker-compose.yml b/docker-compose.yml new file mode 100644 index 0000000..d7d12f7 --- /dev/null +++ b/docker-compose.yml @@ -0,0 +1,66 @@ +services: + blog: + build: . + image: testblog:latest + container_name: simple-blog + ports: + - "8000:5000" + environment: + # BLOG_ADMIN_PASSWORD is only a first-run bootstrap value (the password is + # then stored hashed in the database). Leave it empty to have a random one + # generated and printed in the logs. Reset later with: + # docker compose exec blog python -m blog.manage set-password + - BLOG_ADMIN_PASSWORD=${BLOG_ADMIN_PASSWORD:-} + # Long random signing key. If empty, one is generated and kept in the DB. + - BLOG_SESSION_SECRET=${BLOG_SESSION_SECRET:-} + # Set to 1 when served over HTTPS (including behind a TLS proxy). + - BLOG_SECURE_COOKIES=${BLOG_SECURE_COOKIES:-0} + - BLOG_SESSION_HOURS=${BLOG_SESSION_HOURS:-12} + - BLOG_SESSION_IDLE_MINUTES=${BLOG_SESSION_IDLE_MINUTES:-120} + - BLOG_URL=${BLOG_URL:-http://localhost:8000} + # Resolve visitor country/city for the analytics map (0 disables lookups). + - BLOG_GEOIP=${BLOG_GEOIP:-1} + # Map LAN/local visitors at this server's own region (0 to leave blank). + - BLOG_GEOIP_LOCAL=${BLOG_GEOIP_LOCAL:-1} + # Optional comment-notification email (any SMTP provider). Leaving these + # empty disables emails; in-app moderation alerts still work. + - BLOG_SMTP_HOST=${BLOG_SMTP_HOST:-} + - BLOG_SMTP_PORT=${BLOG_SMTP_PORT:-587} + - BLOG_SMTP_USER=${BLOG_SMTP_USER:-} + - BLOG_SMTP_PASSWORD=${BLOG_SMTP_PASSWORD:-} + - BLOG_SMTP_FROM=${BLOG_SMTP_FROM:-} + - BLOG_NOTIFY_EMAIL=${BLOG_NOTIFY_EMAIL:-} + - BLOG_SMTP_TLS=${BLOG_SMTP_TLS:-1} + # Optional push notifications via the self-hosted ntfy service below. + # Set BLOG_NTFY_TOPIC to a secret topic name to switch them on. + - BLOG_NTFY_URL=${BLOG_NTFY_URL:-http://ntfy:80} + - BLOG_NTFY_TOPIC=${BLOG_NTFY_TOPIC:-} + - BLOG_NTFY_TOKEN=${BLOG_NTFY_TOKEN:-} + - BLOG_NTFY_PRIORITY=${BLOG_NTFY_PRIORITY:-default} + - BLOG_DATA_DIR=/app/data + volumes: + # Persist posts/DB between container restarts + - blog-data:/app/data + # Persist uploaded media so images survive a rebuild (not just a restart) + - uploads-data:/app/static/uploads + restart: unless-stopped + + # Self-hosted push notifications. It only talks to the blog container unless + # you publish its port, and its data is kept in a named volume. + ntfy: + image: binwiederhier/ntfy:v2.37.2 + container_name: simple-blog-ntfy + command: serve + environment: + - TZ=${TZ:-UTC} + volumes: + - ntfy-cache:/var/cache/ntfy + - ./ntfy/server.yml:/etc/ntfy/server.yml:ro + ports: + - "8085:80" + restart: unless-stopped + +volumes: + blog-data: + uploads-data: + ntfy-cache: diff --git a/docs/superpowers/specs/2026-11-05-photo-gallery-design.md b/docs/superpowers/specs/2026-11-05-photo-gallery-design.md new file mode 100644 index 0000000..9cd265d --- /dev/null +++ b/docs/superpowers/specs/2026-11-05-photo-gallery-design.md @@ -0,0 +1,73 @@ +# Photo gallery (dedicated album pages) — design doc + +**Date:** 2026-11-05 +**Feature:** add photo galleries, grouped into albums, viewable on dedicated pages. +**Approach chosen:** A — dedicated album pages (flat albums, single image upload at a time). + +## Intent / why +Give the site a way to display collections of photos as a grid with a click-to-enlarge +lightbox, organized into named groups ("albums"). Reuses the existing image-upload and +lightbox infrastructure rather than inventing new storage. + +## Goals / non-goals +- **Goal:** upload photos, group them into albums, view an album as a grid on its own page, + enlarge via lightbox (Esc / arrows / backdrop). +- **Non-goal:** cropping/editing photos, geolocation, EXIF metadata, image resizing. +- **Anti-goal:** don't slow the site or bloat the schema; keep it in the existing Flask + + SQLite + plain-template style. + +## Constraints (found while investigating) +- Images are stored as **files** in `static/uploads/` (on the named volume, so they persist), + validated by magic-byte signature at upload time; there is **no** database table for media + today. To group them we must track them in a table (filename + album). +- Pages render markdown via `render_markdown()`; lightbox reads images by `data-src`. +- Admin routes use the `@_login_required` decorator + `flash` + `jsonify`; admin templates + extend `admin/base.html` (nav-menu + sidebar, both driven by `active_page`). +- Werkzeug 3.1.9 / Flask 3.0.3; dependency-free. + +## Approach (what you picked) +- **A — dedicated album pages** (`/photos/`), not embedded-in-page shortcodes. +- **Flat albums** (no hierarchy). +- **Single image upload at a time** (matches your current `/upload` handler). + +Rejected: embedded markdown shortcodes (option B) — would force every page author to know a +new syntax; dedicated pages are cleaner URLs and share the existing lightbox. Nested albums +and batch upload were rejected as scope creep for v1. + +## The parts (builder's plan) + +**Data model** (two new tables, appended in `db.py` `init_db()`): +- `media_albums(id, name, slug UNIQUE, description, created_at)` — the groups. +- `media(id, filename, url, album_id FK→media_albums, position, created_at)` — individual photos. + +**Admin (blog/admin.py):** +- Album CRUD: `/admin/albums` (list), `/admin/albums/new`, `/admin/albums//edit`, + `/admin/albums//delete`. +- Media management: `/admin/media` lists all photos grouped by album; ungrouped photos shown under "(none)". Per-photo actions: + - **Assign to album** — dropdown to move a photo into an album (add). + - **Remove from album** — uncouple (`album_id = NULL`, keep file). This is the only default delete; it never removes the file. +- Extend the existing `/upload` handler to create a `media` row and offer album selection in + the response (album = null allowed, so photos can be ungrouped). +- Add nav links (nav-menu + sidebar) for Albums / Media, driven by `active_page`. + +**Public (blog/public.py):** +- Route `/photos/` → render the album's media grid. `_album_by_slug(slug)` helper; + unknown slug → 404. + +**Templates:** +- New `templates/photos.html` — responsive grid, each `` so the existing + `lightbox.js` handles enlarge for free. Empty album / no-media states handled. +- New `templates/admin/albums.html`, `templates/admin/media.html`, and an album edit form. +- Reuse `admin/base.html` (no new shell). + +## Decisions left to builder (my calls, unless you object) +- Album slug auto-generated from name; editable. +- `position` integer for manual ordering within an album; reordering via a simple up/down or + drag-free renumber. +- **Delete album → UNCUPLE, not delete.** `UPDATE media SET album_id = NULL WHERE album_id = ?`. Photos stay in `/uploads` and become ungrouped; nothing is deleted. +- Gallery layout: responsive CSS grid, masonry-ish via `aspect-ratio` to avoid layout shift. + +## Left to builder +Implement above, then verify with a test client: upload → assign album → view `/photos/` +grid → lightbox open/close; **delete album uncouples photos (album_id=NULL, files kept)**; assign/ +remove-from-album re-groups correctly; unknown album 404s. diff --git a/ntfy/server.yml b/ntfy/server.yml new file mode 100644 index 0000000..4760793 --- /dev/null +++ b/ntfy/server.yml @@ -0,0 +1,22 @@ +# Self-hosted ntfy configuration for this blog. +# Docs: https://docs.ntfy.sh/config/ +# +# Uncomment and set base-url to the address your phone uses when it must be +# absolute (e.g. "http://192.168.1.20:8085"). When empty, ntfy derives it from +# each request's Host header, which is fine on a LAN. +# base-url: "http://localhost:8085" + +listen-http: ":80" + +# Keep notifications on disk so a phone that was offline can still fetch them. +cache-file: "/var/cache/ntfy/cache.db" +cache-duration: "48h" + +# This instance is meant for your own devices. Anyone who can reach port 8085 +# and knows the topic can publish or read messages, so the topic is a secret. +# To lock the server down instead, set this to "deny-all" and create a token: +# docker compose exec ntfy ntfy user add --role=admin admin +# docker compose exec ntfy ntfy token add --label=blog admin +# then put the token in BLOG_NTFY_TOKEN and subscribe with the same account. +auth-default-access: "read-write" +enable-signup: false diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..76c411b --- /dev/null +++ b/requirements.txt @@ -0,0 +1,4 @@ +Flask==3.0.3 +markdown==3.7 +bleach==6.1.0 +Pillow==10.4.0 diff --git a/run.py b/run.py new file mode 100644 index 0000000..fb933da --- /dev/null +++ b/run.py @@ -0,0 +1,17 @@ +"""Entry point for the Simple Blog. + +Usage: + python run.py +""" + +import os + +from blog import create_app + +app = create_app() + + +if __name__ == "__main__": + # Read optional PORT from the environment (default 5000) + port = int(os.environ.get("PORT", "5000")) + app.run(host="0.0.0.0", port=port, debug=False) diff --git a/static/css/admin.css b/static/css/admin.css new file mode 100644 index 0000000..e1d5e2c --- /dev/null +++ b/static/css/admin.css @@ -0,0 +1,512 @@ +/* ========================================================================== + Simple Blog — Admin panel styling + ========================================================================== */ + +/* Log out is a POST form (so it needs a CSRF token), styled like a nav link. */ +.logout-form { + display: inline; + margin: 0; +} + +.link-button { + background: none; + border: 0; + padding: 0; + font: inherit; + color: inherit; + cursor: pointer; + text-align: left; +} + +.link-button:hover, +.link-button:focus { + text-decoration: underline; +} + +.admin-shell { + max-width: 1000px; + margin: 0 auto; +} + +/* Condensed top bar: logo left, menu toggle right. No wasted vertical space. */ +.admin-header { + display: flex; + align-items: center; + justify-content: space-between; + height: 56px; + padding: 0 var(--gutter); + background: var(--color-bg); + border-bottom: 1px solid var(--color-border); + box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05); +} + +.admin-header .header-inner { + display: flex; + align-items: center; + justify-content: space-between; + width: 100%; +} + +.admin-header .site-logo a { + font-weight: 700; + font-size: 1.15rem; + color: var(--color-text); + text-decoration: none; +} + +.admin-header .site-logo a:hover { + color: var(--color-accent); +} + +.admin-menu-button { + display: inline-flex; + align-items: center; + gap: 6px; + height: 34px; + padding: 0 14px; + border: 1px solid var(--color-border); + border-radius: 6px; + background: var(--color-bg); + color: var(--color-text); + font-weight: 600; + font-size: 0.9rem; + cursor: pointer; +} + +.admin-menu-button:hover { + border-color: var(--color-accent); + color: var(--color-accent); +} + +/* Lightweight section tabs (pill style, no box). Replaces the old bordered tab row. */ +.admin-subnav { + padding: 18px var(--gutter) 0; + margin-bottom: 28px; +} + +.admin-subnav a { + display: inline-block; + padding: 7px 15px; + border-radius: 999px; + font-weight: 600; + font-size: 0.9rem; + color: var(--color-text); + background: transparent; + border: 1px solid transparent; + text-decoration: none; +} + +.admin-subnav a:hover { + background: #eef4fa; + border-color: var(--color-border); + color: var(--color-accent); +} + +.admin-subnav a.active { + background: var(--color-accent); + border-color: var(--color-accent); + color: #fff; +} + +.admin-wrap { + padding: 28px var(--gutter) 60px; +} + +.admin-panel { + background: var(--color-bg); + border: 1px solid var(--color-border); + border-radius: 8px; + padding: 28px 30px; + margin-bottom: 24px; +} + +.admin-panel h1, +.admin-panel h2 { + margin-top: 0; +} + +.admin-actions { + display: flex; + flex-wrap: wrap; + gap: 14px; + margin-bottom: 28px; +} + +.admin-actions a { + display: inline-flex; + align-items: center; + gap: 8px; + padding: 12px 20px; + border-radius: 6px; + font-weight: 600; + border: 1px solid var(--color-border); + background: var(--color-bg); + color: var(--color-text); +} + +.admin-actions a.primary { + background: var(--color-accent); + border-color: var(--color-accent); + color: #fff; +} + +.admin-actions a.primary:hover { + background: var(--color-link-hover); + color: #fff; +} + +.admin-actions a:hover { + border-color: var(--color-accent); + color: var(--color-link); +} + +table.admin-table { + width: 100%; + border-collapse: collapse; + font-size: 0.92rem; +} + +table.admin-table th, +table.admin-table td { + text-align: left; + padding: 12px 14px; + border-bottom: 1px solid var(--color-border); + vertical-align: middle; +} + +table.admin-table th { + font-size: 0.82rem; + text-transform: uppercase; + letter-spacing: 0.04em; + color: var(--color-muted); + border-bottom: 2px solid var(--color-border); +} + +table.admin-table tr:hover td { + background: #fafafa; +} + +.table-actions { + white-space: nowrap; +} + +.btn { + display: inline-block; + padding: 8px 16px; + border-radius: 5px; + font-weight: 600; + font-size: 0.9rem; + cursor: pointer; + border: 1px solid var(--color-border); + background: var(--color-bg); + color: var(--color-text); + text-decoration: none; +} + +.btn:hover { + border-color: var(--color-accent); + color: var(--color-link); +} + +.btn-primary { + background: var(--color-accent); + border-color: var(--color-accent); + color: #fff; +} + +.btn-primary:hover { + background: var(--color-link-hover); + border-color: var(--color-link-hover); + color: #fff; +} + +.btn-danger { + color: #b71c1c; + border-color: #f5c6cb; + background: #fdecea; +} + +.btn-danger:hover { + background: #b71c1c; + border-color: #b71c1c; + color: #fff; +} + +.form-group { + margin-bottom: 18px; +} + +.form-group label { + display: block; + font-weight: 600; + margin-bottom: 6px; + font-size: 0.95rem; +} + +.form-group input, +.form-group textarea, +.form-group select { + width: 100%; + padding: 11px 12px; + border: 1px solid var(--color-border); + border-radius: 5px; + font-family: var(--font-stack); + font-size: 0.98rem; + background: #fff; +} + +.form-group input:focus, +.form-group textarea:focus, +.form-group select:focus { + outline: none; + border-color: var(--color-accent); +} + +.form-group textarea { + min-height: 320px; + resize: vertical; + font-family: "SFMono-Regular", Consolas, "Liberation Mono", Menlo, monospace; + line-height: 1.5; +} + +.form-row { + display: grid; + grid-template-columns: 1fr 1fr; + gap: 20px; +} + +@media (max-width: 620px) { + .form-row { + grid-template-columns: 1fr; + } +} + +.field-hint { + display: block; + margin-top: 6px; + font-size: 0.82rem; + color: var(--color-muted); +} + +.admin-stat { + text-align: center; +} + +.admin-stat .num { + display: block; + font-size: 2.4rem; + font-weight: 700; + color: var(--color-accent); +} + +.admin-stat .label { + font-size: 0.85rem; + color: var(--color-muted); + text-transform: uppercase; + letter-spacing: 0.05em; +} + +.category-row { + display: flex; + align-items: center; + justify-content: space-between; + padding: 12px 0; + border-bottom: 1px solid var(--color-border); +} + +.category-row:last-child { + border-bottom: 0; +} + +/* --- Analytics: locations, map + trend chart ---------------------------- */ +.admin-stat-grid { + display: grid; + grid-template-columns: repeat(auto-fit, minmax(150px, 1fr)); + gap: 20px; + margin: 24px 0 4px; +} + +.visitor-map { + height: 440px; + width: 100%; + border: 1px solid var(--color-border); + border-radius: 6px; + background: #eef1f5; + z-index: 0; +} + +.chart-wrap { + position: relative; + width: 100%; +} + +.chart-wrap canvas { + display: block; + width: 100%; + height: 280px; +} + +.chart-tooltip { + position: absolute; + padding: 6px 10px; + border-radius: 5px; + background: rgba(17, 24, 39, 0.92); + color: #fff; + font-size: 0.78rem; + line-height: 1.4; + pointer-events: none; + white-space: nowrap; + z-index: 2; +} + +.chart-legend { + display: flex; + flex-wrap: wrap; + gap: 8px 18px; + margin-top: 12px; + font-size: 0.85rem; + color: var(--color-muted); +} + +.chart-legend .swatch { + display: inline-block; + width: 10px; + height: 10px; + margin-right: 6px; + border-radius: 2px; + vertical-align: baseline; +} + +.location-flag { + font-size: 1.1em; + line-height: 1; +} + +.admin-split { + display: grid; + grid-template-columns: 1fr 1fr; + gap: 30px; +} + +.admin-split h2 { + margin-top: 0; +} + +@media (max-width: 860px) { + .admin-split { + grid-template-columns: 1fr; + } + + .visitor-map { + height: 320px; + } +} + +.filter-form { + display: flex; + flex-wrap: wrap; + align-items: flex-end; + gap: 14px 18px; + margin: 0 0 22px; +} + +.filter-form label { + display: flex; + flex-direction: column; + gap: 6px; + font-size: 0.8rem; + font-weight: 600; + text-transform: uppercase; + letter-spacing: 0.04em; + color: var(--color-muted); +} + +.filter-form select { + min-width: 190px; + padding: 8px 10px; + border: 1px solid var(--color-border); + border-radius: 5px; + background: #fff; + color: var(--color-text); + font-family: var(--font-stack); + font-size: 0.92rem; +} + +.location-chip { + display: inline-block; + margin: 2px 6px 2px 0; + padding: 3px 9px; + border: 1px solid var(--color-border); + border-radius: 999px; + background: #f6f8fa; + font-size: 0.82rem; + white-space: nowrap; +} + +.location-chip strong { + margin-left: 3px; +} + +.add-category { + margin-top: 16px; + display: flex; + gap: 10px; +} + +.add-category input { + flex: 1; + padding: 10px 12px; + border: 1px solid var(--color-border); + border-radius: 5px; +} + +.empty-state { + text-align: center; + color: var(--color-muted); + padding: 40px 20px; +} + +/* Flash messages (rendered by admin/base.html) */ +.notice { padding: 10px 14px; border: 1px solid var(--color-border); border-radius: 6px; margin: 10px 0; background: var(--color-bg); color: var(--color-text); } +.notice-success { background: #e7f7ee; border-color: #b7e0c3; color: #1f5c34; } +.notice-error { background: #fdecea; border-color: #f5c2c2; color: #7d2117; } +.notice-info { background: #e7f0fb; border-color: #b9d4f4; color: #12396b; } + +/* --------------------------------------------------------------------------- + Comments moderation + ------------------------------------------------------------------------- */ +.comment-stats { + display:flex; flex-wrap: wrap; gap: 10px 22px; margin: 16px 0 24px; +} +.comment-stats .term { + font-size: 0.95rem; + padding: 4px 12px; + border: 1px solid var(--color-border); + border-radius: 999px; + background: var(--color-bg); + color: var(--color-text); +} +.comment-stats .term.warn { + background: #fff4e5; border-color: #f2d399; color: #7a5210; +} +.comment-mod-list .comment-block { + border-left-width: 0; +} +.comment-mod-list .comment-block .comment-meta { + font-size: 0.85rem; +} +.comment-mod-list .comment-block .comment-actions { + margin-top: 14px; + display:flex; flex-wrap: wrap; gap: 8px; +} +.comment-mod-list .comment-block .comment-actions form { margin: 0; } + +/* Mobile: collapse the section tab row behind the menu toggle */ +@media (max-width: 640px) { + .admin-subnav { + display: none; + } +} + +/* Moderation badge in the admin navigation */ +.nav-badge { display: inline-block; min-width: 18px; padding: 0 5px; margin-left: 6px; border-radius: 9px; background: #d63638; color: #fff; font-size: 11px; line-height: 18px; text-align: center; vertical-align: middle; } diff --git a/static/css/custom.css b/static/css/custom.css new file mode 100644 index 0000000..40ebd2a --- /dev/null +++ b/static/css/custom.css @@ -0,0 +1,14 @@ +:root { + --color-accent:#91b1ba; + --color-link:#91b1ba; + --color-link-hover:#7f9fa8; + --color-text:#b79f9f; + --color-muted:rgba(183,159,159,0.55); + --color-border:rgba(183,159,159,0.92); + --color-bg:#ffffff; + --color-sidebar-bg:rgba(183,159,159,0.97); + --font-stack:Inter, Roboto, sans-serif; + --border-radius:16px; +} + +.posts-grid { grid-template-columns: repeat(1, 1fr); } diff --git a/static/css/style.css b/static/css/style.css new file mode 100644 index 0000000..99abee2 --- /dev/null +++ b/static/css/style.css @@ -0,0 +1,877 @@ +/* ========================================================================== + Simple Blog — GeneratePress-inspired styling (shared / front-end) + Clean, minimal, card-based layout with a sidebar. + ========================================================================== */ + +:root { + --border-radius: 6px; + --color-text: #1e1e1e; + --color-muted: #666; + --color-border: #e5e5e5; + --color-bg: #ffffff; + --color-link: #00a0d1; + --color-link-hover: #007a99; + --color-sidebar-bg: #f7f7f7; + --color-accent: #00a0d1; + --font-stack: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen, + Ubuntu, Cantarell, "Helvetica Neue", Arial, sans-serif; + --max-width: 1140px; + --gutter: 16px; +} + +*, +*::before, +*::after { + box-sizing: border-box; +} + +html { + -webkit-text-size-adjust: 100%; + text-size-adjust: 100%; +} + +body { + margin: 0; + padding: 0; + font-family: var(--font-stack); + color: var(--color-text); + background-color: var(--color-bg); + line-height: 1.7; + font-size: 16px; +} + +a { + color: var(--color-link); + text-decoration: none; + transition: color 0.2s ease; +} + +a:hover { + color: var(--color-link-hover); +} + +img { + max-width: 100%; + height: auto; +} + +/* --------------------------------------------------------------------------- + Header + ------------------------------------------------------------------------- */ +.site-header { + border-bottom: 3px solid var(--color-accent); + background-color: var(--color-bg); +} + +.header-inner { + max-width: var(--max-width); + margin: 0 auto; + padding: 18px var(--gutter); + display: flex; + align-items: center; + justify-content: space-between; + flex-wrap: wrap; + gap: 12px; +} + +.site-logo a { + color: var(--color-text); + font-weight: 700; + font-size: 1.35rem; + letter-spacing: -0.02em; + text-decoration: none; +} + +.site-logo img { + max-height: 44px; + width: auto; +} + +/* --------------------------------------------------------------------------- + Hero header (shown only when an uploaded banner image is present) + The banner spans the whole header width, sitting behind the logo + nav. + ------------------------------------------------------------------------- */ +.header-inner.has-banner { + position: relative; + width: 100%; + max-width: none; + margin: 0; + padding: 0; + min-height: 260px; +} + +.header-inner.has-banner .site-banner-img { + position: absolute; + inset: 0; + width: 100%; + height: 100%; + object-fit: cover; + border-radius: 0; + z-index: 0; +} + +.header-inner.has-banner .site-logo { + position: relative; + z-index: 1; + margin-left: 26px; + color: #fff; + text-shadow: 0 2px 8px rgba(0, 0, 0, 0.55); +} + +.header-inner.has-banner .hero-tagline { + display: block; + font-size: 1rem; + font-style: italic; + opacity: 0.92; + text-shadow: 0 1px 4px rgba(0, 0, 0, 0.55); +} + +.header-inner.has-banner .site-logo a { + color: #fff; + text-decoration: none; +} + +.header-inner.has-banner .main-nav { + position: absolute; + left: 50%; + transform: translateX(-50%); + bottom: 0; + z-index: 1; +} + +.header-inner.has-banner .main-nav button { + color: #fff; + text-shadow: 0 1px 4px rgba(0, 0, 0, 0.55); +} + +.header-inner.has-banner .nav-menu { + background: rgba(0, 0, 0, 0.35); + border-color: rgba(255, 255, 255, 0.35); +} + +@media (max-width: 620px) { + /* The nav is pinned to the bottom of the banner, so the banner must stay tall + enough for the logo (title + tagline) and the nav to coexist without the nav + sliding up over the title/tagline. */ + .header-inner.has-banner { min-height: 260px; } + .header-inner.has-banner .site-logo { margin-left: 16px; } +} + +/* --------------------------------------------------------------------------- + Top navigation (inline links — the old dropdown menu has been removed) + ------------------------------------------------------------------------- */ +.main-nav { + /* Width is set by the parent flex container (space-between) on non-banner + pages; overridden to absolute-center at the bottom only when a banner is shown. */ +} + +.nav-links { + display: flex; + align-items: center; + flex-wrap: wrap; + margin: 0; + padding: 0; + list-style: none; + gap: 6px 20px; +} + +.nav-item a { + color: var(--color-text); + text-decoration: none; + font-weight: 600; + font-size: 0.98rem; + padding: 6px 4px; + border-radius: 4px; + transition: color 0.15s ease, background-color 0.15s ease; +} + +.nav-item a:hover { + color: var(--color-link); + background-color: var(--color-sidebar-bg); +} + +/* With a hero banner the nav sits centered at the bottom of the banner. */ +.header-inner.has-banner .main-nav { + /* On mobile the logo (title + tagline) and the nav are both flex children of + .header-inner, which wraps. Together they exceed the screen width, so the nav + wraps onto a second line that slides up over the title/tagline. Pull the nav + out of the flex row and pin it to the bottom of the banner instead — the + banner is tall enough (260px) for both to coexist without overlap. + NOTE: transform must be reset — an older rule for this selector still set + translateX(-50%) and, at equal specificity, would otherwise persist. */ + position: absolute; + left: 0; + right: 0; + bottom: 0; + z-index: 2; + transform: none; + display: flex; + justify-content: center; + padding: 14px 16px 18px; /* gap above the links so they never touch the tagline */ +} + +.header-inner.has-banner .nav-links { + width: min(92%, 260px); +} + +/* Keep the links in a single centered row on banner pages. The mobile rule below + turns nav links into stacked blocks; here we restore them to inline-block so the + menu reads as one horizontal row instead of a vertical list. */ +.header-inner.has-banner .nav-item a { + display: inline-block; +} + +.header-inner.has-banner .nav-item a { + color: #fff; + text-shadow: 0 1px 3px rgba(0, 0, 0, 0.45); +} + +.header-inner.has-banner .nav-item a:hover { + background-color: rgba(255, 255, 255, 0.2); +} + +@media (max-width: 620px) { + .nav-links { + gap: 0; + } + .nav-item a { + display: block; + padding: 10px 14px; + } +} + +/* --------------------------------------------------------------------------- + Layout + ------------------------------------------------------------------------- */ +.site-main { + max-width: var(--max-width); + margin: 0 auto; + padding: 34px var(--gutter) 50px; +} + +.content-area { + display: grid; + grid-template-columns: 2fr 1fr; + gap: 38px; + align-items: start; +} + +@media (max-width: 860px) { + .content-area { + grid-template-columns: 1fr; + } +} + +/* --------------------------------------------------------------------------- + Page heading + ------------------------------------------------------------------------- */ +.page-heading { + font-size: 1.9rem; + font-weight: 700; + margin: 0 0 26px; + line-height: 1.3; + letter-spacing: -0.01em; +} + +.page-heading a { + color: var(--color-text); +} + +/* --------------------------------------------------------------------------- + Post grid + ------------------------------------------------------------------------- */ +.posts-grid { + display: grid; + grid-template-columns: repeat(2, 1fr); + gap: 26px; +} + +@media (max-width: 620px) { + .posts-grid { + grid-template-columns: 1fr; + } +} + +.post-card { + background: var(--color-card-bg); + border: 1px solid var(--color-border); + border-radius: var(--border-radius); + padding: 30px 28px 26px; + transition: box-shadow 0.2s ease, transform 0.2s ease; +} + +.post-card:hover { + box-shadow: 0 6px 18px rgba(0, 0, 0, 0.05); + transform: translateY(-2px); +} + +.post-card h2, +.post-card h3 { + margin: 0 0 6px; + font-size: 1.6rem; + line-height: 1.25; + font-weight: 700; + letter-spacing: -0.01em; +} + +.post-card h2 a, +.post-card h3 a { + color: var(--color-text); +} + +.post-card h2 a:hover, +.post-card h3 a:hover { + color: var(--color-link); +} + +.post-meta { + font-size: 0.85rem; + color: var(--color-muted); + margin-bottom: 14px; + letter-spacing: 0.02em; +} + +.post-meta strong { + font-weight: 600; + color: var(--color-text); +} + +.post-excerpt { + margin: 0 0 16px; + font-size: 0.98rem; + line-height: 1.6; + color: var(--color-text); +} + +.post-excerpt p { + margin: 0 0 10px; +} + +.post-excerpt p:last-child { + margin-bottom: 0; +} + +.post-tags { + font-size: 0.82rem; + color: var(--color-muted); + margin-bottom: 6px; +} + +.post-tags .tag-icon { + margin-right: 4px; +} + +.post-tags .tag { + color: var(--color-link); + text-decoration: none; +} + +.post-tags .tag:hover { + text-decoration: underline; +} + +.post-footer { + display: flex; + flex-wrap: wrap; + align-items: center; + justify-content: space-between; + gap: 10px; + margin-top: 8px; +} + +.read-more { + font-size: 0.9rem; + font-weight: 600; + color: var(--color-link); + text-decoration: none; +} + +.read-more:hover { + color: var(--color-link-hover); + text-decoration: underline; +} + +.comment-link { + font-size: 0.9rem; + color: var(--color-muted); + text-decoration: none; +} + +.comment-link:hover { + color: var(--color-link); +} + +/* --------------------------------------------------------------------------- + Sidebar / widgets + ------------------------------------------------------------------------- */ +.sidebar .widget { + background: var(--color-sidebar-bg); + border: 1px solid var(--color-border); + border-radius: 6px; + padding: 20px 22px; + margin-bottom: 26px; +} + +.widget-title { + font-size: 1.05rem; + font-weight: 700; + margin: 0 0 14px; + padding-bottom: 10px; + border-bottom: 2px solid var(--color-accent); +} + +.search-form input[type="search"] { + width: 100%; + padding: 10px 12px; + border: 1px solid var(--color-border); + border-radius: 4px; + font-family: var(--font-stack); + font-size: 0.95rem; +} + +.search-form input[type="search"]:focus { + outline: none; + border-color: var(--color-accent); +} + +.search-form button { + margin-top: 8px; + width: 100%; + background-color: var(--color-accent); + color: #fff; + border: 0; + padding: 10px; + border-radius: 4px; + font-weight: 600; + cursor: pointer; +} + +.search-form button:hover { + background-color: var(--color-link-hover); + color: #fff; +} + +.widget ul { + margin: 0; + padding: 0; + list-style: none; +} + +.widget li { + margin-bottom: 8px; +} + +.widget li a, +.widget li span { + color: var(--color-text); + font-size: 0.92rem; +} + +.widget li a:hover { + color: var(--color-link); +} + +.widget ul.submenu li { + padding-left: 14px; + border-left: 2px solid var(--color-border); + margin-left: 6px; +} + +/* --------------------------------------------------------------------------- + Breadcrumb + ------------------------------------------------------------------------- */ +.breadcrumb { + font-size: 0.85rem; + color: var(--color-muted); + margin-bottom: 24px; +} + +.breadcrumb a { + color: var(--color-link); +} + +.breadcrumb span { + margin: 0 8px; +} + +/* --------------------------------------------------------------------------- + Single post + ------------------------------------------------------------------------- */ +.single-post { + background: var(--color-bg); + border: 1px solid var(--color-border); + border-radius: 6px; + padding: 34px 32px; +} + +.single-post .post-title { + font-size: 2.1rem; + font-weight: 700; + line-height: 1.25; + margin: 0 0 20px; + letter-spacing: -0.01em; +} + +.single-post .entry-content { + font-size: 1.02rem; +} + +.single-post .entry-content h1, +.single-post .entry-content h2, +.single-post .entry-content h3 { + margin-top: 1.4em; + margin-bottom: 0.6em; + font-weight: 700; +} + +.single-post .entry-content pre { + background: #1e1e1e; + color: #e0e0e0; + padding: 16px; + border-radius: 6px; + overflow-x: auto; + font-size: 0.88rem; + line-height: 1.5; +} + +.single-post .entry-content pre code { + background: none; + padding: 0; +} + +.single-post .entry-content code { + background: var(--color-sidebar-bg); + padding: 2px 6px; + border-radius: 3px; + font-size: 0.9em; +} + +.single-post .entry-content blockquote { + border-left: 4px solid var(--color-accent); + margin: 1.2em 0; + padding: 8px 20px; + font-style: italic; + color: #444; + background: var(--color-sidebar-bg); + border-radius: 0 6px 6px 0; +} + +.single-post .entry-content img { + border-radius: 6px; + margin: 1.2em 0; +} + +.single-post .entry-content table { + border-collapse: collapse; + width: 100%; + margin: 1.2em 0; +} + +.single-post .entry-content th, +.single-post .entry-content td { + border: 1px solid var(--color-border); + padding: 8px 12px; + text-align: left; +} + +.single-post .entry-content th { + background: var(--color-sidebar-bg); +} + +.post-share { + margin-top: 34px; + padding-top: 24px; + border-top: 1px solid var(--color-border); + font-size: 0.9rem; + color: var(--color-muted); +} + +/* --------------------------------------------------------------------------- + Comments + ------------------------------------------------------------------------- */ +.comments-section { + margin-top: 40px; + border-top: 1px solid var(--color-border); + padding-top: 30px; +} + +.comment-list { margin-bottom: 28px; } +.field-hint { display:block; margin: 6px 0 16px; font-size: 0.85rem; color: var(--color-muted); } +.empty-state { text-align:center; color: var(--color-muted); padding: 30px 20px; } + +.comment-block { + background: var(--color-sidebar-bg); + border: 1px solid var(--color-border); + border-radius: 6px; + padding: 18px 20px; + margin-bottom: 16px; +} +.comment-block .comment-meta { + font-size: 0.85rem; + color: var(--color-muted); + margin-bottom: 8px; + display:flex; + gap: 8px; + flex-wrap: wrap; +} +.comment-block .comment-author { color: var(--color-text); font-weight: 600; } +.comment-block .comment-email { opacity: 0.75; } +.comment-block .comment-body { font-size: 0.98rem; line-height: 1.6; } +.comment-block .comment-actions { margin-top: 12px; } +.comment-pending { border-left: 4px solid var(--color-accent); } + +/* Buttons used by the public comment form / moderation actions. Defined here so + they style on public pages (which load only style.css, not admin.css). */ +.btn { + display:inline-block; padding: 8px 16px; border-radius: 5px; font-weight: 600; + font-size: 0.9rem; cursor:pointer; border: 1px solid var(--color-border); + background: var(--color-bg); color: var(--color-text); text-decoration:none; +} +.btn:hover { border-color: var(--color-accent); color: var(--color-link); } +.btn-primary { + background: var(--color-accent); border-color: var(--color-accent); color: #fff; +} +.btn-primary:hover { background: var(--color-link-hover); border-color: var(--color-link-hover); color: #fff; } +.btn-danger { color: #b71c1c; border-color: #f5c6cb; background: #fdecea; } +.btn-danger:hover { background: #b71c1c; border-color: #b71c1c; color: #fff; } +.btn-sm { padding: 5px 12px; font-size: 0.82rem; line-height: 1; } + +.comment-form { + border-top: 1px solid var(--color-border); padding-top: 24px; +} +.comment-form .form-row { grid-template-columns: 1fr 1fr; gap: 20px; margin-bottom: 16px; } +.comment-form label { display:block; font-weight: 600; margin-bottom: 6px; font-size: 0.95rem; } +.comment-form input, .comment-form textarea { + width: 100%; padding: 11px 12px; border: 1px solid var(--color-border); + border-radius: 5px; font-family: var(--font-stack); font-size: 0.98rem; background: #fff; +} +.comment-form input:focus, .comment-form textarea:focus { + outline: none; border-color: var(--color-accent); +} +.comment-form textarea { min-height: 90px; resize: vertical; } +.comment-form .btn-primary { padding: 11px 22px; } + +/* --------------------------------------------------------------------------- + Notices + ------------------------------------------------------------------------- */ +.notice { + padding: 10px 14px; + border-radius: 4px; + margin-bottom: 16px; + font-size: 0.92rem; +} + +.notice-error { + background: #fdecea; + color: #b71c1c; + border: 1px solid #f5c6cb; +} + +.notice-success { + background: #e7f7ee; + color: #1b5e20; + border: 1px solid #c3e6cb; +} + +.notice-info { + background: #e7f2fd; + color: #0c5468; + border: 1px solid #bee5eb; +} + +/* ------------------------------- Lightbox ------------------------------- */ +/* Full-page image viewer opened by clicking any on rendered pages. */ +.lightbox { + position: fixed; + inset: 0; + z-index: 9000; + display: none; + align-items: center; + justify-content: center; + font-family: -apple-system, "Segoe UI", Roboto, Helvetica, Arial, sans-serif; +} +.lightbox.is-open { + display: flex; +} +.lightbox-backdrop { + position: absolute; + inset: 0; + background: rgba(0, 0, 0, 0.85); + cursor: pointer; + opacity: 0; + transition: opacity 0.25s ease; +} +.lightbox.is-open .lightbox-backdrop { + opacity: 1; +} +.lightbox-wrapper { + position: relative; + z-index: 1; + max-width: 94vw; + max-height: 90vh; + display: flex; + align-items: center; + justify-content: center; + padding: 24px; +} +.lightbox-img { + max-width: 94vw; + max-height: 90vh; + width: auto; + height: auto; + object-fit: contain; + border-radius: 4px; + box-shadow: 0 8px 40px rgba(0, 0, 0, 0.45); +} +.lightbox-img[aria-hidden="true"] { + visibility: hidden; +} + +/* ------------------------------- Gallery hero ------------------------------- */ +.gallery-hero { + margin: 24px 0 8px; + text-align: center; +} +.gallery-hero-img { + max-width: 100%; + border-radius: 6px; + box-shadow: 0 6px 24px rgba(0, 0, 0, 0.18); + cursor: pointer; + transition: transform 0.15s ease, box-shadow 0.15s ease; +} +.gallery-hero-img:hover { + transform: translateY(-2px); + box-shadow: 0 10px 30px rgba(0, 0, 0, 0.28); +} +.hero-caption { + margin-top: 8px; + font-weight: 600; + color: #444; +} + +/* ------------------------------- Gallery lightbox -------------------------- */ +.gallery-lightbox { + position: fixed; + inset: 0; + z-index: 9500; + display: none; + flex-direction: column; + align-items: center; + justify-content: center; + font-family: -apple-system, "Segoe UI", Roboto, Helvetica, Arial, sans-serif; +} +.gallery-lightbox.is-open { + display: flex; +} +.gallery-lightbox-backdrop { + position: absolute; + inset: 0; + background: rgba(0, 0, 0, 0.85); + cursor: pointer; + opacity: 0; + transition: opacity 0.25s ease; +} +.gallery-lightbox.is-open .gallery-lightbox-backdrop { + opacity: 1; +} +.gallery-lightbox-header { + position: relative; + z-index: 2; + color: #fff; + font-size: 1.4rem; + font-weight: 600; + text-align: center; + padding: 18px 12px 4px; + text-shadow: 0 1px 6px rgba(0, 0, 0, 0.5); +} +.gallery-lightbox-body { + position: relative; + z-index: 2; + display: flex; + flex-direction: column; + align-items: center; + gap: 14px; + max-width: 94vw; + width: auto; + padding: 8px 20px; +} +.lightbox-prev, +.lightbox-next { + position: absolute; + top: 50%; + transform: translateY(-50%); + z-index: 3; + width: 46px; + height: 46px; + border: none; + border-radius: 50%; + background: rgba(255, 255, 255, 0.15); + color: #fff; + font-size: 1.6rem; + line-height: 1; + cursor: pointer; + transition: background 0.15s ease; +} +.lightbox-prev { left: 16px; } +.lightbox-next { right: 16px; } +.lightbox-prev:hover, +.lightbox-next:hover { background: rgba(255, 255, 255, 0.3); } +.lightbox-img-main { + max-width: 90vw; + max-height: 78vh; + width: auto; + height: auto; + object-fit: contain; + border-radius: 6px; + box-shadow: 0 10px 40px rgba(0, 0, 0, 0.5); +} +.lightbox-close { + position: absolute; + top: 12px; + right: 18px; + z-index: 4; + width: 38px; + height: 38px; + border: none; + border-radius: 50%; + background: rgba(255, 255, 255, 0.15); + color: #fff; + font-size: 1.6rem; + line-height: 1; + text-align: center; + cursor: pointer; + transition: background 0.15s ease; +} +.lightbox-close:hover { background: rgba(255, 255, 255, 0.3); } + +/* ------------------------------- Album card thumb -------------------------- */ +.album-card { + display: flex; + flex-direction: column; + text-align: left; +} +.album-thumb { + width: 100%; + max-height: 200px; + object-fit: cover; + border-radius: 6px; + margin-bottom: 10px; + display: block; +} + +/* --- Tag browsing, pagination, draft previews ------------------------------ */ +.tag-cloud { display: flex; flex-wrap: wrap; gap: 10px; align-items: center; } +.tag-cloud-page { margin: 24px 0; } +.tag-cloud .term { display: inline-flex; gap: 6px; align-items: baseline; } +.tag-cloud .term small { opacity: .65; font-size: .8em; } +.pagination { display: flex; flex-wrap: wrap; align-items: center; gap: 14px; margin: 28px 0 8px; } +.pagination-info { opacity: .7; font-size: .9em; } +.preview-banner { border-left: 4px solid #d97706; background: #fff7ed; color: #7c2d12; padding: 12px 16px; border-radius: 6px; margin: 16px 0; } +.preview-banner a { font-weight: 600; } + +/* Related posts under an article */ +.related-posts { margin: 36px 0 12px; } +.related-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 14px; } +.related-card { border: 1px solid rgba(0, 0, 0, .12); border-radius: 6px; padding: 14px 16px; } +.related-card h3 { margin: 0 0 6px; font-size: 1rem; line-height: 1.3; } +.related-card .post-meta { display: flex; gap: 10px; font-size: .85em; opacity: .75; } diff --git a/static/js/admin_analytics.js b/static/js/admin_analytics.js new file mode 100644 index 0000000..df722e2 --- /dev/null +++ b/static/js/admin_analytics.js @@ -0,0 +1,268 @@ +/* Analytics dashboard: visitor location map + location trend chart. + * + * Both charts read their data from JSON +{% endblock %} diff --git a/templates/admin/analytics.html b/templates/admin/analytics.html new file mode 100644 index 0000000..5a90b2c --- /dev/null +++ b/templates/admin/analytics.html @@ -0,0 +1,187 @@ +{% extends "admin/base.html" %} +{% block head_extra %} + +{% endblock %} +{% block admin_content %} +
+

Analytics

+

Anonymous visitor tracking. Only an opaque visitor_id cookie is stored; locations are approximate and derived from the visitor's IP — the address itself is never saved.

+
+
{{ total_visitors }}Unique visitors
+
{{ total_visits }}Total visits
+
{{ unique_pages }}Pages viewed
+
{{ 'n/a' if total_visitors == 0 else (total_visits | int / (total_visitors or 1) | round(2)) }}Avg. pages/visit
+
{{ total_countries }}Countries
+
{{ total_cities }}Cities
+
+
+ +
+

Visitor map

+ {% if map_points %} +

Each circle is a city. Larger circles mean more visits — click one for the city, region, country and counts.

+ {% else %} +

No location data yet. The map fills in as visitors arrive; locations come from the visitor's IP (or, for local/LAN visitors, this server's own region).

+ {% endif %} +
+
+ +
+

Location trends

+ {% if location_trend.series %} +

Visits per day over the last {{ location_trend.labels|length }} days, by location. Hover the chart for daily counts.

+
+
+ {% else %} +

No visits in the last 30 days.

+ {% endif %} +
+ +
+
+
+

Top countries

+ + + + {% for r in top_countries %} + + + + + + {% else %} + + {% endfor %} + +
CountryVisitorsVisits
{% if r.country_code %}{{ r.country_code|country_flag }} {% endif %}{{ r.country }}{{ r.visitors }}{{ r.visits }}
No location data yet.
+
+
+

Top cities

+ + + + {% for r in top_cities %} + + + + + + {% else %} + + {% endfor %} + +
CityVisitorsVisits
+ {% if r.country_code %}{{ r.country_code|country_flag }} {% endif %}{{ r.city }} + {% if r.region %}{{ r.region }}, {% endif %}{{ r.country }} + {{ r.visitors }}{{ r.visits }}
No city data yet.
+
+
+
+ +
+

Where visitors to each page come from

+ {% if page_locations %} +

The busiest pages and the countries their readers came from. Counts are unique visitors per country.

+ + + + {% for page in page_locations %} + + + + + + {% endfor %} + +
PageTop locationsVisits
+ {{ page.path }} + {% if page.title %}
{{ page.title }}{% endif %} +
+ {% for c in page.countries %} + {% if c.country_code %}{{ c.country_code|country_flag }} {% endif %}{{ c.country }} {{ c.visitors }} + {% endfor %} + {% if page.more_countries %}+{{ page.more_countries }} more{% endif %} + {{ page.visits }}
+ {% else %} +

No page visits yet.

+ {% endif %} +
+ +
+

Most viewed pages

+ + + + {% for r in top_pages %} + + + + + + {% else %} + + {% endfor %} + +
PageTitleVisits
{{ r.page_path }}{{ r.title or "(untitled)" }}{{ r.c }}
No visits yet.
+
+ +
+

Devices

+ + + + {% for r in top_devices %} + + {% else %} + + {% endfor %} + +
DeviceVisitors
{{ r.device }}{{ r.c }}
No data yet.
+
+ +
+

Browsers

+ + + + {% for r in top_browsers %} + + {% else %} + + {% endfor %} + +
BrowserVisitors
{{ r.browser or "(unknown)" }}{{ r.c }}
No data yet.
+
+ +
+

Where they came from

+ + + + {% for r in top_sources %} + + {% else %} + + {% endfor %} + +
SourceVisitors
{{ r.source }}{% if loop.first %} (raw referrers below){% endif %}{{ r.c }}
No data yet.
+ + + + {% for r in top_domains %} + + {% else %} + + {% endfor %} + +
Referrer domainVisitors
{{ r.referrer_domain or "—" }}{{ r.c }}
No referrers yet.
+
+ + + {% if location_trend.series %} + + {% endif %} + + +{% endblock %} diff --git a/templates/admin/appearance.html b/templates/admin/appearance.html new file mode 100644 index 0000000..1705fd2 --- /dev/null +++ b/templates/admin/appearance.html @@ -0,0 +1,447 @@ +{% extends "admin/base.html" %} +{% block admin_content %} +
+

Appearance

+ + +
+ + + +
+

Site identity

+
+
+ + +
+
+ + +
+
+ +
+ + + Posts use their excerpt first; this is the fallback for home, archive, tag and other pages. +
+ + +
+ + +
+
+ + +
+

Theme

+

These controls render into the Custom CSS box below as you change them. Edit the box directly for anything more advanced.

+ + +
+
+ +
+ + +
+
+
+ +
+ + +
+
+
+ +
+
+ +
+ + +
+
+
+ +
+ + +
+
+
+ + +
+
+ + +
+
+ + +
+
+ + +
+
+ +
+ + +
+ + +
+ + +
+

Custom CSS

+

The theme variables above are rendered here live; add any extra rules below them.

+
+ + + +
+
+ + +
+

Header image

+

Upload a banner/header image for the top of every public page. Leave blank to remove it.

+ {% if header_image %} +
+ + {{ site_title }} + +
+ {% endif %} +
+ + +
+
+ + +
+ + +
+
+ + +
+

Live preview

+

This mini-site uses the exact variables you just set. Changes update as you tweak them.

+
+ + +
+

{{ site_title }}

+
+ {% for _i in range(0, 6) %} + + {% endfor %} +
+
+
+
+ + + + +{% endblock %} diff --git a/templates/admin/base.html b/templates/admin/base.html new file mode 100644 index 0000000..581fa07 --- /dev/null +++ b/templates/admin/base.html @@ -0,0 +1,103 @@ + + + + + + {# Routes that don't pass active_page (posts, comments, …) get their label + from the endpoint, so every admin tab is named correctly. #} + {% set page_label = (active_page or (request.endpoint or 'dashboard').rsplit('.', 1)[-1])|replace('_', ' ')|replace('-', ' ')|title %} + {{ page_label }} · {{ site_title }} + + + + + + + + {# Relative asset base (NOT absolute). Resolves against the PAGE origin, so tinymce assets + follow whatever protocol/host loads the page — works behind reverse proxies (https://domain, + http://IP, LAN host) without needing X-Forwarded-Proto or per-host edits. An absolute base + would be forced to http(s) as Flask sees it internally and break Mixed Content on HTTPS. #} + {# js_base has NO trailing slash; callers add the needed '/' themselves so paths stay clean #} + {% set js_base = "/static/js" %} + + + {% block head_extra %}{% endblock %} + + +
+ +
+ + + +
+ {% with messages = get_flashed_messages(with_categories=true) %} + {% for category, message in messages %} +
{{ message }}
+ {% endfor %} + {% endwith %} + {% block admin_content %}{% endblock %} +
+ + + + + diff --git a/templates/admin/categories.html b/templates/admin/categories.html new file mode 100644 index 0000000..cfd1139 --- /dev/null +++ b/templates/admin/categories.html @@ -0,0 +1,51 @@ +{% extends "admin/base.html" %} +{% block admin_content %} +
+

Categories

+ + + {% if categories is not none %} + + + + + + {% for slug, name in categories %} + + + + + + {% endfor %} + +
NameSlugActions
{{ name }}{{ slug }} + {% if slug != 'general' %} +
+ + +
+ {% else %} + Default — cannot be deleted + {% endif %} +
+ {% else %} +

No categories yet.

+ {% endif %} +
+ + {% if categories is none %} +
+

Add a category

+
+ +
+ + +
+ +
+
+ {% endif %} +{% endblock %} diff --git a/templates/admin/comments.html b/templates/admin/comments.html new file mode 100644 index 0000000..0389396 --- /dev/null +++ b/templates/admin/comments.html @@ -0,0 +1,99 @@ +{% extends "admin/base.html" %} +{% block admin_content %} +
+

Comments

+ +
+ {{ counts.pending }} pending + {{ counts.approved }} approved + {{ counts.rejected }} rejected + {{ counts.spam }} spam +
+ + {% if comments or rejected or spam %} + {% if comments %} +

Pending moderation

+
+ {% for c in comments %} +
+
+ {{ c.author }} + {% if c.email %}{{ c.email }}{% endif %} + +
+
{{ render_markdown(c.body) }}
+
+
+ + +
+
+ + +
+
+ + +
+
+ + +
+
+
+ {% endfor %} +
+ {% endif %} + + {% if rejected %} +

Rejected comments

+
+ {% for c in rejected %} +
+
+ {{ c.author }} + {% if c.email %}{{ c.email }}{% endif %} + +
+
{{ render_markdown(c.body) }}
+
+
+ + +
+
+ + +
+
+
+ {% endfor %} +
+ {% endif %} + + {% if spam %} +

Spam comments

+
+ {% for c in spam %} +
+
+ {{ c.author }} + {% if c.email %}{{ c.email }}{% endif %} + +
+
{{ render_markdown(c.body) }}
+
+
+ + +
+
+
+ {% endfor %} +
+ {% endif %} + {% else %} +

No comments awaiting moderation.

+ {% endif %} +
+{% endblock %} diff --git a/templates/admin/dashboard.html b/templates/admin/dashboard.html new file mode 100644 index 0000000..4a2e102 --- /dev/null +++ b/templates/admin/dashboard.html @@ -0,0 +1,61 @@ +{% extends "admin/base.html" %} +{% block admin_content %} +
+

Dashboard

+
+
{{ count }}Total posts
+
{{ published }}Published
+
{{ drafts }}Drafts
+ + {{ pending_comments }}Awaiting moderation + +
+
+ +
+

Recent posts

+ + + + + + + + + + {% for p in posts[:5] %} + + + + + + {% else %} + + {% endfor %} + +
TitleStatusDate
{{ p.title }}{% if p.status == 'published' %}Published{% else %}Draft{% endif %}{{ parse_date(p.created_at) }}
No posts yet.
+
+ +
+

Comments awaiting moderation

+ {% if pending %} + + + + + + {% for c in pending %} + + + + + + + {% endfor %} + +
AuthorCommentReceived
{{ c.author }}{{ c.body[:120] }}{% if c.body|length > 120 %}…{% endif %}{{ parse_date(c.created_at) }}Review
+ {% else %} +

Nothing waiting for moderation.

+ {% endif %} +
+{% endblock %} diff --git a/templates/admin/import_export.html b/templates/admin/import_export.html new file mode 100644 index 0000000..d577992 --- /dev/null +++ b/templates/admin/import_export.html @@ -0,0 +1,31 @@ +{% extends "admin/base.html" %} +{% block admin_content %} +
+

Import / Export

+

Move content to and from a WordPress site using the standard WXR (XML) format.

+
+ +
+

Export this blog

+

Download everything as a .xml file that you can upload into a fresh WordPress site via its "Tools → Import → WordPress" screen. Posts, categories and comments are included; images are left as-is (see the note below).

+
+ + + +
+

Note: images in the post HTML keep their original URLs, so re-upload them through WordPress's Media Library after importing, or pick the image-reupload option if you want this tool to pull them for you.

+
+ +
+

Import from WordPress

+

Choose a WXR .xml file exported from a WordPress site. Published posts, their categories/tags, and comments are imported into Posts. Existing rows are never overwritten.

+
+ +
+ + +
+ +
+
+{% endblock %} diff --git a/templates/admin/links.html b/templates/admin/links.html new file mode 100644 index 0000000..5e0781c --- /dev/null +++ b/templates/admin/links.html @@ -0,0 +1,53 @@ +{% extends "admin/base.html" %} +{% block admin_content %} +
+

Links

+

+ These appear in the “Links” panel in the site sidebar, in the order + listed below. The panel stays hidden until at least one link is added. +

+ +
+ +
+
+ + +
+
+ + + A bare domain gets https:// added automatically. +
+
+ +
+
+ +
+

Current links

+ {% if links %} + + + + + + {% for link in links %} + + + + + + {% endfor %} + +
LabelURLActions
{{ link.label }}{{ link.url }} +
+ + +
+
+ {% else %} +

No links yet — so the sidebar panel is currently hidden.

+ {% endif %} +
+{% endblock %} diff --git a/templates/admin/media.html b/templates/admin/media.html new file mode 100644 index 0000000..ac48fca --- /dev/null +++ b/templates/admin/media.html @@ -0,0 +1,124 @@ +{% extends "admin/base.html" %} +{% block title %}Media · {{ site_title }}{% endblock %} + +{% block admin_content %} +

Media

+ +
+

Upload a photo

+
+ +
+ + +
+
+ + +
+ +
+
+ + {% if ungrouped %} +
+

Ungrouped photos ({{ ungrouped|length }})

+ {% for m in ungrouped %} + {{ _media_row(m, albums) }} + {% else %} +

No ungrouped photos.

+ {% endfor %} +
+ {% endif %} + + {% for aid, rows in grouped.items() %} +
+

{{ album_names.get(aid, 'Album') }} ({{ rows|length }})

+ {% for m in rows %} + {{ _media_row(m, albums) }} + {% else %} +

No photos.

+ {% endfor %} +
+ {% else %} +

No photos yet. Upload one from the Albums page or a post/page editor.

+ {% endfor %} + + +{% endblock %} + +{% macro _media_row(m, albums) %} +
+ +
+ {{ m.url }} + {{ m.created_at or '' }} +
+
+
+ + +
+ · +
+ + +
+
+
+{% endmacro %} diff --git a/templates/admin/page_edit.html b/templates/admin/page_edit.html new file mode 100644 index 0000000..03a3b35 --- /dev/null +++ b/templates/admin/page_edit.html @@ -0,0 +1,84 @@ +{% extends "admin/base.html" %} +{% block admin_content %} +
+

{% if page %}Edit page{% else %}New page{% endif %}

+ +
+ + +
+
+ + +
+
+ + + URL-friendly version of the title. Leave blank to auto-generate. +
+
+ +
+ + + {% if page %}Uncheck to hide this page from the navigation.{% else %}Live pages appear in the top nav.{% endif %} +
+ +
+ + + +
+
+ +

+ + Cancel +

+
+
+ + +{% endblock %} diff --git a/templates/admin/pages.html b/templates/admin/pages.html new file mode 100644 index 0000000..0ad1497 --- /dev/null +++ b/templates/admin/pages.html @@ -0,0 +1,36 @@ +{% extends "admin/base.html" %} +{% block admin_content %} +
+
+

Pages

+ New page +
+ + {% if pages is none %} +

No pages yet. Create your first one.

+ {% else %} + + + + + + {% for p in pages %} + + + + + + + + {% endfor %} + +
TitleSlugStatusOrder
{{ p.title }}/p/{{ p.slug }}{% if p.published %}Live{% else %}Draft{% endif %}{{ p.position }} + Edit +
+ + +
+
+ {% endif %} +
+{% endblock %} diff --git a/templates/admin/password.html b/templates/admin/password.html new file mode 100644 index 0000000..621f813 --- /dev/null +++ b/templates/admin/password.html @@ -0,0 +1,36 @@ +{% extends "admin/base.html" %} +{% block admin_content %} +
+

Change password

+

+ The current password is required. Changing it signs out every other + browser that is logged in; this session stays signed in. +

+
+ + +
+ + +
+ +
+ + +

At least {{ min_length }} characters; well-known defaults are rejected.

+
+ +
+ + +
+ + +
+
+{% endblock %} diff --git a/templates/admin/post_edit.html b/templates/admin/post_edit.html new file mode 100644 index 0000000..ee2f256 --- /dev/null +++ b/templates/admin/post_edit.html @@ -0,0 +1,179 @@ +{% extends "admin/base.html" %} +{% block admin_content %} +
+

{% if post %}Edit post{% else %}New post{% endif %}

+
+ +
+
+ + +
+
+ + + URL-friendly version of the title. Leave blank to auto-generate. +
+
+ +
+
+ + +
+
+ + + + {% for slug, name in categories %} + + {% endfor %} + +
+
+ +
+
+ + +
+
+ + + Comma separated. +
+
+ +
+ + + + +
+
+ +
+
+ + +
+
+ + + Shown on the post and used for ordering and archive months. Pick an earlier date to backdate it; leave blank for today. +
+
+ +

+ + {% if post %}Preview{% endif %} + Cancel +

+
+
+ + +{% endblock %} diff --git a/templates/admin/posts.html b/templates/admin/posts.html new file mode 100644 index 0000000..adc1b73 --- /dev/null +++ b/templates/admin/posts.html @@ -0,0 +1,42 @@ +{% extends "admin/base.html" %} +{% block admin_content %} +
+

Posts

+ + + + + + + + + + + + + + {% for p in posts %} + + + + + + + + + {% else %} + + {% endfor %} + +
TitleAuthorCategoryStatusCreatedActions
{{ p.title }}{{ p.author }}{{ p.category }}{% if p.status == 'published' %}Published{% else %}Draft{% endif %}{{ parse_date(p.created_at) }} + Edit +
+ + +
+
No posts. Create your first post to get started.
+
+{% endblock %} diff --git a/templates/admin/visit_history.html b/templates/admin/visit_history.html new file mode 100644 index 0000000..508d744 --- /dev/null +++ b/templates/admin/visit_history.html @@ -0,0 +1,38 @@ +{% extends "admin/base.html" %} +{% block admin_content %} +
+

Visitor history

+ + + + + + + + + + + + + +
Visitor ID{{ visitor.visitor_id }}
Browser{{ visitor.browser or "—" }}
Operating system{{ visitor.os or "—" }}
Device{{ visitor.device }}
Location{% if visitor.city or visitor.country %}{% if visitor.country_code %}{{ visitor.country_code|country_flag }} {% endif %}{{ visitor.city or "—" }}{% if visitor.region %}, {{ visitor.region }}{% endif %}{% if visitor.country %}, {{ visitor.country }}{% endif %}{% if visitor.latitude is not none %} ({{ "%.2f"|format(visitor.latitude) }}, {{ "%.2f"|format(visitor.longitude) }}){% endif %}{% else %}—{% endif %}
Source{{ visitor.source }}
Referrer domain{{ visitor.referrer_domain or "direct (no referrer)" }}
Raw referrer{{ visitor.referrer or "—" }}
First seen{{ parse_date(visitor.first_seen) }}
Last seen{{ parse_date(visitor.last_seen) }}
+
+ +
+

Pages visited ({{ visits|length }})

+ + + + {% for v in visits %} + + + + + + {% else %} + + {% endfor %} + +
PageTitleWhen
{{ v.page_path }}{{ v.title or "(untitled)" }}{{ parse_date(v.timestamp) }}
This visitor has not visited any page yet.
+
+{% endblock %} diff --git a/templates/admin/visitors.html b/templates/admin/visitors.html new file mode 100644 index 0000000..7b47864 --- /dev/null +++ b/templates/admin/visitors.html @@ -0,0 +1,86 @@ +{% extends "admin/base.html" %} +{% block admin_content %} +
+

Visitors

+

Every tracked visitor. Click a row to see the pages they visited.

+
+ + + + {% if selected_country or selected_city %} + Clear filters + {% endif %} + {{ rows|length }} shown +
+ + + + + + + + + + + + + + + + + + {% for r in rows %} + + + + + + + + + + + + + {% else %} + + {% endfor %} + +
Visitor IDBrowserOSDeviceLocationSourceReferrer domainFirst seenLast seenVisits
{{ r.visitor_id }}{{ r.browser or "—" }}{{ r.os or "—" }}{{ r.device }}{% if r.city or r.country %}{% if r.country_code %}{{ r.country_code|country_flag }} {% endif %}{{ r.city or "—" }}{% if r.country %}, {{ r.country }}{% endif %}{% else %}—{% endif %}{{ r.source }}{{ r.referrer_domain or "—" }}{{ parse_date(r.first_seen) }}{{ parse_date(r.last_seen) }}{{ r.visits }}
No visitors match these filters.
+
+ + +{% endblock %} diff --git a/templates/base.html b/templates/base.html new file mode 100644 index 0000000..27a77fb --- /dev/null +++ b/templates/base.html @@ -0,0 +1,76 @@ + + + + + + {% block title %}{{ site_title }}{% endblock %} + + + + {% set page_arg = request.args.get('page') %} + + + + + + + + {% set social_image = og_image if og_image else header_image %} + {% if social_image %} + + {% endif %} + + + + {% if social_image %} + + {% endif %} + + + + {% block head %}{% endblock %} + + + + +
+ {% block content %}{% endblock %} +
+ +
+ +
+ + + + + + + + + diff --git a/templates/comments.html b/templates/comments.html new file mode 100644 index 0000000..b6fc7b7 --- /dev/null +++ b/templates/comments.html @@ -0,0 +1,59 @@ +
+

Comments

+ + {% if not comments_enabled %} +

Comments are closed.

+ {% else %} + {% if comment_count > 0 %} +

{{ comment_count }} comment{{ 's' if comment_count != 1 }} so far.

+ {% endif %} + + {% if comments %} +
+ {% for c in comments %} +
+
+ {{ c.author }} + +
+
{{ render_markdown(c.body) }}
+ {% if logged_in and c.author == session.get('username') %} +
+ + +
+ {% endif %} +
+ {% endfor %} +
+ {% else %} +

No comments yet — be the first!

+ {% endif %} + +
+ + {# Bot traps (hidden, no visual change): a field humans never fill in and + the time this page was rendered. #} + + +
+
+ + +
+
+ + +
+
+
+ + +
+ +
+ {% endif %} +
diff --git a/templates/home.html b/templates/home.html new file mode 100644 index 0000000..5f38bd7 --- /dev/null +++ b/templates/home.html @@ -0,0 +1,135 @@ +{% extends "base.html" %} +{% block title %}{% if page == 'tag' %}Tag: {{ tag_name }} · {{ site_title }}{% elif page == 'category' %}Category: {{ category_name }} · {{ site_title }}{% elif page == 'archive' %}{{ parse_date(month ~ '-01') }} · {{ site_title }}{% else %}{{ site_title }}{% endif %}{% endblock %} +{% block meta_description %}{% if page == 'tag' %}Posts tagged “{{ tag_name }}” on {{ site_title }}.{% elif page == 'category' %}Posts in {{ category_name }} on {{ site_title }}.{% else %}{{ meta_description or site_tagline }}{% endif %}{% endblock %} + +{% block head %} + {% if pagination and pagination.has_prev %}{% endif %} + {% if pagination and pagination.has_next %}{% endif %} + {% if page == 'tag' %} + + {% endif %} +{% endblock %} + +{% block content %} + {% if page == "category" %} +

Category: {{ category_name }}

+ {% elif page == "tag" %} +

Tag: {{ tag_name }}

+ {% elif page == "archive" %} +

{{ parse_date(month ~ '-01') }}

+ {% else %} +

Latest Posts

+ {% endif %} + +
+
+ {% if posts %} +
+ {% for p in posts %} +
+

+ {{ p.title }} +

+ + {% if p.excerpt %} +
+ {{ p.excerpt|replace("\n", "\n\n")|safe }} +
+ {% endif %} + +
+ {% endfor %} +
+ {% include "_pagination.html" %} + {% else %} +

No posts yet. Sign in to the admin area to add one.

+ {% endif %} +
+ + +
+{% endblock %} diff --git a/templates/login.html b/templates/login.html new file mode 100644 index 0000000..dd11902 --- /dev/null +++ b/templates/login.html @@ -0,0 +1,26 @@ +{% extends "base.html" %} +{% block title %}Sign in · {{ site_title }}{% endblock %} + +{% block content %} +
+
+

Admin

+ {% with messages = get_flashed_messages(with_categories=true) %} + {% for category, message in messages %} +
{{ message }}
+ {% endfor %} + {% endwith %} +
+ +
+ + +
+ +
+

+ ← Back to site +

+
+
+{% endblock %} diff --git a/templates/page.html b/templates/page.html new file mode 100644 index 0000000..baa15bf --- /dev/null +++ b/templates/page.html @@ -0,0 +1,25 @@ +{% extends "base.html" %} +{% block title %}{{ page.title }} · {{ site_title }}{% endblock %} +{% block og_title %}{{ page.title }}{% endblock %} +{% block og_description %}{{ page.title }} · {{ site_title }}{% endblock %} +{% block twitter_title %}{{ page.title }}{% endblock %} +{% block twitter_description %}{{ page.title }} · {{ site_title }}{% endblock %} + +{% block content %} + + +
+

{{ page.title }}

+
+ {{ render_markdown(page.content) }} +
+
+ + {# comments.html renders its own
+ "Comments" heading; wrapping it + here duplicated both. #} + {% include "comments.html" %} +{% endblock %} diff --git a/templates/photos.html b/templates/photos.html new file mode 100644 index 0000000..1512f1e --- /dev/null +++ b/templates/photos.html @@ -0,0 +1,44 @@ +{% extends "base.html" %} +{% block title %}{{ album.name }} · {{ site_title }}{% endblock %} + +{% block content %} + + +
+

{{ album.name }}

+ {% if album.description %} +

{{ album.description }}

+ {% endif %} + + {% if media %} + + + + + + + + {% else %} +

This album has no photos yet.

+ {% endif %} +
+{% endblock %} diff --git a/templates/post.html b/templates/post.html new file mode 100644 index 0000000..66c27de --- /dev/null +++ b/templates/post.html @@ -0,0 +1,79 @@ +{% extends "base.html" %} +{% block title %}{{ post.title }} · {{ site_title }}{% endblock %} +{% block meta_description %}{{ post.excerpt or post.body|striptags|truncate(160, True, '…') }}{% endblock %} +{% block robots %}{% if preview %}noindex, nofollow{% else %}index, follow{% endif %}{% endblock %} +{% block og_type %}article{% endblock %} +{% block og_title %}{{ post.title }}{% endblock %} +{% block og_description %}{{ post.excerpt or post.body|striptags|truncate(160, True, '…') }}{% endblock %} +{% block twitter_title %}{{ post.title }}{% endblock %} +{% block twitter_description %}{{ post.excerpt or post.body|striptags|truncate(160, True, '…') }}{% endblock %} + +{% block head %} + {# Structured data for search engines (head only — no visual change). #} + +{% endblock %} + +{% block content %} + + + {% if preview %} +
+ Draft preview. This post is not public yet. + Back to the editor +
+ {% endif %} + +
+

{{ post.title }}

+ +
+ {{ render_markdown(post.body) }} +
+
+ Published on {{ parse_date(post.created_at) }} in {{ post.category }}. +
+
+ + {# comments.html renders its own
+ "Comments" heading; wrapping it + here duplicated both. #} + {% if related %} + + {% endif %} + + {% if not preview %}{% include "comments.html" %}{% endif %} +{% endblock %} diff --git a/templates/public/albums.html b/templates/public/albums.html new file mode 100644 index 0000000..d4608bf --- /dev/null +++ b/templates/public/albums.html @@ -0,0 +1,36 @@ +{% extends "base.html" %} +{% block title %}Photos · {{ site_title }}{% endblock %} + +{% block content %} + + +
+

Photos

+ + {% if albums %} + + {% else %} +

No albums yet. Create one from the admin panel.

+ {% endif %} +
+{% endblock %} diff --git a/templates/search.html b/templates/search.html new file mode 100644 index 0000000..60c457d --- /dev/null +++ b/templates/search.html @@ -0,0 +1,37 @@ +{% extends "base.html" %} +{% block title %}Search · {{ site_title }}{% endblock %} +{% block meta_description %}Search {{ site_title }}.{% endblock %} +{% block robots %}noindex, follow{% endblock %} + +{% block content %} +

Search

+
+ + +
+ + {% if query %} +

Results for “{{ query }}”

+
+ {% for p in posts %} +
+

{{ p.title }}

+ + {% if p.excerpt %}
{{ p.excerpt|replace("\n", "\n\n")|safe }}
{% endif %} + +
+ {% else %} +

No posts matched “{{ query }}”.

+ {% endfor %} +
+ {% include "_pagination.html" %} + {% endif %} +{% endblock %} diff --git a/templates/tags.html b/templates/tags.html new file mode 100644 index 0000000..ab0dbe2 --- /dev/null +++ b/templates/tags.html @@ -0,0 +1,23 @@ +{% extends "base.html" %} +{% block title %}Tags · {{ site_title }}{% endblock %} +{% block meta_description %}Browse every topic on {{ site_title }}.{% endblock %} + +{% block content %} + + +

Tags

+ + {% if tag_index %} +
+ {% for t in tag_index %} + {{ t.name }} {{ t.count }} + {% endfor %} +
+ {% else %} +

No tags yet. Add tags to a post from the editor.

+ {% endif %} +{% endblock %}