:chore: Initialisation du projet
This commit is contained in:
1 parent
75a8c6addd
commit
6278d19618
27 files changed
+4418
-81
No files matched your search
@@ -0,0 +1,2 @@
|
||||
"""MKVTool API package."""
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
from pathlib import Path
|
||||
|
||||
from pydantic_settings import BaseSettings, SettingsConfigDict
|
||||
|
||||
|
||||
class AppSettings(BaseSettings):
|
||||
config_dir: Path = Path("./config")
|
||||
database_url: str | None = None
|
||||
|
||||
model_config = SettingsConfigDict(env_prefix="MKVTOOL_", env_file=".env")
|
||||
|
||||
@property
|
||||
def resolved_database_url(self) -> str:
|
||||
if self.database_url:
|
||||
return self.database_url
|
||||
return f"sqlite:///{self.config_dir / 'mkvtool.db'}"
|
||||
|
||||
|
||||
settings = AppSettings()
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
from collections.abc import Generator
|
||||
|
||||
from sqlalchemy import create_engine
|
||||
from sqlalchemy.orm import DeclarativeBase, Session, sessionmaker
|
||||
|
||||
from app.config import settings
|
||||
|
||||
settings.config_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
engine = create_engine(
|
||||
settings.resolved_database_url,
|
||||
connect_args={"check_same_thread": False}
|
||||
if settings.resolved_database_url.startswith("sqlite")
|
||||
else {},
|
||||
)
|
||||
SessionLocal = sessionmaker(bind=engine, expire_on_commit=False)
|
||||
|
||||
|
||||
class Base(DeclarativeBase):
|
||||
pass
|
||||
|
||||
|
||||
def get_db() -> Generator[Session]:
|
||||
with SessionLocal() as session:
|
||||
yield session
|
||||
|
||||
+151
@@ -0,0 +1,151 @@
|
||||
import os
|
||||
import shutil
|
||||
from contextlib import asynccontextmanager
|
||||
from datetime import UTC, datetime
|
||||
from typing import Annotated
|
||||
|
||||
import httpx
|
||||
from fastapi import Depends, FastAPI, HTTPException
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app.database import Base, engine, get_db
|
||||
from app.models import IsoMovie
|
||||
from app.radarr import RadarrClient, movie_file_path
|
||||
from app.schemas import (
|
||||
ConnectionResult,
|
||||
HealthRead,
|
||||
IsoMovieRead,
|
||||
RadarrSettingsRead,
|
||||
RadarrSettingsWrite,
|
||||
ScanResult,
|
||||
)
|
||||
from app.settings_store import radarr_credentials, read_setting, write_setting
|
||||
|
||||
|
||||
@asynccontextmanager
|
||||
async def lifespan(_: FastAPI):
|
||||
Base.metadata.create_all(bind=engine)
|
||||
yield
|
||||
|
||||
|
||||
app = FastAPI(title="MKVTool", version="0.1.0", lifespan=lifespan)
|
||||
app.add_middleware(
|
||||
CORSMiddleware,
|
||||
allow_origins=["http://localhost:5173", "http://127.0.0.1:5173"],
|
||||
allow_methods=["*"],
|
||||
allow_headers=["*"],
|
||||
)
|
||||
|
||||
DbSession = Annotated[Session, Depends(get_db)]
|
||||
|
||||
|
||||
def client_from_db(db: Session) -> RadarrClient:
|
||||
try:
|
||||
url, api_key = radarr_credentials(db)
|
||||
except ValueError as error:
|
||||
raise HTTPException(status_code=409, detail=str(error)) from error
|
||||
return RadarrClient(url, api_key)
|
||||
|
||||
|
||||
@app.get("/api/health", response_model=HealthRead)
|
||||
def health() -> HealthRead:
|
||||
executable = shutil.which("makemkvcon")
|
||||
return HealthRead(
|
||||
status="ok",
|
||||
database="ok",
|
||||
makemkv_available=executable is not None,
|
||||
makemkv_version=os.getenv("MAKEMKV_VERSION") if executable else None,
|
||||
)
|
||||
|
||||
|
||||
@app.get("/api/settings/radarr", response_model=RadarrSettingsRead)
|
||||
def get_radarr_settings(db: DbSession) -> RadarrSettingsRead:
|
||||
return RadarrSettingsRead(
|
||||
url=read_setting(db, "radarr_url"),
|
||||
api_key_configured=read_setting(db, "radarr_api_key") is not None,
|
||||
)
|
||||
|
||||
|
||||
@app.put("/api/settings/radarr", response_model=RadarrSettingsRead)
|
||||
def put_radarr_settings(
|
||||
payload: RadarrSettingsWrite, db: DbSession
|
||||
) -> RadarrSettingsRead:
|
||||
url = str(payload.url).rstrip("/")
|
||||
write_setting(db, "radarr_url", url)
|
||||
if payload.api_key:
|
||||
write_setting(db, "radarr_api_key", payload.api_key)
|
||||
db.commit()
|
||||
return RadarrSettingsRead(
|
||||
url=url, api_key_configured=read_setting(db, "radarr_api_key") is not None
|
||||
)
|
||||
|
||||
|
||||
@app.post("/api/settings/radarr/test", response_model=ConnectionResult)
|
||||
async def test_radarr(db: DbSession) -> ConnectionResult:
|
||||
client = client_from_db(db)
|
||||
try:
|
||||
status = await client.system_status()
|
||||
except (httpx.HTTPError, ValueError) as error:
|
||||
raise HTTPException(
|
||||
status_code=502, detail=f"Connexion Radarr impossible: {error}"
|
||||
) from error
|
||||
version = str(status.get("version", "inconnue"))
|
||||
return ConnectionResult(success=True, version=version, message=f"Radarr {version} accessible")
|
||||
|
||||
|
||||
@app.get("/api/movies", response_model=list[IsoMovieRead])
|
||||
def list_movies(db: DbSession) -> list[IsoMovie]:
|
||||
return list(db.scalars(select(IsoMovie).order_by(IsoMovie.title)).all())
|
||||
|
||||
|
||||
@app.post("/api/scans", response_model=ScanResult)
|
||||
async def scan_radarr(db: DbSession) -> ScanResult:
|
||||
client = client_from_db(db)
|
||||
try:
|
||||
movies = await client.movies()
|
||||
except (httpx.HTTPError, ValueError) as error:
|
||||
raise HTTPException(status_code=502, detail=f"Scan Radarr impossible: {error}") from error
|
||||
|
||||
iso_files = created = updated = 0
|
||||
now = datetime.now(UTC)
|
||||
for movie in movies:
|
||||
movie_file = movie.get("movieFile") or {}
|
||||
path = movie_file_path(movie)
|
||||
if not path or not path.lower().endswith(".iso"):
|
||||
continue
|
||||
movie_id = movie.get("id")
|
||||
movie_file_id = movie_file.get("id")
|
||||
if not isinstance(movie_id, int) or not isinstance(movie_file_id, int):
|
||||
continue
|
||||
iso_files += 1
|
||||
item = db.scalar(
|
||||
select(IsoMovie).where(
|
||||
IsoMovie.radarr_movie_id == movie_id,
|
||||
IsoMovie.radarr_movie_file_id == movie_file_id,
|
||||
)
|
||||
)
|
||||
if item is None:
|
||||
item = IsoMovie(
|
||||
radarr_movie_id=movie_id,
|
||||
radarr_movie_file_id=movie_file_id,
|
||||
title=str(movie.get("title", "Film sans titre")),
|
||||
year=movie.get("year"),
|
||||
path=path,
|
||||
size=movie_file.get("size"),
|
||||
last_seen_at=now,
|
||||
)
|
||||
db.add(item)
|
||||
created += 1
|
||||
else:
|
||||
item.title = str(movie.get("title", item.title))
|
||||
item.year = movie.get("year")
|
||||
item.path = path
|
||||
item.size = movie_file.get("size")
|
||||
item.last_seen_at = now
|
||||
updated += 1
|
||||
db.commit()
|
||||
return ScanResult(
|
||||
scanned_movies=len(movies), iso_files=iso_files, created=created, updated=updated
|
||||
)
|
||||
@@ -0,0 +1,31 @@
|
||||
from datetime import datetime
|
||||
|
||||
from sqlalchemy import BigInteger, DateTime, String, Text, UniqueConstraint, func
|
||||
from sqlalchemy.orm import Mapped, mapped_column
|
||||
|
||||
from app.database import Base
|
||||
|
||||
|
||||
class ApplicationSetting(Base):
|
||||
__tablename__ = "application_settings"
|
||||
|
||||
key: Mapped[str] = mapped_column(String(100), primary_key=True)
|
||||
value: Mapped[str] = mapped_column(Text)
|
||||
|
||||
|
||||
class IsoMovie(Base):
|
||||
__tablename__ = "iso_movies"
|
||||
__table_args__ = (UniqueConstraint("radarr_movie_id", "radarr_movie_file_id"),)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
radarr_movie_id: Mapped[int] = mapped_column(index=True)
|
||||
radarr_movie_file_id: Mapped[int]
|
||||
title: Mapped[str] = mapped_column(String(500))
|
||||
year: Mapped[int | None]
|
||||
path: Mapped[str] = mapped_column(Text)
|
||||
size: Mapped[int | None] = mapped_column(BigInteger)
|
||||
status: Mapped[str] = mapped_column(String(30), default="detected")
|
||||
last_seen_at: Mapped[datetime] = mapped_column(
|
||||
DateTime(timezone=True), server_default=func.now()
|
||||
)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())
|
||||
@@ -0,0 +1,40 @@
|
||||
from pathlib import PurePath
|
||||
|
||||
import httpx
|
||||
|
||||
|
||||
class RadarrClient:
|
||||
def __init__(self, url: str, api_key: str) -> None:
|
||||
self._url = url.rstrip("/")
|
||||
self._headers = {"X-Api-Key": api_key}
|
||||
|
||||
async def _get(self, endpoint: str) -> object:
|
||||
async with httpx.AsyncClient(timeout=30) as client:
|
||||
response = await client.get(f"{self._url}/api/v3/{endpoint}", headers=self._headers)
|
||||
response.raise_for_status()
|
||||
return response.json()
|
||||
|
||||
async def system_status(self) -> dict:
|
||||
result = await self._get("system/status")
|
||||
if not isinstance(result, dict):
|
||||
raise ValueError("Réponse Radarr inattendue")
|
||||
return result
|
||||
|
||||
async def movies(self) -> list[dict]:
|
||||
result = await self._get("movie")
|
||||
if not isinstance(result, list):
|
||||
raise ValueError("Réponse Radarr inattendue")
|
||||
return result
|
||||
|
||||
|
||||
def movie_file_path(movie: dict) -> str | None:
|
||||
movie_file = movie.get("movieFile") or {}
|
||||
path = movie_file.get("path")
|
||||
if path:
|
||||
return str(path)
|
||||
relative_path = movie_file.get("relativePath")
|
||||
movie_path = movie.get("path")
|
||||
if relative_path and movie_path:
|
||||
return str(PurePath(str(movie_path)) / str(relative_path))
|
||||
return None
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
from datetime import datetime
|
||||
|
||||
from pydantic import BaseModel, ConfigDict, Field, HttpUrl
|
||||
|
||||
|
||||
class RadarrSettingsRead(BaseModel):
|
||||
url: str | None
|
||||
api_key_configured: bool
|
||||
|
||||
|
||||
class RadarrSettingsWrite(BaseModel):
|
||||
url: HttpUrl
|
||||
api_key: str | None = Field(default=None, min_length=1)
|
||||
|
||||
|
||||
class ConnectionResult(BaseModel):
|
||||
success: bool
|
||||
version: str | None = None
|
||||
message: str
|
||||
|
||||
|
||||
class IsoMovieRead(BaseModel):
|
||||
model_config = ConfigDict(from_attributes=True)
|
||||
|
||||
id: int
|
||||
radarr_movie_id: int
|
||||
radarr_movie_file_id: int
|
||||
title: str
|
||||
year: int | None
|
||||
path: str
|
||||
size: int | None
|
||||
status: str
|
||||
last_seen_at: datetime
|
||||
|
||||
|
||||
class ScanResult(BaseModel):
|
||||
scanned_movies: int
|
||||
iso_files: int
|
||||
created: int
|
||||
updated: int
|
||||
|
||||
|
||||
class HealthRead(BaseModel):
|
||||
status: str
|
||||
database: str
|
||||
makemkv_available: bool
|
||||
makemkv_version: str | None
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app.models import ApplicationSetting
|
||||
|
||||
|
||||
def read_setting(db: Session, key: str) -> str | None:
|
||||
item = db.get(ApplicationSetting, key)
|
||||
return item.value if item else None
|
||||
|
||||
|
||||
def write_setting(db: Session, key: str, value: str) -> None:
|
||||
item = db.get(ApplicationSetting, key)
|
||||
if item:
|
||||
item.value = value
|
||||
else:
|
||||
db.add(ApplicationSetting(key=key, value=value))
|
||||
|
||||
|
||||
def radarr_credentials(db: Session) -> tuple[str, str]:
|
||||
url = read_setting(db, "radarr_url")
|
||||
api_key = read_setting(db, "radarr_api_key")
|
||||
if not url or not api_key:
|
||||
raise ValueError("La connexion Radarr n'est pas configurée")
|
||||
return url.rstrip("/"), api_key
|
||||
|
||||
Reference in new issue
Block a user