"""Adding torrents (magnet links, .torrent files and URLs), managing them, and their progress on the Downloads page.""" import hashlib from http import HTTPStatus from unittest import mock import pytest from modules.torrents import lib from modules.torrents.downloader import TorrentDownloader, PreparedTorrent, ExecutedTorrent from wrolpi.downloader import Download from wrolpi.errors import ValidationError def bencode(value) -> bytes: if isinstance(value, int): return f'i{value}e'.encode() if isinstance(value, str): value = value.encode() if isinstance(value, bytes): return f'{len(value)}:'.encode() + value if isinstance(value, list): return b'l' + b''.join(bencode(i) for i in value) + b'e' if isinstance(value, dict): return b'd' + b''.join(bencode(k) + bencode(value[k]) for k in sorted(value)) + b'e' raise TypeError(value) INFO = {'name': 'planet.pmtiles', 'piece length': 16384, 'pieces': b'\x00' * 20, 'length': 1000} # The announce URL holds the bytes which start the info dictionary; it must not be mistaken for it. TORRENT = bencode({'announce': 'http://tracker.example/4:infod', 'info': INFO}) HASH = hashlib.sha1(bencode(INFO)).hexdigest() class TestIdentity: def test_torrent_file(self): assert lib.torrent_identity(TORRENT) == (HASH, 'planet.pmtiles') def test_v2_only(self): info = {'name': 'v2', 'piece length': 16384, 'meta version': 2, 'file tree': {}} torrent = bencode({'info': info}) v2 = hashlib.sha256(bencode(info)).hexdigest() assert lib.torrent_identity(torrent)[0] == v2[:40] assert lib.torrent_magnet(torrent) == f'magnet:?xt=urn:btmh:1220{v2}&dn=v2' def test_hybrid(self): """A hybrid torrent (what "Share as torrent" makes) is named by its truncated v2 hash, as qBittorrent names it (libtorrent's "best" hash); its magnet link carries both hashes.""" info = {**INFO, 'meta version': 2, 'file tree': {}} torrent = bencode({'info': info}) v1, v2 = hashlib.sha1(bencode(info)).hexdigest(), hashlib.sha256(bencode(info)).hexdigest() assert lib.torrent_identity(torrent) == (v2[:40], 'planet.pmtiles') magnet = lib.torrent_magnet(torrent) assert magnet == f'magnet:?xt=urn:btih:{v1}&xt=urn:btmh:1220{v2}&dn=planet.pmtiles' assert lib.magnet_identity(magnet) == (v2[:40], 'planet.pmtiles') @pytest.mark.parametrize('torrent', [b'', b'not a torrent', bencode({'announce': 'x'}), bencode([1, 2]), b'd4:infoi1ee', b'x' * (lib.MAX_TORRENT_FILE_BYTES + 1)]) def test_not_a_torrent(self, torrent): with pytest.raises(ValidationError): lib.torrent_identity(torrent) def test_magnet(self): assert lib.magnet_identity(f'magnet:?xt=urn:btih:{HASH.upper()}&dn=planet') == (HASH, 'planet') base32 = __import__('base64').b32encode(bytes.fromhex(HASH)).decode() assert lib.magnet_identity(f'magnet:?xt=urn:btih:{base32}')[0] == HASH with pytest.raises(ValidationError): lib.magnet_identity('magnet:?dn=no-hash') # A v1 magnet link of a hybrid torrent still names it by v1 (qBittorrent knows nothing else of it). v2 = 'c' * 64 assert lib.magnet_identity(f'magnet:?xt=urn:btmh:1220{v2}')[0] == v2[:40] def test_magnet_link_round_trips(self): assert lib.magnet_identity(lib.magnet_link(HASH, None, 'a planet & more')) == (HASH, 'a planet & more') class TestSavePath: def test_in_the_library(self, test_directory): assert lib.check_save_path('maps') == 'maps' assert lib.check_save_path(str(test_directory / 'maps' / 'big')) == 'maps/big' assert lib.check_save_path(None) == lib.DEFAULT_SAVE_PATH @pytest.mark.parametrize('save_path', ['../outside', '/etc', 'config', 'config/torrents', 'maps/../../x']) def test_refused(self, test_directory, save_path): with pytest.raises(ValidationError): lib.check_save_path(save_path) async def test_add_torrent_file(test_torrents_config, fake_qbittorrent): client = fake_qbittorrent(tags=[lib.TAG]) entity = await lib.add_torrent('maps', torrent=TORRENT, client=client) assert entity['slug'] == HASH assert entity['name'] == 'planet.pmtiles' assert entity['save_path'] == 'maps' assert lib.magnet_identity(entity['magnet'])[0] == HASH assert test_torrents_config.get_torrent_file(HASH).read_bytes() == TORRENT _, save_path, torrent, url, tags, stopped = next(c for c in client.calls if c[0] == 'add') assert save_path == str(lib.get_media_directory() / 'maps') assert (torrent, url, tags, stopped) == (TORRENT, None, [lib.TAG], False) async def test_add_magnet_once(test_torrents_config, fake_qbittorrent): client = fake_qbittorrent(tags=[lib.TAG]) magnet = f'magnet:?xt=urn:btih:{HASH}&dn=planet' await lib.add_torrent(None, magnet=magnet, client=client) await lib.add_torrent(None, magnet=magnet, client=client) adds = [c for c in client.calls if c[0] == 'add'] assert len(adds) == 1 assert adds[0][3] == magnet assert test_torrents_config.get(HASH)['save_path'] == lib.DEFAULT_SAVE_PATH async def test_pause_resume_remove(test_torrents_config, fake_qbittorrent): client = fake_qbittorrent(tags=[lib.TAG]) await lib.add_torrent(None, torrent=TORRENT, client=client) await lib.set_paused(HASH, True, client=client) assert test_torrents_config.get(HASH)['paused'] is True assert ('stop', [HASH]) in client.calls await lib.set_paused(HASH, False, client=client) assert ('start', [HASH]) in client.calls await lib.remove_torrent(HASH, delete_files=True, client=client) assert ('delete', [HASH], True) in client.calls assert test_torrents_config.get(HASH) is None assert not test_torrents_config.get_torrent_file(HASH).exists() async def test_share_limits_are_applied(test_torrents_config, fake_qbittorrent): client = fake_qbittorrent(tags=[lib.TAG]) await lib.add_torrent(None, torrent=TORRENT, client=client) await lib.reconcile(client, wrol_mode=False) # No limits: none in qBittorrent either. assert ('set_share_limits', [HASH], -1, -1) in client.calls lib.set_share_limits(HASH, 2.0, 1440) await lib.reconcile(client, wrol_mode=False) assert ('set_share_limits', [HASH], 2.0, 1440) in client.calls calls = len(client.calls) await lib.reconcile(client, wrol_mode=False) assert not [c for c in client.calls[calls:] if c[0] == 'set_share_limits'] with pytest.raises(ValidationError): lib.set_share_limits(HASH, -1) def test_speed_limits(test_wrolpi_config): config = lib.get_wrolpi_config() config.torrent_upload_limit = 500 config.torrent_download_limit = 0 preferences = lib.desired_preferences({}) assert preferences['up_limit'] == 500 * 1024 assert preferences['dl_limit'] == 0 def test_download_rows_show_torrent_progress(test_session, test_directory): download = Download(url=f'magnet:?xt=urn:btih:{HASH}', downloader=lib.TORRENT_DOWNLOADER, status='complete', info_json=dict(torrent_hash=HASH), last_successful_download=lib.get_media_directory() and None) other = Download(url='https://example.com/file', downloader='file', status='complete') test_session.add_all([download, other]) test_session.commit() progress = {} with mock.patch('wrolpi.downloader.set_download_progress', lambda i, p: progress.__setitem__(i, p)), \ mock.patch('wrolpi.downloader.clear_download_progress', lambda i: progress.pop(i, None)): lib.sync_download_rows({HASH: dict(hash=HASH, progress=0.25, dlspeed=1000, eta=125, completed=250, size=1000)}) assert progress[download.id] == dict(percent=25.0, speed=1000, eta='2:05', bytes_downloaded=250, total_bytes=1000) test_session.expire_all() # Downloading: not shown as completed. assert test_session.get(Download, download.id).last_successful_download is None lib.sync_download_rows({HASH: dict(hash=HASH, progress=1.0, size=1000)}) assert download.id not in progress test_session.expire_all() assert test_session.get(Download, download.id).last_successful_download is not None assert other.id not in progress class TestDownloader: async def test_magnet(self, test_torrents_config, fake_qbittorrent): client = fake_qbittorrent(tags=[lib.TAG]) downloader = TorrentDownloader() with mock.patch.object(lib, 'QBittorrent', lambda: client): executed = await downloader.execute_download( PreparedTorrent(url=f'magnet:?xt=urn:btih:{HASH}&dn=planet', save_path='maps'), ctx=mock.Mock()) assert executed == ExecutedTorrent(hash=HASH, name='planet') download = Download(url='x') result = downloader.finalize_download(mock.Mock(), download, executed) assert result.success and result.location == '/admin/torrents' assert download.info_json['torrent_hash'] == HASH async def test_uploaded_file_is_used_over_its_magnet_link(self, test_torrents_config, fake_qbittorrent): client = fake_qbittorrent(tags=[lib.TAG]) test_torrents_config.get_torrent_file(HASH).write_bytes(TORRENT) with mock.patch.object(lib, 'QBittorrent', lambda: client): await TorrentDownloader().execute_download( PreparedTorrent(url=lib.torrent_magnet(TORRENT), save_path='maps'), ctx=mock.Mock()) assert next(c for c in client.calls if c[0] == 'add')[2] == TORRENT async def test_torrent_url(self, test_torrents_config, fake_qbittorrent): client = fake_qbittorrent(tags=[lib.TAG]) with mock.patch.object(lib, 'QBittorrent', lambda: client), \ mock.patch('modules.torrents.downloader.fetch_torrent_file', mock.AsyncMock(return_value=TORRENT)): executed = await TorrentDownloader().execute_download( PreparedTorrent(url='https://example.com/planet.torrent', save_path='maps'), ctx=mock.Mock()) assert executed.hash == HASH async def test_refused(self, test_torrents_config): result = await TorrentDownloader().execute_download( PreparedTorrent(url='ftp://example.com/x.torrent', save_path='maps'), ctx=mock.Mock()) assert result.success is False result = await TorrentDownloader().execute_download( PreparedTorrent(url='magnet:?xt=urn:btih:nothex', save_path='maps'), ctx=mock.Mock()) assert 'info hash' in result.error async def test_fetch_torrent_file_reads_every_chunk(test_directory): """A .torrent file which arrives in many pieces is read whole.""" from aiohttp import web from aiohttp.test_utils import TestServer from modules.torrents.downloader import fetch_torrent_file big = bencode({'announce': 'http://tracker.example/', 'comment': 'x' * 300_000, 'info': INFO}) async def handler(request): response = web.StreamResponse() await response.prepare(request) for i in range(0, len(big), 1000): await response.write(big[i:i + 1000]) return response app = web.Application() app.router.add_get('/planet.torrent', handler) app.router.add_get('/missing.torrent', lambda request: web.Response(status=404)) async with TestServer(app) as server: torrent = await fetch_torrent_file(str(server.make_url('/planet.torrent'))) with pytest.raises(ValidationError, match='404'): await fetch_torrent_file(str(server.make_url('/missing.torrent'))) assert torrent == big assert lib.torrent_identity(torrent) == (HASH, 'planet.pmtiles') class TestAPI: async def test_upload(self, test_torrents_config, async_client, test_session): request, response = await async_client.post('/api/torrents/upload', data={'destination': 'maps'}, files={'torrent': ('planet.torrent', TORRENT)}) assert response.status_code == HTTPStatus.OK, response.json assert response.json == dict(hash=HASH, name='planet.pmtiles') assert test_torrents_config.get_torrent_file(HASH).read_bytes() == TORRENT download = test_session.query(Download).one() assert download.downloader == lib.TORRENT_DOWNLOADER assert lib.magnet_identity(download.url)[0] == HASH assert str(download.destination).endswith('/maps') async def test_upload_refused(self, test_torrents_config, async_client): request, response = await async_client.post('/api/torrents/upload', data={'destination': 'config'}, files={'torrent': ('planet.torrent', TORRENT)}) assert response.status_code == HTTPStatus.BAD_REQUEST request, response = await async_client.post('/api/torrents/upload', files={'torrent': ('bad.torrent', b'nope')}) assert response.status_code == HTTPStatus.BAD_REQUEST async def test_manage(self, test_torrents_config, async_client, fake_qbittorrent, test_wrolpi_config): client = fake_qbittorrent(tags=[lib.TAG]) with mock.patch.object(lib, 'QBittorrent', lambda: client): await lib.add_torrent(None, torrent=TORRENT, client=client) request, response = await async_client.post(f'/api/torrents/{HASH}/pause') assert response.status_code == HTTPStatus.NO_CONTENT assert test_torrents_config.get(HASH)['paused'] is True request, response = await async_client.put(f'/api/torrents/{HASH}/limits', json={'seed_ratio_limit': 3.0, 'seed_time_limit': None}) assert response.status_code == HTTPStatus.NO_CONTENT assert test_torrents_config.get(HASH)['seed_ratio_limit'] == 3.0 request, response = await async_client.get(f'/api/torrents/{HASH}/torrent') assert response.status_code == HTTPStatus.OK assert response.body == TORRENT request, response = await async_client.put('/api/torrents/limits', json={'upload': 100, 'download': 0}) assert response.status_code == HTTPStatus.NO_CONTENT assert lib.get_wrolpi_config().torrent_upload_limit == 100 with mock.patch.object(lib, 'get_vpn_status', mock.AsyncMock(return_value={'state': 'connected'})): request, response = await async_client.get('/api/torrents') torrent = response.json['torrents'][0] assert (torrent['managed'], torrent['paused'], torrent['seed_ratio_limit']) == (True, True, 3.0) assert response.json['limits'] == {'upload': 100, 'download': 0} request, response = await async_client.delete(f'/api/torrents/{HASH}?delete_files=true') assert response.status_code == HTTPStatus.NO_CONTENT assert ('delete', [HASH], True) in client.calls async def test_status_tells_the_navigation(test_torrents_config, async_client, fake_qbittorrent): """/api/status carries the torrents summary the worker publishes, so the navigation can warn without asking qBittorrent or the Controller itself.""" client = fake_qbittorrent(tags=[lib.TAG]) await lib.add_torrent(None, torrent=TORRENT, client=client) with mock.patch.object(lib, 'get_vpn_status', mock.AsyncMock(return_value={'state': 'connecting'})): await lib.sync_torrents(client) request, response = await async_client.get('/api/status') assert response.json['torrents'] == {'count': 1, 'vpn_state': 'connecting', 'running': True}