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>
This commit is contained in:
lrnselfreliance 2026-11-30 15:05:52 -07:00 • committed by GitHub
parent b1334c834b
commit d6a8363903
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
10 changed files with 220 additions and 8 deletions

View file

@ -62,6 +62,10 @@ export function handleEvents(events) {
eventToast('Sync Failed', message, 'error');
}
if (event === 'torrent_refused') {
eventToast('Torrent Refused', message, 'error');
}
if (event === 'map_import_complete') {
eventToast('Map import completed', message, 'success');
}

View file

@ -31,3 +31,15 @@ describe('user_notify_message', () => {
open.mockRestore();
});
});
describe('torrent_refused', () => {
it('says which torrent was refused, and why', () => {
handleEvents([{event: 'torrent_refused', subject: 'torrents', dt: '2026-11-29',
message: 'planet was removed: Torrents cannot be saved in the media directory itself'}]);
expect(toast).toHaveBeenCalledTimes(1);
const options = toast.mock.calls[0][0];
expect(options.title).toBe('Torrent Refused');
expect(options.description).toContain('planet was removed');
});
});

View file

@ -91,6 +91,16 @@ class FakeQBittorrent:
for h in hashes:
self._torrents.pop(h, None)
async def set_location(self, hashes, location):
self.calls.append(('set_location', hashes, location))
for h in hashes:
self._torrents[h]['save_path'] = location
async def set_download_path(self, hashes, path):
self.calls.append(('set_download_path', hashes, path))
for h in hashes:
self._torrents[h]['download_path'] = path
async def export(self, hash_):
return f'torrent {hash_}'.encode() if self.metadata else None

View file

@ -31,6 +31,7 @@ from wrolpi.api_utils import perpetual_signal
from wrolpi.common import MultiFileConfig, get_media_directory, logger, wrol_mode_enabled, \
get_relative_to_media_directory, get_wrolpi_config
from wrolpi.errors import ValidationError
from wrolpi.events import Events
from wrolpi.vars import DOCKERIZED, PYTEST
from modules.torrents.qbittorrent import QBittorrent, QBittorrentError, QBittorrentUnavailable
@ -219,26 +220,50 @@ def magnet_link(v1: Optional[str], v2: Optional[str], name: str) -> str:
return f'magnet:?{"&".join(xts)}&dn={urllib.parse.quote(name)}'
def check_save_path(save_path: str) -> str:
"""A save path relative to the media directory, which must stay in it (torrents are only saved in the library)."""
def check_save_path(save_path: str, allow_media_directory: bool = False) -> str:
"""A save path relative to the media directory, which must stay in it (torrents are only saved in the library).
A downloaded torrent may not be saved in the media directory itself: a torrent's files are chosen by whoever made
it, and one holding a `config` directory would replace WROLPi's. `allow_media_directory` is only for a torrent
WROLPi made of files already in the library (Share)."""
save_path = save_path or DEFAULT_SAVE_PATH
media_directory = get_media_directory()
path = pathlib.Path(save_path)
absolute = (path if path.is_absolute() else media_directory / path).resolve()
if absolute != media_directory and media_directory not in absolute.parents:
raise ValidationError('Torrents can only be saved in the media directory')
if absolute == media_directory and not allow_media_directory:
raise ValidationError('Torrents cannot be saved in the media directory itself; choose a directory in it')
if absolute == media_directory / 'config' or media_directory / 'config' in absolute.parents:
raise ValidationError("Torrents cannot be saved in WROLPi's config directory")
return str(absolute.relative_to(media_directory)) or '.'
def save_path_refusal(save_path: str) -> Optional[str]:
"""Why qBittorrent may not save a torrent in `save_path` (e.g. one chosen in its WebUI), or None."""
try:
check_save_path(save_path)
except ValidationError as e:
return str(e)
return None
def download_path_refusal(torrent: dict) -> Optional[str]:
"""Why qBittorrent may not keep a downloading torrent's incomplete files in its download path (which the WebUI can
set per torrent), or None. A finished torrent's files are in its save path."""
if torrent.get('download_path') and torrent.get('progress', 0) < 1:
return save_path_refusal(torrent['download_path'])
return None
async def add_torrent(save_path: str = None, torrent: bytes = None, magnet: str = None,
client: QBittorrent = None, skip_checking: bool = False) -> dict:
client: QBittorrent = None, skip_checking: bool = False,
allow_media_directory: bool = False) -> dict:
"""Add a torrent from a .torrent file's bytes, or a magnet link: to the config (the source of truth), then to
qBittorrent. Returns its config."""
client = client or QBittorrent()
config = get_torrents_config()
save_path = check_save_path(save_path)
save_path = check_save_path(save_path, allow_media_directory=allow_media_directory)
if torrent:
hash_, name = torrent_identity(torrent)
magnet = torrent_magnet(torrent)
@ -386,7 +411,8 @@ async def reconcile(client: QBittorrent, wrol_mode: bool, state: ReconcileState
"""Make qBittorrent and the config agree; returns what was done (for tests and logs)."""
state = state or ReconcileState()
config = get_torrents_config()
done = dict(added=[], adopted=[], forgotten=[], removed=[], stopped=[], started=[], completed=[])
done = dict(added=[], adopted=[], refused=[], moved_back=[], forgotten=[], removed=[], stopped=[], started=[],
completed=[])
torrents = {t['hash']: t for t in await client.torrents()}
entities = {e['slug']: e for e in config.all()}
@ -401,8 +427,18 @@ async def reconcile(client: QBittorrent, wrol_mode: bool, state: ReconcileState
for slug, torrent in torrents.items():
tags = {t.strip() for t in (torrent.get('tags') or '').split(',') if t.strip()}
if TAG not in tags:
if await adopt(client, torrent):
if TAG not in tags and slug in entities:
# WROLPi's, its tag removed in the WebUI: tagged again, and kept as the config says (below).
await client.add_tags([slug], TAG)
elif TAG not in tags:
if refusal := save_path_refusal(torrent.get('save_path')) or download_path_refusal(torrent):
# Added in the WebUI to the media directory itself, or outside the library: removed before it writes
# anything more (what it already wrote is kept).
await client.delete([slug], delete_files=False)
logger.error(f'Removed torrent {torrent["name"]} added in qBittorrent: {refusal}')
Events.send_torrent_refused(f'{torrent["name"]} was removed: {refusal}')
done['refused'].append(slug)
elif await adopt(client, torrent):
done['adopted'].append(slug)
continue
entity = entities.get(slug)
@ -414,6 +450,20 @@ async def reconcile(client: QBittorrent, wrol_mode: bool, state: ReconcileState
continue
state.seen.add(slug)
save_path = save_path_of(entity)
if pathlib.Path(torrent['save_path']) != pathlib.Path(save_path) \
and (refusal := save_path_refusal(torrent['save_path'])):
# Moved in the WebUI to the media directory itself, or outside the library: moved back.
await client.set_location([slug], save_path)
logger.error(f'Moved torrent {torrent["name"]} back to {save_path}: {refusal}')
Events.send_torrent_refused(f'{torrent["name"]} was moved back to {save_path}: {refusal}')
done['moved_back'].append(slug)
elif refusal := download_path_refusal(torrent):
await client.set_download_path([slug], save_path)
logger.error(f'Torrent {torrent["name"]} keeps its incomplete files in {save_path} again: {refusal}')
Events.send_torrent_refused(f'{torrent["name"]} keeps its incomplete files in {save_path} again: {refusal}')
done['moved_back'].append(slug)
stopped = torrent['state'] in STOPPED_STATES
if wrol_mode:
if not stopped:

View file

@ -104,6 +104,14 @@ class QBittorrent:
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)})

View file

@ -120,7 +120,10 @@ async def share_torrent(path: str, trackers: List[str], web_seeds: List[str], cl
# 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)
# 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'])

View file

@ -86,6 +86,20 @@ class TestSavePath:
with pytest.raises(ValidationError):
lib.check_save_path(save_path)
@pytest.mark.parametrize('save_path', ['.', './', 'maps/..', '{media}'])
def test_not_the_media_directory_itself(self, test_directory, save_path):
"""A torrent saved in the media directory itself could hold a `config` directory, and replace WROLPi's."""
with pytest.raises(ValidationError, match='media directory itself'):
lib.check_save_path(save_path.format(media=test_directory))
async def test_add_torrent_refuses_the_media_directory(test_torrents_config, fake_qbittorrent):
client = fake_qbittorrent(tags=[lib.TAG])
with pytest.raises(ValidationError, match='media directory itself'):
await lib.add_torrent('.', torrent=TORRENT, client=client)
assert test_torrents_config.get(HASH) is None
assert not [c for c in client.calls if c[0] == 'add']
async def test_add_torrent_file(test_torrents_config, fake_qbittorrent):
client = fake_qbittorrent(tags=[lib.TAG])

View file

@ -104,6 +104,16 @@ async def test_share(test_torrents_config, planet, fake_qbittorrent):
assert test_torrents_config.get_torrent_file(HASH).read_bytes() == TORRENT
async def test_share_a_top_level_directory(test_torrents_config, planet, fake_qbittorrent):
"""A torrent WROLPi made of a directory in the media directory is seeded from the media directory; its files are
the directory's, so it cannot replace WROLPi's config."""
client = fake_qbittorrent(tags=[lib.TAG], created=TORRENT, creator_statuses=[{'status': 'Finished'}])
with mock.patch.object(share, 'get_current_job', mock.Mock()), mock.patch.object(share, 'POLL_SECONDS', 0):
await share.share_torrent('maps', [], [], client=client)
assert ('skip_checking', str(lib.get_media_directory())) in client.calls
assert test_torrents_config.get(HASH)['save_path'] == '.'
async def test_share_failed(test_torrents_config, planet, fake_qbittorrent):
client = fake_qbittorrent(tags=[lib.TAG], creator_statuses=[{'status': 'Failed', 'errorMessage': 'disk error'}])
with pytest.raises(lib.QBittorrentError, match='disk error'):

View file

@ -84,6 +84,103 @@ async def test_adopts_torrents_added_in_the_webui(test_torrents_config, fake_qbi
assert (await client.torrents())[0]['tags'] == lib.TAG
@pytest.mark.parametrize('save_path', ['{media}', '{media}/config', '/etc'])
async def test_webui_torrent_outside_a_library_directory_is_refused(test_torrents_config, fake_qbittorrent,
save_path):
"""A torrent added in the WebUI to the media directory itself (or outside the library) could replace WROLPi's
config; it is removed from qBittorrent at once (even before its metadata arrives), its files kept."""
client = fake_qbittorrent([qbt_torrent(A, tags='', state='metaDL', progress=0,
save_path=save_path.format(media=lib.get_media_directory()))],
tags=[lib.TAG], metadata=False)
with mock.patch.object(lib.Events, 'send_torrent_refused') as send_torrent_refused:
done = await lib.reconcile(client, wrol_mode=False)
assert done['refused'] == [A]
assert done['adopted'] == []
assert ('delete', [A], False) in client.calls
assert await client.torrents() == []
assert test_torrents_config.get(A) is None
send_torrent_refused.assert_called_once()
assert f'torrent {A[:4]}' in send_torrent_refused.call_args.args[0]
async def test_moved_out_of_the_library_in_the_webui_is_moved_back(test_torrents_config, fake_qbittorrent):
make_entity(test_torrents_config, A)
client = fake_qbittorrent([qbt_torrent(A, save_path=str(lib.get_media_directory()))], tags=[lib.TAG])
with mock.patch.object(lib.Events, 'send_torrent_refused') as send_torrent_refused:
done = await lib.reconcile(client, wrol_mode=False)
assert done['moved_back'] == [A]
assert ('set_location', [A], str(lib.get_media_directory() / 'torrents')) in client.calls
assert (await client.torrents())[0]['save_path'] == str(lib.get_media_directory() / 'torrents')
send_torrent_refused.assert_called_once()
# Moved to another library directory: that is the user's choice.
await client.set_location([A], str(lib.get_media_directory() / 'maps'))
done = await lib.reconcile(client, wrol_mode=False)
assert done['moved_back'] == []
async def test_shared_from_the_media_directory_is_kept(test_torrents_config, fake_qbittorrent):
"""Share seeds a top-level directory from the media directory; the config records that, so it stays."""
make_entity(test_torrents_config, A)
test_torrents_config.update(A, save_path='.')
client = fake_qbittorrent([qbt_torrent(A, save_path=str(lib.get_media_directory()))], tags=[lib.TAG])
done = await lib.reconcile(client, wrol_mode=False)
assert done['moved_back'] == []
assert not [c for c in client.calls if c[0] in ('set_location', 'delete')]
async def test_untagged_wrolpi_torrent_is_kept_not_refused(test_torrents_config, fake_qbittorrent):
"""A WROLPi torrent whose tag was removed in the WebUI is still WROLPi's: tagged again and moved back, never
removed from qBittorrent (which the next pass would take as "removed in the WebUI", and forget it)."""
make_entity(test_torrents_config, A)
client = fake_qbittorrent([qbt_torrent(A, save_path=str(lib.get_media_directory()))], tags=[lib.TAG])
state = lib.ReconcileState()
with mock.patch.object(lib.Events, 'send_torrent_refused'):
await lib.reconcile(client, wrol_mode=False, state=state)
await client.remove_tags([A], lib.TAG)
await client.set_location([A], str(lib.get_media_directory()))
done = await lib.reconcile(client, wrol_mode=False, state=state)
assert (done['refused'], done['moved_back']) == ([], [A])
assert not [c for c in client.calls if c[0] == 'delete']
torrent, = await client.torrents()
assert lib.TAG in torrent['tags']
assert torrent['save_path'] == str(lib.get_media_directory() / 'torrents')
done = await lib.reconcile(client, wrol_mode=False, state=state)
assert done['forgotten'] == []
assert test_torrents_config.get(A) is not None
assert test_torrents_config.get_torrent_file(A).is_file()
async def test_webui_download_path_outside_a_library_directory_is_refused(test_torrents_config, fake_qbittorrent):
"""qBittorrent keeps a torrent's incomplete files in its download path, which the WebUI can set per torrent."""
client = fake_qbittorrent([qbt_torrent(A, tags='', state='metaDL', progress=0,
download_path=str(lib.get_media_directory()))],
tags=[lib.TAG], metadata=False)
with mock.patch.object(lib.Events, 'send_torrent_refused'):
done = await lib.reconcile(client, wrol_mode=False)
assert done['refused'] == [A]
async def test_wrolpi_torrent_download_path_is_moved_back(test_torrents_config, fake_qbittorrent):
make_entity(test_torrents_config, A)
client = fake_qbittorrent([qbt_torrent(A, state='downloading', progress=0.5,
download_path=str(lib.get_media_directory()))], tags=[lib.TAG])
with mock.patch.object(lib.Events, 'send_torrent_refused') as send_torrent_refused:
done = await lib.reconcile(client, wrol_mode=False)
assert done['moved_back'] == [A]
assert ('set_download_path', [A], str(lib.get_media_directory() / 'torrents')) in client.calls
send_torrent_refused.assert_called_once()
async def test_finished_torrent_download_path_is_left_alone(test_torrents_config, fake_qbittorrent):
"""A finished torrent's files are in its save path; the download path it kept them in is no longer used."""
make_entity(test_torrents_config, A)
client = fake_qbittorrent([qbt_torrent(A, download_path=str(lib.get_media_directory()))], tags=[lib.TAG])
done = await lib.reconcile(client, wrol_mode=False)
assert done['moved_back'] == []
assert not [c for c in client.calls if c[0] == 'set_download_path']
async def test_waits_for_metadata_before_adopting(test_torrents_config, fake_qbittorrent):
client = fake_qbittorrent([qbt_torrent(A, tags='', state='metaDL', progress=0)], tags=[lib.TAG], metadata=False)
done = await lib.reconcile(client, wrol_mode=False)

View file

@ -56,6 +56,10 @@ class Events:
def send_sync_failed(message: str):
send_event('sync_failed', message, subject='sync')
@staticmethod
def send_torrent_refused(message: str):
send_event('torrent_refused', message, subject='torrents')
@staticmethod
def send_user_notify(message: str, url: str = None):
send_event('user_notify_message', message, subject='user_notify', url=url)