Correction git
This commit is contained in:
1 parent
59d5340833
commit
a0d79d8d59
8 files changed
+494
No files matched your search
@@ -0,0 +1,9 @@
|
|||||||
|
{
|
||||||
|
"features": {
|
||||||
|
"ghcr.io/devcontainers/features/node:1": {
|
||||||
|
"version": "1.7.1",
|
||||||
|
"resolved": "ghcr.io/devcontainers/features/node@sha256:8c0de46939b61958041700ee89e3493f3b2e4131a06dc46b4d9423427d06e5f6",
|
||||||
|
"integrity": "sha256:8c0de46939b61958041700ee89e3493f3b2e4131a06dc46b4d9423427d06e5f6"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
+65
@@ -0,0 +1,65 @@
|
|||||||
|
# syntax=docker/dockerfile:1
|
||||||
|
|
||||||
|
ARG MAKEMKV_VERSION=2.0.0
|
||||||
|
|
||||||
|
# --- Interface web ---
|
||||||
|
FROM node:22-slim AS web
|
||||||
|
WORKDIR /web
|
||||||
|
COPY web/package.json web/package-lock.json ./
|
||||||
|
RUN npm ci
|
||||||
|
COPY web/ ./
|
||||||
|
RUN npm run build
|
||||||
|
|
||||||
|
# --- API + worker ---
|
||||||
|
FROM python:3.13-slim AS api
|
||||||
|
ARG MAKEMKV_VERSION
|
||||||
|
|
||||||
|
RUN apt-get update \
|
||||||
|
&& export DEBIAN_FRONTEND=noninteractive \
|
||||||
|
&& apt-get install -y --no-install-recommends \
|
||||||
|
build-essential \
|
||||||
|
ca-certificates \
|
||||||
|
curl \
|
||||||
|
ffmpeg \
|
||||||
|
libavcodec-dev \
|
||||||
|
libavutil-dev \
|
||||||
|
libexpat1-dev \
|
||||||
|
libssl-dev \
|
||||||
|
zlib1g-dev \
|
||||||
|
&& apt-get clean \
|
||||||
|
&& rm -rf /var/lib/apt/lists/*
|
||||||
|
|
||||||
|
# MakeMKV (makemkvcon) — version explicite, licence a fournir via makemkv.
|
||||||
|
RUN curl -fsSLO "https://www.makemkv.com/download/makemkv-oss-${MAKEMKV_VERSION}.tar.gz" \
|
||||||
|
&& curl -fsSLO "https://www.makemkv.com/download/makemkv-bin-${MAKEMKV_VERSION}.tar.gz" \
|
||||||
|
&& tar -xzf "makemkv-oss-${MAKEMKV_VERSION}.tar.gz" \
|
||||||
|
&& tar -xzf "makemkv-bin-${MAKEMKV_VERSION}.tar.gz" \
|
||||||
|
&& cd "makemkv-oss-${MAKEMKV_VERSION}" \
|
||||||
|
&& ./configure --disable-gui \
|
||||||
|
&& make -j"$(nproc)" \
|
||||||
|
&& make install \
|
||||||
|
&& cd "/makemkv-bin-${MAKEMKV_VERSION}" \
|
||||||
|
&& mkdir -p tmp \
|
||||||
|
&& echo accepted > tmp/eula_accepted \
|
||||||
|
&& make -j"$(nproc)" \
|
||||||
|
&& make install \
|
||||||
|
&& cd / \
|
||||||
|
&& rm -rf "makemkv-oss-${MAKEMKV_VERSION}" "makemkv-bin-${MAKEMKV_VERSION}" \
|
||||||
|
"makemkv-oss-${MAKEMKV_VERSION}.tar.gz" "makemkv-bin-${MAKEMKV_VERSION}.tar.gz"
|
||||||
|
|
||||||
|
COPY --from=ghcr.io/astral-sh/uv:0.12.23 /uv /usr/local/bin/uv
|
||||||
|
WORKDIR /app
|
||||||
|
COPY pyproject.toml uv.lock ./
|
||||||
|
RUN uv sync --frozen --no-dev
|
||||||
|
COPY app/ app/
|
||||||
|
COPY --from=web /web/dist /app/web/dist
|
||||||
|
COPY docker/entrypoint.py /entrypoint.py
|
||||||
|
|
||||||
|
ENV MKVTOOL_CONFIG_DIR=/config \
|
||||||
|
MKVTOOL_WEB_DIR=/app/web/dist \
|
||||||
|
MAKEMKV_VERSION=${MAKEMKV_VERSION}
|
||||||
|
RUN mkdir -p /config
|
||||||
|
|
||||||
|
EXPOSE 8000
|
||||||
|
ENTRYPOINT ["python3", "/entrypoint.py"]
|
||||||
|
CMD ["/app/.venv/bin/uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000"]
|
||||||
+104
@@ -0,0 +1,104 @@
|
|||||||
|
"""Authentification locale: premier compte via lien à jeton, sessions en mémoire."""
|
||||||
|
|
||||||
|
import hashlib
|
||||||
|
import hmac
|
||||||
|
import secrets
|
||||||
|
|
||||||
|
from fastapi import Cookie, HTTPException
|
||||||
|
from sqlalchemy import func, select
|
||||||
|
|
||||||
|
from app.database import SessionLocal
|
||||||
|
from app.models import User
|
||||||
|
|
||||||
|
SESSION_COOKIE = "mkvtool_session"
|
||||||
|
_ITERATIONS = 600_000
|
||||||
|
|
||||||
|
_sessions: dict[str, int] = {}
|
||||||
|
setup_token: str | None = None
|
||||||
|
|
||||||
|
|
||||||
|
def hash_password(password: str) -> str:
|
||||||
|
salt = secrets.token_bytes(16)
|
||||||
|
digest = hashlib.pbkdf2_hmac("sha256", password.encode(), salt, _ITERATIONS)
|
||||||
|
return f"pbkdf2_sha256${_ITERATIONS}${salt.hex()}${digest.hex()}"
|
||||||
|
|
||||||
|
|
||||||
|
def verify_password(password: str, stored: str) -> bool:
|
||||||
|
scheme, iterations, salt_hex, digest_hex = stored.split("$")
|
||||||
|
if scheme != "pbkdf2_sha256":
|
||||||
|
return False
|
||||||
|
digest = hashlib.pbkdf2_hmac(
|
||||||
|
"sha256", password.encode(), bytes.fromhex(salt_hex), int(iterations)
|
||||||
|
)
|
||||||
|
return hmac.compare_digest(digest.hex(), digest_hex)
|
||||||
|
|
||||||
|
|
||||||
|
def user_count() -> int:
|
||||||
|
with SessionLocal() as db:
|
||||||
|
return db.scalar(select(func.count()).select_from(User)) or 0
|
||||||
|
|
||||||
|
|
||||||
|
def bootstrap_setup() -> None:
|
||||||
|
"""Au premier lancement (aucun utilisateur), génère le lien de création.
|
||||||
|
|
||||||
|
Le jeton est volontairement en mémoire: un redémarrage avant création
|
||||||
|
en génère un nouveau, et dès qu'un compte existe le lien cesse
|
||||||
|
d'être disponible.
|
||||||
|
"""
|
||||||
|
global setup_token
|
||||||
|
setup_token = None
|
||||||
|
if user_count() == 0:
|
||||||
|
setup_token = secrets.token_urlsafe(32)
|
||||||
|
print(
|
||||||
|
"\n" + "=" * 64 + "\n"
|
||||||
|
" MKVTool — premier lancement: aucun compte n'existe encore.\n"
|
||||||
|
" Ouvrez CE LIEN une seule fois pour créer votre compte :\n"
|
||||||
|
f" /setup?token={setup_token}\n"
|
||||||
|
" (préfixez par l'adresse de votre serveur, ex: http://192.168.1.10:8000)\n"
|
||||||
|
" Le lien cessera de fonctionner dès que le compte sera créé.\n"
|
||||||
|
+ "=" * 64 + "\n",
|
||||||
|
flush=True,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def create_user(username: str, password: str) -> int:
|
||||||
|
with SessionLocal() as db:
|
||||||
|
existing = db.scalar(select(User).where(User.username == username))
|
||||||
|
if existing is not None:
|
||||||
|
raise HTTPException(status_code=409, detail="Ce nom d'utilisateur existe déjà")
|
||||||
|
user = User(username=username, password_hash=hash_password(password))
|
||||||
|
db.add(user)
|
||||||
|
db.commit()
|
||||||
|
return user.id
|
||||||
|
|
||||||
|
|
||||||
|
def check_credentials(username: str, password: str) -> int | None:
|
||||||
|
with SessionLocal() as db:
|
||||||
|
user = db.scalar(select(User).where(User.username == username))
|
||||||
|
if user is None or not verify_password(password, user.password_hash):
|
||||||
|
return None
|
||||||
|
return user.id
|
||||||
|
|
||||||
|
|
||||||
|
def create_session(user_id: int) -> str:
|
||||||
|
token = secrets.token_urlsafe(32)
|
||||||
|
_sessions[token] = user_id
|
||||||
|
return token
|
||||||
|
|
||||||
|
|
||||||
|
def end_session(token: str | None) -> None:
|
||||||
|
if token:
|
||||||
|
_sessions.pop(token, None)
|
||||||
|
|
||||||
|
|
||||||
|
def resolve_session(token: str | None) -> int | None:
|
||||||
|
return _sessions.get(token) if token else None
|
||||||
|
|
||||||
|
|
||||||
|
def current_user(
|
||||||
|
mkvtool_session: str | None = Cookie(default=None, alias=SESSION_COOKIE),
|
||||||
|
) -> int:
|
||||||
|
user_id = resolve_session(mkvtool_session)
|
||||||
|
if user_id is None:
|
||||||
|
raise HTTPException(status_code=401, detail="Non authentifié")
|
||||||
|
return user_id
|
||||||
@@ -0,0 +1,130 @@
|
|||||||
|
"""Conversion d'une ISO en MKV puis import dans la bibliothèque Jellyfin.
|
||||||
|
|
||||||
|
Le MKV est écrit dans un dossier dédié sous le répertoire de téléchargements
|
||||||
|
qBittorrent, puis lié (lien dur `ln`) dans le dossier du film sous la
|
||||||
|
bibliothèque Jellyfin après nettoyage de ce dossier.
|
||||||
|
"""
|
||||||
|
|
||||||
|
import errno
|
||||||
|
import os
|
||||||
|
import re
|
||||||
|
import shutil
|
||||||
|
import subprocess
|
||||||
|
from dataclasses import dataclass
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
from app.config import settings
|
||||||
|
from app.models import IsoMovie
|
||||||
|
|
||||||
|
INVALID_CHARACTERS = re.compile(r'[/\\:*?"<>|]')
|
||||||
|
|
||||||
|
|
||||||
|
def guarded_folder(folder: Path) -> Path:
|
||||||
|
resolved = folder.resolve()
|
||||||
|
films_root = settings.films_dir.resolve()
|
||||||
|
if not resolved.is_relative_to(films_root):
|
||||||
|
raise RuntimeError(f"Refus de toucher un dossier hors de {films_root}: {resolved}")
|
||||||
|
return resolved
|
||||||
|
|
||||||
|
|
||||||
|
def sanitize_component(value: str) -> str:
|
||||||
|
cleaned = INVALID_CHARACTERS.sub(" ", value).strip()
|
||||||
|
cleaned = re.sub(r"\s{2,}", " ", cleaned)
|
||||||
|
return cleaned or "Sans titre"
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class ConversionPaths:
|
||||||
|
downloads_folder: Path
|
||||||
|
mkv_path: Path
|
||||||
|
destination_folder: Path
|
||||||
|
|
||||||
|
|
||||||
|
def conversion_paths(movie: IsoMovie) -> ConversionPaths:
|
||||||
|
title = sanitize_component(movie.title)
|
||||||
|
movie_name = f"{title} {movie.year}" if movie.year else title
|
||||||
|
mkv_name = f"{title} ({movie.year}).mkv" if movie.year else f"{title}.mkv"
|
||||||
|
downloads_folder = settings.downloads_dir / movie_name
|
||||||
|
|
||||||
|
iso_folder = Path(movie.path).parent
|
||||||
|
films_root = settings.films_dir.resolve()
|
||||||
|
if iso_folder.resolve().is_relative_to(films_root):
|
||||||
|
destination_folder = iso_folder
|
||||||
|
else:
|
||||||
|
destination_folder = films_root / movie_name
|
||||||
|
return ConversionPaths(
|
||||||
|
downloads_folder=downloads_folder,
|
||||||
|
mkv_path=downloads_folder / mkv_name,
|
||||||
|
destination_folder=destination_folder,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def extract_mkv(movie: IsoMovie, mkv_path: Path) -> None:
|
||||||
|
mkv_path.parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
if settings.simulate_conversion:
|
||||||
|
# Simulation en attendant MakeMKV sur le NAS : fichier MKV de substitution.
|
||||||
|
mkv_path.write_text(
|
||||||
|
"MKV simule par MKVTool — MakeMKV n'est pas installe dans cet environnement.\n"
|
||||||
|
)
|
||||||
|
return
|
||||||
|
if shutil.which("makemkvcon") is None:
|
||||||
|
raise RuntimeError("MakeMKV (makemkvcon) n'est pas installe sur le serveur")
|
||||||
|
result = subprocess.run(
|
||||||
|
["makemkvcon", "mkv", f"iso:{movie.path}", "0", str(mkv_path.parent)],
|
||||||
|
capture_output=True,
|
||||||
|
text=True,
|
||||||
|
)
|
||||||
|
if result.returncode != 0:
|
||||||
|
detail = result.stderr.strip() or result.stdout.strip()
|
||||||
|
raise RuntimeError(f"MakeMKV a echoue: {detail}")
|
||||||
|
produced = sorted(mkv_path.parent.glob("*.mkv"))
|
||||||
|
if not produced:
|
||||||
|
raise RuntimeError("MakeMKV n'a produit aucun fichier MKV")
|
||||||
|
produced[0].replace(mkv_path)
|
||||||
|
|
||||||
|
|
||||||
|
def import_mkv(mkv_path: Path, destination_folder: Path) -> Path:
|
||||||
|
"""Crée le lien du MKV dans le dossier du film, sans toucher au reste.
|
||||||
|
|
||||||
|
L'ISO et les autres fichiers du dossier ne sont supprimés qu'à la
|
||||||
|
validation manuelle (finalize_validation).
|
||||||
|
"""
|
||||||
|
resolved = guarded_folder(destination_folder)
|
||||||
|
resolved.mkdir(parents=True, exist_ok=True)
|
||||||
|
target = resolved / mkv_path.name
|
||||||
|
if target.exists() or target.is_symlink():
|
||||||
|
target.unlink()
|
||||||
|
try:
|
||||||
|
os.link(mkv_path, target)
|
||||||
|
except OSError as error:
|
||||||
|
if error.errno != errno.EXDEV:
|
||||||
|
raise
|
||||||
|
# Volumes différents: un lien dur est impossible, on retombe sur un lien symbolique.
|
||||||
|
os.symlink(mkv_path, target)
|
||||||
|
return target
|
||||||
|
|
||||||
|
|
||||||
|
def finalize_validation(destination_folder: Path, keep_name: str) -> None:
|
||||||
|
"""Supprime l'ISO et les autres fichiers du dossier, ne garde que le MKV lié."""
|
||||||
|
resolved = guarded_folder(destination_folder)
|
||||||
|
for entry in resolved.iterdir():
|
||||||
|
if entry.name == keep_name:
|
||||||
|
continue
|
||||||
|
if entry.is_dir() and not entry.is_symlink():
|
||||||
|
shutil.rmtree(entry)
|
||||||
|
else:
|
||||||
|
entry.unlink()
|
||||||
|
|
||||||
|
|
||||||
|
def cancel_conversion(mkv_path: Path, destination_folder: Path) -> None:
|
||||||
|
"""Annule une conversion en attente de validation.
|
||||||
|
|
||||||
|
Supprime le MKV converti et son lien dans le dossier du film (s'ils
|
||||||
|
existent); l'ISO et le reste du dossier ne sont pas touches.
|
||||||
|
"""
|
||||||
|
target = destination_folder / mkv_path.name
|
||||||
|
for path in (target, mkv_path):
|
||||||
|
if path.is_symlink() or path.exists():
|
||||||
|
path.unlink()
|
||||||
|
if mkv_path.parent.is_dir() and not any(mkv_path.parent.iterdir()):
|
||||||
|
mkv_path.parent.rmdir()
|
||||||
@@ -0,0 +1,64 @@
|
|||||||
|
"""Client qBittorrent WebUI (API v2) pour la suppression des torrents."""
|
||||||
|
|
||||||
|
from pathlib import PurePath
|
||||||
|
|
||||||
|
import httpx
|
||||||
|
|
||||||
|
|
||||||
|
class QbittorrentClient:
|
||||||
|
def __init__(self, url: str, username: str, password: str) -> None:
|
||||||
|
self._url = url.rstrip("/")
|
||||||
|
self._username = username
|
||||||
|
self._password = password
|
||||||
|
|
||||||
|
async def _request(self, method: str, endpoint: str, **kwargs) -> httpx.Response:
|
||||||
|
async with httpx.AsyncClient(timeout=30) as client:
|
||||||
|
login = await client.post(
|
||||||
|
f"{self._url}/api/v2/auth/login",
|
||||||
|
data={"username": self._username, "password": self._password},
|
||||||
|
headers={"Referer": self._url},
|
||||||
|
)
|
||||||
|
login.raise_for_status()
|
||||||
|
if login.text.strip() != "Ok.":
|
||||||
|
raise ValueError("Authentification qBittorrent refusée")
|
||||||
|
response = await client.request(
|
||||||
|
method,
|
||||||
|
f"{self._url}{endpoint}",
|
||||||
|
headers={"Referer": self._url},
|
||||||
|
**kwargs,
|
||||||
|
)
|
||||||
|
response.raise_for_status()
|
||||||
|
return response
|
||||||
|
|
||||||
|
async def version(self) -> str:
|
||||||
|
response = await self._request("GET", "/api/v2/app/version")
|
||||||
|
return response.text.strip()
|
||||||
|
|
||||||
|
async def torrents(self) -> list[dict]:
|
||||||
|
response = await self._request("GET", "/api/v2/torrents/info")
|
||||||
|
data = response.json()
|
||||||
|
if not isinstance(data, list):
|
||||||
|
raise ValueError("Réponse qBittorrent inattendue")
|
||||||
|
return data
|
||||||
|
|
||||||
|
async def delete(self, hashes: list[str], delete_files: bool) -> None:
|
||||||
|
await self._request(
|
||||||
|
"POST",
|
||||||
|
"/api/v2/torrents/delete",
|
||||||
|
data={
|
||||||
|
"hashes": "|".join(hashes),
|
||||||
|
"deleteFiles": "true" if delete_files else "false",
|
||||||
|
},
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def match_torrent(torrents: list[dict], iso_path: str) -> dict | None:
|
||||||
|
"""Retrouve le torrent correspondant à l'ISO (nom, ou fichier contenu)."""
|
||||||
|
file_name = PurePath(iso_path).name.lower()
|
||||||
|
stem = file_name.rsplit(".", 1)[0]
|
||||||
|
for torrent in torrents:
|
||||||
|
name = str(torrent.get("name", "")).lower()
|
||||||
|
content = str(torrent.get("content_path", "")).lower()
|
||||||
|
if name in {file_name, stem} or PurePath(content).name == file_name:
|
||||||
|
return torrent
|
||||||
|
return None
|
||||||
@@ -0,0 +1,63 @@
|
|||||||
|
"""Worker de conversion: traite les films en file, une conversion à la fois."""
|
||||||
|
|
||||||
|
import asyncio
|
||||||
|
import traceback
|
||||||
|
|
||||||
|
from sqlalchemy import select
|
||||||
|
|
||||||
|
from app.config import settings
|
||||||
|
from app.converter import conversion_paths, extract_mkv, import_mkv
|
||||||
|
from app.database import SessionLocal
|
||||||
|
from app.models import IsoMovie
|
||||||
|
|
||||||
|
|
||||||
|
async def _process(movie_id: int) -> None:
|
||||||
|
with SessionLocal() as db:
|
||||||
|
movie = db.get(IsoMovie, movie_id)
|
||||||
|
if movie is None or movie.status != "queued":
|
||||||
|
return
|
||||||
|
paths = conversion_paths(movie)
|
||||||
|
step = "converting"
|
||||||
|
try:
|
||||||
|
movie.status = "converting"
|
||||||
|
movie.last_error = None
|
||||||
|
db.commit()
|
||||||
|
# Reprise: si le MKV existe deja (echec precedent apres l'extraction),
|
||||||
|
# on ne relance pas MakeMKV et on reprend a l'import.
|
||||||
|
if not paths.mkv_path.exists():
|
||||||
|
await asyncio.to_thread(extract_mkv, movie, paths.mkv_path)
|
||||||
|
step = "importing"
|
||||||
|
movie.status = "importing"
|
||||||
|
db.commit()
|
||||||
|
await asyncio.to_thread(import_mkv, paths.mkv_path, paths.destination_folder)
|
||||||
|
# Le passage en "completed" (ISO supprimee) se fait manuellement
|
||||||
|
# via l'endpoint de validation apres verification par l'utilisateur.
|
||||||
|
movie.status = "validating"
|
||||||
|
movie.failed_step = None
|
||||||
|
except Exception as error: # noqa: BLE001 - le worker doit survivre a toute erreur
|
||||||
|
movie.status = "failed"
|
||||||
|
movie.failed_step = step
|
||||||
|
movie.last_error = f"{error}"
|
||||||
|
traceback.print_exc()
|
||||||
|
db.commit()
|
||||||
|
|
||||||
|
|
||||||
|
async def _process_next() -> bool:
|
||||||
|
with SessionLocal() as db:
|
||||||
|
movie_id = db.scalar(
|
||||||
|
select(IsoMovie.id)
|
||||||
|
.where(IsoMovie.status == "queued")
|
||||||
|
.order_by(IsoMovie.id)
|
||||||
|
.limit(1)
|
||||||
|
)
|
||||||
|
if movie_id is None:
|
||||||
|
return False
|
||||||
|
await _process(movie_id)
|
||||||
|
return True
|
||||||
|
|
||||||
|
|
||||||
|
async def conversion_worker() -> None:
|
||||||
|
while True:
|
||||||
|
processed = await _process_next()
|
||||||
|
if not processed:
|
||||||
|
await asyncio.sleep(settings.worker_interval)
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
services:
|
||||||
|
mkvtool:
|
||||||
|
build:
|
||||||
|
context: .
|
||||||
|
args:
|
||||||
|
MAKEMKV_VERSION: "2.0.0"
|
||||||
|
container_name: mkvtool
|
||||||
|
restart: unless-stopped
|
||||||
|
ports:
|
||||||
|
- "8000:8000"
|
||||||
|
environment:
|
||||||
|
# UID/GID numeriques du proprietaire des dossiers films et telechargements
|
||||||
|
# sur le NAS (ls -ln /nas_storage/jellyfin/films). Le conteneur demarre en
|
||||||
|
# root, attribue /config, puis tourne sous cette identite: aucun groupe a
|
||||||
|
# ajouter cote NAS, et le bit "other" en ecriture est inutile.
|
||||||
|
PUID: "1020"
|
||||||
|
PGID: "100"
|
||||||
|
TZ: "Europe/Paris"
|
||||||
|
# Sur le NAS: desactiver la simulation MakeMKV.
|
||||||
|
MKVTOOL_SIMULATE_CONVERSION: "false"
|
||||||
|
volumes:
|
||||||
|
# Montages aux MEMES chemins que Radarr/qBittorrent: les chemins ISO
|
||||||
|
# enregistres par le scan restent valides tels quels.
|
||||||
|
- /volume1/docker/mkvtool:/config
|
||||||
|
- /qbittorrentdownloads:/qbittorrentdownloads
|
||||||
|
- /nas_storage/jellyfin/films:/nas_storage/jellyfin/films
|
||||||
@@ -0,0 +1,33 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""Point d'entrée du conteneur MKVTool: applique PUID/PGID puis lance l'API.
|
||||||
|
|
||||||
|
Le conteneur démarre en root (nécessaire pour attribuer /config). Si
|
||||||
|
PUID/PGID sont définis, /config est donné à cet utilisateur puis le
|
||||||
|
processus abandonne ses privilèges et exécute la commande sous
|
||||||
|
PUID:PGID — le même modèle que les images LinuxServer.io
|
||||||
|
(Radarr, qBittorrent, Jellyfin...).
|
||||||
|
|
||||||
|
Les droits Linux sont numériques: il suffit que PUID/PGID correspondent
|
||||||
|
à l'UID/GID propriétaire des dossiers sur le NAS pour que le service
|
||||||
|
puisse créer, supprimer et lier des fichiers dedans, sans que le bit
|
||||||
|
« other » soit en écriture et sans ajouter de groupe côté hôte.
|
||||||
|
"""
|
||||||
|
import os
|
||||||
|
import subprocess
|
||||||
|
import sys
|
||||||
|
|
||||||
|
puid = int(os.environ.get("PUID", "0") or "0")
|
||||||
|
pgid = int(os.environ.get("PGID", "0") or "0")
|
||||||
|
config_dir = os.environ.get("MKVTOOL_CONFIG_DIR", "/config")
|
||||||
|
|
||||||
|
if os.geteuid() == 0 and puid:
|
||||||
|
if os.path.isdir(config_dir):
|
||||||
|
subprocess.run(
|
||||||
|
["chown", "-R", f"{puid}:{pgid or puid}", config_dir], check=False
|
||||||
|
)
|
||||||
|
os.setgroups([pgid] if pgid else [])
|
||||||
|
if pgid:
|
||||||
|
os.setgid(pgid)
|
||||||
|
os.setuid(puid)
|
||||||
|
|
||||||
|
os.execvp(sys.argv[1], sys.argv[1:])
|
||||||
Reference in new issue
Block a user