wrolpi/modules/torrents/share.py
lrnselfreliance 2c3300b8b0
Torrents over a fail-closed VPN (#1026)
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>
2026-11-28 14:26:24 -07:00

126 lines
5.9 KiB
Python

"""
"Share as torrent": make a torrent of a file or directory already in the library, and seed it.
qBittorrent hashes the files (a 659 GB file takes an hour or more on a Raspberry Pi), so this runs as a Job, which
shows its progress and can be cancelled. The new torrent is a hybrid (v1 and v2) torrent, with the trackers and web
seeds given; WROLPi adds it to config/torrents/ and qBittorrent without hashing the files again.
"""
import asyncio
import pathlib
import urllib.parse
from typing import List
from modules.torrents import lib
from modules.torrents.qbittorrent import QBittorrent, QBittorrentError
from wrolpi.common import get_media_directory, logger
from wrolpi.errors import ValidationError
from wrolpi.jobs import enqueue_job, get_current_job, register_job
logger = logger.getChild(__name__)
SHARE_JOB = 'share_torrent'
POLL_SECONDS = 2
def publishes_config(path: pathlib.Path, media_directory: pathlib.Path) -> bool:
"""True when a torrent of `path` would include WROLPi's config directory (the VPN's key and login, and more): it
is config/, is inside it, or holds it (the library itself)."""
config_directory = media_directory / 'config'
return path == config_directory or config_directory in path.parents or path in config_directory.parents
def check_share_path(path: str) -> pathlib.Path:
"""The absolute path of a file or directory in the library (not WROLPi's config) to make a torrent of."""
path = (path or '').rstrip('/')
if not path:
raise ValidationError('Choose a file or directory to share')
lib.check_save_path(path)
media_directory = get_media_directory().resolve()
absolute = (media_directory / path).resolve()
if not absolute.exists():
raise ValidationError(f'{path} does not exist')
if publishes_config(absolute, media_directory):
raise ValidationError("A torrent cannot include WROLPi's config directory")
if absolute.is_dir():
files = False
for item in absolute.rglob('*'):
if item.is_symlink():
# A link would publish what it points at. A link to a folder could lead anywhere (and its own links
# are not walked here), so only links to files in the library are allowed.
target = item.resolve()
if target.is_dir():
raise ValidationError(f'{item.relative_to(media_directory)} links to a folder; a torrent cannot '
f'include links to folders')
if publishes_config(target, media_directory) or media_directory not in target.parents:
raise ValidationError(f'{item.relative_to(media_directory)} links outside the library or into '
f"WROLPi's config directory")
files = files or item.is_file()
if not files:
raise ValidationError(f'{path} has no files to share')
return absolute
def check_urls(urls: List[str], schemes: tuple, what: str) -> List[str]:
checked = []
for url in urls or []:
url = url.strip()
if not url:
continue
parsed = urllib.parse.urlparse(url)
if parsed.scheme not in schemes or not parsed.hostname or any(c in url for c in '|\r\n '):
raise ValidationError(f'{url!r} is not a {what} ({" or ".join(schemes)})')
if url not in checked:
checked.append(url)
return checked
def check_trackers(trackers: List[str]) -> List[str]:
return check_urls(trackers, ('udp', 'http', 'https'), 'tracker URL')
def check_web_seeds(web_seeds: List[str]) -> List[str]:
return check_urls(web_seeds, ('http', 'https'), 'web seed URL')
def share(path: str, trackers: List[str], web_seeds: List[str]) -> str:
"""Check the request and start the Job; returns its ID."""
source = check_share_path(path)
trackers, web_seeds = check_trackers(trackers), check_web_seeds(web_seeds)
relative = source.relative_to(get_media_directory())
return enqueue_job(SHARE_JOB, description=f'Make a torrent of {relative}', path=str(relative), trackers=trackers,
web_seeds=web_seeds)
@register_job(SHARE_JOB)
async def share_torrent(path: str, trackers: List[str], web_seeds: List[str], client: QBittorrent = None) -> dict:
job = get_current_job()
client = client or QBittorrent()
source = check_share_path(path)
logger.info(f'Making a torrent of {path}')
task_id = await client.create_torrent(str(source), trackers, web_seeds)
try:
while True:
status = await client.torrent_creator_status(task_id)
if status['status'] == 'Finished':
break
if status['status'] == 'Failed':
raise QBittorrentError(f'qBittorrent could not make the torrent: {status.get("errorMessage")}')
if job:
job.set_progress(status.get('progress'))
if job.cancel_requested():
raise asyncio.CancelledError('The torrent was cancelled while it was being made')
await asyncio.sleep(POLL_SECONDS)
torrent = await client.torrent_creator_file(task_id)
finally:
# A cancelled task stops hashing; a finished one is no longer needed.
try:
await client.delete_torrent_creator_task(task_id)
except QBittorrentError as e:
logger.warning(f'Could not delete the torrent creator task {task_id}: {e}')
# Seed from where the files already are: the torrent is named after them, in their directory.
save_path = str(source.parent.relative_to(get_media_directory())) or '.'
entity = await lib.add_torrent(save_path, torrent=torrent, client=client, skip_checking=True)
lib.get_torrents_config().update(entity['slug'], complete=True)
logger.info(f'Made the torrent {entity["name"]} ({entity["slug"]}), and seeding it')
return dict(hash=entity['slug'], name=entity['name'], magnet=entity['magnet'])