mirror of
https://github.com/lrnselfreliance/wrolpi.git
synced 2026-12-03 13:19:58 -05:00
Torrents reach the Internet only through a fail-closed VPN (WireGuard or OpenVPN, any provider), so peers never see a WROLPi's own address. - A network namespace (Pi/Debian) or the vpn container (Docker) with an nftables kill switch; NAT-PMP or fixed port forwarding. - qBittorrent inside it, sandboxed; torrents kept in config/torrents/. - Torrent download form, Torrents page, Share as torrent, nav warning, and VPN settings in both Controller UIs. - Help docs: Torrents, and The VPN for Torrents. QA'd on a Raspberry Pi with a real provider over WireGuard and OpenVPN. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
85 lines
3.7 KiB
Python
85 lines
3.7 KiB
Python
"""
|
|
Torrents from the Download menu: a magnet link, or the URL of a .torrent file.
|
|
|
|
The Download finishes once the torrent is added (to config/torrents/, then qBittorrent); a torrent can take days, and
|
|
no download worker waits for it. The torrents worker shows its progress on the Download, and marks it completed
|
|
when the torrent is.
|
|
"""
|
|
import pathlib
|
|
from dataclasses import dataclass
|
|
|
|
from sqlalchemy.orm import Session
|
|
|
|
from modules.torrents import lib
|
|
from wrolpi.common import aiohttp_get, get_relative_to_media_directory
|
|
from wrolpi.downloader import Download, DownloadContext, DownloadResult, Downloader
|
|
from wrolpi.errors import ValidationError
|
|
|
|
|
|
@dataclass
|
|
class PreparedTorrent:
|
|
url: str
|
|
save_path: str
|
|
|
|
|
|
@dataclass
|
|
class ExecutedTorrent:
|
|
hash: str
|
|
name: str
|
|
|
|
|
|
class TorrentDownloader(Downloader):
|
|
name = lib.TORRENT_DOWNLOADER
|
|
pretty_name = 'Torrent'
|
|
listable = False
|
|
|
|
def normalize_domain(self, url: str) -> str:
|
|
# Magnet links have no domain; torrents are limited by qBittorrent, not the daily download limits.
|
|
return 'torrents'
|
|
|
|
def prepare_download(self, session: Session, download: Download) -> PreparedTorrent:
|
|
save_path = lib.DEFAULT_SAVE_PATH
|
|
if download.destination:
|
|
save_path = str(get_relative_to_media_directory(download.destination))
|
|
return PreparedTorrent(url=download.url, save_path=save_path)
|
|
|
|
async def execute_download(self, prepared: PreparedTorrent, ctx: DownloadContext,
|
|
download: Download = None) -> ExecutedTorrent | DownloadResult:
|
|
url = prepared.url.strip()
|
|
try:
|
|
if url.lower().startswith('magnet:'):
|
|
hash_, _ = lib.magnet_identity(url)
|
|
torrent_file = lib.get_torrents_config().get_torrent_file(hash_)
|
|
# An uploaded .torrent is saved before its Download is made; use it rather than the magnet link.
|
|
torrent = torrent_file.read_bytes() if torrent_file.is_file() else None
|
|
entity = await lib.add_torrent(prepared.save_path, torrent=torrent, magnet=None if torrent else url)
|
|
elif url.lower().startswith(('http://', 'https://')):
|
|
entity = await lib.add_torrent(prepared.save_path, torrent=await fetch_torrent_file(url))
|
|
else:
|
|
return DownloadResult(success=False, error='A torrent must be a magnet link or a .torrent URL')
|
|
except (ValidationError, lib.QBittorrentError, lib.QBittorrentUnavailable) as e:
|
|
return DownloadResult(success=False, error=str(e))
|
|
return ExecutedTorrent(hash=entity['slug'], name=entity['name'])
|
|
|
|
def finalize_download(self, session: Session, download: Download, executed: ExecutedTorrent) -> DownloadResult:
|
|
# The torrents worker finds this Download's torrent by its hash.
|
|
download.info_json = dict(torrent_hash=executed.hash, name=executed.name)
|
|
return DownloadResult(success=True, location='/admin/torrents')
|
|
|
|
|
|
async def fetch_torrent_file(url: str) -> bytes:
|
|
"""A .torrent file from a website. (Only this small file comes from the website; the torrent itself is
|
|
downloaded through the VPN.)"""
|
|
torrent = bytearray()
|
|
async with aiohttp_get(url, timeout=60) as response:
|
|
if response.status != 200:
|
|
raise ValidationError(f'Could not download the .torrent file ({response.status})')
|
|
# `read(n)` returns whatever has arrived (up to n), not the whole file; read every chunk.
|
|
async for chunk in response.content.iter_chunked(64 * 1024):
|
|
torrent.extend(chunk)
|
|
if len(torrent) > lib.MAX_TORRENT_FILE_BYTES:
|
|
raise ValidationError('That file is too large to be a .torrent file')
|
|
return bytes(torrent)
|
|
|
|
|
|
torrent_downloader = TorrentDownloader()
|