"""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