wrolpi/modules/torrents/share.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

129 lines
6.1 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 '.'
# The torrent's files are the shared file or directory (never config/, see check_share_path), so it may be seeded
# from the media directory itself.
entity = await lib.add_torrent(save_path, torrent=torrent, client=client, skip_checking=True,
allow_media_directory=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'])