Initial commit: simpleblog

This commit is contained in:
2026-11-14 17:05:01 +00:00
commit 31c4580da4
91 changed files with 53494 additions and 0 deletions
+11
View File
@@ -0,0 +1,11 @@
__pycache__/
*.pyc
.venv/
venv/
.git/
.gitignore
.env
data/
build/
dist/
*.log
+18
View File
@@ -0,0 +1,18 @@
# Secrets / local env
.env
.env.*
# Python
__pycache__/
*.py[cod]
.venv/
# Local agent config (never push)
.pi/
# Throwaway dev / verification scripts
appearance_test.py
proxy_test.py
verify_gallery.py
verify_upload.py
pw_cmd.txt
+35
View File
@@ -0,0 +1,35 @@
# Simple Blog — single-container image
# Built from this directory. No external services required.
FROM python:3.11-slim
# Keep Python warnings out of stdout/stderr
ENV PYTHONUNBUFFERED=1 \
PYTHONDONTWRITEBYTECODE=1 \
PIP_NO_CACHE_DIR=1
WORKDIR /app
# Install dependencies first (better layer caching)
COPY requirements.txt .
RUN pip install --upgrade pip && pip install -r requirements.txt
# Copy the application
COPY blog/ ./blog/
COPY templates/ ./templates/
COPY static/ ./static/
COPY run.py ./
# Create the data directory for the SQLite database
RUN mkdir -p /app/data
# The app listens on all interfaces on port 5000
EXPOSE 5000
# Default environment (override with -e or docker-compose). No password or
# session secret is baked in: without them the app generates strong ones on
# first boot (the temporary password is printed once to the logs).
ENV PORT=5000 \
BLOG_DATA_DIR=/app/data
# Run the application
CMD ["python", "run.py"]
View File
+397
View File
@@ -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
View File
File diff suppressed because it is too large Load Diff
+518
View File
@@ -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
View File
@@ -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
View File
@@ -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()
+62
View File
@@ -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
View File
@@ -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())
+71
View File
@@ -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
View File
@@ -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
View File
@@ -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",
}
+168
View File
@@ -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("&", "&amp;")
.replace("<", "&lt;")
.replace(">", "&gt;"))
def _attr_escape(value):
"""Escape a value for use inside an attribute."""
if value is None:
return ""
return (_INVALID_XML.sub("", str(value))
.replace("&", "&amp;")
.replace("<", "&lt;")
.replace(">", "&gt;")
.replace('"', "&quot;")
.replace("'", "&apos;"))
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)
+193
View File
@@ -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
+66
View File
@@ -0,0 +1,66 @@
services:
blog:
build: .
image: testblog:latest
container_name: simple-blog
ports:
- "8000:5000"
environment:
# BLOG_ADMIN_PASSWORD is only a first-run bootstrap value (the password is
# then stored hashed in the database). Leave it empty to have a random one
# generated and printed in the logs. Reset later with:
# docker compose exec blog python -m blog.manage set-password
- BLOG_ADMIN_PASSWORD=${BLOG_ADMIN_PASSWORD:-}
# Long random signing key. If empty, one is generated and kept in the DB.
- BLOG_SESSION_SECRET=${BLOG_SESSION_SECRET:-}
# Set to 1 when served over HTTPS (including behind a TLS proxy).
- BLOG_SECURE_COOKIES=${BLOG_SECURE_COOKIES:-0}
- BLOG_SESSION_HOURS=${BLOG_SESSION_HOURS:-12}
- BLOG_SESSION_IDLE_MINUTES=${BLOG_SESSION_IDLE_MINUTES:-120}
- BLOG_URL=${BLOG_URL:-http://localhost:8000}
# Resolve visitor country/city for the analytics map (0 disables lookups).
- BLOG_GEOIP=${BLOG_GEOIP:-1}
# Map LAN/local visitors at this server's own region (0 to leave blank).
- BLOG_GEOIP_LOCAL=${BLOG_GEOIP_LOCAL:-1}
# Optional comment-notification email (any SMTP provider). Leaving these
# empty disables emails; in-app moderation alerts still work.
- BLOG_SMTP_HOST=${BLOG_SMTP_HOST:-}
- BLOG_SMTP_PORT=${BLOG_SMTP_PORT:-587}
- BLOG_SMTP_USER=${BLOG_SMTP_USER:-}
- BLOG_SMTP_PASSWORD=${BLOG_SMTP_PASSWORD:-}
- BLOG_SMTP_FROM=${BLOG_SMTP_FROM:-}
- BLOG_NOTIFY_EMAIL=${BLOG_NOTIFY_EMAIL:-}
- BLOG_SMTP_TLS=${BLOG_SMTP_TLS:-1}
# Optional push notifications via the self-hosted ntfy service below.
# Set BLOG_NTFY_TOPIC to a secret topic name to switch them on.
- BLOG_NTFY_URL=${BLOG_NTFY_URL:-http://ntfy:80}
- BLOG_NTFY_TOPIC=${BLOG_NTFY_TOPIC:-}
- BLOG_NTFY_TOKEN=${BLOG_NTFY_TOKEN:-}
- BLOG_NTFY_PRIORITY=${BLOG_NTFY_PRIORITY:-default}
- BLOG_DATA_DIR=/app/data
volumes:
# Persist posts/DB between container restarts
- blog-data:/app/data
# Persist uploaded media so images survive a rebuild (not just a restart)
- uploads-data:/app/static/uploads
restart: unless-stopped
# Self-hosted push notifications. It only talks to the blog container unless
# you publish its port, and its data is kept in a named volume.
ntfy:
image: binwiederhier/ntfy:v2.37.2
container_name: simple-blog-ntfy
command: serve
environment:
- TZ=${TZ:-UTC}
volumes:
- ntfy-cache:/var/cache/ntfy
- ./ntfy/server.yml:/etc/ntfy/server.yml:ro
ports:
- "8085:80"
restart: unless-stopped
volumes:
blog-data:
uploads-data:
ntfy-cache:
@@ -0,0 +1,73 @@
# Photo gallery (dedicated album pages) — design doc
**Date:** 2026-11-05
**Feature:** add photo galleries, grouped into albums, viewable on dedicated pages.
**Approach chosen:** A — dedicated album pages (flat albums, single image upload at a time).
## Intent / why
Give the site a way to display collections of photos as a grid with a click-to-enlarge
lightbox, organized into named groups ("albums"). Reuses the existing image-upload and
lightbox infrastructure rather than inventing new storage.
## Goals / non-goals
- **Goal:** upload photos, group them into albums, view an album as a grid on its own page,
enlarge via lightbox (Esc / arrows / backdrop).
- **Non-goal:** cropping/editing photos, geolocation, EXIF metadata, image resizing.
- **Anti-goal:** don't slow the site or bloat the schema; keep it in the existing Flask +
SQLite + plain-template style.
## Constraints (found while investigating)
- Images are stored as **files** in `static/uploads/` (on the named volume, so they persist),
validated by magic-byte signature at upload time; there is **no** database table for media
today. To group them we must track them in a table (filename + album).
- Pages render markdown via `render_markdown()`; lightbox reads images by `data-src`.
- Admin routes use the `@_login_required` decorator + `flash` + `jsonify`; admin templates
extend `admin/base.html` (nav-menu + sidebar, both driven by `active_page`).
- Werkzeug 3.1.9 / Flask 3.0.3; dependency-free.
## Approach (what you picked)
- **A — dedicated album pages** (`/photos/<slug>`), not embedded-in-page shortcodes.
- **Flat albums** (no hierarchy).
- **Single image upload at a time** (matches your current `/upload` handler).
Rejected: embedded markdown shortcodes (option B) — would force every page author to know a
new syntax; dedicated pages are cleaner URLs and share the existing lightbox. Nested albums
and batch upload were rejected as scope creep for v1.
## The parts (builder's plan)
**Data model** (two new tables, appended in `db.py` `init_db()`):
- `media_albums(id, name, slug UNIQUE, description, created_at)` — the groups.
- `media(id, filename, url, album_id FK→media_albums, position, created_at)` — individual photos.
**Admin (blog/admin.py):**
- Album CRUD: `/admin/albums` (list), `/admin/albums/new`, `/admin/albums/<slug>/edit`,
`/admin/albums/<slug>/delete`.
- Media management: `/admin/media` lists all photos grouped by album; ungrouped photos shown under "(none)". Per-photo actions:
- **Assign to album** — dropdown to move a photo into an album (add).
- **Remove from album** — uncouple (`album_id = NULL`, keep file). This is the only default delete; it never removes the file.
- Extend the existing `/upload` handler to create a `media` row and offer album selection in
the response (album = null allowed, so photos can be ungrouped).
- Add nav links (nav-menu + sidebar) for Albums / Media, driven by `active_page`.
**Public (blog/public.py):**
- Route `/photos/<slug>` → render the album's media grid. `_album_by_slug(slug)` helper;
unknown slug → 404.
**Templates:**
- New `templates/photos.html` — responsive grid, each `<img data-src=...>` so the existing
`lightbox.js` handles enlarge for free. Empty album / no-media states handled.
- New `templates/admin/albums.html`, `templates/admin/media.html`, and an album edit form.
- Reuse `admin/base.html` (no new shell).
## Decisions left to builder (my calls, unless you object)
- Album slug auto-generated from name; editable.
- `position` integer for manual ordering within an album; reordering via a simple up/down or
drag-free renumber.
- **Delete album → UNCUPLE, not delete.** `UPDATE media SET album_id = NULL WHERE album_id = ?`. Photos stay in `/uploads` and become ungrouped; nothing is deleted.
- Gallery layout: responsive CSS grid, masonry-ish via `aspect-ratio` to avoid layout shift.
## Left to builder
Implement above, then verify with a test client: upload → assign album → view `/photos/<slug>`
grid → lightbox open/close; **delete album uncouples photos (album_id=NULL, files kept)**; assign/
remove-from-album re-groups correctly; unknown album 404s.
+22
View File
@@ -0,0 +1,22 @@
# Self-hosted ntfy configuration for this blog.
# Docs: https://docs.ntfy.sh/config/
#
# Uncomment and set base-url to the address your phone uses when it must be
# absolute (e.g. "http://192.168.1.20:8085"). When empty, ntfy derives it from
# each request's Host header, which is fine on a LAN.
# base-url: "http://localhost:8085"
listen-http: ":80"
# Keep notifications on disk so a phone that was offline can still fetch them.
cache-file: "/var/cache/ntfy/cache.db"
cache-duration: "48h"
# This instance is meant for your own devices. Anyone who can reach port 8085
# and knows the topic can publish or read messages, so the topic is a secret.
# To lock the server down instead, set this to "deny-all" and create a token:
# docker compose exec ntfy ntfy user add --role=admin admin
# docker compose exec ntfy ntfy token add --label=blog admin
# then put the token in BLOG_NTFY_TOKEN and subscribe with the same account.
auth-default-access: "read-write"
enable-signup: false
+4
View File
@@ -0,0 +1,4 @@
Flask==3.0.3
markdown==3.7
bleach==6.1.0
Pillow==10.4.0
+17
View File
@@ -0,0 +1,17 @@
"""Entry point for the Simple Blog.
Usage:
python run.py
"""
import os
from blog import create_app
app = create_app()
if __name__ == "__main__":
# Read optional PORT from the environment (default 5000)
port = int(os.environ.get("PORT", "5000"))
app.run(host="0.0.0.0", port=port, debug=False)
+512
View File
@@ -0,0 +1,512 @@
/* ==========================================================================
Simple Blog — Admin panel styling
========================================================================== */
/* Log out is a POST form (so it needs a CSRF token), styled like a nav link. */
.logout-form {
display: inline;
margin: 0;
}
.link-button {
background: none;
border: 0;
padding: 0;
font: inherit;
color: inherit;
cursor: pointer;
text-align: left;
}
.link-button:hover,
.link-button:focus {
text-decoration: underline;
}
.admin-shell {
max-width: 1000px;
margin: 0 auto;
}
/* Condensed top bar: logo left, menu toggle right. No wasted vertical space. */
.admin-header {
display: flex;
align-items: center;
justify-content: space-between;
height: 56px;
padding: 0 var(--gutter);
background: var(--color-bg);
border-bottom: 1px solid var(--color-border);
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
}
.admin-header .header-inner {
display: flex;
align-items: center;
justify-content: space-between;
width: 100%;
}
.admin-header .site-logo a {
font-weight: 700;
font-size: 1.15rem;
color: var(--color-text);
text-decoration: none;
}
.admin-header .site-logo a:hover {
color: var(--color-accent);
}
.admin-menu-button {
display: inline-flex;
align-items: center;
gap: 6px;
height: 34px;
padding: 0 14px;
border: 1px solid var(--color-border);
border-radius: 6px;
background: var(--color-bg);
color: var(--color-text);
font-weight: 600;
font-size: 0.9rem;
cursor: pointer;
}
.admin-menu-button:hover {
border-color: var(--color-accent);
color: var(--color-accent);
}
/* Lightweight section tabs (pill style, no box). Replaces the old bordered tab row. */
.admin-subnav {
padding: 18px var(--gutter) 0;
margin-bottom: 28px;
}
.admin-subnav a {
display: inline-block;
padding: 7px 15px;
border-radius: 999px;
font-weight: 600;
font-size: 0.9rem;
color: var(--color-text);
background: transparent;
border: 1px solid transparent;
text-decoration: none;
}
.admin-subnav a:hover {
background: #eef4fa;
border-color: var(--color-border);
color: var(--color-accent);
}
.admin-subnav a.active {
background: var(--color-accent);
border-color: var(--color-accent);
color: #fff;
}
.admin-wrap {
padding: 28px var(--gutter) 60px;
}
.admin-panel {
background: var(--color-bg);
border: 1px solid var(--color-border);
border-radius: 8px;
padding: 28px 30px;
margin-bottom: 24px;
}
.admin-panel h1,
.admin-panel h2 {
margin-top: 0;
}
.admin-actions {
display: flex;
flex-wrap: wrap;
gap: 14px;
margin-bottom: 28px;
}
.admin-actions a {
display: inline-flex;
align-items: center;
gap: 8px;
padding: 12px 20px;
border-radius: 6px;
font-weight: 600;
border: 1px solid var(--color-border);
background: var(--color-bg);
color: var(--color-text);
}
.admin-actions a.primary {
background: var(--color-accent);
border-color: var(--color-accent);
color: #fff;
}
.admin-actions a.primary:hover {
background: var(--color-link-hover);
color: #fff;
}
.admin-actions a:hover {
border-color: var(--color-accent);
color: var(--color-link);
}
table.admin-table {
width: 100%;
border-collapse: collapse;
font-size: 0.92rem;
}
table.admin-table th,
table.admin-table td {
text-align: left;
padding: 12px 14px;
border-bottom: 1px solid var(--color-border);
vertical-align: middle;
}
table.admin-table th {
font-size: 0.82rem;
text-transform: uppercase;
letter-spacing: 0.04em;
color: var(--color-muted);
border-bottom: 2px solid var(--color-border);
}
table.admin-table tr:hover td {
background: #fafafa;
}
.table-actions {
white-space: nowrap;
}
.btn {
display: inline-block;
padding: 8px 16px;
border-radius: 5px;
font-weight: 600;
font-size: 0.9rem;
cursor: pointer;
border: 1px solid var(--color-border);
background: var(--color-bg);
color: var(--color-text);
text-decoration: none;
}
.btn:hover {
border-color: var(--color-accent);
color: var(--color-link);
}
.btn-primary {
background: var(--color-accent);
border-color: var(--color-accent);
color: #fff;
}
.btn-primary:hover {
background: var(--color-link-hover);
border-color: var(--color-link-hover);
color: #fff;
}
.btn-danger {
color: #b71c1c;
border-color: #f5c6cb;
background: #fdecea;
}
.btn-danger:hover {
background: #b71c1c;
border-color: #b71c1c;
color: #fff;
}
.form-group {
margin-bottom: 18px;
}
.form-group label {
display: block;
font-weight: 600;
margin-bottom: 6px;
font-size: 0.95rem;
}
.form-group input,
.form-group textarea,
.form-group select {
width: 100%;
padding: 11px 12px;
border: 1px solid var(--color-border);
border-radius: 5px;
font-family: var(--font-stack);
font-size: 0.98rem;
background: #fff;
}
.form-group input:focus,
.form-group textarea:focus,
.form-group select:focus {
outline: none;
border-color: var(--color-accent);
}
.form-group textarea {
min-height: 320px;
resize: vertical;
font-family: "SFMono-Regular", Consolas, "Liberation Mono", Menlo, monospace;
line-height: 1.5;
}
.form-row {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 20px;
}
@media (max-width: 620px) {
.form-row {
grid-template-columns: 1fr;
}
}
.field-hint {
display: block;
margin-top: 6px;
font-size: 0.82rem;
color: var(--color-muted);
}
.admin-stat {
text-align: center;
}
.admin-stat .num {
display: block;
font-size: 2.4rem;
font-weight: 700;
color: var(--color-accent);
}
.admin-stat .label {
font-size: 0.85rem;
color: var(--color-muted);
text-transform: uppercase;
letter-spacing: 0.05em;
}
.category-row {
display: flex;
align-items: center;
justify-content: space-between;
padding: 12px 0;
border-bottom: 1px solid var(--color-border);
}
.category-row:last-child {
border-bottom: 0;
}
/* --- Analytics: locations, map + trend chart ---------------------------- */
.admin-stat-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
gap: 20px;
margin: 24px 0 4px;
}
.visitor-map {
height: 440px;
width: 100%;
border: 1px solid var(--color-border);
border-radius: 6px;
background: #eef1f5;
z-index: 0;
}
.chart-wrap {
position: relative;
width: 100%;
}
.chart-wrap canvas {
display: block;
width: 100%;
height: 280px;
}
.chart-tooltip {
position: absolute;
padding: 6px 10px;
border-radius: 5px;
background: rgba(17, 24, 39, 0.92);
color: #fff;
font-size: 0.78rem;
line-height: 1.4;
pointer-events: none;
white-space: nowrap;
z-index: 2;
}
.chart-legend {
display: flex;
flex-wrap: wrap;
gap: 8px 18px;
margin-top: 12px;
font-size: 0.85rem;
color: var(--color-muted);
}
.chart-legend .swatch {
display: inline-block;
width: 10px;
height: 10px;
margin-right: 6px;
border-radius: 2px;
vertical-align: baseline;
}
.location-flag {
font-size: 1.1em;
line-height: 1;
}
.admin-split {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 30px;
}
.admin-split h2 {
margin-top: 0;
}
@media (max-width: 860px) {
.admin-split {
grid-template-columns: 1fr;
}
.visitor-map {
height: 320px;
}
}
.filter-form {
display: flex;
flex-wrap: wrap;
align-items: flex-end;
gap: 14px 18px;
margin: 0 0 22px;
}
.filter-form label {
display: flex;
flex-direction: column;
gap: 6px;
font-size: 0.8rem;
font-weight: 600;
text-transform: uppercase;
letter-spacing: 0.04em;
color: var(--color-muted);
}
.filter-form select {
min-width: 190px;
padding: 8px 10px;
border: 1px solid var(--color-border);
border-radius: 5px;
background: #fff;
color: var(--color-text);
font-family: var(--font-stack);
font-size: 0.92rem;
}
.location-chip {
display: inline-block;
margin: 2px 6px 2px 0;
padding: 3px 9px;
border: 1px solid var(--color-border);
border-radius: 999px;
background: #f6f8fa;
font-size: 0.82rem;
white-space: nowrap;
}
.location-chip strong {
margin-left: 3px;
}
.add-category {
margin-top: 16px;
display: flex;
gap: 10px;
}
.add-category input {
flex: 1;
padding: 10px 12px;
border: 1px solid var(--color-border);
border-radius: 5px;
}
.empty-state {
text-align: center;
color: var(--color-muted);
padding: 40px 20px;
}
/* Flash messages (rendered by admin/base.html) */
.notice { padding: 10px 14px; border: 1px solid var(--color-border); border-radius: 6px; margin: 10px 0; background: var(--color-bg); color: var(--color-text); }
.notice-success { background: #e7f7ee; border-color: #b7e0c3; color: #1f5c34; }
.notice-error { background: #fdecea; border-color: #f5c2c2; color: #7d2117; }
.notice-info { background: #e7f0fb; border-color: #b9d4f4; color: #12396b; }
/* ---------------------------------------------------------------------------
Comments moderation
------------------------------------------------------------------------- */
.comment-stats {
display:flex; flex-wrap: wrap; gap: 10px 22px; margin: 16px 0 24px;
}
.comment-stats .term {
font-size: 0.95rem;
padding: 4px 12px;
border: 1px solid var(--color-border);
border-radius: 999px;
background: var(--color-bg);
color: var(--color-text);
}
.comment-stats .term.warn {
background: #fff4e5; border-color: #f2d399; color: #7a5210;
}
.comment-mod-list .comment-block {
border-left-width: 0;
}
.comment-mod-list .comment-block .comment-meta {
font-size: 0.85rem;
}
.comment-mod-list .comment-block .comment-actions {
margin-top: 14px;
display:flex; flex-wrap: wrap; gap: 8px;
}
.comment-mod-list .comment-block .comment-actions form { margin: 0; }
/* Mobile: collapse the section tab row behind the menu toggle */
@media (max-width: 640px) {
.admin-subnav {
display: none;
}
}
/* Moderation badge in the admin navigation */
.nav-badge { display: inline-block; min-width: 18px; padding: 0 5px; margin-left: 6px; border-radius: 9px; background: #d63638; color: #fff; font-size: 11px; line-height: 18px; text-align: center; vertical-align: middle; }
+14
View File
@@ -0,0 +1,14 @@
:root {
--color-accent:#91b1ba;
--color-link:#91b1ba;
--color-link-hover:#7f9fa8;
--color-text:#b79f9f;
--color-muted:rgba(183,159,159,0.55);
--color-border:rgba(183,159,159,0.92);
--color-bg:#ffffff;
--color-sidebar-bg:rgba(183,159,159,0.97);
--font-stack:Inter, Roboto, sans-serif;
--border-radius:16px;
}
.posts-grid { grid-template-columns: repeat(1, 1fr); }
+877
View File
@@ -0,0 +1,877 @@
/* ==========================================================================
Simple Blog — GeneratePress-inspired styling (shared / front-end)
Clean, minimal, card-based layout with a sidebar.
========================================================================== */
:root {
--border-radius: 6px;
--color-text: #1e1e1e;
--color-muted: #666;
--color-border: #e5e5e5;
--color-bg: #ffffff;
--color-link: #00a0d1;
--color-link-hover: #007a99;
--color-sidebar-bg: #f7f7f7;
--color-accent: #00a0d1;
--font-stack: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen,
Ubuntu, Cantarell, "Helvetica Neue", Arial, sans-serif;
--max-width: 1140px;
--gutter: 16px;
}
*,
*::before,
*::after {
box-sizing: border-box;
}
html {
-webkit-text-size-adjust: 100%;
text-size-adjust: 100%;
}
body {
margin: 0;
padding: 0;
font-family: var(--font-stack);
color: var(--color-text);
background-color: var(--color-bg);
line-height: 1.7;
font-size: 16px;
}
a {
color: var(--color-link);
text-decoration: none;
transition: color 0.2s ease;
}
a:hover {
color: var(--color-link-hover);
}
img {
max-width: 100%;
height: auto;
}
/* ---------------------------------------------------------------------------
Header
------------------------------------------------------------------------- */
.site-header {
border-bottom: 3px solid var(--color-accent);
background-color: var(--color-bg);
}
.header-inner {
max-width: var(--max-width);
margin: 0 auto;
padding: 18px var(--gutter);
display: flex;
align-items: center;
justify-content: space-between;
flex-wrap: wrap;
gap: 12px;
}
.site-logo a {
color: var(--color-text);
font-weight: 700;
font-size: 1.35rem;
letter-spacing: -0.02em;
text-decoration: none;
}
.site-logo img {
max-height: 44px;
width: auto;
}
/* ---------------------------------------------------------------------------
Hero header (shown only when an uploaded banner image is present)
The banner spans the whole header width, sitting behind the logo + nav.
------------------------------------------------------------------------- */
.header-inner.has-banner {
position: relative;
width: 100%;
max-width: none;
margin: 0;
padding: 0;
min-height: 260px;
}
.header-inner.has-banner .site-banner-img {
position: absolute;
inset: 0;
width: 100%;
height: 100%;
object-fit: cover;
border-radius: 0;
z-index: 0;
}
.header-inner.has-banner .site-logo {
position: relative;
z-index: 1;
margin-left: 26px;
color: #fff;
text-shadow: 0 2px 8px rgba(0, 0, 0, 0.55);
}
.header-inner.has-banner .hero-tagline {
display: block;
font-size: 1rem;
font-style: italic;
opacity: 0.92;
text-shadow: 0 1px 4px rgba(0, 0, 0, 0.55);
}
.header-inner.has-banner .site-logo a {
color: #fff;
text-decoration: none;
}
.header-inner.has-banner .main-nav {
position: absolute;
left: 50%;
transform: translateX(-50%);
bottom: 0;
z-index: 1;
}
.header-inner.has-banner .main-nav button {
color: #fff;
text-shadow: 0 1px 4px rgba(0, 0, 0, 0.55);
}
.header-inner.has-banner .nav-menu {
background: rgba(0, 0, 0, 0.35);
border-color: rgba(255, 255, 255, 0.35);
}
@media (max-width: 620px) {
/* The nav is pinned to the bottom of the banner, so the banner must stay tall
enough for the logo (title + tagline) and the nav to coexist without the nav
sliding up over the title/tagline. */
.header-inner.has-banner { min-height: 260px; }
.header-inner.has-banner .site-logo { margin-left: 16px; }
}
/* ---------------------------------------------------------------------------
Top navigation (inline links — the old dropdown menu has been removed)
------------------------------------------------------------------------- */
.main-nav {
/* Width is set by the parent flex container (space-between) on non-banner
pages; overridden to absolute-center at the bottom only when a banner is shown. */
}
.nav-links {
display: flex;
align-items: center;
flex-wrap: wrap;
margin: 0;
padding: 0;
list-style: none;
gap: 6px 20px;
}
.nav-item a {
color: var(--color-text);
text-decoration: none;
font-weight: 600;
font-size: 0.98rem;
padding: 6px 4px;
border-radius: 4px;
transition: color 0.15s ease, background-color 0.15s ease;
}
.nav-item a:hover {
color: var(--color-link);
background-color: var(--color-sidebar-bg);
}
/* With a hero banner the nav sits centered at the bottom of the banner. */
.header-inner.has-banner .main-nav {
/* On mobile the logo (title + tagline) and the nav are both flex children of
.header-inner, which wraps. Together they exceed the screen width, so the nav
wraps onto a second line that slides up over the title/tagline. Pull the nav
out of the flex row and pin it to the bottom of the banner instead — the
banner is tall enough (260px) for both to coexist without overlap.
NOTE: transform must be reset — an older rule for this selector still set
translateX(-50%) and, at equal specificity, would otherwise persist. */
position: absolute;
left: 0;
right: 0;
bottom: 0;
z-index: 2;
transform: none;
display: flex;
justify-content: center;
padding: 14px 16px 18px; /* gap above the links so they never touch the tagline */
}
.header-inner.has-banner .nav-links {
width: min(92%, 260px);
}
/* Keep the links in a single centered row on banner pages. The mobile rule below
turns nav links into stacked blocks; here we restore them to inline-block so the
menu reads as one horizontal row instead of a vertical list. */
.header-inner.has-banner .nav-item a {
display: inline-block;
}
.header-inner.has-banner .nav-item a {
color: #fff;
text-shadow: 0 1px 3px rgba(0, 0, 0, 0.45);
}
.header-inner.has-banner .nav-item a:hover {
background-color: rgba(255, 255, 255, 0.2);
}
@media (max-width: 620px) {
.nav-links {
gap: 0;
}
.nav-item a {
display: block;
padding: 10px 14px;
}
}
/* ---------------------------------------------------------------------------
Layout
------------------------------------------------------------------------- */
.site-main {
max-width: var(--max-width);
margin: 0 auto;
padding: 34px var(--gutter) 50px;
}
.content-area {
display: grid;
grid-template-columns: 2fr 1fr;
gap: 38px;
align-items: start;
}
@media (max-width: 860px) {
.content-area {
grid-template-columns: 1fr;
}
}
/* ---------------------------------------------------------------------------
Page heading
------------------------------------------------------------------------- */
.page-heading {
font-size: 1.9rem;
font-weight: 700;
margin: 0 0 26px;
line-height: 1.3;
letter-spacing: -0.01em;
}
.page-heading a {
color: var(--color-text);
}
/* ---------------------------------------------------------------------------
Post grid
------------------------------------------------------------------------- */
.posts-grid {
display: grid;
grid-template-columns: repeat(2, 1fr);
gap: 26px;
}
@media (max-width: 620px) {
.posts-grid {
grid-template-columns: 1fr;
}
}
.post-card {
background: var(--color-card-bg);
border: 1px solid var(--color-border);
border-radius: var(--border-radius);
padding: 30px 28px 26px;
transition: box-shadow 0.2s ease, transform 0.2s ease;
}
.post-card:hover {
box-shadow: 0 6px 18px rgba(0, 0, 0, 0.05);
transform: translateY(-2px);
}
.post-card h2,
.post-card h3 {
margin: 0 0 6px;
font-size: 1.6rem;
line-height: 1.25;
font-weight: 700;
letter-spacing: -0.01em;
}
.post-card h2 a,
.post-card h3 a {
color: var(--color-text);
}
.post-card h2 a:hover,
.post-card h3 a:hover {
color: var(--color-link);
}
.post-meta {
font-size: 0.85rem;
color: var(--color-muted);
margin-bottom: 14px;
letter-spacing: 0.02em;
}
.post-meta strong {
font-weight: 600;
color: var(--color-text);
}
.post-excerpt {
margin: 0 0 16px;
font-size: 0.98rem;
line-height: 1.6;
color: var(--color-text);
}
.post-excerpt p {
margin: 0 0 10px;
}
.post-excerpt p:last-child {
margin-bottom: 0;
}
.post-tags {
font-size: 0.82rem;
color: var(--color-muted);
margin-bottom: 6px;
}
.post-tags .tag-icon {
margin-right: 4px;
}
.post-tags .tag {
color: var(--color-link);
text-decoration: none;
}
.post-tags .tag:hover {
text-decoration: underline;
}
.post-footer {
display: flex;
flex-wrap: wrap;
align-items: center;
justify-content: space-between;
gap: 10px;
margin-top: 8px;
}
.read-more {
font-size: 0.9rem;
font-weight: 600;
color: var(--color-link);
text-decoration: none;
}
.read-more:hover {
color: var(--color-link-hover);
text-decoration: underline;
}
.comment-link {
font-size: 0.9rem;
color: var(--color-muted);
text-decoration: none;
}
.comment-link:hover {
color: var(--color-link);
}
/* ---------------------------------------------------------------------------
Sidebar / widgets
------------------------------------------------------------------------- */
.sidebar .widget {
background: var(--color-sidebar-bg);
border: 1px solid var(--color-border);
border-radius: 6px;
padding: 20px 22px;
margin-bottom: 26px;
}
.widget-title {
font-size: 1.05rem;
font-weight: 700;
margin: 0 0 14px;
padding-bottom: 10px;
border-bottom: 2px solid var(--color-accent);
}
.search-form input[type="search"] {
width: 100%;
padding: 10px 12px;
border: 1px solid var(--color-border);
border-radius: 4px;
font-family: var(--font-stack);
font-size: 0.95rem;
}
.search-form input[type="search"]:focus {
outline: none;
border-color: var(--color-accent);
}
.search-form button {
margin-top: 8px;
width: 100%;
background-color: var(--color-accent);
color: #fff;
border: 0;
padding: 10px;
border-radius: 4px;
font-weight: 600;
cursor: pointer;
}
.search-form button:hover {
background-color: var(--color-link-hover);
color: #fff;
}
.widget ul {
margin: 0;
padding: 0;
list-style: none;
}
.widget li {
margin-bottom: 8px;
}
.widget li a,
.widget li span {
color: var(--color-text);
font-size: 0.92rem;
}
.widget li a:hover {
color: var(--color-link);
}
.widget ul.submenu li {
padding-left: 14px;
border-left: 2px solid var(--color-border);
margin-left: 6px;
}
/* ---------------------------------------------------------------------------
Breadcrumb
------------------------------------------------------------------------- */
.breadcrumb {
font-size: 0.85rem;
color: var(--color-muted);
margin-bottom: 24px;
}
.breadcrumb a {
color: var(--color-link);
}
.breadcrumb span {
margin: 0 8px;
}
/* ---------------------------------------------------------------------------
Single post
------------------------------------------------------------------------- */
.single-post {
background: var(--color-bg);
border: 1px solid var(--color-border);
border-radius: 6px;
padding: 34px 32px;
}
.single-post .post-title {
font-size: 2.1rem;
font-weight: 700;
line-height: 1.25;
margin: 0 0 20px;
letter-spacing: -0.01em;
}
.single-post .entry-content {
font-size: 1.02rem;
}
.single-post .entry-content h1,
.single-post .entry-content h2,
.single-post .entry-content h3 {
margin-top: 1.4em;
margin-bottom: 0.6em;
font-weight: 700;
}
.single-post .entry-content pre {
background: #1e1e1e;
color: #e0e0e0;
padding: 16px;
border-radius: 6px;
overflow-x: auto;
font-size: 0.88rem;
line-height: 1.5;
}
.single-post .entry-content pre code {
background: none;
padding: 0;
}
.single-post .entry-content code {
background: var(--color-sidebar-bg);
padding: 2px 6px;
border-radius: 3px;
font-size: 0.9em;
}
.single-post .entry-content blockquote {
border-left: 4px solid var(--color-accent);
margin: 1.2em 0;
padding: 8px 20px;
font-style: italic;
color: #444;
background: var(--color-sidebar-bg);
border-radius: 0 6px 6px 0;
}
.single-post .entry-content img {
border-radius: 6px;
margin: 1.2em 0;
}
.single-post .entry-content table {
border-collapse: collapse;
width: 100%;
margin: 1.2em 0;
}
.single-post .entry-content th,
.single-post .entry-content td {
border: 1px solid var(--color-border);
padding: 8px 12px;
text-align: left;
}
.single-post .entry-content th {
background: var(--color-sidebar-bg);
}
.post-share {
margin-top: 34px;
padding-top: 24px;
border-top: 1px solid var(--color-border);
font-size: 0.9rem;
color: var(--color-muted);
}
/* ---------------------------------------------------------------------------
Comments
------------------------------------------------------------------------- */
.comments-section {
margin-top: 40px;
border-top: 1px solid var(--color-border);
padding-top: 30px;
}
.comment-list { margin-bottom: 28px; }
.field-hint { display:block; margin: 6px 0 16px; font-size: 0.85rem; color: var(--color-muted); }
.empty-state { text-align:center; color: var(--color-muted); padding: 30px 20px; }
.comment-block {
background: var(--color-sidebar-bg);
border: 1px solid var(--color-border);
border-radius: 6px;
padding: 18px 20px;
margin-bottom: 16px;
}
.comment-block .comment-meta {
font-size: 0.85rem;
color: var(--color-muted);
margin-bottom: 8px;
display:flex;
gap: 8px;
flex-wrap: wrap;
}
.comment-block .comment-author { color: var(--color-text); font-weight: 600; }
.comment-block .comment-email { opacity: 0.75; }
.comment-block .comment-body { font-size: 0.98rem; line-height: 1.6; }
.comment-block .comment-actions { margin-top: 12px; }
.comment-pending { border-left: 4px solid var(--color-accent); }
/* Buttons used by the public comment form / moderation actions. Defined here so
they style on public pages (which load only style.css, not admin.css). */
.btn {
display:inline-block; padding: 8px 16px; border-radius: 5px; font-weight: 600;
font-size: 0.9rem; cursor:pointer; border: 1px solid var(--color-border);
background: var(--color-bg); color: var(--color-text); text-decoration:none;
}
.btn:hover { border-color: var(--color-accent); color: var(--color-link); }
.btn-primary {
background: var(--color-accent); border-color: var(--color-accent); color: #fff;
}
.btn-primary:hover { background: var(--color-link-hover); border-color: var(--color-link-hover); color: #fff; }
.btn-danger { color: #b71c1c; border-color: #f5c6cb; background: #fdecea; }
.btn-danger:hover { background: #b71c1c; border-color: #b71c1c; color: #fff; }
.btn-sm { padding: 5px 12px; font-size: 0.82rem; line-height: 1; }
.comment-form {
border-top: 1px solid var(--color-border); padding-top: 24px;
}
.comment-form .form-row { grid-template-columns: 1fr 1fr; gap: 20px; margin-bottom: 16px; }
.comment-form label { display:block; font-weight: 600; margin-bottom: 6px; font-size: 0.95rem; }
.comment-form input, .comment-form textarea {
width: 100%; padding: 11px 12px; border: 1px solid var(--color-border);
border-radius: 5px; font-family: var(--font-stack); font-size: 0.98rem; background: #fff;
}
.comment-form input:focus, .comment-form textarea:focus {
outline: none; border-color: var(--color-accent);
}
.comment-form textarea { min-height: 90px; resize: vertical; }
.comment-form .btn-primary { padding: 11px 22px; }
/* ---------------------------------------------------------------------------
Notices
------------------------------------------------------------------------- */
.notice {
padding: 10px 14px;
border-radius: 4px;
margin-bottom: 16px;
font-size: 0.92rem;
}
.notice-error {
background: #fdecea;
color: #b71c1c;
border: 1px solid #f5c6cb;
}
.notice-success {
background: #e7f7ee;
color: #1b5e20;
border: 1px solid #c3e6cb;
}
.notice-info {
background: #e7f2fd;
color: #0c5468;
border: 1px solid #bee5eb;
}
/* ------------------------------- Lightbox ------------------------------- */
/* Full-page image viewer opened by clicking any <img> on rendered pages. */
.lightbox {
position: fixed;
inset: 0;
z-index: 9000;
display: none;
align-items: center;
justify-content: center;
font-family: -apple-system, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
}
.lightbox.is-open {
display: flex;
}
.lightbox-backdrop {
position: absolute;
inset: 0;
background: rgba(0, 0, 0, 0.85);
cursor: pointer;
opacity: 0;
transition: opacity 0.25s ease;
}
.lightbox.is-open .lightbox-backdrop {
opacity: 1;
}
.lightbox-wrapper {
position: relative;
z-index: 1;
max-width: 94vw;
max-height: 90vh;
display: flex;
align-items: center;
justify-content: center;
padding: 24px;
}
.lightbox-img {
max-width: 94vw;
max-height: 90vh;
width: auto;
height: auto;
object-fit: contain;
border-radius: 4px;
box-shadow: 0 8px 40px rgba(0, 0, 0, 0.45);
}
.lightbox-img[aria-hidden="true"] {
visibility: hidden;
}
/* ------------------------------- Gallery hero ------------------------------- */
.gallery-hero {
margin: 24px 0 8px;
text-align: center;
}
.gallery-hero-img {
max-width: 100%;
border-radius: 6px;
box-shadow: 0 6px 24px rgba(0, 0, 0, 0.18);
cursor: pointer;
transition: transform 0.15s ease, box-shadow 0.15s ease;
}
.gallery-hero-img:hover {
transform: translateY(-2px);
box-shadow: 0 10px 30px rgba(0, 0, 0, 0.28);
}
.hero-caption {
margin-top: 8px;
font-weight: 600;
color: #444;
}
/* ------------------------------- Gallery lightbox -------------------------- */
.gallery-lightbox {
position: fixed;
inset: 0;
z-index: 9500;
display: none;
flex-direction: column;
align-items: center;
justify-content: center;
font-family: -apple-system, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
}
.gallery-lightbox.is-open {
display: flex;
}
.gallery-lightbox-backdrop {
position: absolute;
inset: 0;
background: rgba(0, 0, 0, 0.85);
cursor: pointer;
opacity: 0;
transition: opacity 0.25s ease;
}
.gallery-lightbox.is-open .gallery-lightbox-backdrop {
opacity: 1;
}
.gallery-lightbox-header {
position: relative;
z-index: 2;
color: #fff;
font-size: 1.4rem;
font-weight: 600;
text-align: center;
padding: 18px 12px 4px;
text-shadow: 0 1px 6px rgba(0, 0, 0, 0.5);
}
.gallery-lightbox-body {
position: relative;
z-index: 2;
display: flex;
flex-direction: column;
align-items: center;
gap: 14px;
max-width: 94vw;
width: auto;
padding: 8px 20px;
}
.lightbox-prev,
.lightbox-next {
position: absolute;
top: 50%;
transform: translateY(-50%);
z-index: 3;
width: 46px;
height: 46px;
border: none;
border-radius: 50%;
background: rgba(255, 255, 255, 0.15);
color: #fff;
font-size: 1.6rem;
line-height: 1;
cursor: pointer;
transition: background 0.15s ease;
}
.lightbox-prev { left: 16px; }
.lightbox-next { right: 16px; }
.lightbox-prev:hover,
.lightbox-next:hover { background: rgba(255, 255, 255, 0.3); }
.lightbox-img-main {
max-width: 90vw;
max-height: 78vh;
width: auto;
height: auto;
object-fit: contain;
border-radius: 6px;
box-shadow: 0 10px 40px rgba(0, 0, 0, 0.5);
}
.lightbox-close {
position: absolute;
top: 12px;
right: 18px;
z-index: 4;
width: 38px;
height: 38px;
border: none;
border-radius: 50%;
background: rgba(255, 255, 255, 0.15);
color: #fff;
font-size: 1.6rem;
line-height: 1;
text-align: center;
cursor: pointer;
transition: background 0.15s ease;
}
.lightbox-close:hover { background: rgba(255, 255, 255, 0.3); }
/* ------------------------------- Album card thumb -------------------------- */
.album-card {
display: flex;
flex-direction: column;
text-align: left;
}
.album-thumb {
width: 100%;
max-height: 200px;
object-fit: cover;
border-radius: 6px;
margin-bottom: 10px;
display: block;
}
/* --- Tag browsing, pagination, draft previews ------------------------------ */
.tag-cloud { display: flex; flex-wrap: wrap; gap: 10px; align-items: center; }
.tag-cloud-page { margin: 24px 0; }
.tag-cloud .term { display: inline-flex; gap: 6px; align-items: baseline; }
.tag-cloud .term small { opacity: .65; font-size: .8em; }
.pagination { display: flex; flex-wrap: wrap; align-items: center; gap: 14px; margin: 28px 0 8px; }
.pagination-info { opacity: .7; font-size: .9em; }
.preview-banner { border-left: 4px solid #d97706; background: #fff7ed; color: #7c2d12; padding: 12px 16px; border-radius: 6px; margin: 16px 0; }
.preview-banner a { font-weight: 600; }
/* Related posts under an article */
.related-posts { margin: 36px 0 12px; }
.related-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 14px; }
.related-card { border: 1px solid rgba(0, 0, 0, .12); border-radius: 6px; padding: 14px 16px; }
.related-card h3 { margin: 0 0 6px; font-size: 1rem; line-height: 1.3; }
.related-card .post-meta { display: flex; gap: 10px; font-size: .85em; opacity: .75; }
+268
View File
@@ -0,0 +1,268 @@
/* Analytics dashboard: visitor location map + location trend chart.
*
* Both charts read their data from JSON <script> blocks embedded by
* templates/admin/analytics.html, so there is no extra API request and no
* chart library to load. Leaflet (vendored under /static/vendor/leaflet) is
* used for the map only when it is present.
*/
(function () {
"use strict";
var PALETTE = [
"#1f6feb", "#e36209", "#2ea043", "#8250df", "#cf222e", "#8b949e",
];
function readJSON(id) {
var el = document.getElementById(id);
if (!el) return null;
try {
return JSON.parse(el.textContent);
} catch (err) {
return null;
}
}
function dayLabel(iso) {
var parts = String(iso).split("-");
var date = new Date(Date.UTC(+parts[0], +parts[1] - 1, +parts[2]));
return date.toLocaleDateString(undefined, {
month: "short", day: "numeric", timeZone: "UTC",
});
}
function niceMax(value) {
if (value <= 4) return 4;
var power = Math.pow(10, Math.floor(Math.log10(value)));
var steps = [1, 2, 2.5, 5, 10];
for (var i = 0; i < steps.length; i++) {
if (steps[i] * power >= value) return steps[i] * power;
}
return value;
}
function drawTrend() {
var data = readJSON("location-trend-data");
var canvas = document.getElementById("location-trend-chart");
if (!data || !canvas || !data.series || !data.series.length) return;
var wrap = canvas.parentNode;
var tooltip = document.createElement("div");
tooltip.className = "chart-tooltip";
tooltip.hidden = true;
wrap.appendChild(tooltip);
var legend = document.getElementById("location-trend-legend");
data.series.forEach(function (series, index) {
var item = document.createElement("span");
var swatch = document.createElement("span");
swatch.className = "swatch";
swatch.style.backgroundColor = PALETTE[index % PALETTE.length];
item.appendChild(swatch);
item.appendChild(document.createTextNode(series.name));
legend.appendChild(item);
});
var PAD = { top: 14, right: 14, bottom: 30, left: 44 };
var HEIGHT = 280;
var hoverIndex = -1;
function render() {
var width = Math.max(320, wrap.clientWidth);
var dpr = window.devicePixelRatio || 1;
canvas.width = Math.round(width * dpr);
canvas.height = Math.round(HEIGHT * dpr);
canvas.style.width = width + "px";
canvas.style.height = HEIGHT + "px";
var ctx = canvas.getContext("2d");
ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
ctx.clearRect(0, 0, width, HEIGHT);
var plotW = width - PAD.left - PAD.right;
var plotH = HEIGHT - PAD.top - PAD.bottom;
var max = 0;
data.series.forEach(function (series) {
series.data.forEach(function (value) {
if (value > max) max = value;
});
});
max = niceMax(max);
var count = data.labels.length;
function xAt(index) {
return PAD.left + (count === 1 ? plotW / 2 : (index / (count - 1)) * plotW);
}
function yAt(value) {
return PAD.top + plotH - (value / max) * plotH;
}
ctx.strokeStyle = "#e5e7eb";
ctx.fillStyle = "#6b7280";
ctx.font = "12px system-ui, -apple-system, sans-serif";
ctx.lineWidth = 1;
ctx.textAlign = "right";
ctx.textBaseline = "middle";
for (var tick = 0; tick <= 4; tick++) {
var tickValue = (max / 4) * tick;
var tickY = yAt(tickValue);
ctx.beginPath();
ctx.moveTo(PAD.left, tickY);
ctx.lineTo(width - PAD.right, tickY);
ctx.stroke();
ctx.fillText(String(Math.round(tickValue)), PAD.left - 8, tickY);
}
ctx.textAlign = "center";
ctx.textBaseline = "top";
var stride = Math.max(1, Math.ceil(count / 7));
for (var i = 0; i < count; i += stride) {
ctx.fillText(dayLabel(data.labels[i]), xAt(i), HEIGHT - PAD.bottom + 8);
}
data.series.forEach(function (series, index) {
ctx.strokeStyle = PALETTE[index % PALETTE.length];
ctx.lineWidth = 2;
ctx.lineJoin = "round";
ctx.beginPath();
series.data.forEach(function (value, i) {
var x = xAt(i);
var y = yAt(value);
if (i === 0) ctx.moveTo(x, y);
else ctx.lineTo(x, y);
});
ctx.stroke();
});
if (hoverIndex >= 0) {
var hoverX = xAt(hoverIndex);
ctx.strokeStyle = "rgba(31, 111, 235, 0.35)";
ctx.lineWidth = 1;
ctx.beginPath();
ctx.moveTo(hoverX, PAD.top);
ctx.lineTo(hoverX, HEIGHT - PAD.bottom);
ctx.stroke();
var lines = [dayLabel(data.labels[hoverIndex])];
data.series.forEach(function (series, index) {
var value = series.data[hoverIndex] || 0;
if (!value) return;
ctx.fillStyle = PALETTE[index % PALETTE.length];
ctx.beginPath();
ctx.arc(hoverX, yAt(value), 3, 0, Math.PI * 2);
ctx.fill();
lines.push(series.name + ": " + value);
});
tooltip.textContent = lines.join(" \u00b7 ");
tooltip.hidden = false;
var left = Math.min(Math.max(hoverX + 10, 8), width - tooltip.offsetWidth - 8);
tooltip.style.left = left + "px";
tooltip.style.top = PAD.top + "px";
} else {
tooltip.hidden = true;
}
}
canvas.addEventListener("mousemove", function (event) {
var rect = canvas.getBoundingClientRect();
var plotW = Math.max(1, rect.width - PAD.left - PAD.right);
var count = data.labels.length;
var ratio = (event.clientX - rect.left - PAD.left) / plotW;
var index = Math.round(ratio * (count - 1));
index = Math.max(0, Math.min(count - 1, index));
if (index !== hoverIndex) {
hoverIndex = index;
render();
}
});
canvas.addEventListener("mouseleave", function () {
hoverIndex = -1;
render();
});
var resizeTimer = null;
window.addEventListener("resize", function () {
clearTimeout(resizeTimer);
resizeTimer = setTimeout(render, 150);
});
render();
}
function escapeHtml(value) {
return String(value == null ? "" : value)
.replace(/&/g, "&amp;")
.replace(/</g, "&lt;")
.replace(/>/g, "&gt;")
.replace(/"/g, "&quot;")
.replace(/'/g, "&#39;");
}
function initMap() {
var points = readJSON("visitor-map-data") || [];
var container = document.getElementById("visitor-map");
if (!container || typeof L === "undefined") return;
var map = L.map(container, { minZoom: 2, worldCopyJump: true }).setView([20, 0], 2);
L.tileLayer("https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png", {
maxZoom: 19,
attribution:
'&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors',
}).addTo(map);
// Keep the world map visible even before the first located visit.
if (!points.length) {
setTimeout(function () { map.invalidateSize(); }, 0);
return;
}
var maxVisits = 1;
points.forEach(function (point) {
if (point.visits > maxVisits) maxVisits = point.visits;
});
var bounds = [];
points.forEach(function (point) {
var radius = 5 + 16 * Math.sqrt(point.visits / maxVisits);
var label = [point.city, point.region, point.country]
.filter(Boolean)
.join(", ");
L.circleMarker([point.lat, point.lon], {
radius: radius,
color: "#1f6feb",
weight: 1.5,
fillColor: "#1f6feb",
fillOpacity: 0.3,
})
.addTo(map)
.bindPopup(
"<strong>" + escapeHtml(label || "Unknown location") + "</strong><br>" +
escapeHtml(point.visits) + " visit(s) from " +
escapeHtml(point.visitors) + " visitor(s)"
);
bounds.push([point.lat, point.lon]);
});
if (bounds.length === 1) {
map.setView(bounds[0], 5);
} else {
map.fitBounds(L.latLngBounds(bounds).pad(0.25), { maxZoom: 6 });
}
setTimeout(function () {
map.invalidateSize();
}, 0);
window.addEventListener("resize", function () {
map.invalidateSize();
});
}
function start() {
drawTrend();
initMap();
}
if (document.readyState === "loading") {
document.addEventListener("DOMContentLoaded", start);
} else {
start();
}
})();
+114
View File
@@ -0,0 +1,114 @@
// gallery_lightbox.js — full-album gallery viewer for /photos/<slug>.
// A random image from the album is shown as a hero at the top of the page.
// Clicking the hero (or any thumbnail) opens a modal showing every photo of the
// album, with the album title, prev/next navigation and a thumbnail strip.
// Esc, backdrop click, or the close button close it. Dependency-free / offline.
(function () {
"use strict";
var imgs = [];
var lightbox = null;
var mainImg = null;
var idx = -1;
function collectGallery() {
var out = [];
if (document.querySelectorAll) {
var nodes = document.querySelectorAll(".gallery-img");
for (var i = 0; i < nodes.length; i++) out.push(nodes[i]);
}
return out;
}
function buildLightbox() {
// Reuse the existing viewer ONLY while it is still attached to the DOM.
// Once close() has removed it, `lightbox` must be rebuilt so the next
// thumbnail click doesn't set its src on a detached (invisible) node.
if (lightbox && lightbox.isConnected) return lightbox;
lightbox = document.getElementById("gallery-lightbox");
if (!lightbox) return null;
var closeBtn = document.querySelector(".lightbox-close");
var prevBtn = document.querySelector(".lightbox-prev");
var nextBtn = document.querySelector(".lightbox-next");
mainImg = lightbox.querySelector(".lightbox-img-main");
if (closeBtn) closeBtn.addEventListener("click", close);
if (prevBtn) prevBtn.addEventListener("click", function () { show(idx - 1); });
if (nextBtn) nextBtn.addEventListener("click", function () { show(idx + 1); });
lightbox.addEventListener("click", function (e) {
// Don't close when clicking a control button or the main image; only the
// dark backdrop should dismiss the viewer.
var t = e.target;
if (t.closest(".lightbox-close, .lightbox-prev, .lightbox-next")) return;
if (mainImg && mainImg.contains(t)) return;
close();
});
document.addEventListener("keydown", function (e) {
if (!lightbox || !lightbox.classList.contains("is-open")) return;
if (e.key === "Escape") { close(); }
else if (e.key === "ArrowRight" || e.key === "ArrowDown") { e.preventDefault(); show(idx + 1); }
else if (e.key === "ArrowLeft" || e.key === "ArrowUp") { e.preventDefault(); show(idx - 1); }
});
return lightbox;
}
// Pick a random thumbnail to feature as the hero.
function pickRandomHero() {
var g = collectGallery();
if (!g.length) return null;
return g[Math.floor(Math.random() * g.length)];
}
function show(i) {
var g = collectGallery();
if (!g.length) return;
idx = (i + g.length) % g.length;
var el = g[idx];
var src = el.getAttribute("data-src") || el.getAttribute("src") || "";
buildLightbox(); // ensure the viewer (mainImg) exists before we use it
if (mainImg && mainImg.getAttribute("src")) mainImg.removeAttribute("src"); // avoid flash
mainImg.setAttribute("src", src);
lightbox.classList.add("is-open");
document.body.style.overflow = "hidden";
}
function open() {
var heroImg = document.querySelector(".gallery-hero-img");
if (heroImg && !heroImg.getAttribute("src")) {
var heroEl = pickRandomHero();
if (heroEl) heroImg.setAttribute("src", heroEl.getAttribute("data-src") || heroEl.getAttribute("src"));
}
buildLightbox();
show(0);
}
function close() {
if (!lightbox) return;
lightbox.classList.remove("is-open");
document.body.style.overflow = "";
lightbox = null; // drop the cached node so buildLightbox() rebuilds next open
setTimeout(function () { if (!lightbox.classList.contains("is-open")) lightbox.remove(); }, 300);
}
// Wire up clicks: the hero opens the gallery (showing image 0), while any
// individual thumbnail opens the gallery showing THAT photo.
var heroFigure = document.getElementById("gallery-hero");
if (heroFigure) heroFigure.addEventListener("click", open);
var g = collectGallery();
for (let k = 0; k < g.length; k++) {
// NOTE: `let` gives each thumbnail its OWN copy of `k`, so clicking one
// shows THAT photo. With the original `var k`, every handler shared the
// final loop value (g.length) and always called show(0) instead — the bug.
g[k].addEventListener("click", function () { buildLightbox(); show(k); });
}
// Feature a random image on load.
if (document.readyState === "loading") {
document.addEventListener("DOMContentLoaded", pickRandomHero);
} else {
pickRandomHero();
}
})();
File diff suppressed because one or more lines are too long
+134
View File
@@ -0,0 +1,134 @@
// lightbox.js — tiny dependency-free image viewer for rendered pages.
// Click any <img> (from an uploaded TinyMCE image, or inline markdown) to open
// it full-size in an overlay within the page. Esc, backdrop click, or arrow keys
// close / navigate. Images with class "no-lightbox" (or data-no-lightbox) and
// the site banner stay non-clickable. No external CDN → works offline.
(function () {
"use strict";
var EXCLUDE_CLASSES = ["no-lightbox", "site-banner-img"];
function isExcluded(img) {
if (img.hasAttribute("data-no-lightbox")) return true;
var cls = (img.getAttribute("class") || "").toLowerCase();
for (var i = 0; i < EXCLUDE_CLASSES.length; i++) {
if (cls.indexOf(EXCLUDE_CLASSES[i]) !== -1) return true;
}
return false;
}
// Collect clickable images in document order (once).
var images = [];
var doc = document;
if (doc.querySelectorAll) {
var nodes = doc.querySelectorAll("img");
for (var n = 0; n < nodes.length; n++) {
if (!isExcluded(nodes[n])) images.push(nodes[n]);
}
}
var lightbox = null;
var imgEl = null;
var idx = -1;
function buildLightbox() {
if (lightbox) return lightbox;
lightbox = document.createElement("div");
lightbox.className = "lightbox";
lightbox.setAttribute("role", "dialog");
lightbox.setAttribute("aria-modal", "true");
lightbox.setAttribute("aria-label", "Image viewer");
var backdrop = document.createElement("div");
backdrop.className = "lightbox-backdrop";
var wrapper = document.createElement("div");
wrapper.className = "lightbox-wrapper";
imgEl = document.createElement("img");
imgEl.className = "lightbox-img";
imgEl.alt = "";
wrapper.appendChild(imgEl);
lightbox.appendChild(backdrop);
lightbox.appendChild(wrapper);
lightbox.addEventListener("click", onLightboxClick);
return lightbox;
}
function ensureLightbox() {
buildLightbox();
// Re-attach if the viewer was removed from the DOM (e.g. after a close),
// so clicking another image still reopens it.
if (lightbox && lightbox.parentNode !== document.body) {
document.body.appendChild(lightbox);
}
return lightbox;
}
function openAt(i) {
ensureLightbox(); // ensure the viewer (imgEl + lightbox) exists before we use them
idx = (i + images.length) % images.length;
var src = images[idx].getAttribute("src");
if (!src) src = images[idx].getAttribute("data-src") || "";
if (imgEl.getAttribute("src")) imgEl.removeAttribute("src"); // avoid flash
imgEl.setAttribute("src", src);
lightbox.classList.add("is-open");
document.body.style.overflow = "hidden";
}
function close() {
lightbox.classList.remove("is-open");
document.body.style.overflow = "";
setTimeout(function () { if (!lightbox.classList.contains("is-open")) lightbox.remove(); }, 300);
}
function next() { openAt(idx + 1); }
function prev() { openAt(idx - 1); }
function isClickable(img) {
if (img.hasAttribute("data-no-lightbox")) return false;
var cls = (img.getAttribute("class") || "").toLowerCase();
for (var i = 0; i < EXCLUDE_CLASSES.length; i++) {
if (cls.indexOf(EXCLUDE_CLASSES[i]) !== -1) return false;
}
return true;
}
function onImgClick(e) {
var t = e.target;
if (t.tagName !== "IMG" || !isClickable(t)) return; // delegated: currentTarget is always the listener element, never the img
e.preventDefault();
e.stopPropagation();
openAt(idx + 1);
}
function onLightboxClick(e) {
// Clicking anywhere in the viewer except the image itself closes it.
if (imgEl && imgEl.contains(e.target)) return;
close();
}
function onKeyDown(e) {
if (lightbox && lightbox.classList.contains("is-open")) {
if (e.key === "Escape") { close(); }
else if (e.key === "ArrowRight" || e.key === "ArrowDown") { e.preventDefault(); next(); }
else if (e.key === "ArrowLeft" || e.key === "ArrowUp") { e.preventDefault(); prev(); }
}
}
if (images.length > 0) {
// Delegate off the document so it survives images added later.
doc.addEventListener("click", onImgClick);
doc.addEventListener("keydown", onKeyDown);
// Re-scan on DOMContentLoaded in case images appear after load.
if (doc.readyState === "loading") {
doc.addEventListener("DOMContentLoaded", function () {
var again = doc.querySelectorAll("img");
for (var j = 0; j < again.length; j++) {
if (!images.indexOf(again[j])) images.push(again[j]);
}
});
}
}
})();
File diff suppressed because one or more lines are too long
+1
View File
@@ -0,0 +1 @@
!function(){"use strict";var e=tinymce.util.Tools.resolve("tinymce.PluginManager"),t=tinymce.util.Tools.resolve("tinymce.dom.RangeUtils"),o=tinymce.util.Tools.resolve("tinymce.util.Tools");const n=e=>e.options.get("allow_html_in_named_anchor");const a="a:not([href])",r=e=>!e,i=e=>e.getAttribute("id")||e.getAttribute("name")||"",l=e=>(e=>"a"===e.nodeName.toLowerCase())(e)&&!e.getAttribute("href")&&""!==i(e),s=e=>e.dom.getParent(e.selection.getStart(),a),d=(e,a)=>{const r=s(e);r?((e,t,o)=>{o.removeAttribute("name"),o.id=t,e.addVisual(),e.undoManager.add()})(e,a,r):((e,a)=>{e.undoManager.transact(()=>{n(e)||e.selection.collapse(!0),e.selection.isCollapsed()?e.insertContent(e.dom.createHTML("a",{id:a})):((e=>{const n=e.dom;t(n).walk(e.selection.getRng(),e=>{o.each(e,e=>{var t;l(t=e)&&!t.firstChild&&n.remove(e,!1)})})})(e),e.formatter.remove("namedAnchor",void 0,void 0,!0),e.formatter.apply("namedAnchor",{value:a}),e.addVisual())})})(e,a),e.focus()},c=e=>(e=>r(e.attr("href"))&&!r(e.attr("id")||e.attr("name")))(e)&&!e.firstChild,m=e=>t=>{for(let o=0;o<t.length;o++){const n=t[o];c(n)&&n.attr("contenteditable",e)}},u=e=>t=>{const o=()=>{t.setEnabled(e.selection.isEditable())};return e.on("NodeChange",o),o(),()=>{e.off("NodeChange",o)}},h="anchor";e.add(h,e=>((e=>{(0,e.options.register)("allow_html_in_named_anchor",{processor:"boolean",default:!1})})(e),(e=>{e.on("PreInit",()=>{e.parser.addNodeFilter("a",m("false")),e.serializer.addNodeFilter("a",m(null))})})(e),(e=>{e.addCommand("mceAnchor",()=>{(e=>{const t=(e=>{const t=s(e);return t?i(t):""})(e);e.windowManager.open({title:"Anchor",size:"normal",body:{type:"panel",items:[{name:"id",type:"input",label:"ID",placeholder:"example"}]},buttons:[{type:"cancel",name:"cancel",text:"Cancel"},{type:"submit",name:"save",text:"Save",primary:!0}],initialData:{id:t},onSubmit:t=>{((e,t)=>/^[A-Za-z][A-Za-z0-9\-:._]*$/.test(t)?(d(e,t),!0):(e.windowManager.alert("ID should start with a letter, followed only by letters, numbers, dashes, dots, colons or underscores."),!1))(e,t.getData().id)&&t.close()}})})(e)})})(e),(e=>{const t=()=>e.execCommand("mceAnchor");e.ui.registry.addToggleButton("anchor",{icon:"bookmark",tooltip:"Anchor",onAction:t,onSetup:t=>{const o=e.selection.selectorChangedWithUnbind("a:not([href])",t.setActive).unbind,n=u(e)(t);return()=>{o(),n()}}}),e.ui.registry.addMenuItem("anchor",{icon:"bookmark",text:"Anchor...",onAction:t,onSetup:u(e)})})(e),e.on("PreInit",()=>{(e=>{e.formatter.register("namedAnchor",{inline:"a",selector:a,remove:"all",split:!0,deep:!0,attributes:{id:"%value"},onmatch:(e,t,o)=>l(e)})})(e)}),{getMetadata:()=>({name:"Anchor",type:"opensource",slug:h})}))}();
+1
View File
@@ -0,0 +1 @@
!function(){"use strict";var e=tinymce.util.Tools.resolve("tinymce.PluginManager");const t=e=>"string"===(e=>{const t=typeof e;return null===e?"null":"object"===t&&Array.isArray(e)?"array":"object"===t&&(n=o=e,(r=String).prototype.isPrototypeOf(n)||o.constructor?.name===r.name)?"string":t;var n,o,r})(e);const n=e=>void 0===e;const o=e=>!(e=>null==e)(e),r=Object.hasOwnProperty,a=e=>"\ufeff"===e,s=e=>t=>t.options.get(e),l=s("autolink_pattern"),c=s("link_default_target"),i=s("link_default_protocol"),d=s("allow_unsafe_link_target");var u=tinymce.util.Tools.resolve("tinymce.dom.TextSeeker");const f=e=>3===e.nodeType,g=e=>1===e.nodeType,m=e=>/^[(\[{ \u00a0]$/.test(e),k=(e,t,n)=>{for(let o=t-1;o>=0;o--){const t=e.charAt(o);if(!a(t)&&n(t))return o}return-1},p=(e,t)=>{const o=e.schema.getVoidElements(),a=l(e),{dom:s,selection:c}=e;if(null!==s.getParent(c.getNode(),"a[href]")||e.mode.isReadOnly())return null;const d=c.getRng(),p=u(s,e=>{return s.isBlock(e)||(t=o,n=e.nodeName.toLowerCase(),r.call(t,n))||"false"===s.getContentEditable(e)||null!==s.getParent(e,"a[href]");var t,n}),{container:y,offset:w}=((e,t)=>{let n=e,o=t;for(;g(n)&&n.childNodes[o];)n=n.childNodes[o],o=f(n)?n.data.length:n.childNodes.length;return{container:n,offset:o}})(d.endContainer,d.endOffset),h=s.getParent(y,s.isBlock)??s.getRoot(),_=p.backwards(y,w+t,(e,t)=>{const n=e.data,o=k(n,t,(r=m,e=>!r(e)));var r,a;return-1===o||(a=n[o],/[?!,.;:]/.test(a))?o:o+1},h);if(!_)return null;let v=_.container;const A=p.backwards(_.container,_.offset,(e,t)=>{v=e;const n=k(e.data,t,m);return-1===n?n:n+1},h),C=s.createRng();A?C.setStart(A.container,A.offset):C.setStart(v,0),C.setEnd(_.container,_.offset);const b=C.toString().replace(/\uFEFF/g,"").match(a);if(b){let t=b[0];return $="www.",(P=t).length>=4&&P.substr(0,4)===$?t=i(e)+"://"+t:((e,t,o=0,r)=>{const a=e.indexOf(t,o);return-1!==a&&(!!n(r)||a+t.length<=r)})(t,"@")&&!(e=>/^([A-Za-z][A-Za-z\d.+-]*:\/\/)|mailto:/.test(e))(t)&&(t="mailto:"+t),{rng:C,url:t}}var P,$;return null},y=(e,n)=>{const{dom:o,selection:r}=e,{rng:a,url:s}=n,l=r.getBookmark();r.setRng(a);const i="createlink",u={command:i,ui:!1,value:s};if(!e.dispatch("BeforeExecCommand",u).isDefaultPrevented()){e.getDoc().execCommand(i,!1,s),e.dispatch("ExecCommand",u);const n=c(e);if(t(n)){const t=r.getNode();o.setAttrib(t,"target",n),"_blank"!==n||d(e)||o.setAttrib(t,"rel","noopener")}}r.moveToBookmark(l),e.nodeChanged()},w=e=>{const t=p(e,-1);o(t)&&y(e,t)},h=w,_="autolink";e.add(_,e=>((e=>{const t=e.options.register;t("autolink_pattern",{processor:"regexp",default:new RegExp("^"+/(?:[A-Za-z][A-Za-z\d.+-]{0,14}:\/\/(?:[-.~*+=!&;:'%@?^${}(),\w]+@)?|www\.|[-;:&=+$,.\w]+@)[A-Za-z\d-]+(?:\.[A-Za-z\d-]+)*(?::\d+)?(?:\/(?:[-.~*+=!;:'%@$(),\/\w]*[-~*+=%@$()\/\w])?)?(?:\?(?:[-.~*+=!&;:'%@?^${}(),\/\w]+))?(?:#(?:[-.~*+=!&;:'%@?^${}(),\/\w]+))?/g.source+"$","i")}),t("link_default_target",{processor:"string"}),t("link_default_protocol",{processor:"string",default:"https"})})(e),(e=>{e.on("keydown",t=>{13!==t.keyCode||t.isDefaultPrevented()||(e=>{const t=p(e,0);o(t)&&y(e,t)})(e)}),e.on("keyup",t=>{32===t.keyCode?w(e):(48===t.keyCode&&t.shiftKey||221===t.keyCode)&&h(e)})})(e),{getMetadata:()=>({name:"Autolink",type:"opensource",slug:_})}))}();
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
+1
View File
@@ -0,0 +1 @@
!function(){"use strict";var t=tinymce.util.Tools.resolve("tinymce.PluginManager");const e=(t,e,o)=>{t.dom.toggleClass(t.getBody(),"mce-visualblocks"),o.set(!o.get()),((t,e)=>{t.dispatch("VisualBlocks",{state:e})})(t,o.get())},o=t=>t.options.get("visualblocks_default_state");const s=(t,e)=>o=>{o.setActive(e.get());const s=t=>o.setActive(t.state);return t.on("VisualBlocks",s),()=>t.off("VisualBlocks",s)},l="visualblocks";t.add(l,(t,a)=>{(t=>{(0,t.options.register)("visualblocks_default_state",{processor:"boolean",default:!1})})(t);const c=(()=>{let t=!1;return{get:()=>t,set:e=>{t=e}}})();return((t,o,s)=>{t.addCommand("mceVisualBlocks",()=>{e(t,0,s)})})(t,0,c),((t,e)=>{const o=()=>t.execCommand("mceVisualBlocks");t.ui.registry.addToggleButton("visualblocks",{icon:"visualblocks",tooltip:"Show blocks",onAction:o,onSetup:s(t,e),context:"any"}),t.ui.registry.addToggleMenuItem("visualblocks",{text:"Show blocks",icon:"visualblocks",onAction:o,onSetup:s(t,e),context:"any"})})(t,c),((t,s,l)=>{t.on("PreviewFormats AfterPreviewFormats",e=>{l.get()&&t.dom.toggleClass(t.getBody(),"mce-visualblocks","afterpreviewformats"===e.type)}),t.on("init",()=>{o(t)&&e(t,0,l)})})(t,0,c),{getMetadata:()=>({name:"Visual Blocks",type:"opensource",slug:l})}})}();
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
+43095
View File
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,3 @@
‰PNG

....fakepngdata

After

Width:  |  Height:  |  Size: 23 B

@@ -0,0 +1,3 @@
‰PNG

....fakepngdata

After

Width:  |  Height:  |  Size: 23 B

@@ -0,0 +1,3 @@
‰PNG

....fakepngdata

After

Width:  |  Height:  |  Size: 23 B

@@ -0,0 +1,3 @@
臼NG

XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

After

Width:  |  Height:  |  Size: 72 B

@@ -0,0 +1,3 @@
臼NG

XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

After

Width:  |  Height:  |  Size: 72 B

@@ -0,0 +1,3 @@
‰PNG

....fakepngdata

After

Width:  |  Height:  |  Size: 23 B

@@ -0,0 +1,3 @@
‰PNG

....fakepngdata

After

Width:  |  Height:  |  Size: 23 B

@@ -0,0 +1,3 @@
‰PNG

....fakepngdata

After

Width:  |  Height:  |  Size: 23 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 696 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 618 B

+661
View File
@@ -0,0 +1,661 @@
/* required styles */
.leaflet-pane,
.leaflet-tile,
.leaflet-marker-icon,
.leaflet-marker-shadow,
.leaflet-tile-container,
.leaflet-pane > svg,
.leaflet-pane > canvas,
.leaflet-zoom-box,
.leaflet-image-layer,
.leaflet-layer {
position: absolute;
left: 0;
top: 0;
}
.leaflet-container {
overflow: hidden;
}
.leaflet-tile,
.leaflet-marker-icon,
.leaflet-marker-shadow {
-webkit-user-select: none;
-moz-user-select: none;
user-select: none;
-webkit-user-drag: none;
}
/* Prevents IE11 from highlighting tiles in blue */
.leaflet-tile::selection {
background: transparent;
}
/* Safari renders non-retina tile on retina better with this, but Chrome is worse */
.leaflet-safari .leaflet-tile {
image-rendering: -webkit-optimize-contrast;
}
/* hack that prevents hw layers "stretching" when loading new tiles */
.leaflet-safari .leaflet-tile-container {
width: 1600px;
height: 1600px;
-webkit-transform-origin: 0 0;
}
.leaflet-marker-icon,
.leaflet-marker-shadow {
display: block;
}
/* .leaflet-container svg: reset svg max-width decleration shipped in Joomla! (joomla.org) 3.x */
/* .leaflet-container img: map is broken in FF if you have max-width: 100% on tiles */
.leaflet-container .leaflet-overlay-pane svg {
max-width: none !important;
max-height: none !important;
}
.leaflet-container .leaflet-marker-pane img,
.leaflet-container .leaflet-shadow-pane img,
.leaflet-container .leaflet-tile-pane img,
.leaflet-container img.leaflet-image-layer,
.leaflet-container .leaflet-tile {
max-width: none !important;
max-height: none !important;
width: auto;
padding: 0;
}
.leaflet-container img.leaflet-tile {
/* See: https://bugs.chromium.org/p/chromium/issues/detail?id=600120 */
mix-blend-mode: plus-lighter;
}
.leaflet-container.leaflet-touch-zoom {
-ms-touch-action: pan-x pan-y;
touch-action: pan-x pan-y;
}
.leaflet-container.leaflet-touch-drag {
-ms-touch-action: pinch-zoom;
/* Fallback for FF which doesn't support pinch-zoom */
touch-action: none;
touch-action: pinch-zoom;
}
.leaflet-container.leaflet-touch-drag.leaflet-touch-zoom {
-ms-touch-action: none;
touch-action: none;
}
.leaflet-container {
-webkit-tap-highlight-color: transparent;
}
.leaflet-container a {
-webkit-tap-highlight-color: rgba(51, 181, 229, 0.4);
}
.leaflet-tile {
filter: inherit;
visibility: hidden;
}
.leaflet-tile-loaded {
visibility: inherit;
}
.leaflet-zoom-box {
width: 0;
height: 0;
-moz-box-sizing: border-box;
box-sizing: border-box;
z-index: 800;
}
/* workaround for https://bugzilla.mozilla.org/show_bug.cgi?id=888319 */
.leaflet-overlay-pane svg {
-moz-user-select: none;
}
.leaflet-pane { z-index: 400; }
.leaflet-tile-pane { z-index: 200; }
.leaflet-overlay-pane { z-index: 400; }
.leaflet-shadow-pane { z-index: 500; }
.leaflet-marker-pane { z-index: 600; }
.leaflet-tooltip-pane { z-index: 650; }
.leaflet-popup-pane { z-index: 700; }
.leaflet-map-pane canvas { z-index: 100; }
.leaflet-map-pane svg { z-index: 200; }
.leaflet-vml-shape {
width: 1px;
height: 1px;
}
.lvml {
behavior: url(#default#VML);
display: inline-block;
position: absolute;
}
/* control positioning */
.leaflet-control {
position: relative;
z-index: 800;
pointer-events: visiblePainted; /* IE 9-10 doesn't have auto */
pointer-events: auto;
}
.leaflet-top,
.leaflet-bottom {
position: absolute;
z-index: 1000;
pointer-events: none;
}
.leaflet-top {
top: 0;
}
.leaflet-right {
right: 0;
}
.leaflet-bottom {
bottom: 0;
}
.leaflet-left {
left: 0;
}
.leaflet-control {
float: left;
clear: both;
}
.leaflet-right .leaflet-control {
float: right;
}
.leaflet-top .leaflet-control {
margin-top: 10px;
}
.leaflet-bottom .leaflet-control {
margin-bottom: 10px;
}
.leaflet-left .leaflet-control {
margin-left: 10px;
}
.leaflet-right .leaflet-control {
margin-right: 10px;
}
/* zoom and fade animations */
.leaflet-fade-anim .leaflet-popup {
opacity: 0;
-webkit-transition: opacity 0.2s linear;
-moz-transition: opacity 0.2s linear;
transition: opacity 0.2s linear;
}
.leaflet-fade-anim .leaflet-map-pane .leaflet-popup {
opacity: 1;
}
.leaflet-zoom-animated {
-webkit-transform-origin: 0 0;
-ms-transform-origin: 0 0;
transform-origin: 0 0;
}
svg.leaflet-zoom-animated {
will-change: transform;
}
.leaflet-zoom-anim .leaflet-zoom-animated {
-webkit-transition: -webkit-transform 0.25s cubic-bezier(0,0,0.25,1);
-moz-transition: -moz-transform 0.25s cubic-bezier(0,0,0.25,1);
transition: transform 0.25s cubic-bezier(0,0,0.25,1);
}
.leaflet-zoom-anim .leaflet-tile,
.leaflet-pan-anim .leaflet-tile {
-webkit-transition: none;
-moz-transition: none;
transition: none;
}
.leaflet-zoom-anim .leaflet-zoom-hide {
visibility: hidden;
}
/* cursors */
.leaflet-interactive {
cursor: pointer;
}
.leaflet-grab {
cursor: -webkit-grab;
cursor: -moz-grab;
cursor: grab;
}
.leaflet-crosshair,
.leaflet-crosshair .leaflet-interactive {
cursor: crosshair;
}
.leaflet-popup-pane,
.leaflet-control {
cursor: auto;
}
.leaflet-dragging .leaflet-grab,
.leaflet-dragging .leaflet-grab .leaflet-interactive,
.leaflet-dragging .leaflet-marker-draggable {
cursor: move;
cursor: -webkit-grabbing;
cursor: -moz-grabbing;
cursor: grabbing;
}
/* marker & overlays interactivity */
.leaflet-marker-icon,
.leaflet-marker-shadow,
.leaflet-image-layer,
.leaflet-pane > svg path,
.leaflet-tile-container {
pointer-events: none;
}
.leaflet-marker-icon.leaflet-interactive,
.leaflet-image-layer.leaflet-interactive,
.leaflet-pane > svg path.leaflet-interactive,
svg.leaflet-image-layer.leaflet-interactive path {
pointer-events: visiblePainted; /* IE 9-10 doesn't have auto */
pointer-events: auto;
}
/* visual tweaks */
.leaflet-container {
background: #ddd;
outline-offset: 1px;
}
.leaflet-container a {
color: #0078A8;
}
.leaflet-zoom-box {
border: 2px dotted #38f;
background: rgba(255,255,255,0.5);
}
/* general typography */
.leaflet-container {
font-family: "Helvetica Neue", Arial, Helvetica, sans-serif;
font-size: 12px;
font-size: 0.75rem;
line-height: 1.5;
}
/* general toolbar styles */
.leaflet-bar {
box-shadow: 0 1px 5px rgba(0,0,0,0.65);
border-radius: 4px;
}
.leaflet-bar a {
background-color: #fff;
border-bottom: 1px solid #ccc;
width: 26px;
height: 26px;
line-height: 26px;
display: block;
text-align: center;
text-decoration: none;
color: black;
}
.leaflet-bar a,
.leaflet-control-layers-toggle {
background-position: 50% 50%;
background-repeat: no-repeat;
display: block;
}
.leaflet-bar a:hover,
.leaflet-bar a:focus {
background-color: #f4f4f4;
}
.leaflet-bar a:first-child {
border-top-left-radius: 4px;
border-top-right-radius: 4px;
}
.leaflet-bar a:last-child {
border-bottom-left-radius: 4px;
border-bottom-right-radius: 4px;
border-bottom: none;
}
.leaflet-bar a.leaflet-disabled {
cursor: default;
background-color: #f4f4f4;
color: #bbb;
}
.leaflet-touch .leaflet-bar a {
width: 30px;
height: 30px;
line-height: 30px;
}
.leaflet-touch .leaflet-bar a:first-child {
border-top-left-radius: 2px;
border-top-right-radius: 2px;
}
.leaflet-touch .leaflet-bar a:last-child {
border-bottom-left-radius: 2px;
border-bottom-right-radius: 2px;
}
/* zoom control */
.leaflet-control-zoom-in,
.leaflet-control-zoom-out {
font: bold 18px 'Lucida Console', Monaco, monospace;
text-indent: 1px;
}
.leaflet-touch .leaflet-control-zoom-in, .leaflet-touch .leaflet-control-zoom-out {
font-size: 22px;
}
/* layers control */
.leaflet-control-layers {
box-shadow: 0 1px 5px rgba(0,0,0,0.4);
background: #fff;
border-radius: 5px;
}
.leaflet-control-layers-toggle {
background-image: url(images/layers.png);
width: 36px;
height: 36px;
}
.leaflet-retina .leaflet-control-layers-toggle {
background-image: url(images/layers-2x.png);
background-size: 26px 26px;
}
.leaflet-touch .leaflet-control-layers-toggle {
width: 44px;
height: 44px;
}
.leaflet-control-layers .leaflet-control-layers-list,
.leaflet-control-layers-expanded .leaflet-control-layers-toggle {
display: none;
}
.leaflet-control-layers-expanded .leaflet-control-layers-list {
display: block;
position: relative;
}
.leaflet-control-layers-expanded {
padding: 6px 10px 6px 6px;
color: #333;
background: #fff;
}
.leaflet-control-layers-scrollbar {
overflow-y: scroll;
overflow-x: hidden;
padding-right: 5px;
}
.leaflet-control-layers-selector {
margin-top: 2px;
position: relative;
top: 1px;
}
.leaflet-control-layers label {
display: block;
font-size: 13px;
font-size: 1.08333em;
}
.leaflet-control-layers-separator {
height: 0;
border-top: 1px solid #ddd;
margin: 5px -10px 5px -6px;
}
/* Default icon URLs */
.leaflet-default-icon-path { /* used only in path-guessing heuristic, see L.Icon.Default */
background-image: url(images/marker-icon.png);
}
/* attribution and scale controls */
.leaflet-container .leaflet-control-attribution {
background: #fff;
background: rgba(255, 255, 255, 0.8);
margin: 0;
}
.leaflet-control-attribution,
.leaflet-control-scale-line {
padding: 0 5px;
color: #333;
line-height: 1.4;
}
.leaflet-control-attribution a {
text-decoration: none;
}
.leaflet-control-attribution a:hover,
.leaflet-control-attribution a:focus {
text-decoration: underline;
}
.leaflet-attribution-flag {
display: inline !important;
vertical-align: baseline !important;
width: 1em;
height: 0.6669em;
}
.leaflet-left .leaflet-control-scale {
margin-left: 5px;
}
.leaflet-bottom .leaflet-control-scale {
margin-bottom: 5px;
}
.leaflet-control-scale-line {
border: 2px solid #777;
border-top: none;
line-height: 1.1;
padding: 2px 5px 1px;
white-space: nowrap;
-moz-box-sizing: border-box;
box-sizing: border-box;
background: rgba(255, 255, 255, 0.8);
text-shadow: 1px 1px #fff;
}
.leaflet-control-scale-line:not(:first-child) {
border-top: 2px solid #777;
border-bottom: none;
margin-top: -2px;
}
.leaflet-control-scale-line:not(:first-child):not(:last-child) {
border-bottom: 2px solid #777;
}
.leaflet-touch .leaflet-control-attribution,
.leaflet-touch .leaflet-control-layers,
.leaflet-touch .leaflet-bar {
box-shadow: none;
}
.leaflet-touch .leaflet-control-layers,
.leaflet-touch .leaflet-bar {
border: 2px solid rgba(0,0,0,0.2);
background-clip: padding-box;
}
/* popup */
.leaflet-popup {
position: absolute;
text-align: center;
margin-bottom: 20px;
}
.leaflet-popup-content-wrapper {
padding: 1px;
text-align: left;
border-radius: 12px;
}
.leaflet-popup-content {
margin: 13px 24px 13px 20px;
line-height: 1.3;
font-size: 13px;
font-size: 1.08333em;
min-height: 1px;
}
.leaflet-popup-content p {
margin: 17px 0;
margin: 1.3em 0;
}
.leaflet-popup-tip-container {
width: 40px;
height: 20px;
position: absolute;
left: 50%;
margin-top: -1px;
margin-left: -20px;
overflow: hidden;
pointer-events: none;
}
.leaflet-popup-tip {
width: 17px;
height: 17px;
padding: 1px;
margin: -10px auto 0;
pointer-events: auto;
-webkit-transform: rotate(45deg);
-moz-transform: rotate(45deg);
-ms-transform: rotate(45deg);
transform: rotate(45deg);
}
.leaflet-popup-content-wrapper,
.leaflet-popup-tip {
background: white;
color: #333;
box-shadow: 0 3px 14px rgba(0,0,0,0.4);
}
.leaflet-container a.leaflet-popup-close-button {
position: absolute;
top: 0;
right: 0;
border: none;
text-align: center;
width: 24px;
height: 24px;
font: 16px/24px Tahoma, Verdana, sans-serif;
color: #757575;
text-decoration: none;
background: transparent;
}
.leaflet-container a.leaflet-popup-close-button:hover,
.leaflet-container a.leaflet-popup-close-button:focus {
color: #585858;
}
.leaflet-popup-scrolled {
overflow: auto;
}
.leaflet-oldie .leaflet-popup-content-wrapper {
-ms-zoom: 1;
}
.leaflet-oldie .leaflet-popup-tip {
width: 24px;
margin: 0 auto;
-ms-filter: "progid:DXImageTransform.Microsoft.Matrix(M11=0.70710678, M12=0.70710678, M21=-0.70710678, M22=0.70710678)";
filter: progid:DXImageTransform.Microsoft.Matrix(M11=0.70710678, M12=0.70710678, M21=-0.70710678, M22=0.70710678);
}
.leaflet-oldie .leaflet-control-zoom,
.leaflet-oldie .leaflet-control-layers,
.leaflet-oldie .leaflet-popup-content-wrapper,
.leaflet-oldie .leaflet-popup-tip {
border: 1px solid #999;
}
/* div icon */
.leaflet-div-icon {
background: #fff;
border: 1px solid #666;
}
/* Tooltip */
/* Base styles for the element that has a tooltip */
.leaflet-tooltip {
position: absolute;
padding: 6px;
background-color: #fff;
border: 1px solid #fff;
border-radius: 3px;
color: #222;
white-space: nowrap;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
pointer-events: none;
box-shadow: 0 1px 3px rgba(0,0,0,0.4);
}
.leaflet-tooltip.leaflet-interactive {
cursor: pointer;
pointer-events: auto;
}
.leaflet-tooltip-top:before,
.leaflet-tooltip-bottom:before,
.leaflet-tooltip-left:before,
.leaflet-tooltip-right:before {
position: absolute;
pointer-events: none;
border: 6px solid transparent;
background: transparent;
content: "";
}
/* Directions */
.leaflet-tooltip-bottom {
margin-top: 6px;
}
.leaflet-tooltip-top {
margin-top: -6px;
}
.leaflet-tooltip-bottom:before,
.leaflet-tooltip-top:before {
left: 50%;
margin-left: -6px;
}
.leaflet-tooltip-top:before {
bottom: 0;
margin-bottom: -12px;
border-top-color: #fff;
}
.leaflet-tooltip-bottom:before {
top: 0;
margin-top: -12px;
margin-left: -6px;
border-bottom-color: #fff;
}
.leaflet-tooltip-left {
margin-left: -6px;
}
.leaflet-tooltip-right {
margin-left: 6px;
}
.leaflet-tooltip-left:before,
.leaflet-tooltip-right:before {
top: 50%;
margin-top: -6px;
}
.leaflet-tooltip-left:before {
right: 0;
margin-right: -12px;
border-left-color: #fff;
}
.leaflet-tooltip-right:before {
left: 0;
margin-left: -12px;
border-right-color: #fff;
}
/* Printing */
@media print {
/* Prevent printers from removing background-images of controls. */
.leaflet-control {
-webkit-print-color-adjust: exact;
print-color-adjust: exact;
}
}
File diff suppressed because one or more lines are too long
+11
View File
@@ -0,0 +1,11 @@
{% if pagination and pagination.pages > 1 %}
<nav class="pagination" aria-label="Pagination">
{% if pagination.has_prev %}
<a class="btn" rel="prev" href="{{ pagination.prev_url }}">&larr; Newer posts</a>
{% endif %}
<span class="pagination-info">Page {{ pagination.page }} of {{ pagination.pages }}</span>
{% if pagination.has_next %}
<a class="btn" rel="next" href="{{ pagination.next_url }}">Older posts &rarr;</a>
{% endif %}
</nav>
{% endif %}
+141
View File
@@ -0,0 +1,141 @@
{% extends "admin/base.html" %}
{% block title %}Albums &middot; {{ site_title }}{% endblock %}
{% block admin_content %}
<h1>Albums</h1>
<div class="admin-panel">
<h2>Upload a photo to an album</h2>
<form id="album-upload-form" method="POST" action="{{ url_for('admin.upload') }}" enctype="multipart/form-data" class="stack">
<input type="hidden" name="csrf_token" value="{{ csrf_token }}">
<div class="form-group">
<label for="album-photo-file">Photo file</label>
<input type="file" id="album-photo-file" name="file" accept="image/*" multiple required>
<small>Choose one or more photos to add to this album.</small>
</div>
<div class="form-group">
<label for="album-photo-album">Album</label>
<select id="album-photo-album" name="album" required>
{% for a in albums %}
<option value="{{ a.slug }}">{{ a.name }}</option>
{% endfor %}
</select>
</div>
<button type="submit" class="btn btn-primary">Upload photo</button>
</form>
</div>
<div class="admin-panel">
<h2>New album</h2>
<form method="POST" action="{{ url_for('admin.album_new') }}" class="stack">
<input type="hidden" name="csrf_token" value="{{ csrf_token }}">
<div class="form-group">
<label for="name">Album name</label>
<input type="text" id="name" name="name" placeholder="e.g. Road trip 2026" required>
</div>
<div class="form-group">
<label for="description">Description</label>
<textarea id="description" name="description" rows="3"></textarea>
</div>
<button type="submit" class="btn btn-primary">Create album</button>
</form>
</div>
{% if editing %}
<div class="admin-panel">
<h2>Edit: {{ editing.name }}</h2>
<form method="POST" action="{{ url_for('admin.album_edit', slug=editing.slug) }}" class="stack">
<input type="hidden" name="csrf_token" value="{{ csrf_token }}">
<div class="form-group">
<label for="name">Album name</label>
<input type="text" id="name" name="name" value="{{ editing.name }}" required>
</div>
<div class="form-group">
<label for="description">Description</label>
<textarea id="description" name="description" rows="3">{{ editing.description or '' }}</textarea>
</div>
<button type="submit" class="btn btn-primary">Save changes</button>
</form>
</div>
{% endif %}
<div class="admin-panel">
<h2>All albums</h2>
{% if albums %}
<table class="admin-table">
<thead><tr><th>Name</th><th>Photos</th><th></th></tr></thead>
<tbody>
{% for a in albums %}
<tr>
<td><a href="{{ url_for('public.photos', slug=a.slug) }}">{{ a.name }}</a></td>
<td>{{ album_counts.get(a.id, 0) }}</td>
<td>
<a class="primary" href="{{ url_for('admin.album_edit', slug=a.slug) }}">Edit</a>
<span class="field-hint">·</span>
<form method="POST" action="{{ url_for('admin.album_delete', slug=a.slug) }}" style="display:inline;" onsubmit="return confirm('Delete this album? Its photos stay, but become ungrouped.');">
<input type="hidden" name="csrf_token" value="{{ csrf_token }}">
<button class="btn btn-danger" type="submit">Delete</button>
</form>
</td>
</tr>
{% endfor %}
</tbody>
</table>
{% else %}
<p class="empty-state">No albums yet.</p>
{% endif %}
</div>
{% if ungrouped_count %}
<p><a class="primary" href="{{ url_for('admin.media_list') }}">Manage photos ({{ ungrouped_count }} ungrouped)</a></p>
{% endif %}
<script>
// NOTE: one file per request, with FormData built from scratch. Cloning the
// form (new FormData(form)) also re-sends the <input type="file"> parts, so
// the server stored the selected photo twice.
// NOTE: every upload is awaited before location.reload(). The old version
// fired all the fetches and reloaded synchronously in the same tick, which
// aborted the in-flight requests — the album came back unchanged, so uploads
// looked broken even though /admin/upload was healthy.
(function () {
var form = document.getElementById("album-upload-form");
if (!form) return;
form.addEventListener("submit", async function (e) {
e.preventDefault();
var fileInput = form.elements["album-photo-file"];
var files = Array.prototype.slice.call(fileInput.files);
if (!files.length) { alert("Choose one or more photos."); return; }
var album = form.elements["album-photo-album"].value;
var albumName = album ? form.elements["album-photo-album"].options[form.elements["album-photo-album"].selectedIndex].text : "";
var csrf = form.elements["csrf_token"].value;
var btn = form.querySelector("button[type=submit]");
btn.disabled = true;
var ok = 0, failed = [];
for (var i = 0; i < files.length; i++) {
btn.textContent = "Uploading " + (i + 1) + "/" + files.length + "...";
var fd = new FormData();
fd.append("csrf_token", csrf);
if (album) fd.append("album", album);
fd.append("file", files[i], files[i].name);
try {
var r = await fetch(form.action, { method: "POST", credentials: "same-origin", body: fd });
if (!r.ok) throw new Error("HTTP " + r.status);
await r.json();
ok++;
} catch (err) {
failed.push(files[i].name + ": " + err.message);
}
}
btn.disabled = false;
btn.textContent = "Upload photo";
if (failed.length) {
alert(ok + " added to '" + albumName + "', " + failed.length + " failed:\n" + failed.join("\n"));
} else {
alert(ok + " photo" + (ok === 1 ? "" : "s") + " added to '" + albumName + "'.");
}
location.reload();
});
})();
</script>
{% endblock %}
+187
View File
@@ -0,0 +1,187 @@
{% extends "admin/base.html" %}
{% block head_extra %}
<link rel="stylesheet" href="{{ url_for('static', filename='vendor/leaflet/leaflet.css') }}">
{% endblock %}
{% block admin_content %}
<div class="admin-panel">
<h1>Analytics</h1>
<p class="muted">Anonymous visitor tracking. Only an opaque <code>visitor_id</code> cookie is stored; locations are approximate and derived from the visitor's IP — the address itself is never saved.</p>
<div class="admin-stat-grid">
<div class="admin-stat"><span class="num">{{ total_visitors }}</span><span class="label">Unique visitors</span></div>
<div class="admin-stat"><span class="num">{{ total_visits }}</span><span class="label">Total visits</span></div>
<div class="admin-stat"><span class="num">{{ unique_pages }}</span><span class="label">Pages viewed</span></div>
<div class="admin-stat"><span class="num">{{ 'n/a' if total_visitors == 0 else (total_visits | int / (total_visitors or 1) | round(2)) }}</span><span class="label">Avg. pages/visit</span></div>
<div class="admin-stat"><span class="num">{{ total_countries }}</span><span class="label">Countries</span></div>
<div class="admin-stat"><span class="num">{{ total_cities }}</span><span class="label">Cities</span></div>
</div>
</div>
<div class="admin-panel">
<h2>Visitor map</h2>
{% if map_points %}
<p class="muted">Each circle is a city. Larger circles mean more visits — click one for the city, region, country and counts.</p>
{% else %}
<p class="empty-state">No location data yet. The map fills in as visitors arrive; locations come from the visitor's IP (or, for local/LAN visitors, this server's own region).</p>
{% endif %}
<div id="visitor-map" class="visitor-map"></div>
</div>
<div class="admin-panel">
<h2>Location trends</h2>
{% if location_trend.series %}
<p class="muted">Visits per day over the last {{ location_trend.labels|length }} days, by location. Hover the chart for daily counts.</p>
<div class="chart-wrap"><canvas id="location-trend-chart" height="280"></canvas></div>
<div id="location-trend-legend" class="chart-legend"></div>
{% else %}
<p class="empty-state">No visits in the last 30 days.</p>
{% endif %}
</div>
<div class="admin-panel">
<div class="admin-split">
<div>
<h2>Top countries</h2>
<table class="admin-table">
<thead><tr><th>Country</th><th>Visitors</th><th>Visits</th></tr></thead>
<tbody>
{% for r in top_countries %}
<tr>
<td>{% if r.country_code %}<span class="location-flag">{{ r.country_code|country_flag }}</span> {% endif %}{{ r.country }}</td>
<td>{{ r.visitors }}</td>
<td>{{ r.visits }}</td>
</tr>
{% else %}
<tr><td colspan="3" class="empty-state">No location data yet.</td></tr>
{% endfor %}
</tbody>
</table>
</div>
<div>
<h2>Top cities</h2>
<table class="admin-table">
<thead><tr><th>City</th><th>Visitors</th><th>Visits</th></tr></thead>
<tbody>
{% for r in top_cities %}
<tr>
<td>
{% if r.country_code %}<span class="location-flag">{{ r.country_code|country_flag }}</span> {% endif %}{{ r.city }}
<span class="muted">{% if r.region %}{{ r.region }}, {% endif %}{{ r.country }}</span>
</td>
<td>{{ r.visitors }}</td>
<td>{{ r.visits }}</td>
</tr>
{% else %}
<tr><td colspan="3" class="empty-state">No city data yet.</td></tr>
{% endfor %}
</tbody>
</table>
</div>
</div>
</div>
<div class="admin-panel">
<h2>Where visitors to each page come from</h2>
{% if page_locations %}
<p class="muted">The busiest pages and the countries their readers came from. Counts are unique visitors per country.</p>
<table class="admin-table">
<thead><tr><th>Page</th><th>Top locations</th><th>Visits</th></tr></thead>
<tbody>
{% for page in page_locations %}
<tr>
<td>
<a href="{{ page.path }}"><code>{{ page.path }}</code></a>
{% if page.title %}<br><span class="muted">{{ page.title }}</span>{% endif %}
</td>
<td>
{% for c in page.countries %}
<span class="location-chip">{% if c.country_code %}{{ c.country_code|country_flag }} {% endif %}{{ c.country }} <strong>{{ c.visitors }}</strong></span>
{% endfor %}
{% if page.more_countries %}<span class="muted">+{{ page.more_countries }} more</span>{% endif %}
</td>
<td>{{ page.visits }}</td>
</tr>
{% endfor %}
</tbody>
</table>
{% else %}
<p class="empty-state">No page visits yet.</p>
{% endif %}
</div>
<div class="admin-panel">
<h2>Most viewed pages</h2>
<table class="admin-table">
<thead><tr><th>Page</th><th>Title</th><th>Visits</th></tr></thead>
<tbody>
{% for r in top_pages %}
<tr>
<td><code>{{ r.page_path }}</code></td>
<td>{{ r.title or "(untitled)" }}</td>
<td>{{ r.c }}</td>
</tr>
{% else %}
<tr><td colspan="3" class="empty-state">No visits yet.</td></tr>
{% endfor %}
</tbody>
</table>
</div>
<div class="admin-panel">
<h2>Devices</h2>
<table class="admin-table">
<thead><tr><th>Device</th><th>Visitors</th></tr></thead>
<tbody>
{% for r in top_devices %}
<tr><td>{{ r.device }}</td><td>{{ r.c }}</td></tr>
{% else %}
<tr><td colspan="2" class="empty-state">No data yet.</td></tr>
{% endfor %}
</tbody>
</table>
</div>
<div class="admin-panel">
<h2>Browsers</h2>
<table class="admin-table">
<thead><tr><th>Browser</th><th>Visitors</th></tr></thead>
<tbody>
{% for r in top_browsers %}
<tr><td>{{ r.browser or "(unknown)" }}</td><td>{{ r.c }}</td></tr>
{% else %}
<tr><td colspan="2" class="empty-state">No data yet.</td></tr>
{% endfor %}
</tbody>
</table>
</div>
<div class="admin-panel">
<h2>Where they came from</h2>
<table class="admin-table">
<thead><tr><th>Source</th><th>Visitors</th></tr></thead>
<tbody>
{% for r in top_sources %}
<tr><td>{{ r.source }}{% if loop.first %} <span class="term" style="font-size:.8em">(raw referrers below)</span>{% endif %}</td><td>{{ r.c }}</td></tr>
{% else %}
<tr><td colspan="2" class="empty-state">No data yet.</td></tr>
{% endfor %}
</tbody>
</table>
<table class="admin-table">
<thead><tr><th>Referrer domain</th><th>Visitors</th></tr></thead>
<tbody>
{% for r in top_domains %}
<tr><td>{{ r.referrer_domain or "&mdash;" }}</td><td>{{ r.c }}</td></tr>
{% else %}
<tr><td colspan="2" class="empty-state">No referrers yet.</td></tr>
{% endfor %}
</tbody>
</table>
</div>
<script type="application/json" id="visitor-map-data">{{ map_points | tojson }}</script>
{% if location_trend.series %}
<script type="application/json" id="location-trend-data">{{ location_trend | tojson }}</script>
{% endif %}
<script src="{{ url_for('static', filename='vendor/leaflet/leaflet.js') }}"></script>
<script src="{{ url_for('static', filename='js/admin_analytics.js') }}"></script>
{% endblock %}
+447
View File
@@ -0,0 +1,447 @@
{% extends "admin/base.html" %}
{% block admin_content %}
<div class="admin-panel">
<h1>Appearance</h1>
<!-- ==========================================================================
ONE FORM. Every control lives in a single <form>, so a single "Save all"
submits site_title / site_tagline / comments_enabled AND custom_css (the
merged theme + raw CSS) together. Because they are all submitted at once,
saving one section can no longer clobber another — the handler only writes
keys that are present in request.form, and here every key is always present.
Theme styling (accent / background / text / sidebar / font / columns /
header layout / radius / dark) is rendered into the raw-CSS textarea live
as you tweak the controls (see buildTheme() below), so that textarea is the
single source of truth for custom_css: it holds the generated :root block
plus any hand-written CSS you add. The "Reset theme to defaults" button
regenerates the :root block from the built-in defaults.
========================================================================== -->
<form id="appearance-form" method="post" action="{{ url_for('admin.appearance') }}" enctype="multipart/form-data">
<input type="hidden" name="csrf_token" value="{{ csrf_token }}">
<!-- --- Site identity ---------------------------------------------------- -->
<div class="admin-panel identity">
<h2>Site identity</h2>
<div class="form-row">
<div class="form-group">
<label for="site-title">Site title</label>
<input type="text" id="site-title" name="site_title" value="{{ site_title }}" autocomplete="off">
</div>
<div class="form-group">
<label for="site-tagline">Tagline / statement</label>
<input type="text" id="site-tagline" name="site_tagline" value="{{ site_tagline }}" autocomplete="off">
</div>
</div>
<div class="form-group">
<label for="meta-description">Default meta description</label>
<input type="text" id="meta-description" name="meta_description" value="{{ meta_description }}" autocomplete="off"
placeholder="Used by search engines and social previews when a page has no excerpt">
<span class="field-hint">Posts use their excerpt first; this is the fallback for home, archive, tag and other pages.</span>
</div>
<!-- Use radio buttons (not checkbox+hidden): a checkbox's unchecked state
omits the key, so the old hidden "0" trick relied on "0" being truthy,
which it isn't in Python — meaning admins could never switch comments
OFF via this page. Radios submit an explicit 1/0 that the route reads
verbatim. -->
<div class="form-group">
<label class="checkbox-label">
<input type="radio" name="comments_enabled" value="1" {% if comments_enabled %}checked{% endif %}>
Enable comments on posts and pages
</label>
<label class="checkbox-label">
<input type="radio" name="comments_enabled" value="0" {% if not comments_enabled %}checked{% endif %}>
Disable comments on posts and pages
</label>
</div>
</div>
<!-- --- Theme editor (GUI) ------------------------------------------------ -->
<div class="theme-editor">
<h2>Theme</h2>
<p class="field-hint">These controls render into the Custom CSS box below as you change them. Edit the box directly for anything more advanced.</p>
<!-- Colour controls -->
<div class="form-row">
<div class="form-group">
<label for="t-accent">Accent / link colour</label>
<div class="swatch-row">
<input type="color" id="t-accent" name="t-accent" value="{{ theme.accent }}">
<input type="text" id="t-accent-hex" class="hex-input" value="{{ theme.accent }}" spellcheck="false" autocomplete="off">
</div>
</div>
<div class="form-group">
<label for="t-bg">Page background</label>
<div class="swatch-row">
<input type="color" id="t-bg" name="t-bg" value="{{ theme.background }}">
<input type="text" id="t-bg-hex" class="hex-input" value="{{ theme.background }}" spellcheck="false" autocomplete="off">
</div>
</div>
</div>
<div class="form-row">
<div class="form-group">
<label for="t-text">Text colour</label>
<div class="swatch-row">
<input type="color" id="t-text" name="t-text" value="{{ theme.text }}">
<input type="text" id="t-text-hex" class="hex-input" value="{{ theme.text }}" spellcheck="false" autocomplete="off">
</div>
</div>
<div class="form-group">
<label for="t-sidebar">Sidebar / panel background</label>
<div class="swatch-row">
<input type="color" id="t-sidebar" name="t-sidebar" value="{{ theme.sidebar }}">
<input type="text" id="t-sidebar-hex" class="hex-input" value="{{ theme.sidebar }}" spellcheck="false" autocomplete="off">
</div>
</div>
<div class="form-group">
<label for="t-font">Font family</label>
<select id="t-font" name="t-font">
{% for opt in theme.fonts %}
<option value="{{ opt.value }}" {% if opt.value == theme.font %}selected{% endif %}>{{ opt.label }}</option>
{% endfor %}
</select>
</div>
</div>
<!-- Layout controls -->
<div class="form-row">
<div class="form-group">
<label for="t-posts">Post grid columns</label>
<select id="t-posts" name="t-posts">
{% for opt in theme.post_columns %}
<option value="{{ opt.value }}" {% if opt.value == theme.posts %}selected{% endif %}>{{ opt.label }}</option>
{% endfor %}
</select>
</div>
<div class="form-group">
<label for="t-header">Site header</label>
<select id="t-header" name="t-header">
{% for opt in theme.header_layouts %}
<option value="{{ opt.value }}" {% if opt.value == theme.header %}selected{% endif %}>{{ opt.label }}</option>
{% endfor %}
</select>
</div>
</div>
<div class="form-group">
<label for="t-radius">Corner radius: <span id="radius-val">{{ theme.radius }}px</span></label>
<input type="range" id="t-radius" name="t-radius" min="0" max="24" step="1" value="{{ theme.radius }}">
</div>
<label class="checkbox-label" for="t-dark">
<input type="checkbox" id="t-dark" name="t-dark" {% if theme.dark %}checked{% endif %}>
Enable dark mode
</label>
</div>
<!-- --- Raw custom CSS (single source of truth for custom_css) ------------- -->
<div class="admin-panel">
<h2>Custom CSS</h2>
<p class="field-hint">The theme variables above are rendered here live; add any extra rules below them.</p>
<div class="form-group">
<label for="custom-css-editor">Custom CSS</label>
<textarea id="custom-css-editor" rows="16" placeholder="body { background: #fff; }"></textarea>
<input type="hidden" id="custom-css-hidden" name="custom_css" value="{{ custom_css }}">
</div>
</div>
<!-- --- Header image ------------------------------------------------------ -->
<div class="admin-panel">
<h2>Header image</h2>
<p class="field-hint">Upload a banner/header image for the top of every public page. Leave blank to remove it.</p>
{% if header_image %}
<div class="form-group">
<label>Current header image</label>
<img src="{{ header_image }}" alt="{{ site_title }}" style="max-height:90px;width:auto;border:1px solid var(--color-border);border-radius:6px;">
<button type="submit" class="btn-danger" name="remove_header" value="1">Remove</button>
</div>
{% endif %}
<div class="form-group">
<label for="header-image">Header image</label>
<input type="file" id="header-image" name="header_image" accept="image/png,image/jpeg,image/gif,image/webp">
</div>
</div>
<!-- --- Actions ------------------------------------------------------------ -->
<div class="admin-panel">
<button type="submit" class="btn-primary">Save all</button>
<button type="button" id="reset-theme" class="btn-secondary">Reset theme to defaults</button>
</div>
</form>
<!-- Live preview of the themed site -->
<div class="theme-preview-wrap">
<h2>Live preview</h2>
<p class="field-hint">This mini-site uses the exact variables you just set. Changes update as you tweak them.</p>
<div id="theme-preview" class="theme-preview">
<style id="theme-vars"></style>
<header class="site-header" id="preview-header">
<div class="header-inner">
<div class="site-logo"><span id="preview-logo">{{ site_title }}</span></div>
<nav class="main-nav" aria-label="preview nav">
<button type="button" id="preview-menu">Menu</button>
<ul class="nav-menu" id="preview-nav">
<li><a href="#!">Dashboard</a></li>
<li><a href="#!">Posts</a></li>
<li><a href="#!">Categories</a></li>
</ul>
</nav>
</div>
</header>
<main class="site-main" id="preview-main">
<p class="page-heading"><a href="#!">{{ site_title }}</a></p>
<section class="posts-grid" id="preview-posts">
{% for _i in range(0, 6) %}
<article class="post-card">
<h2><a href="#!">I Spent weeks Fighting My Local AI Coding Agent — Here's Everything I Learned</a></h2>
<p class="post-meta"><span>October 27, 2026 by brian</span></p>
<div class="post-excerpt">
<p>How I built a coding agent that runs entirely on my own hardware — no API, no cloud, no monthly bill — and the build steps that actually work. A while back I decided I wanted a coding agent I could leave running without paying for it.</p>
<p>Something that …</p>
</div>
<div class="post-tags"><span class="tag-icon">📁</span><a class="tag" href="#!">ai</a><a class="tag" href="#!">emerging_technology</a><a class="tag" href="#!">thoughts</a></div>
<div class="post-footer"><a href="#!" class="read-more">Read more →</a><a href="#!" class="comment-link">💬 Leave a comment</a></div>
</article>
{% endfor %}
</section>
</main>
</div>
</div>
<style>
/* --- Theme editor controls ------------------------------------------------- */
.theme-editor { border: 1px solid var(--color-border); border-radius: 8px; padding: 20px 24px; }
.swatch-row { display: flex; align-items: center; gap: 12px; margin-top: 6px; }
.swatch-row input[type="color"] { width: 56px; height: 40px; padding: 3px; border: 1px solid var(--color-border); border-radius: 6px; background: #fff; cursor: pointer; }
.swatch-row .hex-input { flex: 1; padding: 11px 12px; border: 1px solid var(--color-border); border-radius: 5px; font-family: var(--font-stack); }
.checkbox-label { display: flex; align-items: center; gap: 8px; margin: 16px 0 14px; font-size: 0.95rem; color: var(--color-text); }
.checkbox-label input { width: auto; }
/* --- Live preview (mini site) ---------------------------------------------- */
.theme-preview-wrap > h2 { margin-top: 0; }
.theme-preview { border: 1px solid var(--color-border); border-radius: 8px; overflow: hidden; background: #fff; }
.theme-preview .site-header { border-bottom-width: 2px; }
@media (max-width: 620px) {
.theme-preview .nav-menu { display: none !important; }
}
/* --- Action buttons -------------------------------------------------------- */
.admin-panel > .form-group:not(:last-of-type) button[type="submit"],
.admin-panel > .form-group:not(:last-of-type) input[type="file"] { margin-bottom: 12px; }
</style>
<script>
(function () {
// Defaults match the built-in theme.css :root so a fresh site looks unchanged.
var DEFAULTS = {
accent: '#00a0d1', background: '#ffffff', text: '#1e1e1e',
font: '"-apple-system", BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen, Ubuntu, Cantarell, "Helvetica Neue", Arial, sans-serif',
posts: 1, header: 'side', radius: 6, dark: false
};
var state = {
accent: document.getElementById('t-accent').value,
background: document.getElementById('t-bg').value,
text: document.getElementById('t-text').value,
sidebar: document.getElementById('t-sidebar').value,
font: document.getElementById('t-font').value,
posts: document.getElementById('t-posts').value,
header: document.getElementById('t-header').value,
radius: document.getElementById('t-radius').value,
dark: document.getElementById('t-dark').checked
};
function toHex(col) {
try { return getComputedStyle(document.documentElement || { style: function () {} }).getPropertyValue('color').trim(); } catch (e) {}
var c = document.createElement('canvas').getContext('2d');
c.fillStyle = col; return '#' + c.fillStyle.toString().slice(4);
}
// Build the :root variable block + grid/header rules as a CSS string. This is
// exactly what gets spliced into the raw-CSS textarea on submit (and reset), so
// the textarea stays the single source of truth for custom_css.
function buildTheme() {
var light = [
['--color-accent', state.accent],
['--color-link', state.accent],
['--color-link-hover', shade(state.accent, -18)],
['--color-text', state.text],
['--color-muted', lerpAlpha(state.text, 0.55)],
['--color-border', lerpAlpha(state.text, 0.92)],
['--color-bg', state.background],
['--color-sidebar-bg', state.sidebar],
['--color-card-bg', '#f7f8fa'],
['--font-stack', state.font],
['--border-radius', Math.round(Number(state.radius)) + 'px']
];
var dark = [
['--color-accent', state.accent],
['--color-link', state.accent],
['--color-link-hover', shade(state.accent, -22)],
['--color-text', state.text],
['--color-muted', lerpAlpha(state.text, 0.55)],
['--color-border', lerpAlpha(state.text, 0.92)],
['--color-bg', state.background],
['--color-sidebar-bg', state.sidebar],
['--color-card-bg', 'rgba(255, 255, 255, 0.03)'],
['--font-stack', state.font],
['--border-radius', Math.round(Number(state.radius)) + 'px']
];
var vars = (state.dark ? dark : light).map(function (pair) { return pair.join(':') + ';'; }).join('\n ');
var rules = [];
var cols = Number(state.posts);
rules.push('.posts-grid { grid-template-columns: repeat(' + cols + ', 1fr); }');
rules.push('#preview-header { flex-direction: ' + (state.header === 'stacked' ? 'column' : 'row') + '; }');
var out = ':root {\n' + vars + '\n}\n';
if (rules.length) out += '\n' + rules.join('\n') + '\n';
// Emit an explicit marker when dark mode is on. The old detection looked for
// a literal #121212/#1c1c1c background, but buildTheme() writes --color-bg
// from the chosen colour — so a custom dark background would silently lose
// dark mode on reload. This marker is unambiguous and always present in dark.
if (state.dark) out += '/* theme-dark */\n';
return out;
}
function renderVars() { document.getElementById('theme-vars').textContent = buildTheme(); }
// The hidden field is the single source of truth for custom_css. It always holds
// the generated theme block (from buildTheme()) followed by whatever manual CSS the
// user has typed in the editor. This avoids parsing/stripping the textarea on every
// change — no risk of duplicating the grid rules, dark marker, or manual CSS.
function setHidden() {
var ta = document.getElementById('custom-css-editor');
var hidden = document.getElementById('custom-css-hidden');
hidden.value = buildTheme() + '\n\n' + (ta.value || '');
}
// On load: the hidden field already holds the stored custom_css (from {{ custom_css }}).
// Split it into the generated block + manual CSS and show only the manual CSS in the
// editor. Any later change to a control or a keystroke rebuilds the hidden field.
function loadEditor() {
var ta = document.getElementById('custom-css-editor');
var stored = document.getElementById('custom-css-hidden').value;
var gen = buildTheme();
var match = new RegExp('^' + gen.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')).exec(stored);
ta.value = match ? stored.slice(match[0].length) : stored;
}
document.getElementById('custom-css-editor').addEventListener('input', function () {
setHidden();
});
// Apply the current state to the live preview DOM.
function applyPreview() {
var root = document.documentElement;
root.style.setProperty('--color-accent', state.accent);
root.style.setProperty('--color-link', state.accent);
root.style.setProperty('--color-link-hover', shade(state.accent, -18));
root.style.setProperty('--color-text', state.text);
root.style.setProperty('--color-bg', state.background);
root.style.setProperty('--font-stack', state.font);
root.style.setProperty('--color-sidebar-bg', state.sidebar);
document.getElementById('preview-posts').style.gridTemplateColumns = 'repeat(' + state.posts + ', 1fr)';
document.getElementById('preview-header').style.flexDirection = state.header === 'stacked' ? 'column' : 'row';
document.getElementById('preview-header').style.alignItems = state.header === 'stacked' ? 'stretch' : 'center';
var r = Math.round(Number(state.radius));
['post-card', '.site-header', '#preview-logo'].forEach(function (sel) {
var el = document.querySelector(sel);
if (el) el.style.borderRadius = r + 'px';
});
document.getElementById('theme-preview').classList.toggle('dark', state.dark);
}
function shade(hex, pct) {
var m = hex.replace('#', '');
if (m.length === 3) m = m.split('').map(function (c) { return c + c; }).join('');
var num = parseInt(m, 16);
var r = Math.max(0, Math.min(255, ((num >> 16) & 255) + pct));
var g = Math.max(0, Math.min(255, ((num >> 8) & 255) + pct));
var b = Math.max(0, Math.min(255, (num & 255) + pct));
return '#' + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1);
}
function lerpAlpha(hex, alpha) {
var m = hex.replace('#', '');
if (m.length === 3) m = m.split('').map(function (c) { return c + c; }).join('');
var num = parseInt(m, 16);
var r = (num >> 16) & 255, g = (num >> 8) & 255, b = num & 255;
return 'rgba(' + r + ',' + g + ',' + b + ',' + alpha + ')';
}
function syncRadiusLabel() { document.getElementById('radius-val').textContent = state.radius + 'px'; }
function bindPair(pickerId, hexId) {
var picker = document.getElementById(pickerId), hex = document.getElementById(hexId);
picker.addEventListener('input', function () {
state[pickerId.slice(2)] = picker.value;
hex.value = picker.value;
setHidden(); renderVars(); applyPreview();
});
hex.addEventListener('input', function () {
var v = hex.value.trim().replace(/^#/, '');
if (/^[\da-fA-F]{6}$/.test(v)) {
state[pickerId.slice(2)] = '#' + v;
picker.value = '#' + v;
setHidden(); renderVars(); applyPreview();
}
});
}
function bind() {
bindPair('t-accent', 't-accent-hex');
bindPair('t-bg', 't-bg-hex');
bindPair('t-text', 't-text-hex');
bindPair('t-sidebar', 't-sidebar-hex');
['t-font', 't-posts', 't-header'].forEach(function (id) {
document.getElementById(id).addEventListener('change', function () {
state[id.slice(2)] = document.getElementById(id).value;
setHidden(); renderVars(); applyPreview(); syncRadiusLabel();
});
});
document.getElementById('t-radius').addEventListener('input', function () {
state.radius = this.value;
document.getElementById('radius-val').textContent = this.value + 'px';
setHidden(); renderVars(); applyPreview();
});
document.getElementById('t-dark').addEventListener('change', function () {
state.dark = this.checked;
setHidden(); renderVars(); applyPreview();
});
// Reset theme controls (and the raw-CSS textarea's generated block) to defaults.
document.getElementById('reset-theme').addEventListener('click', function () {
var form = document.getElementById('appearance-form');
var set = function (id, v) { var el = document.getElementById(id); if (el) el.value = v; };
set('site-title', 'My Blog');
set('site-tagline', 'Thoughts on tech, self-hosting and life.');
set('t-accent', DEFAULTS.accent);
set('t-bg', DEFAULTS.background);
set('t-text', DEFAULTS.text);
set('t-sidebar', DEFAULTS.sidebar);
set('t-font', DEFAULTS.font);
set('t-posts', DEFAULTS.posts);
set('t-header', DEFAULTS.header);
set('t-radius', DEFAULTS.radius);
var dark = document.getElementById('t-dark'); if (dark) dark.checked = DEFAULTS.dark;
// Clear any manual CSS the user typed, then rebuild the hidden field from defaults.
document.getElementById('custom-css-editor').value = '';
setHidden(); renderVars(); applyPreview();
});
}
bind();
renderVars();
loadEditor();
applyPreview();
})();
</script>
{% endblock %}
+103
View File
@@ -0,0 +1,103 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
{# Routes that don't pass active_page (posts, comments, …) get their label
from the endpoint, so every admin tab is named correctly. #}
{% set page_label = (active_page or (request.endpoint or 'dashboard').rsplit('.', 1)[-1])|replace('_', ' ')|replace('-', ' ')|title %}
<title>{{ page_label }} &middot; {{ site_title }}</title>
<link rel="stylesheet" href="{{ url_for('static', filename='css/style.css') }}">
<link rel="stylesheet" href="{{ url_for('static', filename='css/admin.css') }}">
<!-- TinyMCE oxide skin (UI + content styles), served locally. -->
<link rel="stylesheet" href="{{ url_for('static', filename='js/skins/ui/oxide/skin.min.css') }}">
<link rel="stylesheet" href="{{ url_for('static', filename='js/skins/ui/oxide/content.min.css') }}">
<!-- TinyMCE WYSIWYG editor (replaces the Quill/TipTap build). Loaded locally in <head>;
it only initializes on pages containing a #body-editor element. Community edition,
no license key → no tin.cloud validation; theme/skin assets are served from /static/js/. -->
<!-- Absolute base is REQUIRED: this app is a subpath (/admin/*) and TinyMCE resolves its
theme/skin assets against the document root, so a relative path would 404. An absolute
base_url makes every asset resolve correctly regardless of subpath. Update host/port
here if you ever redeploy elsewhere. -->
{# Relative asset base (NOT absolute). Resolves against the PAGE origin, so tinymce assets
follow whatever protocol/host loads the page — works behind reverse proxies (https://domain,
http://IP, LAN host) without needing X-Forwarded-Proto or per-host edits. An absolute base
would be forced to http(s) as Flask sees it internally and break Mixed Content on HTTPS. #}
{# js_base has NO trailing slash; callers add the needed '/' themselves so paths stay clean #}
{% set js_base = "/static/js" %}
<script>
window.tinyMCEPreInit = { base: '{{ js_base }}', suffix: '.min' };
</script>
<script src="{{ url_for('static', filename='js/tinymce.min.js') }}"></script>
{% block head_extra %}{% endblock %}
</head>
<body>
<header class="admin-header">
<div class="header-inner">
<div class="site-logo"><a href="{{ url_for('admin.dashboard') }}">{{ site_title }}</a></div>
<nav class="main-nav" aria-label="Admin navigation">
<button type="button" aria-expanded="false" id="menuButton">Menu</button>
<ul class="nav-menu" id="navMenu" role="menu">
<li role="none"><a href="{{ url_for('admin.dashboard') }}" role="menuitem">Dashboard</a></li>
<li role="none"><a href="{{ url_for('admin.posts') }}" role="menuitem">Posts</a></li>
<li role="none"><a href="{{ url_for('admin.categories') }}" role="menuitem">Categories</a></li>
<li role="none"><a href="{{ url_for('admin.albums') }}" role="menuitem">Albums</a></li>
<li role="none"><a href="{{ url_for('admin.media_list') }}" role="menuitem">Media</a></li>
<li role="none"><a href="{{ url_for('admin.comments') }}" role="menuitem">Comments{% if pending_comments %}<span class="nav-badge" title="{{ pending_comments }} awaiting moderation">{{ pending_comments }}</span>{% endif %}</a></li>
<li role="none"><a href="{{ url_for('admin.analytics') }}" role="menuitem">Analytics</a></li>
<li role="none"><a href="{{ url_for('admin.visitors') }}" role="menuitem">Visitors</a></li>
<li role="none"><a href="{{ url_for('admin.import_export') }}" role="menuitem">Import/Export</a></li>
<li role="none"><a href="{{ url_for('admin.admin_password') }}" role="menuitem">Password</a></li>
<li role="none"><a href="{{ url_for('public.index') }}" role="menuitem">View site</a></li>
<li role="none">
<form method="post" action="{{ url_for('admin.admin_logout') }}" class="logout-form">
<input type="hidden" name="csrf_token" value="{{ csrf_token }}">
<button type="submit" role="menuitem" class="link-button">Log out</button>
</form>
</li>
</ul>
</nav>
</div>
</header>
<div class="admin-subnav">
<a href="{{ url_for('admin.dashboard') }}" class="{% if active_page == 'dashboard' %}active{% endif %}">Dashboard</a>
<a href="{{ url_for('admin.posts') }}" class="{% if active_page == 'posts' %}active{% endif %}">Posts</a>
<a href="{{ url_for('admin.categories') }}" class="{% if active_page == 'categories' %}active{% endif %}">Categories</a>
<a href="{{ url_for('admin.albums') }}" class="{% if active_page == 'albums' %}active{% endif %}">Albums</a>
<a href="{{ url_for('admin.media_list') }}" class="{% if active_page == 'media' %}active{% endif %}">Media</a>
<a href="{{ url_for('admin.comments') }}" class="{% if active_page == 'comments' %}active{% endif %}">Comments{% if pending_comments %}<span class="nav-badge">{{ pending_comments }}</span>{% endif %}</a>
<a href="{{ url_for('admin.pages') }}" class="{% if active_page == 'pages' %}active{% endif %}">Pages</a>
<a href="{{ url_for('admin.links') }}" class="{% if active_page == 'links' %}active{% endif %}">Links</a>
<a href="{{ url_for('admin.appearance') }}" class="{% if active_page == 'appearance' %}active{% endif %}">Appearance</a>
<a href="{{ url_for('admin.analytics') }}" class="{% if active_page == 'analytics' %}active{% endif %}">Analytics</a>
<a href="{{ url_for('admin.visitors') }}" class="{% if active_page == 'visitors' %}active{% endif %}">Visitors</a>
<a href="{{ url_for('admin.import_export') }}" class="{% if active_page == 'import-export' %}active{% endif %}">Import/Export</a>
<a href="{{ url_for('admin.admin_password') }}" class="{% if active_page == 'password' %}active{% endif %}">Password</a>
</div>
<div class="admin-wrap">
{% with messages = get_flashed_messages(with_categories=true) %}
{% for category, message in messages %}
<div class="notice notice-{{ category }}">{{ message }}</div>
{% endfor %}
{% endwith %}
{% block admin_content %}{% endblock %}
</div>
<script>
(function () {
var btn = document.getElementById("menuButton");
var menu = document.getElementById("navMenu");
if (btn && menu) {
btn.addEventListener("click", function () {
var open = menu.classList.toggle("open");
btn.setAttribute("aria-expanded", String(open));
});
}
})();
</script>
<!-- (Quill + turndown removed; TinyMCE is loaded in <head> and initializes
only on pages containing a #body-editor element.) -->
</body>
</html>
+51
View File
@@ -0,0 +1,51 @@
{% extends "admin/base.html" %}
{% block admin_content %}
<div class="admin-panel">
<h1>Categories</h1>
<div class="admin-actions">
<a class="primary" href="{{ url_for('admin.category_new') }}">+ New category</a>
</div>
{% if categories is not none %}
<table class="admin-table">
<thead>
<tr><th>Name</th><th>Slug</th><th style="width:120px;">Actions</th></tr>
</thead>
<tbody>
{% for slug, name in categories %}
<tr class="category-row">
<td>{{ name }}</td>
<td><code>{{ slug }}</code></td>
<td>
{% if slug != 'general' %}
<form method="post" action="{{ url_for('admin.category_delete', slug=slug) }}" style="display:inline;" onsubmit="return confirm('Delete this category?');">
<input type="hidden" name="csrf_token" value="{{ csrf_token }}">
<button class="btn btn-danger" type="submit">Delete</button>
</form>
{% else %}
<span class="field-hint">Default — cannot be deleted</span>
{% endif %}
</td>
</tr>
{% endfor %}
</tbody>
</table>
{% else %}
<p class="empty-state">No categories yet.</p>
{% endif %}
</div>
{% if categories is none %}
<div class="admin-panel">
<h2>Add a category</h2>
<form method="post" action="{{ url_for('admin.category_new') }}">
<input type="hidden" name="csrf_token" value="{{ csrf_token }}">
<div class="form-group">
<label for="name">Category name</label>
<input type="text" id="name" name="name" placeholder="e.g. Technology" required>
</div>
<button type="submit" class="btn btn-primary">Create category</button>
</form>
</div>
{% endif %}
{% endblock %}
+99
View File
@@ -0,0 +1,99 @@
{% extends "admin/base.html" %}
{% block admin_content %}
<div class="admin-panel">
<h1>Comments</h1>
<div class="comment-stats">
<span class="term {% if counts.pending > 0 %}warn{% endif %}">{{ counts.pending }} pending</span>
<span>{{ counts.approved }} approved</span>
<span>{{ counts.rejected }} rejected</span>
<span>{{ counts.spam }} spam</span>
</div>
{% if comments or rejected or spam %}
{% if comments %}
<h2>Pending moderation</h2>
<div class="comment-mod-list">
{% for c in comments %}
<div class="comment-block comment-pending">
<div class="comment-meta">
<span class="comment-author">{{ c.author }}</span>
{% if c.email %}<span class="comment-email">{{ c.email }}</span>{% endif %}
<time datetime="{{ c.created_at }}">{{ parse_date(c.created_at) }}</time>
</div>
<div class="comment-body">{{ render_markdown(c.body) }}</div>
<div class="comment-actions">
<form method="post" action="{{ url_for('admin.comment_approve', cid=c.id) }}" style="display:inline;">
<input type="hidden" name="csrf_token" value="{{ csrf_token }}">
<button class="btn btn-sm btn-success" type="submit">Approve</button>
</form>
<form method="post" action="{{ url_for('admin.comment_reject', cid=c.id) }}" style="display:inline;">
<input type="hidden" name="csrf_token" value="{{ csrf_token }}">
<button class="btn btn-sm" type="submit">Reject</button>
</form>
<form method="post" action="{{ url_for('admin.comment_spam', cid=c.id) }}" style="display:inline;">
<input type="hidden" name="csrf_token" value="{{ csrf_token }}">
<button class="btn btn-sm btn-warning" type="submit">Spam</button>
</form>
<form method="post" action="{{ url_for('admin.comment_delete', cid=c.id) }}" style="display:inline;" onsubmit="return confirm('Delete this comment permanently?');">
<input type="hidden" name="csrf_token" value="{{ csrf_token }}">
<button class="btn btn-sm btn-danger" type="submit">Delete</button>
</form>
</div>
</div>
{% endfor %}
</div>
{% endif %}
{% if rejected %}
<h2>Rejected comments</h2>
<div class="comment-mod-list">
{% for c in rejected %}
<div class="comment-block comment-rejected">
<div class="comment-meta">
<span class="comment-author">{{ c.author }}</span>
{% if c.email %}<span class="comment-email">{{ c.email }}</span>{% endif %}
<time datetime="{{ c.created_at }}">{{ parse_date(c.created_at) }}</time>
</div>
<div class="comment-body">{{ render_markdown(c.body) }}</div>
<div class="comment-actions">
<form method="post" action="{{ url_for('admin.comment_unreject', cid=c.id) }}" style="display:inline;">
<input type="hidden" name="csrf_token" value="{{ csrf_token }}">
<button class="btn btn-sm btn-success" type="submit">Un-reject</button>
</form>
<form method="post" action="{{ url_for('admin.comment_delete', cid=c.id) }}" style="display:inline;" onsubmit="return confirm('Delete this comment permanently?');">
<input type="hidden" name="csrf_token" value="{{ csrf_token }}">
<button class="btn btn-sm btn-danger" type="submit">Delete</button>
</form>
</div>
</div>
{% endfor %}
</div>
{% endif %}
{% if spam %}
<h2>Spam comments</h2>
<div class="comment-mod-list">
{% for c in spam %}
<div class="comment-block comment-spam">
<div class="comment-meta">
<span class="comment-author">{{ c.author }}</span>
{% if c.email %}<span class="comment-email">{{ c.email }}</span>{% endif %}
<time datetime="{{ c.created_at }}">{{ parse_date(c.created_at) }}</time>
</div>
<div class="comment-body">{{ render_markdown(c.body) }}</div>
<div class="comment-actions">
<form method="post" action="{{ url_for('admin.comment_delete', cid=c.id) }}" style="display:inline;" onsubmit="return confirm('Delete this comment permanently?');">
<input type="hidden" name="csrf_token" value="{{ csrf_token }}">
<button class="btn btn-sm btn-danger" type="submit">Delete</button>
</form>
</div>
</div>
{% endfor %}
</div>
{% endif %}
{% else %}
<p class="empty-state">No comments awaiting moderation.</p>
{% endif %}
</div>
{% endblock %}
+61
View File
@@ -0,0 +1,61 @@
{% extends "admin/base.html" %}
{% block admin_content %}
<div class="admin-panel">
<h1>Dashboard</h1>
<div style="display:grid;grid-template-columns:repeat(auto-fit,minmax(160px,1fr));gap:20px;margin:24px 0;">
<div class="admin-stat"><span class="num">{{ count }}</span><span class="label">Total posts</span></div>
<div class="admin-stat"><span class="num">{{ published }}</span><span class="label">Published</span></div>
<div class="admin-stat"><span class="num">{{ drafts }}</span><span class="label">Drafts</span></div>
<a class="admin-stat" href="{{ url_for('admin.comments') }}" style="text-decoration:none;">
<span class="num">{{ pending_comments }}</span><span class="label">Awaiting moderation</span>
</a>
</div>
</div>
<div class="admin-panel">
<h2>Recent posts</h2>
<table class="admin-table">
<thead>
<tr>
<th>Title</th>
<th>Status</th>
<th>Date</th>
</tr>
</thead>
<tbody>
{% for p in posts[:5] %}
<tr>
<td><a href="{{ url_for('admin.post_edit', pid=p.id) }}">{{ p.title }}</a></td>
<td>{% if p.status == 'published' %}<span class="term">Published</span>{% else %}Draft{% endif %}</td>
<td>{{ parse_date(p.created_at) }}</td>
</tr>
{% else %}
<tr><td colspan="3" class="empty-state">No posts yet.</td></tr>
{% endfor %}
</tbody>
</table>
</div>
<div class="admin-panel">
<h2>Comments awaiting moderation</h2>
{% if pending %}
<table class="admin-table">
<thead>
<tr><th>Author</th><th>Comment</th><th>Received</th><th></th></tr>
</thead>
<tbody>
{% for c in pending %}
<tr>
<td>{{ c.author }}</td>
<td>{{ c.body[:120] }}{% if c.body|length > 120 %}…{% endif %}</td>
<td>{{ parse_date(c.created_at) }}</td>
<td><a class="btn" href="{{ url_for('admin.comments') }}">Review</a></td>
</tr>
{% endfor %}
</tbody>
</table>
{% else %}
<p class="empty-state">Nothing waiting for moderation.</p>
{% endif %}
</div>
{% endblock %}
+31
View File
@@ -0,0 +1,31 @@
{% extends "admin/base.html" %}
{% block admin_content %}
<div class="admin-panel">
<h1>Import / Export</h1>
<p class="muted">Move content to and from a WordPress site using the standard WXR (XML) format.</p>
</div>
<div class="admin-panel">
<h2>Export this blog</h2>
<p>Download everything as a <strong>.xml</strong> file that you can upload into a fresh WordPress site via its "Tools → Import → WordPress" screen. Posts, categories and comments are included; images are left as-is (see the note below).</p>
<form id="export-form" method="post" action="{{ url_for('admin.import_export') }}">
<input type="hidden" name="csrf_token" value="{{ csrf_token }}">
<input type="hidden" name="export" value="1">
<button type="submit" class="btn-primary">Download simple-blog-export.xml</button>
</form>
<p class="muted small">Note: images in the post HTML keep their original URLs, so re-upload them through WordPress's Media Library after importing, or pick the image-reupload option if you want this tool to pull them for you.</p>
</div>
<div class="admin-panel">
<h2>Import from WordPress</h2>
<p>Choose a WXR <strong>.xml</strong> file exported from a WordPress site. Published posts, their categories/tags, and comments are imported into Posts. Existing rows are never overwritten.</p>
<form id="import-form" method="post" action="{{ url_for('admin.import_wxr_route') }}" enctype="multipart/form-data">
<input type="hidden" name="csrf_token" value="{{ csrf_token }}">
<div class="form-group">
<label for="file">WXR file (.xml)</label>
<input type="file" id="file" name="file" accept=".xml,application/xml">
</div>
<button type="submit" class="btn-primary">Import</button>
</form>
</div>
{% endblock %}
+53
View File
@@ -0,0 +1,53 @@
{% extends "admin/base.html" %}
{% block admin_content %}
<div class="admin-panel">
<h1>Links</h1>
<p class="field-hint">
These appear in the &ldquo;Links&rdquo; panel in the site sidebar, in the order
listed below. The panel stays hidden until at least one link is added.
</p>
<form method="post" action="{{ url_for('admin.links') }}">
<input type="hidden" name="csrf_token" value="{{ csrf_token }}">
<div class="form-row">
<div class="form-group">
<label for="link-label">Label</label>
<input type="text" id="link-label" name="label" placeholder="GitHub" maxlength="80" required>
</div>
<div class="form-group">
<label for="link-url">URL</label>
<input type="text" id="link-url" name="url" placeholder="https://github.com/you" maxlength="500" required>
<span class="field-hint">A bare domain gets https:// added automatically.</span>
</div>
</div>
<button type="submit" class="btn btn-primary">Add link</button>
</form>
</div>
<div class="admin-panel">
<h2>Current links</h2>
{% if links %}
<table class="admin-table">
<thead>
<tr><th>Label</th><th>URL</th><th style="width:120px;">Actions</th></tr>
</thead>
<tbody>
{% for link in links %}
<tr>
<td>{{ link.label }}</td>
<td><a href="{{ link.url }}" target="_blank" rel="noopener noreferrer">{{ link.url }}</a></td>
<td>
<form method="post" action="{{ url_for('admin.link_delete', lid=link.id) }}" onsubmit="return confirm('Remove this link?');">
<input type="hidden" name="csrf_token" value="{{ csrf_token }}">
<button type="submit" class="btn btn-danger btn-small">Delete</button>
</form>
</td>
</tr>
{% endfor %}
</tbody>
</table>
{% else %}
<p class="empty-state">No links yet — so the sidebar panel is currently hidden.</p>
{% endif %}
</div>
{% endblock %}
+124
View File
@@ -0,0 +1,124 @@
{% extends "admin/base.html" %}
{% block title %}Media &middot; {{ site_title }}{% endblock %}
{% block admin_content %}
<h1>Media</h1>
<div class="admin-panel">
<h2>Upload a photo</h2>
<form id="media-upload-form" method="POST" action="{{ url_for('admin.upload') }}" enctype="multipart/form-data" class="stack">
<input type="hidden" name="csrf_token" value="{{ csrf_token }}">
<div class="form-group">
<label for="media-photo-file">Photo file</label>
<input type="file" id="media-photo-file" name="file" accept="image/*" multiple required>
</div>
<div class="form-group">
<label for="media-photo-album">Add to album (optional)</label>
<select id="media-photo-album" name="album">
<option value="">— Leave ungrouped —</option>
{% for a in albums %}
<option value="{{ a.slug }}">{{ a.name }}</option>
{% endfor %}
</select>
</div>
<button type="submit" class="btn btn-primary">Upload photo</button>
</form>
</div>
{% if ungrouped %}
<div class="admin-panel">
<h2>Ungrouped photos ({{ ungrouped|length }})</h2>
{% for m in ungrouped %}
{{ _media_row(m, albums) }}
{% else %}
<p class="empty-state">No ungrouped photos.</p>
{% endfor %}
</div>
{% endif %}
{% for aid, rows in grouped.items() %}
<div class="admin-panel">
<h2>{{ album_names.get(aid, 'Album') }} ({{ rows|length }})</h2>
{% for m in rows %}
{{ _media_row(m, albums) }}
{% else %}
<p class="empty-state">No photos.</p>
{% endfor %}
</div>
{% else %}
<p class="empty-state">No photos yet. Upload one from the Albums page or a post/page editor.</p>
{% endfor %}
<script>
// NOTE: one file per request, with FormData built from scratch. Cloning the
// form (new FormData(form)) also re-sends the <input type="file"> parts, so
// the server stored the selected photo twice.
// NOTE: every upload is awaited before location.reload(). The old version
// fired all the fetches and reloaded synchronously in the same tick, which
// aborted the in-flight requests — the page came back with no new photos,
// so uploads looked broken even though /admin/upload was healthy.
(function () {
var form = document.getElementById("media-upload-form");
if (!form) return;
form.addEventListener("submit", async function (e) {
e.preventDefault();
var fileInput = form.elements["media-photo-file"];
var files = Array.prototype.slice.call(fileInput.files);
if (!files.length) { alert("Choose one or more photos."); return; }
var album = form.elements["media-photo-album"].value;
var csrf = form.elements["csrf_token"].value;
var btn = form.querySelector("button[type=submit]");
btn.disabled = true;
var ok = 0, failed = [];
for (var i = 0; i < files.length; i++) {
btn.textContent = "Uploading " + (i + 1) + "/" + files.length + "...";
var fd = new FormData();
fd.append("csrf_token", csrf);
if (album) fd.append("album", album);
fd.append("file", files[i], files[i].name);
try {
var r = await fetch(form.action, { method: "POST", credentials: "same-origin", body: fd });
if (!r.ok) throw new Error("HTTP " + r.status);
await r.json();
ok++;
} catch (err) {
failed.push(files[i].name + ": " + err.message);
}
}
btn.disabled = false;
btn.textContent = "Upload photo";
if (failed.length) {
alert(ok + " uploaded, " + failed.length + " failed:\n" + failed.join("\n"));
} else {
alert(ok + " photo" + (ok === 1 ? "" : "s") + " uploaded.");
}
location.reload();
});
})();
</script>
{% endblock %}
{% macro _media_row(m, albums) %}
<div class="media-row">
<img class="media-thumb" src="{{ m.thumb_url or m.url }}" data-src="{{ m.url }}" alt="" style="width:60px;height:60px;object-fit:cover;">
<div class="media-info">
<a href="{{ m.url }}" target="_blank" rel="noreferrer">{{ m.url }}</a>
<small>{{ m.created_at or '' }}</small>
</div>
<div class="media-actions">
<form method="POST" action="{{ url_for('admin.media_assign', mid=m.id) }}" style="display:inline;">
<input type="hidden" name="csrf_token" value="{{ csrf_token }}">
<select name="album_id" onchange="this.form.submit()">
{% for a in albums %}
<option value="{{ a.id }}">{{ a.name }}</option>
{% endfor %}
</select>
</form>
<span class="field-hint">·</span>
<form method="POST" action="{{ url_for('admin.media_remove', mid=m.id) }}" style="display:inline;" onsubmit="return confirm('Remove this photo permanently? The file will be deleted.');">
<input type="hidden" name="csrf_token" value="{{ csrf_token }}">
<button class="btn btn-danger" type="submit">Remove</button>
</form>
</div>
</div>
{% endmacro %}
+84
View File
@@ -0,0 +1,84 @@
{% extends "admin/base.html" %}
{% block admin_content %}
<div class="admin-panel">
<h1>{% if page %}Edit page{% else %}New page{% endif %}</h1>
<form method="post" action="{% if page %}{{ url_for('admin.page_edit', pid=page.id) }}{% else %}{{ url_for('admin.page_new') }}{% endif %}">
<input type="hidden" name="csrf_token" value="{{ csrf_token }}">
<div class="form-row">
<div class="form-group">
<label for="title">Title *</label>
<input type="text" id="title" name="title" value="{{ (page or {}).get('title', '') if page else '' }}" required>
</div>
<div class="form-group">
<label for="slug">Slug</label>
<input type="text" id="slug" name="slug" value="{{ (page or {}).get('slug', '') if page else '' }}" placeholder="auto-generated-from-title">
<span class="field-hint">URL-friendly version of the title. Leave blank to auto-generate.</span>
</div>
</div>
<div class="form-group">
<label for="published">Published</label>
<input type="checkbox" id="published" name="published" {% if page %}checked{% endif %}>
<span class="field-hint">{% if page %}Uncheck to hide this page from the navigation.{% else %}Live pages appear in the top nav.{% endif %}</span>
</div>
<div class="form-group">
<label for="content">Content <span class="field-hint">(Rich text editor — Markdown, links, images)</span></label>
<!-- Hidden field holds the stored HTML. TinyMCE loads it into #page-editor
on init and writes it back here on submit; the public pipeline passes
stored HTML straight through (render_markdown/to_html detect it). -->
<input type="hidden" id="content" name="content" value="{{ body_html|forceescape }}">
<div id="page-editor" class="tinymce-editor"></div>
</div>
<p>
<button type="submit" class="btn btn-primary">Save</button>
<a class="btn" href="{{ url_for('admin.pages') }}">Cancel</a>
</p>
</form>
</div>
<script>
// TinyMCE: load stored HTML on init, write it back to #content on submit.
document.addEventListener('DOMContentLoaded', function () {
var contentField = document.getElementById("content");
try {
tinymce.init({
base_url: '{{ js_base }}',
theme_url: '{{ js_base }}/themes/silver/theme.min.js',
icons_url: '{{ js_base }}/icons/default/icons.min.js',
model_url: '{{ js_base }}/models/dom/model.min.js',
license_key: 'gpl',
skin: 'oxide',
content_css: '/static/js/skins/ui/oxide/content.min.css',
selector: '#page-editor',
init_instance_callback: function (editor) {
editor.setContent(contentField ? contentField.value : '');
},
convert_urls: false,
plugins: 'anchor autolink charmap codesample emoticons image link lists media searchreplace table visualblocks wordcount',
toolbar: 'undo redo | blocks fontfamily fontsize | bold italic underline strikethrough | link image media table | align lineheight | numlist bullist indent outdent | emoticons charmap | removeformat',
});
} catch (e) {
console.error('[debug] page editor init FAILED:', e);
}
// Write the WYSIWYG content back to the hidden #content field on submit.
// A div-based editor does NOT save into a separate hidden field via its
// default behaviour (TinyMCE would restore the div instead), so we must
// bridge it explicitly — same pattern as post_edit.html's #body editor.
// Same bug as post_edit.html: document.querySelector('form') returns the
// logout form in the admin header, so the editor content was never copied
// into #content and saved pages had an empty body.
var form = contentField ? contentField.form : null;
if (form) {
form.addEventListener('submit', function () {
var editor = tinymce.get('page-editor') || tinymce.activeEditor;
if (editor && contentField) contentField.value = editor.getContent();
});
}
});
</script>
{% endblock %}
+36
View File
@@ -0,0 +1,36 @@
{% extends "admin/base.html" %}
{% block admin_content %}
<div class="admin-panel">
<div class="page-head">
<h1>Pages</h1>
<a class="btn btn-primary" href="{{ url_for('admin.page_new') }}">New page</a>
</div>
{% if pages is none %}
<p class="empty-state">No pages yet. Create your first one.</p>
{% else %}
<table class="data-table">
<thead>
<tr><th>Title</th><th>Slug</th><th>Status</th><th>Order</th><th></th></tr>
</thead>
<tbody>
{% for p in pages %}
<tr>
<td><a href="{{ url_for('admin.page_edit', pid=p.id) }}">{{ p.title }}</a></td>
<td><code>/p/{{ p.slug }}</code></td>
<td>{% if p.published %}<span class="badge badge-live">Live</span>{% else %}<span class="badge badge-draft">Draft</span>{% endif %}</td>
<td>{{ p.position }}</td>
<td class="actions">
<a class="btn btn-small" href="{{ url_for('admin.page_edit', pid=p.id) }}">Edit</a>
<form method="post" action="{{ url_for('admin.page_delete', pid=p.id) }}" onsubmit="return confirm('Delete this page?');">
<input type="hidden" name="csrf_token" value="{{ csrf_token }}">
<button type="submit" class="btn btn-danger btn-small">Delete</button>
</form>
</td>
</tr>
{% endfor %}
</tbody>
</table>
{% endif %}
</div>
{% endblock %}
+36
View File
@@ -0,0 +1,36 @@
{% extends "admin/base.html" %}
{% block admin_content %}
<div class="admin-panel" style="max-width:520px;">
<h1>Change password</h1>
<p class="field-hint">
The current password is required. Changing it signs out every other
browser that is logged in; this session stays signed in.
</p>
<form method="post" action="{{ url_for('admin.admin_password') }}">
<input type="hidden" name="csrf_token" value="{{ csrf_token }}">
<div class="form-group">
<label for="current-password">Current password</label>
<input type="password" id="current-password" name="current_password"
autocomplete="current-password" maxlength="1024" required autofocus>
</div>
<div class="form-group">
<label for="new-password">New password</label>
<input type="password" id="new-password" name="new_password"
autocomplete="new-password" minlength="{{ min_length }}"
maxlength="1024" required>
<p class="field-hint">At least {{ min_length }} characters; well-known defaults are rejected.</p>
</div>
<div class="form-group">
<label for="confirm-password">Repeat new password</label>
<input type="password" id="confirm-password" name="confirm_password"
autocomplete="new-password" minlength="{{ min_length }}"
maxlength="1024" required>
</div>
<button type="submit" class="btn btn-primary">Update password</button>
</form>
</div>
{% endblock %}
+179
View File
@@ -0,0 +1,179 @@
{% extends "admin/base.html" %}
{% block admin_content %}
<div class="admin-panel">
<h1>{% if post %}Edit post{% else %}New post{% endif %}</h1>
<form method="post" action="{% if post %}{{ url_for('admin.post_edit', pid=post.id) }}{% else %}{{ url_for('admin.post_new') }}{% endif %}">
<input type="hidden" name="csrf_token" value="{{ csrf_token }}">
<div class="form-row">
<div class="form-group">
<label for="title">Title *</label>
<input type="text" id="title" name="title" value="{{ (post or {}).get('title', '') if post else '' }}" required>
</div>
<div class="form-group">
<label for="slug">Slug</label>
<input type="text" id="slug" name="slug" value="{{ (post or {}).get('slug', '') if post else '' }}" placeholder="auto-generated-from-title">
<span class="field-hint">URL-friendly version of the title. Leave blank to auto-generate.</span>
</div>
</div>
<div class="form-row">
<div class="form-group">
<label for="author">Author</label>
<input type="text" id="author" name="author" value="{{ (post or {}).get('author', 'editor') if post else '' }}">
</div>
<div class="form-group">
<label for="category">Category</label>
<input type="text" id="category" name="category" value="{{ (post or {}).get('category', 'General') if post else '' }}" list="category-options">
<datalist id="category-options">
{% for slug, name in categories %}
<option value="{{ name }}"></option>
{% endfor %}
</datalist>
</div>
</div>
<div class="form-row">
<div class="form-group">
<label for="excerpt">Excerpt</label>
<input type="text" id="excerpt" name="excerpt" value="{{ (post or {}).get('excerpt', '') if post else '' }}" placeholder="Short summary shown on the homepage">
</div>
<div class="form-group">
<label for="tags">Tags</label>
<input type="text" id="tags" name="tags" value="{{ (post or {}).get('tags', '') if post else '' }}" placeholder="ai, selfhost, tips">
<span class="field-hint">Comma separated.</span>
</div>
</div>
<div class="form-group">
<label for="body">Body <span class="field-hint">(Rich text editor)</span></label>
<!-- Hidden field holds the stored HTML. TinyMCE loads it into #body-editor
on init and writes it back here on submit; the public pipeline passes
stored HTML straight through (render_markdown/to_html detect it). -->
<!-- forceescape is REQUIRED: body_html is Markup, so Jinja would emit
quotes unescaped and the first src="/..." would terminate the value
attribute, truncating the stored body. -->
<input type="hidden" id="body" name="body" value="{{ body_html|forceescape }}">
<div id="body-editor" class="tinymce-editor"></div>
</div>
<div class="form-row">
<div class="form-group">
<label for="status">Status</label>
<select id="status" name="status">
<option value="published" {% if post and post.status == 'published' %}selected{% endif %}>Published</option>
<option value="draft" {% if post and post.status == 'draft' %}selected{% endif %}>Draft</option>
</select>
</div>
<div class="form-group">
<label for="post_date">Post date</label>
<input type="date" id="post_date" name="post_date"
value="{{ post.created_at[:10] if post and post.created_at else request.form.get('post_date', '') }}">
<span class="field-hint">Shown on the post and used for ordering and archive months. Pick an earlier date to backdate it; leave blank for today.</span>
</div>
</div>
<p>
<button type="submit" class="btn btn-primary">Save</button>
{% if post %}<a class="btn" href="{{ preview_url(post) }}" target="_blank" rel="noreferrer">Preview</a>{% endif %}
<a class="btn" href="{{ url_for('admin.posts') }}">Cancel</a>
</p>
</form>
</div>
<script>
// TinyMCE: load stored HTML on init, write it back to #body on submit,
// and upload images to /admin/upload (multipart csrf_token form field).
document.addEventListener('DOMContentLoaded', function () {
var bodyField = document.getElementById('body');
console.log('[debug] editor init started; tinymce global defined:', !!(window.tinymce));
try {
tinymce.init({
// Community edition — no license key → no tin.cloud validation, works on any domain.
// Asset resolution uses TWO TinyMCE mechanisms (see static/tinymce.min.js):
// * base_url → drives plugins/icons/skins/langs (built as baseURL + "/plugins/..." etc.)
// * theme_url / model_url / icons_url → each asset's own URL, with a RELATIVE fallback
// when unset. On this subpath app the fallback would resolve against /admin/ and 404,
// so every non-base_url asset is given an explicit ABSOLUTE url.
// js_base (defined in base.html from request.host) makes these match however the
// app is reached — no hardcoded localhost, so it works on your LAN host too.
base_url: '{{ js_base }}',
theme_url: '{{ js_base }}/themes/silver/theme.min.js',
icons_url: '{{ js_base }}/icons/default/icons.min.js',
model_url: '{{ js_base }}/models/dom/model.min.js',
// Community Edition — license_key: 'gpl' agrees to the open-source terms so the bundled
// LicenseKeyManager plugin takes the 'use_gpl' path and does NOT request its own plugin
// file (plugins/licensekeymanager/plugin.min.js), which we don't serve and which 404s.
// NOTE: the config option is 'license_key' (underscore). TinyMCE does NOT read
// camelCase 'licenseKey', so that value would be silently ignored and the editor would
// be disabled. Free, works on ANY domain (no tiny.cloud validation, no Setup Partner bot).
license_key: 'gpl',
skin: 'oxide', // oxide SKIN provides BOTH the toolbar chrome AND content.min.css.
// NOTE: do NOT pair silver theme here — the silver theme looks for its own
// skins/content/silver/content.css (absent) and falls back to skins/content/default/...
// which 404s. The oxide skin is self-contained, so no separate theme is needed.
content_css: '/static/js/skins/ui/oxide/content.min.css',
selector: '#body-editor',
// NOTE: there is NO `initialData` option in TinyMCE (that's TipTap/
// ProseMirror). It is silently ignored -> the editor always opened
// empty, so editing an existing post showed no body. Set it explicitly
// once the editor instance exists.
init_instance_callback: function (editor) {
editor.setContent(bodyField ? bodyField.value : '');
},
// Keep stored image URLs as written (/static/uploads/...). Without
// this TinyMCE rewrites them relative to the CURRENT page (/admin/...),
// so a body saved on the edit page stored '../../static/uploads/...'.
convert_urls: false,
plugins: 'anchor autolink charmap codesample emoticons image link lists media searchreplace table visualblocks wordcount',
toolbar: 'undo redo | blocks fontfamily fontsize | bold italic underline strikethrough | link image media table | align lineheight | numlist bullist indent outdent | emoticons charmap | removeformat',
// NOTE: TinyMCE 8 calls this as (blobInfo, progress) and awaits the
// RETURNED PROMISE, which must resolve to the final URL string (or an
// object with .url). The old v5 (blobInfo, success, failure) callback
// form is gone: calling success(url) here hits the progress callback,
// the promise resolves to undefined, and TinyMCE throws
// "Cannot read properties of undefined (reading 'url')".
images_upload_handler: function (blobInfo) {
var f = blobInfo.blob();
// NOTE: use the MIME SUBTYPE (index 1), not the category (index 0).
// 'image/jpeg'.split('/')[0] === 'image' (matches no map key -> falls back to 'png'),
// which labels a JPEG as .png and fails the server's PNG signature check (400).
var type = (f.type || '').split('/')[1];
var ext = { png: 'png', jpg: 'jpg', jpeg: 'jpg', gif: 'gif', webp: 'webp' }[type] || 'png';
var fd = new FormData();
fd.append('file', f, 'tiny-image.' + ext);
var csrf = document.querySelector('[name="csrf_token"]');
if (csrf) fd.append('csrf_token', csrf.value);
return fetch('/admin/upload', { method: 'POST', body: fd })
.then(function (r) {
if (!r.ok) throw new Error('Upload failed: HTTP ' + r.status);
return r.json();
})
.then(function (d) {
if (!d || !d.url) throw new Error('Upload response had no url');
return d.url;
});
},
images_restricted_types: 'image/png,image/jpeg,image/gif,image/webp',
});
console.log('[debug] init returned; editors created:', tinymce.get().length, '| body-editor exists:', tinymce.get('body-editor') !== null);
// NOTE: bind to the editor's OWN form. document.querySelector('form')
// returned the logout form in the admin header (first form in the DOM),
// so this listener never ran for the post form: the editor's content was
// never copied into #body and every NEW post saved an empty body.
var form = bodyField ? bodyField.form : null;
if (form) {
form.addEventListener('submit', function () {
// NOTE: tinymce.get() takes an ELEMENT ID, not a CSS selector.
// tinymce.get('#body-editor') returns null -> .getContent() throws ->
// the old silent catch left #body empty, so every save stored no body.
var editor = tinymce.get('body-editor') || tinymce.activeEditor;
if (editor && bodyField) bodyField.value = editor.getContent();
});
}
} catch (e) {
console.error('[debug] editor init FAILED:', e);
}
});
</script>
{% endblock %}
+42
View File
@@ -0,0 +1,42 @@
{% extends "admin/base.html" %}
{% block admin_content %}
<div class="admin-panel">
<h1>Posts</h1>
<div class="admin-actions">
<a class="primary" href="{{ url_for('admin.post_new') }}">+ New post</a>
<a href="{{ url_for('admin.dashboard') }}">Dashboard</a>
</div>
<table class="admin-table">
<thead>
<tr>
<th>Title</th>
<th>Author</th>
<th>Category</th>
<th>Status</th>
<th>Created</th>
<th style="width:130px;">Actions</th>
</tr>
</thead>
<tbody>
{% for p in posts %}
<tr>
<td><a href="{{ url_for('public.post', slug=p.slug) }}">{{ p.title }}</a></td>
<td>{{ p.author }}</td>
<td>{{ p.category }}</td>
<td>{% if p.status == 'published' %}<span class="term">Published</span>{% else %}Draft{% endif %}</td>
<td>{{ parse_date(p.created_at) }}</td>
<td class="table-actions">
<a class="btn" href="{{ url_for('admin.post_edit', pid=p.id) }}">Edit</a>
<form method="post" action="{{ url_for('admin.post_delete', pid=p.id) }}" style="display:inline;" onsubmit="return confirm('Delete this post?');">
<input type="hidden" name="csrf_token" value="{{ csrf_token }}">
<button class="btn btn-danger" type="submit">Delete</button>
</form>
</td>
</tr>
{% else %}
<tr><td colspan="6" class="empty-state">No posts. Create your first post to get started.</td></tr>
{% endfor %}
</tbody>
</table>
</div>
{% endblock %}
+38
View File
@@ -0,0 +1,38 @@
{% extends "admin/base.html" %}
{% block admin_content %}
<div class="admin-panel">
<h1>Visitor history</h1>
<table class="admin-table">
<tbody>
<tr><th>Visitor ID</th><td><code>{{ visitor.visitor_id }}</code></td></tr>
<tr><th>Browser</th><td>{{ visitor.browser or "&mdash;" }}</td></tr>
<tr><th>Operating system</th><td>{{ visitor.os or "&mdash;" }}</td></tr>
<tr><th>Device</th><td>{{ visitor.device }}</td></tr>
<tr><th>Location</th><td>{% if visitor.city or visitor.country %}{% if visitor.country_code %}<span class="location-flag">{{ visitor.country_code|country_flag }}</span> {% endif %}{{ visitor.city or "—" }}{% if visitor.region %}, {{ visitor.region }}{% endif %}{% if visitor.country %}, {{ visitor.country }}{% endif %}{% if visitor.latitude is not none %} <span class="muted">({{ "%.2f"|format(visitor.latitude) }}, {{ "%.2f"|format(visitor.longitude) }})</span>{% endif %}{% else %}&mdash;{% endif %}</td></tr>
<tr><th>Source</th><td><span class="term">{{ visitor.source }}</span></td></tr>
<tr><th>Referrer domain</th><td>{{ visitor.referrer_domain or "direct (no referrer)" }}</td></tr>
<tr><th>Raw referrer</th><td>{{ visitor.referrer or "&mdash;" }}</td></tr>
<tr><th>First seen</th><td>{{ parse_date(visitor.first_seen) }}</td></tr>
<tr><th>Last seen</th><td>{{ parse_date(visitor.last_seen) }}</td></tr>
</tbody>
</table>
</div>
<div class="admin-panel">
<h2>Pages visited ({{ visits|length }})</h2>
<table class="admin-table">
<thead><tr><th>Page</th><th>Title</th><th>When</th></tr></thead>
<tbody>
{% for v in visits %}
<tr>
<td><code>{{ v.page_path }}</code></td>
<td>{{ v.title or "(untitled)" }}</td>
<td>{{ parse_date(v.timestamp) }}</td>
</tr>
{% else %}
<tr><td colspan="3" class="empty-state">This visitor has not visited any page yet.</td></tr>
{% endfor %}
</tbody>
</table>
</div>
{% endblock %}
+86
View File
@@ -0,0 +1,86 @@
{% extends "admin/base.html" %}
{% block admin_content %}
<div class="admin-panel">
<h1>Visitors</h1>
<p class="muted">Every tracked visitor. Click a row to see the pages they visited.</p>
<form method="get" action="{{ url_for('admin.visitors') }}" class="filter-form">
<label>
<span>Country</span>
<select name="country" id="country-filter">
<option value="">All countries</option>
{% for c in countries %}
<option value="{{ c.country_code }}" {% if c.country_code == selected_country %}selected{% endif %}>
{{ c.country_code|country_flag }} {{ c.country }} ({{ c.c }})
</option>
{% endfor %}
</select>
</label>
<label>
<span>City</span>
<select name="city" id="city-filter">
<option value="">All cities</option>
{% for city in cities %}
<option value="{{ city }}" {% if city == selected_city %}selected{% endif %}>{{ city }}</option>
{% endfor %}
</select>
</label>
<noscript><button type="submit" class="btn">Filter</button></noscript>
{% if selected_country or selected_city %}
<a class="btn" href="{{ url_for('admin.visitors') }}">Clear filters</a>
{% endif %}
<span class="muted">{{ rows|length }} shown</span>
</form>
<table class="admin-table">
<thead>
<tr>
<th>Visitor ID</th>
<th>Browser</th>
<th>OS</th>
<th>Device</th>
<th>Location</th>
<th>Source</th>
<th>Referrer domain</th>
<th>First seen</th>
<th>Last seen</th>
<th>Visits</th>
</tr>
</thead>
<tbody>
{% for r in rows %}
<tr>
<td><a href="{{ url_for('admin.visit_history', vid=r.visitor_id) }}"><code>{{ r.visitor_id }}</code></a></td>
<td>{{ r.browser or "&mdash;" }}</td>
<td>{{ r.os or "&mdash;" }}</td>
<td>{{ r.device }}</td>
<td>{% if r.city or r.country %}{% if r.country_code %}<span class="location-flag">{{ r.country_code|country_flag }}</span> {% endif %}{{ r.city or "—" }}{% if r.country %}<span class="muted">, {{ r.country }}</span>{% endif %}{% else %}&mdash;{% endif %}</td>
<td><span class="term">{{ r.source }}</span></td>
<td>{{ r.referrer_domain or "&mdash;" }}</td>
<td>{{ parse_date(r.first_seen) }}</td>
<td>{{ parse_date(r.last_seen) }}</td>
<td>{{ r.visits }}</td>
</tr>
{% else %}
<tr><td colspan="10" class="empty-state">No visitors match these filters.</td></tr>
{% endfor %}
</tbody>
</table>
</div>
<script>
(function () {
var country = document.getElementById("country-filter");
var city = document.getElementById("city-filter");
if (!country || !city) return;
// Changing country resets the city, otherwise a city that no longer
// belongs to the selection would keep filtering the table to zero rows.
country.addEventListener("change", function () {
city.value = "";
country.form.submit();
});
city.addEventListener("change", function () {
city.form.submit();
});
})();
</script>
{% endblock %}
+76
View File
@@ -0,0 +1,76 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>{% block title %}{{ site_title }}{% endblock %}</title>
<meta name="description" content="{% block meta_description %}{{ meta_description or site_tagline }}{% endblock %}">
<meta name="robots" content="{% block robots %}index, follow{% endblock %}">
<!-- Canonical + social-preview tags (rendered on every page). Paginated
listings keep their ?page= so page 2 doesn't canonicalise to page 1. -->
{% set page_arg = request.args.get('page') %}
<link rel="canonical" href="{{ request.url.split('?')[0] }}{% if page_arg and page_arg != '1' %}?page={{ page_arg }}{% endif %}">
<link rel="alternate" type="application/atom+xml" title="{{ site_title }}"
href="{{ url_for('public.feed') }}">
<meta property="og:type" content="{% block og_type %}website{% endblock %}">
<meta property="og:site_name" content="{{ site_title }}">
<meta property="og:title" content="{% block og_title %}{{ site_title }}{% endblock %}">
<meta property="og:description" content="{% block og_description %}{{ meta_description or site_tagline }}{% endblock %}">
<meta property="og:url" content="{{ request.url.split('?')[0] }}">
{% set social_image = og_image if og_image else header_image %}
{% if social_image %}
<meta property="og:image" content="{{ social_image }}">
{% endif %}
<meta name="twitter:card" content="{{ 'summary_large_image' if social_image else 'summary' }}">
<meta name="twitter:title" content="{% block twitter_title %}{{ site_title }}{% endblock %}">
<meta name="twitter:description" content="{% block twitter_description %}{{ meta_description or site_tagline }}{% endblock %}">
{% if social_image %}
<meta name="twitter:image" content="{{ social_image }}">
{% endif %}
<link rel="stylesheet" href="{{ url_for('static', filename='css/style.css') }}">
<!-- Admin-custom CSS, written by /admin/appearance and served as a static asset. -->
<link rel="stylesheet" href="{{ url_for('static', filename='css/custom.css') }}">
{% block head %}{% endblock %}
</head>
<body>
<header class="site-header">
<div class="header-inner {% if header_image %}has-banner{% endif %}">
{% if header_image %}
<img src="{{ header_image }}" class="site-banner-img" alt="{{ site_title }}">
{% endif %}
<div class="site-logo">
<a href="{{ url_for('public.index') }}">{{ site_title }}</a>
{% if site_tagline %}<span class="hero-tagline">{{ site_tagline }}</span>{% endif %}
</div>
<nav class="main-nav" aria-label="Main navigation">
<ul class="nav-links">
<li class="nav-item"><a href="{{ url_for('public.index') }}">Home</a></li>
<li class="nav-item"><a href="{{ url_for('public.photos_index') }}">Photos</a></li>
{% for p in pages %}
<li class="nav-item"><a href="{{ url_for('public.page', slug=p.slug) }}">{{ p.title }}</a></li>
{% endfor %}
</ul>
</nav>
</div>
</header>
<main class="site-main">
{% block content %}{% endblock %}
</main>
<footer class="site-footer">
<div class="footer-inner">
<span>&copy; {{ current_year() }}</span>
<span>Built with a simple CMS</span>
</div>
</footer>
<!-- (The old dropdown menu button/JS was removed; navigation is now simple
inline links shown directly in the header.) -->
<!-- Click any page image (incl. uploaded TinyMCE images) to view it full-size. -->
<script src="{{ url_for('static', filename='js/lightbox.js') }}"></script>
<!-- Full-album gallery viewer for /photos/<slug>. -->
<script src="{{ url_for('static', filename='js/gallery_lightbox.js') }}"></script>
</body>
</html>
+59
View File
@@ -0,0 +1,59 @@
<section class="comments-section" aria-label="Comments">
<h2 class="page-heading">Comments</h2>
{% if not comments_enabled %}
<p class="empty-state">Comments are closed.</p>
{% else %}
{% if comment_count > 0 %}
<p class="field-hint">{{ comment_count }} comment{{ 's' if comment_count != 1 }} so far.</p>
{% endif %}
{% if comments %}
<div class="comment-list">
{% for c in comments %}
<article class="comment-block" data-comment-id="{{ c.id }}">
<div class="comment-meta">
<span class="comment-author">{{ c.author }}</span>
<time datetime="{{ c.created_at }}">{{ parse_date(c.created_at) }}</time>
</div>
<div class="comment-body">{{ render_markdown(c.body) }}</div>
{% if logged_in and c.author == session.get('username') %}
<form method="post" action="{{ url_for('public.public_comment_delete', cid=c.id) }}" style="display:inline;" onsubmit="return confirm('Delete this comment?');">
<input type="hidden" name="csrf_token" value="{{ csrf_token }}">
<button class="btn btn-sm btn-danger" type="submit">Delete my comment</button>
</form>
{% endif %}
</article>
{% endfor %}
</div>
{% else %}
<p class="empty-state">No comments yet — be the first!</p>
{% endif %}
<form method="post" action="{% if object_type == 'post' %}{{ url_for('public.post_comment', slug=slug) }}{% else %}{{ url_for('public.page_comment', slug=slug) }}{% endif %}" class="comment-form">
<input type="hidden" name="csrf_token" value="{{ csrf_token }}">
{# Bot traps (hidden, no visual change): a field humans never fill in and
the time this page was rendered. #}
<div hidden aria-hidden="true">
<label for="c-website">Website</label>
<input type="text" id="c-website" name="website" tabindex="-1" autocomplete="off">
</div>
<input type="hidden" name="ts" value="{{ now_ts }}">
<div class="form-row">
<div class="form-group">
<label for="c-author">Name</label>
<input type="text" id="c-author" name="author" required autocomplete="name" placeholder="Your name">
</div>
<div class="form-group">
<label for="c-email">Email <small>(optional, not published)</small></label>
<input type="email" id="c-email" name="email" autocomplete="email" placeholder="you@example.com">
</div>
</div>
<div class="form-group">
<label for="c-body">Comment</label>
<textarea id="c-body" name="body" rows="4" required placeholder="Share your thoughts…"></textarea>
</div>
<button type="submit" class="btn-primary">Post comment</button>
</form>
{% endif %}
</section>
+135
View File
@@ -0,0 +1,135 @@
{% extends "base.html" %}
{% block title %}{% if page == 'tag' %}Tag: {{ tag_name }} &middot; {{ site_title }}{% elif page == 'category' %}Category: {{ category_name }} &middot; {{ site_title }}{% elif page == 'archive' %}{{ parse_date(month ~ '-01') }} &middot; {{ site_title }}{% else %}{{ site_title }}{% endif %}{% endblock %}
{% block meta_description %}{% if page == 'tag' %}Posts tagged &ldquo;{{ tag_name }}&rdquo; on {{ site_title }}.{% elif page == 'category' %}Posts in {{ category_name }} on {{ site_title }}.{% else %}{{ meta_description or site_tagline }}{% endif %}{% endblock %}
{% block head %}
{% if pagination and pagination.has_prev %}<link rel="prev" href="{{ pagination.prev_url }}">{% endif %}
{% if pagination and pagination.has_next %}<link rel="next" href="{{ pagination.next_url }}">{% endif %}
{% if page == 'tag' %}
<link rel="alternate" type="application/atom+xml" title="Tag: {{ tag_name }}"
href="{{ url_for('public.tag_feed', slug=tag_slug) }}">
{% endif %}
{% endblock %}
{% block content %}
{% if page == "category" %}
<h1 class="page-heading">Category: {{ category_name }}</h1>
{% elif page == "tag" %}
<h1 class="page-heading">Tag: {{ tag_name }}</h1>
{% elif page == "archive" %}
<h1 class="page-heading">{{ parse_date(month ~ '-01') }}</h1>
{% else %}
<h1 class="page-heading">Latest Posts</h1>
{% endif %}
<div class="content-area">
<section class="posts">
{% if posts %}
<div class="posts-grid">
{% for p in posts %}
<article class="post-card">
<h2>
<a href="{{ url_for('public.post', slug=p.slug) }}">{{ p.title }}</a>
</h2>
<div class="post-meta">
<span><strong>{{ parse_date(p.created_at) }}</strong></span>
<span>by {{ p.author }}</span>
</div>
{% if p.excerpt %}
<div class="post-excerpt">
{{ p.excerpt|replace("\n", "\n\n")|safe }}
</div>
{% endif %}
<div class="post-footer">
<div class="post-tax">
{% if p.category %}<span class="term">{{ p.category }}</span> &middot; {% endif %}
{% for t in p.tags|tag_list %}
<a class="term" href="{{ url_for('public.tag', slug=t.slug) }}">{{ t.name }}</a>
{% endfor %}
</div>
<a class="read-more" href="{{ url_for('public.post', slug=p.slug) }}">Read more &rarr;</a>
</div>
</article>
{% endfor %}
</div>
{% include "_pagination.html" %}
{% else %}
<p class="empty-state">No posts yet. Sign in to the admin area to add one.</p>
{% endif %}
</section>
<aside class="sidebar">
{# Link tree managed from /admin/links. Rendered only once at least one
link exists, so the panel never appears empty. #}
{% if sidebar.links %}
<div class="widget">
<h2 class="widget-title">Links</h2>
<ul>
{% for link in sidebar.links %}
<li>
{% if link.url.startswith('http') %}
<a href="{{ link.url }}" target="_blank" rel="noopener noreferrer">{{ link.label }}</a>
{% else %}
<a href="{{ link.url }}">{{ link.label }}</a>
{% endif %}
</li>
{% endfor %}
</ul>
</div>
{% endif %}
<div class="widget">
<h2 class="widget-title">Search</h2>
<form class="search-form" method="get" action="{{ url_for('public.search') }}">
<input type="search" name="q" placeholder="Search posts…" value="{{ query if query else '' }}" aria-label="Search">
<button type="submit">Search</button>
</form>
</div>
<div class="widget">
<h2 class="widget-title">Recent Posts</h2>
<ul>
{% for p in sidebar.recent %}
<li><a href="{{ url_for('public.post', slug=p.slug) }}">{{ p.title }}</a></li>
{% else %}
<li><span>No recent posts.</span></li>
{% endfor %}
</ul>
</div>
<div class="widget">
<h2 class="widget-title">Archives</h2>
<ul>
{# One link per month from a GROUP BY query, so pagination can't hide
older months the way deriving this from the current page's posts did. #}
{% for row in sidebar.months %}
<li><a href="{{ url_for('public.archive', month=row.month) }}">{{ parse_date(row.month ~ '-01') }}</a></li>
{% else %}
<li><span>No archives yet.</span></li>
{% endfor %}
</ul>
</div>
<div class="widget">
<h2 class="widget-title">Categories</h2>
<ul>
{% for slug, name in category_map.items() %}
<li><a href="{{ url_for('public.category', slug=slug) }}">{{ name }}</a></li>
{% endfor %}
</ul>
</div>
<div class="widget">
<h2 class="widget-title">Tags</h2>
<div class="tag-cloud">
{% for t in sidebar.tags %}
<a class="term" href="{{ url_for('public.tag', slug=t.slug) }}">{{ t.name }} <small>{{ t.count }}</small></a>
{% else %}
<span class="field-hint">No tags yet.</span>
{% endfor %}
</div>
{% if sidebar.tags %}<p class="field-hint"><a href="{{ url_for('public.tags') }}">All tags &rarr;</a></p>{% endif %}
</div>
</aside>
</div>
{% endblock %}
+26
View File
@@ -0,0 +1,26 @@
{% extends "base.html" %}
{% block title %}Sign in &middot; {{ site_title }}{% endblock %}
{% block content %}
<div class="admin-wrap" style="max-width:420px;">
<div class="admin-panel">
<h1 class="page-heading" style="font-size:1.6rem;">Admin</h1>
{% with messages = get_flashed_messages(with_categories=true) %}
{% for category, message in messages %}
<div class="notice notice-{{ category }}">{{ message }}</div>
{% endfor %}
{% endwith %}
<form method="post" action="{{ url_for('admin.admin_login') }}">
<input type="hidden" name="csrf_token" value="{{ csrf_token }}">
<div class="form-group">
<label for="password">Password</label>
<input type="password" id="password" name="password" autocomplete="current-password" maxlength="1024" autofocus required>
</div>
<button type="submit" class="btn btn-primary" style="width:100%;">Sign in</button>
</form>
<p style="font-size:0.85rem;color:var(--color-muted);margin-top:18px;">
<a href="{{ url_for('public.index') }}" style="color:var(--color-link);">← Back to site</a>
</p>
</div>
</div>
{% endblock %}
+25
View File
@@ -0,0 +1,25 @@
{% extends "base.html" %}
{% block title %}{{ page.title }} &middot; {{ site_title }}{% endblock %}
{% block og_title %}{{ page.title }}{% endblock %}
{% block og_description %}{{ page.title }} &middot; {{ site_title }}{% endblock %}
{% block twitter_title %}{{ page.title }}{% endblock %}
{% block twitter_description %}{{ page.title }} &middot; {{ site_title }}{% endblock %}
{% block content %}
<nav class="breadcrumb">
<a href="{{ url_for('public.index') }}">Home</a>
<span>&rsaquo;</span>
<span>{{ page.title }}</span>
</nav>
<article class="single-post">
<h1 class="page-heading">{{ page.title }}</h1>
<div class="entry-content">
{{ render_markdown(page.content) }}
</div>
</article>
{# comments.html renders its own <section> + "Comments" heading; wrapping it
here duplicated both. #}
{% include "comments.html" %}
{% endblock %}
+44
View File
@@ -0,0 +1,44 @@
{% extends "base.html" %}
{% block title %}{{ album.name }} &middot; {{ site_title }}{% endblock %}
{% block content %}
<nav class="breadcrumb">
<a href="{{ url_for('public.index') }}">Home</a>
<span>&rsaquo;</span>
<span>{{ album.name }}</span>
</nav>
<article class="single-post">
<h1 class="page-heading">{{ album.name }}</h1>
{% if album.description %}
<p class="lead">{{ album.description }}</p>
{% endif %}
{% if media %}
<!-- Random featured image; click it (or any thumbnail) to open the gallery lightbox. -->
<figure class="gallery-hero" id="gallery-hero">
<img class="gallery-hero-img" data-no-lightbox src="{{ media[0].url }}" alt="{{ album.name }}">
<figcaption class="hero-caption">{{ album.name }}</figcaption>
</figure>
<div class="gallery" style="display:grid;grid-template-columns:repeat(auto-fill,minmax(200px,1fr));gap:12px;">
{% for m in media %}
<img class="gallery-img" data-no-lightbox src="{{ m.thumb_url or m.url }}" data-src="{{ m.url }}" alt="" loading="lazy">
{% endfor %}
</div>
<!-- Gallery lightbox (populated by gallery_lightbox.js). -->
<div class="gallery-lightbox" id="gallery-lightbox" hidden>
<button type="button" class="lightbox-close" aria-label="Close gallery">&times;</button>
<header class="lightbox-header">{{ album.name }}</header>
<div class="lightbox-body">
<button type="button" class="lightbox-prev" aria-label="Previous photo">&#8249;</button>
<img class="lightbox-img-main" src="" alt="">
<button type="button" class="lightbox-next" aria-label="Next photo">&#8250;</button>
</div>
</div>
{% else %}
<p class="empty-state">This album has no photos yet.</p>
{% endif %}
</article>
{% endblock %}
+79
View File
@@ -0,0 +1,79 @@
{% extends "base.html" %}
{% block title %}{{ post.title }} &middot; {{ site_title }}{% endblock %}
{% block meta_description %}{{ post.excerpt or post.body|striptags|truncate(160, True, '…') }}{% endblock %}
{% block robots %}{% if preview %}noindex, nofollow{% else %}index, follow{% endif %}{% endblock %}
{% block og_type %}article{% endblock %}
{% block og_title %}{{ post.title }}{% endblock %}
{% block og_description %}{{ post.excerpt or post.body|striptags|truncate(160, True, '…') }}{% endblock %}
{% block twitter_title %}{{ post.title }}{% endblock %}
{% block twitter_description %}{{ post.excerpt or post.body|striptags|truncate(160, True, '…') }}{% endblock %}
{% block head %}
{# Structured data for search engines (head only — no visual change). #}
<script type="application/ld+json">
{
"@context": "https://schema.org",
"@type": "BlogPosting",
"headline": {{ post.title|tojson }},
"datePublished": {{ post.created_at|replace(' ', 'T')|tojson }},
"dateModified": {{ post.updated_at|replace(' ', 'T')|tojson }},
"author": {"@type": "Person", "name": {{ post.author|tojson }}},
{% if og_image %}"image": {{ og_image|tojson }},
{% endif %}"url": {{ request.url.split('?')[0]|tojson }}
}
</script>
{% endblock %}
{% block content %}
<nav class="breadcrumb">
<a href="{{ url_for('public.index') }}">Home</a>
<span>&rsaquo;</span>
<a href="{{ url_for('public.category', slug=cat_slug) }}">{{ post.category }}</a>
<span>&rsaquo;</span>
<span>{{ post.title }}</span>
</nav>
{% if preview %}
<div class="preview-banner">
<strong>Draft preview.</strong> This post is not public yet.
<a href="{{ url_for('admin.post_edit', pid=post.id) }}">Back to the editor</a>
</div>
{% endif %}
<article class="single-post">
<h1 class="post-title">{{ post.title }}</h1>
<div class="post-meta">
<span><strong>{{ parse_date(post.created_at) }}</strong></span>
<span>by {{ post.author }}</span>
{% if post.category %}<span>{{ post.category }}</span>{% endif %}
{% if post.tags %}<span>Tags: {% for t in post.tags|tag_list %}<a href="{{ url_for('public.tag', slug=t.slug) }}">{{ t.name }}</a>{% if not loop.last %}, {% endif %}{% endfor %}</span>{% endif %}
</div>
<div class="entry-content">
{{ render_markdown(post.body) }}
</div>
<div class="post-share">
Published on {{ parse_date(post.created_at) }} in {{ post.category }}.
</div>
</article>
{# comments.html renders its own <section> + "Comments" heading; wrapping it
here duplicated both. #}
{% if related %}
<section class="related-posts" aria-label="Related posts">
<h2 class="page-heading">{% if related_fallback %}More from the blog{% else %}Related posts{% endif %}</h2>
<div class="related-grid">
{% for r in related %}
<article class="related-card">
<h3><a href="{{ url_for('public.post', slug=r.slug) }}">{{ r.title }}</a></h3>
<div class="post-meta">
<span>{{ parse_date(r.created_at) }}</span>
{% if r.category %}<span>{{ r.category }}</span>{% endif %}
</div>
</article>
{% endfor %}
</div>
</section>
{% endif %}
{% if not preview %}{% include "comments.html" %}{% endif %}
{% endblock %}
+36
View File
@@ -0,0 +1,36 @@
{% extends "base.html" %}
{% block title %}Photos &middot; {{ site_title }}{% endblock %}
{% block content %}
<nav class="breadcrumb">
<a href="{{ url_for('public.index') }}">Home</a>
<span>&rsaquo;</span>
<span>Photos</span>
</nav>
<article class="single-post">
<h1 class="page-heading">Photos</h1>
{% if albums %}
<div class="gallery" style="display:grid;grid-template-columns:repeat(auto-fill,minmax(220px,1fr));gap:16px;">
{% for a in albums %}
<a class="album-card" href="{{ url_for('public.photos', slug=a.slug) }}">
{% if album_thumbs.get(a.id) %}
{# The whole card opens the album. Without data-no-lightbox the
page-wide single-image viewer swallowed this click and showed
only the preview photo instead of navigating to the gallery. #}
<img class="album-thumb" src="{{ album_thumbs.get(a.id) }}" alt="{{ a.name }}" loading="lazy" data-no-lightbox>
{% endif %}
<h2>{{ a.name }}</h2>
{% if a.description %}
<p class="lead">{{ a.description }}</p>
{% endif %}
<span class="album-count">{{ album_counts.get(a.id, 0) }} photo{{ '' if album_counts.get(a.id, 0) == 1 else 's' }}</span>
</a>
{% endfor %}
</div>
{% else %}
<p class="empty-state">No albums yet. Create one from the admin panel.</p>
{% endif %}
</article>
{% endblock %}
+37
View File
@@ -0,0 +1,37 @@
{% extends "base.html" %}
{% block title %}Search &middot; {{ site_title }}{% endblock %}
{% block meta_description %}Search {{ site_title }}.{% endblock %}
{% block robots %}noindex, follow{% endblock %}
{% block content %}
<h1 class="page-heading">Search</h1>
<form class="search-form" method="get" action="{{ url_for('public.search') }}">
<input type="search" name="q" placeholder="Search posts…" value="{{ query }}" aria-label="Search">
<button type="submit">Search</button>
</form>
{% if query %}
<h2 class="page-heading" style="font-size:1.3rem;">Results for &ldquo;{{ query }}&rdquo;</h2>
<div class="posts-grid">
{% for p in posts %}
<article class="post-card">
<h2><a href="{{ url_for('public.post', slug=p.slug) }}">{{ p.title }}</a></h2>
<div class="post-meta"><span><strong>{{ parse_date(p.created_at) }}</strong></span><span>by {{ p.author }}</span></div>
{% if p.excerpt %}<div class="post-excerpt">{{ p.excerpt|replace("\n", "\n\n")|safe }}</div>{% endif %}
<div class="post-footer">
<div class="post-tax">
{% if p.category %}<span class="term">{{ p.category }}</span> &middot; {% endif %}
{% for t in p.tags|tag_list %}
<a class="term" href="{{ url_for('public.tag', slug=t.slug) }}">{{ t.name }}</a>
{% endfor %}
</div>
<a class="read-more" href="{{ url_for('public.post', slug=p.slug) }}">Read more &rarr;</a>
</div>
</article>
{% else %}
<p class="empty-state">No posts matched &ldquo;{{ query }}&rdquo;.</p>
{% endfor %}
</div>
{% include "_pagination.html" %}
{% endif %}
{% endblock %}
+23
View File
@@ -0,0 +1,23 @@
{% extends "base.html" %}
{% block title %}Tags &middot; {{ site_title }}{% endblock %}
{% block meta_description %}Browse every topic on {{ site_title }}.{% endblock %}
{% block content %}
<nav class="breadcrumb">
<a href="{{ url_for('public.index') }}">Home</a>
<span>&rsaquo;</span>
<span>Tags</span>
</nav>
<h1 class="page-heading">Tags</h1>
{% if tag_index %}
<div class="tag-cloud tag-cloud-page">
{% for t in tag_index %}
<a class="term" href="{{ url_for('public.tag', slug=t.slug) }}">{{ t.name }} <small>{{ t.count }}</small></a>
{% endfor %}
</div>
{% else %}
<p class="empty-state">No tags yet. Add tags to a post from the editor.</p>
{% endif %}
{% endblock %}