File size: 2,105 Bytes
25e4412
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
"""Who may see a song or job, and deleting a song with everything that belongs to it.

Shared by the API routes and the public site's cleanup (stemdeck/housekeeping.py). A song of another visitor is
reported as "not found", exactly like a song that doesn't exist, so ids reveal nothing.
"""

from __future__ import annotations

import re
import shutil
from pathlib import Path

from fastapi import HTTPException
from sqlmodel import Session, col, delete, select

from stemdeck.jobrunner import runner
from stemdeck.models import TERMINAL_JOB_STATUSES, Job, Mix, Song, Stem
from stemdeck.settings import get_settings

SONG_ID = re.compile(r"[0-9a-f]{32}")


def song_folder(song_id: str) -> Path:
    if not SONG_ID.fullmatch(song_id):
        raise HTTPException(404, "Song not found.")
    return get_settings().songs_dir / song_id


def owned_song(session: Session, song_id: str, owner: str) -> Song:
    song = session.get(Song, song_id)
    if song is None or song.owner != owner:
        raise HTTPException(404, "Song not found.")
    return song


def owned_job(session: Session, job_id: str, owner: str) -> Job:
    job = session.get(Job, job_id)
    song = session.get(Song, job.song_id) if job is not None else None
    if job is None or song is None or song.owner != owner:
        raise HTTPException(404, "Job not found.")
    return job


def remove_song(session: Session, song_id: str) -> None:
    """Cancel the song's unfinished jobs, then delete its rows and its folder."""
    active = session.exec(select(Job).where(Job.song_id == song_id,
                                            col(Job.status).not_in(TERMINAL_JOB_STATUSES))).all()
    for job in active:
        runner.cancel(job.id)
    session.expire_all()
    for table in (Stem, Mix, Job):
        session.exec(delete(table).where(table.song_id == song_id))  # type: ignore[arg-type, attr-defined]
    song = session.get(Song, song_id)
    if song is not None:
        session.delete(song)
    session.commit()
    if SONG_ID.fullmatch(song_id):
        shutil.rmtree(get_settings().songs_dir / song_id, ignore_errors=True)