Initial commit: simpleblog
This commit is contained in:
@@ -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()
|
||||
+1514
File diff suppressed because it is too large
Load Diff
@@ -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")
|
||||
+388
@@ -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
|
||||
]
|
||||
+508
@@ -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 <strong>the author</strong> 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()
|
||||
@@ -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 ""
|
||||
+290
@@ -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())
|
||||
@@ -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)
|
||||
+169
@@ -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)
|
||||
+871
@@ -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'<img[^>]+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 = ['<?xml version="1.0" encoding="UTF-8"?>',
|
||||
'<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">']
|
||||
for path, lastmod in rows:
|
||||
out.append(" <url>")
|
||||
loc = request.url_root if path == "" else (base + path)
|
||||
out.append(" <loc>%s</loc>" % xml_escape(loc))
|
||||
# Real modification dates: this used to always be "today", telling
|
||||
# crawlers every page changed on every crawl.
|
||||
if lastmod:
|
||||
out.append(" <lastmod>%s</lastmod>" % str(lastmod)[:10])
|
||||
out.append(" </url>")
|
||||
out.append("</urlset>")
|
||||
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 <img> 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/<month>")
|
||||
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/<slug>")
|
||||
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/<int:pid>/<token>")
|
||||
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/<slug>")
|
||||
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/<slug>")
|
||||
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/<slug>/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/<slug>")
|
||||
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/<slug>")
|
||||
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/<slug>/comment", methods=["POST"])
|
||||
def post_comment(slug):
|
||||
return _submit_comment("post", slug)
|
||||
|
||||
|
||||
@bp.route("/p/<slug>/comment", methods=["POST"])
|
||||
def page_comment(slug):
|
||||
return _submit_comment("page", slug)
|
||||
|
||||
|
||||
@bp.route("/comment/<int:cid>/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 = [
|
||||
'<?xml version="1.0" encoding="utf-8"?>',
|
||||
'<feed xmlns="http://www.w3.org/2005/Atom">',
|
||||
" <title>%s</title>" % xml_escape(title),
|
||||
' <link rel="alternate" type="text/html" href="%s"/>' % xml_escape(base + "/"),
|
||||
' <link rel="self" type="application/atom+xml" href="%s"/>' % xml_escape(self_url),
|
||||
" <id>%s</id>" % xml_escape(self_url),
|
||||
" <updated>%s</updated>" % updated,
|
||||
" <generator>Simple Blog</generator>",
|
||||
" <author><name>%s</name></author>" % xml_escape(_site_title()),
|
||||
]
|
||||
for p in posts:
|
||||
url = base + url_for("public.post", slug=p["slug"])
|
||||
out += [
|
||||
" <entry>",
|
||||
" <title>%s</title>" % xml_escape(p["title"] or ""),
|
||||
' <link rel="alternate" type="text/html" href="%s"/>' % xml_escape(url),
|
||||
" <id>%s</id>" % xml_escape(url),
|
||||
" <published>%s</published>" % _rfc3339(p["created_at"]),
|
||||
" <updated>%s</updated>" % _rfc3339(p["updated_at"] or p["created_at"]),
|
||||
" <author><name>%s</name></author>" % xml_escape(p["author"] or "editor"),
|
||||
]
|
||||
if p["category"]:
|
||||
out.append(' <category term="%s"/>' % xml_escape(p["category"]))
|
||||
out += [
|
||||
' <content type="html">%s</content>'
|
||||
% xml_escape(str(render_markdown(p["body"]))),
|
||||
" </entry>",
|
||||
]
|
||||
out.append("</feed>")
|
||||
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/<slug>/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",
|
||||
}
|
||||
@@ -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 <item> elements; categories and tags are
|
||||
expressed as <category domain="category"> / domain="post_tag">; comments appear
|
||||
as <wfw:comment> 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 <pubDate>/<date_time_gmt> 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
|
||||
# <item>), so build everything into one list in document order.
|
||||
out = []
|
||||
out.append('<?xml version="1.0" encoding="UTF-8"?>')
|
||||
out.append(
|
||||
'<rss version="2.0"'
|
||||
+ "".join(f' xmlns:{p}="{u}"' for p, u in NS)
|
||||
+ '>'
|
||||
)
|
||||
out.append(" <channel>")
|
||||
out.append(f" <title>{_xml_escape(site_title)}</title>")
|
||||
out.append(f" <link>{_xml_escape(site_url.rstrip('/'))}</link>")
|
||||
out.append(f" <description>{_xml_escape(site_description)}</description>")
|
||||
out.append(' <language>en_US</language>')
|
||||
out.append(' <docs>http://blogs.law.harvard.edu/tech/rss</docs>')
|
||||
out.append(' <generator>Simple Blog WXR Export</generator>')
|
||||
|
||||
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(" <item>")
|
||||
wxr_status = "publish" if p["status"] == "published" else "draft"
|
||||
out.append(f' <wp:status>{_xml_escape(wxr_status)}</wp:status>')
|
||||
out.append(f' <wp:post_name>{_xml_escape(p["slug"])}</wp:post_name>')
|
||||
out.append(f" <title>{_xml_escape(p['title'])}</title>")
|
||||
out.append(f" <link>{_xml_escape(url)}</link>")
|
||||
out.append(f' <guid isPermaLink="true">{_xml_escape(url)}</guid>')
|
||||
out.append(
|
||||
f' <dc:creator>{_xml_escape(p["author"] or "editor")}</dc:creator>'
|
||||
)
|
||||
out.append(f" <pubDate>{_rfc822(created)}</pubDate>")
|
||||
out.append(f" <dc:date>{_rfc822(created)}</dc:date>")
|
||||
|
||||
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' <category domain="category">{_xml_escape(slug_)}</category>'
|
||||
)
|
||||
for tag in tags:
|
||||
out.append(
|
||||
f' <category domain="post_tag">{_xml_escape(tag)}</category>'
|
||||
)
|
||||
|
||||
# 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(' <wfw:comment ' + ' '.join(attrs) + '>')
|
||||
out.append(f" {_xml_escape(c['body'])}")
|
||||
out.append(" </wfw:comment>")
|
||||
|
||||
out.append(f' <wfw:commentRss>{_xml_escape(url + "#comments")}</wfw:commentRss>')
|
||||
out.append(f" <slash:comments>{len(comments)}</slash:comments>")
|
||||
out.append(f" <content:encoded>{_xml_escape(p['body'])}</content:encoded>")
|
||||
out.append(" </item>")
|
||||
|
||||
out.append(" </channel>")
|
||||
out.append("</rss>")
|
||||
return "\n".join(out)
|
||||
@@ -0,0 +1,193 @@
|
||||
"""Parse a WXR (WordPress export) feed and load it into this blog.
|
||||
|
||||
Reads posts (<item>), categories/tags (<category domain="…">), and comments
|
||||
(<wfw:comment>) 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 <channel> 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 <wfw:comment> is nested inside this post's <item>, 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
|
||||
Reference in New Issue
Block a user