wrolpi/modules/torrents/qbittorrent.py
lrnselfreliance d6a8363903
Torrents: refuse to download into the media directory itself (#1038)
* Torrents: refuse to download into the media directory itself

A torrent's files are chosen by whoever made it. Saved in the media
directory itself, a torrent holding a config directory would put its
files in WROLPi's config directory. Downloads now need a directory in
the media directory. Share still seeds a top-level directory from the
media directory: its files are the shared directory's.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Torrents: refuse a WebUI save path WROLPi would refuse

A torrent added in qBittorrent's WebUI to the media directory itself (or
outside the library) is removed from qBittorrent, its files kept, and a
"Torrent Refused" event says why. A torrent moved there in the WebUI is
moved back to its config's save path.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Torrents: keep an untagged WROLPi torrent; refuse a WebUI download path

A WROLPi torrent whose tag was removed in the WebUI was removed from
qBittorrent when its save path was refused, and forgotten (config and
.torrent deleted) on the next pass. It is now tagged again and kept as
the config says, as adopt() did before.

qBittorrent keeps a downloading torrent's incomplete files in its
download path, which the WebUI can set per torrent. A WebUI torrent with
a refused download path is removed (files kept); a WROLPi torrent's is
set back to its save path. A finished torrent's download path is unused,
and left alone.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 15:05:52 -07:00

146 lines
6.9 KiB
Python

"""
A small client of qBittorrent's WebUI API (v2, qBittorrent 5).
qBittorrent runs inside the VPN's network namespace. WROLPi reaches its WebUI through the namespace's uplink, from
which it needs no password (see qbittorrent_prepare.py).
"""
import json
from typing import List, Optional
import aiohttp
from wrolpi.vars import DOCKERIZED
WEBUI_PORT = 8091
# Docker: qBittorrent runs in the `vpn` container, beside the tunnel. Raspberry Pi / Debian: the `wrolpi-vpn`
# namespace's end of its veth pair (etc/raspberrypios/wrolpi-vpn-netns.sh).
QBITTORRENT_URL = f'http://vpn:{WEBUI_PORT}' if DOCKERIZED else f'http://10.211.0.2:{WEBUI_PORT}'
TIMEOUT = aiohttp.ClientTimeout(total=10)
class QBittorrentUnavailable(Exception):
"""qBittorrent is not running, or cannot be reached."""
class QBittorrentError(Exception):
"""qBittorrent refused a request."""
class QBittorrent:
def __init__(self, url: str = QBITTORRENT_URL):
self.url = url.rstrip('/')
async def _request(self, method: str, path: str, params: dict = None, data=None) -> bytes:
try:
async with aiohttp.ClientSession(timeout=TIMEOUT) as session:
async with session.request(method, f'{self.url}/api/v2/{path}', params=params, data=data) as response:
body = await response.read()
if response.status >= 400:
raise QBittorrentError(f'qBittorrent refused {path} ({response.status}): {body[:200]!r}')
return body
except (aiohttp.ClientConnectionError, TimeoutError) as e:
raise QBittorrentUnavailable(f'Cannot reach qBittorrent at {self.url}: {e}') from e
async def _get_json(self, path: str, **params):
return json.loads(await self._request('GET', path, params=params or None))
async def version(self) -> str:
return (await self._request('GET', 'app/version')).decode()
async def preferences(self) -> dict:
return await self._get_json('app/preferences')
async def set_preferences(self, preferences: dict):
await self._request('POST', 'app/setPreferences', data={'json': json.dumps(preferences)})
async def transfer_info(self) -> dict:
return await self._get_json('transfer/info')
async def torrents(self) -> List[dict]:
return await self._get_json('torrents/info')
async def tags(self) -> List[str]:
return await self._get_json('torrents/tags')
async def create_tags(self, *tags: str):
await self._request('POST', 'torrents/createTags', data={'tags': ','.join(tags)})
async def add_tags(self, hashes: List[str], *tags: str):
await self._request('POST', 'torrents/addTags', data={'hashes': '|'.join(hashes), 'tags': ','.join(tags)})
async def remove_tags(self, hashes: List[str], *tags: str):
await self._request('POST', 'torrents/removeTags', data={'hashes': '|'.join(hashes), 'tags': ','.join(tags)})
async def add(self, save_path: str, torrent: bytes = None, url: str = None, tags: List[str] = None,
stopped: bool = False, skip_checking: bool = False):
"""Add a torrent from a .torrent file's bytes, or a magnet link / URL."""
form = aiohttp.FormData()
if torrent:
form.add_field('torrents', torrent, filename='file.torrent', content_type='application/x-bittorrent')
elif url:
form.add_field('urls', url)
else:
raise ValueError('A torrent or a URL is required')
form.add_field('savepath', save_path)
form.add_field('stopped', 'true' if stopped else 'false')
if skip_checking:
# Its files were just hashed to make it; do not hash them again.
form.add_field('skip_checking', 'true')
if tags:
form.add_field('tags', ','.join(tags))
body = await self._request('POST', 'torrents/add', data=form)
if body.strip() == b'Fails.':
raise QBittorrentError('qBittorrent could not add the torrent')
async def delete(self, hashes: List[str], delete_files: bool = False):
await self._request('POST', 'torrents/delete',
data={'hashes': '|'.join(hashes), 'deleteFiles': 'true' if delete_files else 'false'})
async def export(self, hash_: str) -> Optional[bytes]:
"""The .torrent file of a torrent, or None while a magnet link's metadata has not arrived."""
try:
return await self._request('GET', 'torrents/export', params={'hash': hash_})
except QBittorrentError:
return None
async def set_location(self, hashes: List[str], location: str):
"""Move torrents (and their files) to the `location` directory."""
await self._request('POST', 'torrents/setLocation', data={'hashes': '|'.join(hashes), 'location': location})
async def set_download_path(self, hashes: List[str], path: str):
"""Keep the torrents' incomplete files in the `path` directory."""
await self._request('POST', 'torrents/setDownloadPath', data={'id': '|'.join(hashes), 'path': path})
async def start(self, hashes: List[str]):
await self._request('POST', 'torrents/start', data={'hashes': '|'.join(hashes)})
async def stop(self, hashes: List[str]):
await self._request('POST', 'torrents/stop', data={'hashes': '|'.join(hashes)})
async def set_share_limits(self, hashes: List[str], ratio_limit: float, seeding_time_limit: int):
"""Stop seeding at a ratio / after minutes seeding; -2 is qBittorrent's global setting, -1 is no limit."""
await self._request('POST', 'torrents/setShareLimits', data={
'hashes': '|'.join(hashes), 'ratioLimit': str(ratio_limit), 'seedingTimeLimit': str(seeding_time_limit),
'inactiveSeedingTimeLimit': '-2'})
async def create_torrent(self, source_path: str, trackers: List[str], url_seeds: List[str]) -> str:
"""Start making a hybrid (v1 and v2) torrent of a file or directory; returns the task's ID. qBittorrent does
not add it; WROLPi does."""
body = await self._request('POST', 'torrentcreator/addTask', data={
'sourcePath': source_path, 'format': 'hybrid', 'startSeeding': 'false',
'trackers': '|'.join(trackers), 'urlSeeds': '|'.join(url_seeds)})
return json.loads(body)['taskID']
async def torrent_creator_status(self, task_id: str) -> dict:
"""{'status': 'Queued' | 'Running' | 'Finished' | 'Failed', 'progress': 0-100, 'errorMessage': ...}"""
tasks = await self._get_json('torrentcreator/status', taskID=task_id)
if not tasks:
raise QBittorrentError(f'qBittorrent has no torrent creator task {task_id}')
return tasks[0]
async def torrent_creator_file(self, task_id: str) -> bytes:
return await self._request('GET', 'torrentcreator/torrentFile', params={'taskID': task_id})
async def delete_torrent_creator_task(self, task_id: str):
await self._request('POST', 'torrentcreator/deleteTask', data={'taskID': task_id})