Files
StarPunk/starpunk/routes/admin.py
T
PhilandClaude Opus 5.5 978c13358b feat: article titles and summaries stored apart from the text (v2.16.0, ADR-076)
Articles as the IndieWeb defines them: a name separate from the content.

- Migration 023 adds notes.title and notes.summary. A one-time Python data
  step (migrations.DATA_MIGRATIONS) moves each note's '# Heading' first line
  into title, rewrites the file and hash, empties FTS for a rebuild, and puts
  files back if the migration fails. Trashed notes included.
- Micropub: name -> title, summary stored when sent with content, summary
  updatable, q=source returns both. MCP tools take a summary.
- Feeds: titles only for articles (RSS/JSON none, Atom empty); Atom and
  JSON Feed summaries; the title is no longer repeated in the content.
- Pages: p-name/p-summary on the article page. Homepage and tag pages show
  articles as title, summary and "Read more" without images (hidden u-photo
  keeps the post type for parsers).
- Crossposts: articles go out as title, summary, link and hashtags, no
  images; the Bluesky card is the article. Notes unchanged.
- Editor: Title and Summary fields; an article may have no body.
- Fix: a line starting with a hashtag ('#indieweb ...') was rendered as a
  heading and crossposted without its '#' (HashtagLineExtension).
- Fix: excerpts showed raw Markdown; they are plain text now.

Back up the database and the data folder before deploying: the migration
rewrites note files.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 17:05:38 -07:00

759 lines
23 KiB
Python

"""
Admin routes for StarPunk
Handles authenticated admin functionality including dashboard, note creation,
editing, and deletion. All routes require authentication.
"""
from flask import Blueprint, current_app, flash, g, jsonify, redirect, render_template, request, url_for
import logging
import os
import shutil
logger = logging.getLogger(__name__)
from starpunk.auth import require_auth
from starpunk.notes import (
create_note,
delete_note,
list_notes,
get_note,
update_note,
)
# Create blueprint
bp = Blueprint("admin", __name__, url_prefix="/admin")
@bp.route("/")
@require_auth
def dashboard():
"""
Admin dashboard with note list
Displays all notes (published and drafts) with management controls.
Requires authentication.
Per v1.6.0: Added pagination (25 items per page)
Returns:
Rendered dashboard template with paginated note list
Decorator: @require_auth
Template: templates/admin/dashboard.html
Access: g.user_me (set by require_auth decorator)
"""
from flask import current_app
import math
# Get pagination params (v1.6.0)
page = int(request.args.get('page', 1))
per_page = 25
# Get all notes (published and drafts)
all_notes = list_notes()
# Calculate pagination
total_notes = len(all_notes)
total_pages = math.ceil(total_notes / per_page) if total_notes > 0 else 1
# Slice for current page
start_idx = (page - 1) * per_page
end_idx = start_idx + per_page
notes = all_notes[start_idx:end_idx]
# Get pending webmention count (v1.6.0)
webmention_pending_count = 0
if current_app.config.get('WEBMENTION_ENABLED', False):
try:
from starpunk.webmention_queries import count_webmentions
webmention_pending_count = count_webmentions(status_filter='pending')
except Exception:
pass
# WebSub subscribers (v2.10.0)
websub_stats = None
if current_app.config.get('WEBSUB_ENABLED', True):
try:
from starpunk import websub
from starpunk.database import get_db
websub_stats = websub.stats(get_db(current_app))
except Exception:
pass
return render_template(
"admin/dashboard.html",
notes=notes,
page=page,
total_pages=total_pages,
webmention_pending_count=webmention_pending_count,
websub_stats=websub_stats,
user_me=g.me
)
@bp.route("/new", methods=["GET"])
@require_auth
def new_note_form():
"""
Display create note form
Shows empty form for creating a new note.
Requires authentication.
Returns:
Rendered new note form template
Decorator: @require_auth
Template: templates/admin/new.html
"""
from starpunk.syndication import get_targets
return render_template("admin/new.html", syndication_targets=get_targets().values())
@bp.route("/new", methods=["POST"])
@require_auth
def create_note_submit():
"""
Handle new note submission
Creates a new note from submitted form data.
Requires authentication.
Form data:
content: Markdown content (required)
published: Checkbox for published status (optional)
custom_slug: Optional custom slug (v1.2.0 Phase 1)
media_files: Multiple file upload (v1.2.0 Phase 3)
captions[]: Captions for each media file (v1.2.0 Phase 3)
tags: Comma-separated tag list (v1.3.0 Phase 3)
title, summary: Optional; a title makes it an article (v2.16.0)
Returns:
Redirect to dashboard on success, back to form on error
Decorator: @require_auth
"""
from starpunk.media import save_media, attach_media_to_note
from starpunk.tags import parse_tag_input
content = request.form.get("content", "").strip()
published = "published" in request.form
custom_slug = request.form.get("custom_slug", "").strip()
tags_input = request.form.get("tags", "")
title = request.form.get("title", "").strip() or None
summary = request.form.get("summary", "").strip() or None
# With photos, WebSub hears about the note once they're attached (v2.10.1)
has_uploads = any(f.filename for f in request.files.getlist('media_files'))
if not (content or title or has_uploads):
flash("A note needs text, a title or an image", "error")
return redirect(url_for("admin.new_note_form"))
# Parse tags (v1.3.0 Phase 3)
tags = parse_tag_input(tags_input)
try:
# Create note first (per Q4)
note = create_note(
content,
published=published,
custom_slug=custom_slug if custom_slug else None,
tags=tags if tags else None,
has_media=has_uploads,
title=title,
summary=summary,
)
# Handle media uploads (v1.2.0 Phase 3)
media_files = request.files.getlist('media_files')
captions = request.form.getlist('captions[]')
if media_files and any(f.filename for f in media_files):
# Per Q35: Accept valid, reject invalid (not atomic)
media_ids = []
errors = []
for i, file in enumerate(media_files):
if not file.filename:
continue
try:
# Read file data
file_data = file.read()
# Save and optimize media
media_info = save_media(file_data, file.filename)
media_ids.append(media_info['id'])
except ValueError as e:
errors.append(f"{file.filename}: {str(e)}")
except Exception as e:
errors.append(f"{file.filename}: Upload failed")
if media_ids:
# Ensure captions list matches media_ids length
while len(captions) < len(media_ids):
captions.append('')
# Attach media to note
attach_media_to_note(note.id, media_ids, captions[:len(media_ids)])
if errors:
flash(f"Note created, but some images failed: {'; '.join(errors)}", "warning")
if not media_ids:
# No photo made it; announce the note as it is (v2.10.1)
from starpunk.notes import _websub_changed
_websub_changed(note)
# Crosspost after media is attached so images go out too (v2.1.0)
if "syndication_form" in request.form:
from starpunk.syndication import select_targets
select_targets(note.id, request.form.getlist("syndicate_to"))
flash(f"Note created: {note.slug}", "success")
return redirect(url_for("admin.dashboard"))
except ValueError as e:
flash(f"Error creating note: {e}", "error")
return redirect(url_for("admin.new_note_form"))
except Exception as e:
flash(f"Unexpected error creating note: {e}", "error")
return redirect(url_for("admin.new_note_form"))
@bp.route("/edit/<int:note_id>", methods=["GET"])
@require_auth
def edit_note_form(note_id: int):
"""
Display edit note form
Shows form pre-filled with existing note content for editing.
Requires authentication.
Args:
note_id: Database ID of note to edit
Returns:
Rendered edit form template or 404 if note not found
Decorator: @require_auth
Template: templates/admin/edit.html
"""
from starpunk.tags import get_note_tags
note = get_note(id=note_id)
if not note:
flash("Note not found", "error")
return redirect(url_for("admin.dashboard")), 404
# Pre-load tags for the edit form (v1.3.0 Phase 3), as entered so saving keeps the order
tags = get_note_tags(note.id, entered_order=True)
object.__setattr__(note, '_cached_tags', tags)
from starpunk.syndication import get_note_syndications, get_targets
syndications = get_note_syndications(note.id)
enabled = {s["target"] for s in syndications if s["enabled"]}
return render_template(
"admin/edit.html",
note=note,
syndication_targets=get_targets().values(),
syndications=syndications,
syndication_enabled=enabled,
backfeed_enabled=current_app.config.get("BACKFEED_ENABLED", False),
)
@bp.route("/edit/<int:note_id>", methods=["POST"])
@require_auth
def update_note_submit(note_id: int):
"""
Handle note update submission
Updates existing note with submitted form data.
Requires authentication.
Args:
note_id: Database ID of note to update
Form data:
content: Updated markdown content (required)
published: Checkbox for published status (optional)
tags: Comma-separated tag list (v1.3.0 Phase 3)
title, summary: Empty removes them; a form without the field leaves them (v2.16.0)
Returns:
Redirect to dashboard on success, back to form on error
Decorator: @require_auth
"""
from starpunk.notes import UNCHANGED
from starpunk.tags import parse_tag_input
# Check if note exists first
existing_note = get_note(id=note_id, load_content=False)
if not existing_note:
flash("Note not found", "error")
return redirect(url_for("admin.dashboard")), 404
content = request.form.get("content", "").strip()
published = "published" in request.form
tags_input = request.form.get("tags", "")
title = request.form["title"].strip() if "title" in request.form else UNCHANGED
summary = request.form["summary"].strip() if "summary" in request.form else UNCHANGED
has_title = existing_note.title if title is UNCHANGED else title
# Likes/reposts may have no comment, articles no body
if not content and not (existing_note.reacts_to or has_title):
flash("Content cannot be empty", "error")
return redirect(url_for("admin.edit_note_form", note_id=note_id))
# Parse tags (v1.3.0 Phase 3)
tags = parse_tag_input(tags_input)
try:
note = update_note(
id=note_id,
content=content,
published=published,
# An empty Tags field removes all tags (v2.14.1); a form without
# the field leaves them alone
tags=tags if "tags" in request.form else None,
title=title,
summary=summary,
)
if "syndication_form" in request.form:
from starpunk.syndication import select_targets
select_targets(note.id, request.form.getlist("syndicate_to"))
flash(f"Note updated: {note.slug}", "success")
return redirect(url_for("admin.dashboard"))
except ValueError as e:
flash(f"Error updating note: {e}", "error")
return redirect(url_for("admin.edit_note_form", note_id=note_id))
except Exception as e:
flash(f"Unexpected error updating note: {e}", "error")
return redirect(url_for("admin.edit_note_form", note_id=note_id))
@bp.route("/delete/<int:note_id>", methods=["POST"])
@require_auth
def delete_note_submit(note_id: int):
"""
Handle note deletion
Deletes a note after confirmation.
Requires authentication.
Args:
note_id: Database ID of note to delete
Form data:
confirm: Must be 'yes' to proceed with deletion
Returns:
Redirect to dashboard with success/error message
Decorator: @require_auth
"""
# Check if note exists first (per ADR-012)
existing_note = get_note(id=note_id, load_content=False)
if not existing_note:
flash("Note not found", "error")
return redirect(url_for("admin.dashboard")), 404
# Check for confirmation
if request.form.get("confirm") != "yes":
flash("Deletion cancelled", "info")
return redirect(url_for("admin.dashboard"))
try:
delete_note(id=note_id, soft=False)
flash("Note deleted successfully", "success")
except ValueError as e:
flash(f"Error deleting note: {e}", "error")
except Exception as e:
flash(f"Unexpected error deleting note: {e}", "error")
return redirect(url_for("admin.dashboard"))
@bp.route("/health")
@require_auth
def health_diagnostics():
"""
Full health diagnostics endpoint for admin use
Per developer Q&A Q10:
- Always requires authentication
- Provides comprehensive diagnostics
- Includes database pool statistics and system info
Returns:
JSON with complete system diagnostics
Response codes:
200: Diagnostics retrieved successfully
500: Critical health issues detected
Decorator: @require_auth
"""
from flask import current_app
from starpunk.database.pool import get_pool_stats
diagnostics = {
"status": "healthy",
"version": current_app.config.get("VERSION", "unknown"),
"environment": current_app.config.get("ENV", "unknown"),
"process_id": os.getpid(),
"checks": {},
"database": {}
}
overall_healthy = True
# Database connectivity check
try:
from starpunk.database import get_db
db = get_db()
result = db.execute("SELECT 1").fetchone()
db.close()
diagnostics["checks"]["database"] = {
"status": "healthy",
"message": "Database accessible"
}
# Get database pool statistics
try:
pool_stats = get_pool_stats()
diagnostics["database"]["pool"] = pool_stats
except Exception as e:
diagnostics["database"]["pool"] = {"error": str(e)}
except Exception as e:
diagnostics["checks"]["database"] = {
"status": "unhealthy",
"error": str(e)
}
overall_healthy = False
# Filesystem check
try:
data_path = current_app.config.get("DATA_PATH", "data")
if not os.path.exists(data_path):
raise Exception("Data path not accessible")
diagnostics["checks"]["filesystem"] = {
"status": "healthy",
"path": data_path,
"writable": os.access(data_path, os.W_OK),
"readable": os.access(data_path, os.R_OK)
}
except Exception as e:
diagnostics["checks"]["filesystem"] = {
"status": "unhealthy",
"error": str(e)
}
overall_healthy = False
# Disk space check
try:
data_path = current_app.config.get("DATA_PATH", "data")
stat = shutil.disk_usage(data_path)
percent_free = (stat.free / stat.total) * 100
diagnostics["checks"]["disk"] = {
"status": "healthy" if percent_free > 10 else ("warning" if percent_free > 5 else "critical"),
"total_gb": round(stat.total / (1024**3), 2),
"used_gb": round(stat.used / (1024**3), 2),
"free_gb": round(stat.free / (1024**3), 2),
"percent_free": round(percent_free, 2),
"percent_used": round((stat.used / stat.total) * 100, 2)
}
if percent_free <= 5:
overall_healthy = False
except Exception as e:
diagnostics["checks"]["disk"] = {
"status": "unhealthy",
"error": str(e)
}
overall_healthy = False
# Update overall status
diagnostics["status"] = "healthy" if overall_healthy else "unhealthy"
return jsonify(diagnostics), 200 if overall_healthy else 500
# Webmention Admin Routes (v1.6.0)
@bp.route("/webmentions")
@require_auth
def webmentions():
"""
Webmention list with filtering and pagination (v1.6.0 Phase 5)
Lists all webmentions with status filters and pagination.
Query params:
status: Filter by moderation_status ('pending', 'approved', 'hidden')
page: Page number (default: 1)
Returns:
Rendered webmentions list template
Decorator: @require_auth
Template: templates/admin/webmentions.html
"""
from starpunk.webmention_queries import list_webmentions
status_filter = request.args.get('status')
origin_filter = request.args.get('origin') or None
page = int(request.args.get('page', 1))
webmentions, total_pages = list_webmentions(
status_filter=status_filter,
page=page,
per_page=25,
origin_filter=origin_filter,
)
from starpunk import backfeed
return render_template(
"admin/webmentions.html",
webmentions=webmentions,
status_filter=status_filter,
origin_filter=origin_filter,
backfeed=backfeed.status(),
notify=_notify_status(),
page=page,
total_pages=total_pages,
user_me=g.me
)
@bp.route("/webmentions/<int:id>")
@require_auth
def webmention_detail(id: int):
"""
Webmention detail view (v1.6.0 Phase 5)
Shows full details of a single webmention with moderation actions.
Args:
id: Webmention database ID
Returns:
Rendered webmention detail template or 404 if not found
Decorator: @require_auth
Template: templates/admin/webmention_detail.html
"""
from starpunk.webmention_queries import get_webmention
webmention = get_webmention(id)
if not webmention:
flash("Webmention not found", "error")
return redirect(url_for("admin.webmentions")), 404
return render_template(
"admin/webmention_detail.html",
webmention=webmention,
user_me=g.me
)
@bp.route("/webmentions/<int:id>/action", methods=["POST"])
@require_auth
def webmention_action(id: int):
"""
Individual webmention moderation action (v1.6.0 Phase 5)
Approve, hide, or delete a single webmention.
Args:
id: Webmention database ID
Form data:
action: 'approve', 'hide', or 'delete'
Returns:
Redirect to webmention detail or list
Decorator: @require_auth
"""
from starpunk.webmention_queries import update_webmention_status, delete_webmentions
action = request.form.get('action')
if action not in ('approve', 'hide', 'delete'):
flash("Invalid action", "error")
return redirect(url_for("admin.webmention_detail", id=id))
try:
if action == 'delete':
deleted = delete_webmentions([id])
if deleted > 0:
flash("Webmention deleted", "success")
else:
flash("Webmention not found", "error")
return redirect(url_for("admin.webmentions"))
else:
# Approve or hide
status = 'approved' if action == 'approve' else 'hidden'
updated = update_webmention_status([id], status)
if updated > 0:
flash(f"Webmention {status}", "success")
else:
flash("Webmention not found", "error")
return redirect(url_for("admin.webmention_detail", id=id))
except Exception as e:
logger.error(f"Error performing webmention action: {e}")
flash(f"Error: {e}", "error")
return redirect(url_for("admin.webmention_detail", id=id))
@bp.route("/webmentions/bulk-action", methods=["POST"])
@require_auth
def webmention_bulk_action():
"""
Bulk webmention moderation actions (v1.6.0 Phase 5)
Approve, hide, or delete multiple webmentions at once.
Form data:
action: 'approve', 'hide', or 'delete'
ids[]: List of webmention IDs
Returns:
Redirect to webmentions list
Decorator: @require_auth
"""
from starpunk.webmention_queries import update_webmention_status, delete_webmentions
action = request.form.get('action')
ids = request.form.getlist('ids')
if not ids:
flash("No webmentions selected", "warning")
return redirect(url_for("admin.webmentions"))
# Convert IDs to integers
try:
webmention_ids = [int(id) for id in ids]
except ValueError:
flash("Invalid webmention IDs", "error")
return redirect(url_for("admin.webmentions"))
if action not in ('approve', 'hide', 'delete'):
flash("Invalid action", "error")
return redirect(url_for("admin.webmentions"))
try:
if action == 'delete':
deleted = delete_webmentions(webmention_ids)
flash(f"Deleted {deleted} webmention(s)", "success")
else:
# Approve or hide
status = 'approved' if action == 'approve' else 'hidden'
updated = update_webmention_status(webmention_ids, status)
flash(f"Updated {updated} webmention(s) to {status}", "success")
return redirect(url_for("admin.webmentions"))
except Exception as e:
logger.error(f"Error performing bulk action: {e}")
flash(f"Error: {e}", "error")
return redirect(url_for("admin.webmentions"))
# Connected Micropub apps (v2.0.0)
@bp.route("/tokens")
@require_auth
def tokens():
"""List active IndieAuth tokens. Template: templates/admin/tokens.html"""
from starpunk.indieauth import list_active_tokens
return render_template("admin/tokens.html", tokens=list_active_tokens(), user_me=g.me)
@bp.route("/tokens/<int:token_id>/revoke", methods=["POST"])
@require_auth
def revoke_token(token_id):
"""Revoke one IndieAuth token"""
from starpunk.indieauth import revoke_token_by_id
revoke_token_by_id(token_id)
flash("App access revoked", "success")
return redirect(url_for("admin.tokens"))
def _notify_status() -> dict:
"""Notification settings and last error for the Webmentions page (v2.14.0)"""
from starpunk import notifications
from starpunk.database import get_db
return {
"enabled": notifications.enabled(current_app.config),
"events": sorted(notifications.events(current_app.config)),
"priority": current_app.config.get("NOTIFY_PRIORITY") or "normal",
"services": [u.split("://", 1)[0] for u in notifications.urls(current_app.config)],
"last_error": notifications.last_error(get_db(current_app)),
}
@bp.route("/notifications/test", methods=["POST"])
@require_auth
def notifications_test():
"""Send a test notification to every NOTIFY_URLS service (v2.14.0)"""
from starpunk import notifications
ok, error = notifications.send(current_app.config, "StarPunk test notification",
"Notifications from StarPunk are working.")
notifications._record(current_app.config["DATABASE_PATH"], ok, error)
flash("Test notification sent" if ok else f"Test notification failed: {error or 'unknown error'}",
"success" if ok else "error")
return redirect(url_for("admin.webmentions"))
@bp.route("/backfeed/backfill", methods=["POST"])
@require_auth
def backfeed_backfill():
"""Check every crosspost once for responses, whatever its age (v2.13.0)"""
from starpunk import backfeed
count = backfeed.start_backfill()
flash(f"Backfill started: {count} crosspost(s) to check", "success")
return redirect(url_for("admin.webmentions"))
@bp.route("/syndication/<int:syndication_id>/check", methods=["POST"])
@require_auth
def check_syndication_responses(syndication_id):
"""Check one crosspost's responses at the next worker pass (v2.13.0)"""
from starpunk import backfeed
backfeed.check_now(syndication_id)
flash("Responses will be checked shortly", "success")
return redirect(request.referrer or url_for("admin.dashboard"))
@bp.route("/syndication/<int:syndication_id>/retry", methods=["POST"])
@require_auth
def retry_syndication(syndication_id):
"""Retry a crosspost now"""
from starpunk.syndication import retry
retry(syndication_id)
flash("Crosspost queued", "success")
return redirect(request.referrer or url_for("admin.dashboard"))