mirror of
https://github.com/lrnselfreliance/wrolpi.git
synced 2026-11-30 20:06:22 -05:00
* 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>
158 lines
8.7 KiB
Python
158 lines
8.7 KiB
Python
"""Share as torrent: make a torrent of a file or directory in the library, and seed it."""
|
|
import asyncio
|
|
from http import HTTPStatus
|
|
from unittest import mock
|
|
|
|
import pytest
|
|
|
|
from modules.torrents import lib, share
|
|
from modules.torrents.test.test_adding import TORRENT, HASH
|
|
from wrolpi.errors import ValidationError
|
|
|
|
|
|
@pytest.fixture
|
|
def planet(test_directory):
|
|
path = test_directory / 'maps' / 'planet.pmtiles'
|
|
path.parent.mkdir(parents=True)
|
|
path.write_bytes(b'tiles')
|
|
return path
|
|
|
|
|
|
class TestCheck:
|
|
|
|
def test_share_path(self, test_directory, planet):
|
|
assert share.check_share_path('maps/planet.pmtiles') == planet
|
|
assert share.check_share_path('maps/') == planet.parent
|
|
|
|
@pytest.mark.parametrize('path,message', [
|
|
('', 'Choose'), ('missing.bin', 'does not exist'), ('../outside', 'media directory'),
|
|
('config/torrents', 'config'), ('empty', 'no files'),
|
|
])
|
|
def test_refused(self, test_directory, planet, path, message):
|
|
(test_directory / 'empty').mkdir()
|
|
(test_directory / 'config' / 'torrents').mkdir(parents=True, exist_ok=True)
|
|
with pytest.raises(ValidationError, match=message):
|
|
share.check_share_path(path)
|
|
|
|
@pytest.mark.parametrize('path', ['.', './', '/', 'maps/..', 'config', 'config/vpn'])
|
|
def test_never_the_config(self, test_directory, planet, path):
|
|
(test_directory / 'config' / 'vpn').mkdir(parents=True, exist_ok=True)
|
|
(test_directory / 'config' / 'vpn' / 'wireguard.conf').write_text('PrivateKey = secret')
|
|
with pytest.raises(ValidationError):
|
|
share.check_share_path(path)
|
|
|
|
def test_links_out_are_refused(self, test_directory, planet):
|
|
(test_directory / 'config' / 'vpn').mkdir(parents=True, exist_ok=True)
|
|
(test_directory / 'config' / 'vpn' / 'wireguard.conf').write_text('PrivateKey = secret')
|
|
(test_directory / 'maps' / 'keys').symlink_to(test_directory / 'config' / 'vpn')
|
|
with pytest.raises(ValidationError, match='links to a folder'):
|
|
share.check_share_path('maps')
|
|
(test_directory / 'maps' / 'keys').unlink()
|
|
(test_directory / 'maps' / 'hosts').symlink_to('/etc/hosts')
|
|
with pytest.raises(ValidationError, match='outside the library'):
|
|
share.check_share_path('maps')
|
|
(test_directory / 'maps' / 'hosts').unlink()
|
|
# A link to the library itself would publish everything.
|
|
(test_directory / 'maps' / 'all').symlink_to(test_directory)
|
|
with pytest.raises(ValidationError, match='links to a folder'):
|
|
share.check_share_path('maps')
|
|
(test_directory / 'maps' / 'all').unlink()
|
|
# A link to a folder could lead anywhere (its own links are not walked).
|
|
(test_directory / 'videos').mkdir()
|
|
(test_directory / 'maps' / 'videos').symlink_to(test_directory / 'videos')
|
|
with pytest.raises(ValidationError, match='links to a folder'):
|
|
share.check_share_path('maps')
|
|
(test_directory / 'maps' / 'videos').unlink()
|
|
# A link to a file elsewhere in the library is fine; one to a file in config/ is not.
|
|
(test_directory / 'videos' / 'a.mp4').write_bytes(b'video')
|
|
(test_directory / 'maps' / 'a.mp4').symlink_to(test_directory / 'videos' / 'a.mp4')
|
|
assert share.check_share_path('maps') == planet.parent
|
|
(test_directory / 'maps' / 'key').symlink_to(test_directory / 'config' / 'vpn' / 'wireguard.conf')
|
|
with pytest.raises(ValidationError, match='config directory'):
|
|
share.check_share_path('maps')
|
|
|
|
def test_urls(self):
|
|
assert share.check_trackers(['udp://t.example:1337/announce', ' https://t.example/announce ', '',
|
|
'udp://t.example:1337/announce']) == \
|
|
['udp://t.example:1337/announce', 'https://t.example/announce']
|
|
assert share.check_web_seeds(['https://cdn.example/planet.pmtiles']) == ['https://cdn.example/planet.pmtiles']
|
|
for bad in ('ftp://t.example/', 'udp://', 'https://a.example/x|https://b.example/y', 'not a url'):
|
|
with pytest.raises(ValidationError):
|
|
share.check_trackers([bad])
|
|
with pytest.raises(ValidationError):
|
|
share.check_web_seeds(['udp://t.example:1337/announce'])
|
|
|
|
|
|
async def test_share(test_torrents_config, planet, fake_qbittorrent):
|
|
client = fake_qbittorrent(tags=[lib.TAG], created=TORRENT, creator_statuses=[
|
|
{'status': 'Running', 'progress': 40}, {'status': 'Finished', 'progress': None}])
|
|
job = mock.Mock()
|
|
job.cancel_requested.return_value = False
|
|
with mock.patch.object(share, 'get_current_job', lambda: job), mock.patch.object(share, 'POLL_SECONDS', 0):
|
|
result = await share.share_torrent('maps/planet.pmtiles', ['udp://t.example:1337/announce'],
|
|
['https://cdn.example/planet.pmtiles'], client=client)
|
|
assert result['hash'] == HASH
|
|
assert lib.magnet_identity(result['magnet'])[0] == HASH
|
|
assert ('create_torrent', str(planet), ['udp://t.example:1337/announce'],
|
|
['https://cdn.example/planet.pmtiles']) in client.calls
|
|
job.set_progress.assert_called_with(40)
|
|
# Seeded from where the files are, without hashing them again; the creator's task is cleaned up.
|
|
assert ('skip_checking', str(planet.parent)) in client.calls
|
|
assert ('delete_torrent_creator_task', 'task-1') in client.calls
|
|
entity = test_torrents_config.get(HASH)
|
|
assert (entity['save_path'], entity['complete']) == ('maps', True)
|
|
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'):
|
|
await share.share_torrent('maps/planet.pmtiles', [], [], client=client)
|
|
assert ('delete_torrent_creator_task', 'task-1') in client.calls
|
|
assert test_torrents_config.get(HASH) is None
|
|
|
|
|
|
async def test_share_cancelled(test_torrents_config, planet, fake_qbittorrent):
|
|
client = fake_qbittorrent(tags=[lib.TAG], creator_statuses=[{'status': 'Running', 'progress': 10}])
|
|
job = mock.Mock()
|
|
job.cancel_requested.return_value = True
|
|
with mock.patch.object(share, 'get_current_job', lambda: job), pytest.raises(asyncio.CancelledError):
|
|
await share.share_torrent('maps/planet.pmtiles', [], [], client=client)
|
|
# Stops qBittorrent hashing.
|
|
assert ('delete_torrent_creator_task', 'task-1') in client.calls
|
|
assert not [c for c in client.calls if c[0] == 'add']
|
|
|
|
|
|
async def test_share_api(test_torrents_config, async_client, planet, test_wrolpi_config):
|
|
with mock.patch.object(share, 'enqueue_job', return_value='job-1') as enqueue_job:
|
|
request, response = await async_client.post('/api/torrents/share', json={
|
|
'path': 'maps/planet.pmtiles', 'trackers': ['udp://t.example:1337/announce'],
|
|
'web_seeds': ['https://cdn.example/planet.pmtiles'], 'remember_trackers': True})
|
|
assert response.status_code == HTTPStatus.CREATED, response.json
|
|
assert response.json == {'job_id': 'job-1'}
|
|
assert enqueue_job.call_args.kwargs == dict(
|
|
description='Make a torrent of maps/planet.pmtiles', path='maps/planet.pmtiles',
|
|
trackers=['udp://t.example:1337/announce'], web_seeds=['https://cdn.example/planet.pmtiles'])
|
|
# Offered next time.
|
|
assert lib.get_wrolpi_config().torrent_trackers == ['udp://t.example:1337/announce']
|
|
|
|
request, response = await async_client.post('/api/torrents/share', json={
|
|
'path': 'config', 'trackers': ['udp://other.example:1/announce'], 'remember_trackers': True})
|
|
assert response.status_code == HTTPStatus.BAD_REQUEST
|
|
# A refused request changes nothing.
|
|
assert lib.get_wrolpi_config().torrent_trackers == ['udp://t.example:1337/announce']
|
|
|
|
|
|
def test_default_trackers(test_wrolpi_config):
|
|
assert lib.get_wrolpi_config().torrent_trackers == [
|
|
'udp://tracker.opentrackr.org:1337/announce', 'udp://tracker.torrent.eu.org:451/announce']
|