97672ffdcd
- Run now (jobs.run_now): playlists without a daily sync time are never
registered as scheduler jobs, so the old registered-job check 404'd. Fall
back to running the playlist directly via pipeline_runner for any
playlist:<name> key that isn't registered.
- Spotify removed GET /playlists/{id}/tracks in its February 2026 API changes
in favor of /items (identical response shape). New apps are already 403'd on
the old endpoint. Migrate both callers (app/services/spotify_client.py and
pipeline/lib/spotify-retag.py) to /items. (The vendored sldl downloader uses
its own bundled Spotify library and would need an upstream update when
/tracks is fully removed.)
- Friendlier on-screen error for a Spotify 403 (check credentials + playlist
must be public) and a README troubleshooting entry covering the 403, the
public-playlist requirement, and the org-only extended-quota reality.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
128 lines
5.6 KiB
Python
128 lines
5.6 KiB
Python
from fastapi import APIRouter, BackgroundTasks, Depends, HTTPException, Request
|
|
from fastapi.responses import PlainTextResponse, RedirectResponse
|
|
from fastapi.templating import Jinja2Templates
|
|
from sqlalchemy import select
|
|
|
|
from app.db import get_db
|
|
from app.models import JobRun, ScheduledJob
|
|
from app.security.deps import require_auth
|
|
from app.services import pipeline_runner, playlist_service, scheduler_service
|
|
|
|
router = APIRouter(prefix="/settings/jobs", tags=["jobs"])
|
|
templates = Jinja2Templates(directory="app/templates")
|
|
|
|
|
|
def _format_next_run(dt) -> str:
|
|
"""Same HH:MM (24h, zero-padded) convention the playlists' simplified
|
|
time field uses, with a short day qualifier when it's not today --
|
|
maintenance jobs can be weekly/monthly, so the date can't just be
|
|
dropped the way it is for playlists' plain daily time."""
|
|
if dt is None:
|
|
return "-"
|
|
now = dt.__class__.now(dt.tzinfo)
|
|
if dt.date() == now.date():
|
|
return dt.strftime("%H:%M")
|
|
return dt.strftime("%a %H:%M")
|
|
|
|
|
|
def _job_list_context(db):
|
|
scheduler = scheduler_service.get_scheduler()
|
|
registered = {j.id: j for j in (scheduler.get_jobs() if scheduler else [])}
|
|
enabled_by_key = {
|
|
row.job_key: row.enabled for row in db.execute(select(ScheduledJob)).scalars()
|
|
}
|
|
maintenance_jobs = []
|
|
for job_key in scheduler_service.MAINTENANCE_JOBS:
|
|
job = registered.get(job_key)
|
|
next_run = getattr(job, "next_run_time", None) if job else None
|
|
maintenance_jobs.append(
|
|
{
|
|
"job_key": job_key,
|
|
"label": scheduler_service.humanize_job_key(job_key),
|
|
"description": scheduler_service.MAINTENANCE_JOB_DESCRIPTIONS.get(job_key, ""),
|
|
"next_run": _format_next_run(next_run),
|
|
"enabled": enabled_by_key.get(job_key, True),
|
|
}
|
|
)
|
|
recent_runs = list(
|
|
db.execute(select(JobRun).order_by(JobRun.started_at.desc()).limit(50)).scalars()
|
|
)
|
|
return {
|
|
"maintenance_jobs": maintenance_jobs,
|
|
"recent_runs": recent_runs,
|
|
"humanize_job_key": scheduler_service.humanize_job_key,
|
|
}
|
|
|
|
|
|
@router.get("")
|
|
async def jobs_index(request: Request, user: dict = Depends(require_auth), db=Depends(get_db)):
|
|
return templates.TemplateResponse(request, "jobs/index.html", _job_list_context(db))
|
|
|
|
|
|
@router.get("/_runs_table")
|
|
async def runs_table_partial(request: Request, user: dict = Depends(require_auth), db=Depends(get_db)):
|
|
"""HTMX polling target: just the recent-runs table body, so the jobs
|
|
page can auto-refresh run status without a full page reload."""
|
|
return templates.TemplateResponse(request, "jobs/_runs_table.html", _job_list_context(db))
|
|
|
|
|
|
@router.post("/{job_key:path}/run")
|
|
async def run_now(
|
|
job_key: str, background: BackgroundTasks, user: dict = Depends(require_auth), db=Depends(get_db)
|
|
):
|
|
scheduler = scheduler_service.get_scheduler()
|
|
if scheduler is None:
|
|
raise HTTPException(503, "scheduler not running")
|
|
# Validate the job exists now (so a bad key still 404s), then run it in the
|
|
# background and redirect immediately. A playlist sync can take the better
|
|
# part of an hour; awaiting it here would hang the browser/reverse proxy.
|
|
# Progress shows up in the runs table below, which polls every few seconds.
|
|
if scheduler.get_job(job_key) is not None:
|
|
background.add_task(scheduler_service.trigger_now, scheduler, job_key)
|
|
return RedirectResponse(url="/settings/jobs?started=1", status_code=303)
|
|
|
|
# Playlists with no cron_expr (or paused) are never registered with the
|
|
# scheduler by sync_playlist_jobs -- that's "unscheduled/manual-only" by
|
|
# design, not missing. Run it directly through pipeline_runner instead of
|
|
# requiring a scheduler job to exist, so "Run now" works for those too.
|
|
if job_key.startswith("playlist:"):
|
|
playlist = playlist_service.get_by_name(db, job_key.removeprefix("playlist:"))
|
|
if playlist is not None:
|
|
background.add_task(
|
|
pipeline_runner.run_playlist, playlist.name, playlist.no_m3u, "manual"
|
|
)
|
|
return RedirectResponse(url="/settings/jobs?started=1", status_code=303)
|
|
|
|
raise HTTPException(404, f"no such registered job: {job_key}")
|
|
|
|
|
|
@router.post("/{job_key:path}/toggle")
|
|
async def toggle_enabled(job_key: str, user: dict = Depends(require_auth), db=Depends(get_db)):
|
|
scheduler = scheduler_service.get_scheduler()
|
|
if scheduler is None:
|
|
raise HTTPException(503, "scheduler not running")
|
|
row = db.execute(select(ScheduledJob).where(ScheduledJob.job_key == job_key)).scalar_one_or_none()
|
|
currently_enabled = row.enabled if row else True
|
|
scheduler_service.set_maintenance_enabled(scheduler, job_key, not currently_enabled)
|
|
return RedirectResponse(url="/settings/jobs", status_code=303)
|
|
|
|
|
|
@router.get("/runs/{run_id}/log", response_class=PlainTextResponse)
|
|
async def view_log(run_id: int, user: dict = Depends(require_auth), db=Depends(get_db)):
|
|
run = db.get(JobRun, run_id)
|
|
if run is None or not run.log_path:
|
|
raise HTTPException(404, "no such run/log")
|
|
from pathlib import Path
|
|
|
|
from app.settings import settings
|
|
|
|
# Containment check: only ever serve files from under the logs dir. Paths
|
|
# are app-generated so this is defense in depth against a malformed row.
|
|
logs_dir = settings.logs_dir.resolve()
|
|
path = Path(run.log_path).resolve()
|
|
if logs_dir != path and logs_dir not in path.parents:
|
|
raise HTTPException(404, "no such run/log")
|
|
if not path.exists():
|
|
raise HTTPException(404, "log file no longer exists")
|
|
return path.read_text(errors="replace")
|