291 lines
9.2 KiB
Python
291 lines
9.2 KiB
Python
"""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())
|