Files
simpleblog/blog/db.py
T
2026-11-14 17:05:01 +00:00

509 lines
20 KiB
Python

"""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()