From 7b6fc60de5c392e620608db839f8e74f767dfba5 Mon Sep 17 00:00:00 2001 From: Roland Date: Wed, 6 May 2026 17:13:46 -0600 Subject: [PATCH] Migrating ScrapeDownloader. --- wrolpi/files/test/test_scrape_downloader.py | 171 +++++++++++++++++++- wrolpi/scrape_downloader.py | 89 +++++++--- 2 files changed, 238 insertions(+), 22 deletions(-) diff --git a/wrolpi/files/test/test_scrape_downloader.py b/wrolpi/files/test/test_scrape_downloader.py index d82f44fd..4e389215 100644 --- a/wrolpi/files/test/test_scrape_downloader.py +++ b/wrolpi/files/test/test_scrape_downloader.py @@ -4,9 +4,15 @@ import mock import pytest from wrolpi.dates import Seconds -from wrolpi.downloader import DownloadResult +from wrolpi.downloader import Download, DownloadResult +from wrolpi.errors import UnrecoverableDownloadError from wrolpi.files.downloader import FileDownloader -from wrolpi.scrape_downloader import ScrapeHTMLDownloader +from wrolpi.scrape_downloader import ( + ExecutedScrape, + PreparedScrape, + ScrapeHTMLDownloader, + scrape_html_downloader, +) EXAMPLE_HTTP = ''' @@ -94,3 +100,164 @@ async def test_scrape_html_downloader_api(async_client, test_session, test_downl settings=dict(depth=1, max_pages=1, suffix='.mp4')) request, response = await async_client.post('/api/download', json=body) assert response.status == HTTPStatus.BAD_REQUEST + + +# --------------------------------------------------------------------------- +# Phase-split unit tests. +# +# These exercise prepare_download / execute_download / finalize_download in +# isolation — no async_client, no test_download_manager, no +# wait_for_all_downloads polling. They reuse make_test_ctx from the archive +# conftest so we don't need to duplicate the helper. +# --------------------------------------------------------------------------- + +from modules.archive.conftest import make_test_ctx # noqa: E402 + + +def test_prepare_max_attempts_raises(test_session): + """prepare_download enforces the attempt cap before any I/O.""" + download = Download( + url='https://example.com/x', + downloader='scrape_html', + attempts=4, + destination='/tmp/dest', + settings={'suffix': '.pdf'}, + ) + + with pytest.raises(UnrecoverableDownloadError): + scrape_html_downloader.prepare_download(test_session, download) + + +def test_prepare_requires_suffix(test_session, test_directory): + """Missing settings['suffix'] is unrecoverable.""" + download = Download( + url='https://example.com/x', + downloader='scrape_html', + destination=str(test_directory / 'dest'), + settings={}, + ) + + with pytest.raises(UnrecoverableDownloadError, match='Suffix'): + scrape_html_downloader.prepare_download(test_session, download) + + +def test_prepare_requires_destination(test_session): + """Missing destination is unrecoverable.""" + download = Download( + url='https://example.com/x', + downloader='scrape_html', + settings={'suffix': '.pdf'}, + ) + + with pytest.raises(UnrecoverableDownloadError, match='Destination'): + scrape_html_downloader.prepare_download(test_session, download) + + +def test_prepare_lowercases_suffix_and_creates_destination(test_session, test_directory): + """Suffix is normalised to lowercase and the destination directory is created.""" + dest = test_directory / 'new_dest' + assert not dest.exists() + download = Download( + url='https://example.com/x', + downloader='scrape_html', + destination=str(dest), + settings={'suffix': '.PDF', 'depth': 2, 'max_pages': 50}, + ) + + prepared = scrape_html_downloader.prepare_download(test_session, download) + + assert isinstance(prepared, PreparedScrape) + assert prepared.suffix == '.pdf' + assert prepared.depth == 2 + assert prepared.max_pages == 50 + assert prepared.destination == dest + assert dest.is_dir() + + +@pytest.mark.asyncio +async def test_execute_collects_matching_urls(test_directory): + """execute_download walks pages and returns URLs matching the suffix. No DB, + no Sanic, no DownloadManager — the I/O phase is fully isolated.""" + prepared = PreparedScrape( + url='https://example.com/dir', + depth=1, + suffix='.pdf', + max_pages=100, + destination=test_directory, + ) + + with mock.patch('wrolpi.scrape_downloader.ScrapeHTMLDownloader.fetch_html', fake_fetch_html): + executed = await scrape_html_downloader.execute_download(prepared, make_test_ctx()) + + assert isinstance(executed, ExecutedScrape) + assert sorted(executed.download_urls) == sorted([ + 'https://example.com/one.pdf', + 'https://example.com/two.pdf', + 'https://example.com/dir/three.pdf', + ]) + assert executed.page_count == 1 + assert executed.suffix == '.pdf' + + +@pytest.mark.asyncio +async def test_execute_respects_max_pages(test_directory): + """max_pages caps the crawl; deeper pages are skipped after the limit.""" + prepared = PreparedScrape( + url='https://example.com/dir', + depth=3, + suffix='.html', # links to other.html mean each page yields more pages + max_pages=1, + destination=test_directory, + ) + + with mock.patch('wrolpi.scrape_downloader.ScrapeHTMLDownloader.fetch_html', fake_fetch_html): + executed = await scrape_html_downloader.execute_download(prepared, make_test_ctx()) + + assert executed.page_count == 1 + assert executed.max_pages == 1 + # Only the first page was crawled, but its other.html link should still be collected. + assert 'https://example.com/dir/other.html' in executed.download_urls + + +def test_finalize_returns_failure_when_no_urls_found(test_session, test_directory): + """No matching URLs → DownloadResult with success=False and a descriptive error.""" + executed = ExecutedScrape( + download_urls=[], + page_count=5, + max_pages=100, + suffix='.pdf', + destination=test_directory, + ) + download = Download(url='https://example.com/x', downloader='scrape_html', settings={'suffix': '.pdf'}) + + result = scrape_html_downloader.finalize_download(test_session, download, executed) + + assert result.success is False + assert '.pdf' in (result.error or '') + assert '5 pages' in (result.error or '') + + +def test_finalize_returns_success_with_downloads_and_settings(test_session, test_directory): + """Populated executed → success result; settings get destination injected; max_pages + triggers the warning.""" + executed = ExecutedScrape( + download_urls=['https://example.com/a.pdf', 'https://example.com/b.pdf'], + page_count=10, + max_pages=10, # equal to page_count → warning is set + suffix='.pdf', + destination=test_directory / 'dest', + ) + download = Download( + url='https://example.com/x', + downloader='scrape_html', + settings={'suffix': '.pdf', 'depth': 1}, + ) + + result = scrape_html_downloader.finalize_download(test_session, download, executed) + + assert result.success is True + assert result.downloads == executed.download_urls + assert result.settings['destination'] == str(executed.destination) + assert result.settings['suffix'] == '.pdf' # original setting preserved + assert result.error == 'Reached max page count.' + assert result.location == f'/files?folders={executed.destination}' diff --git a/wrolpi/scrape_downloader.py b/wrolpi/scrape_downloader.py index 82da3bbb..44f97852 100644 --- a/wrolpi/scrape_downloader.py +++ b/wrolpi/scrape_downloader.py @@ -1,9 +1,13 @@ import pathlib from copy import copy +from dataclasses import dataclass +from typing import List from urllib.parse import urlparse +from sqlalchemy.orm import Session + from wrolpi.common import logger, get_html_soup, aiohttp_get -from wrolpi.downloader import Downloader, Download, DownloadResult +from wrolpi.downloader import Downloader, Download, DownloadContext, DownloadResult from wrolpi.errors import UnrecoverableDownloadError logger = logger.getChild(__name__) @@ -25,6 +29,27 @@ def resolve_url(parent_url: str, url: str): return f'{parent_url}/{url}' +@dataclass +class PreparedScrape: + """Plan produced by ScrapeHTMLDownloader.prepare_download.""" + url: str + depth: int + suffix: str # already lowercased + max_pages: int + destination: pathlib.Path + + +@dataclass +class ExecutedScrape: + """Output of ScrapeHTMLDownloader.execute_download: URLs collected, plus enough state + for finalize_download to build the user-facing DownloadResult.""" + download_urls: List[str] + page_count: int + max_pages: int + suffix: str + destination: pathlib.Path + + class ScrapeHTMLDownloader(Downloader): """Scrape downloads HTML pages searching for files with a particular suffix. @@ -42,16 +67,19 @@ class ScrapeHTMLDownloader(Downloader): async with aiohttp_get(url, timeout=60 * 5) as response: return await response.text() - async def do_download(self, download: Download) -> DownloadResult: - if download.attempts > 3: + def prepare_download(self, session: Session, download: Download) -> PreparedScrape: + """Validate settings and ensure the destination directory exists. + + session is unused here — scrape has no DB work in any phase — but the API still + requires it. + """ + if (download.attempts or 0) > 3: raise UnrecoverableDownloadError(f'Max download attempts reached for {download.url}') - urls = [download.url, ] - download_urls = list() - - depth = download.settings.get('depth') or 1 - suffix = download.settings.get('suffix') - max_pages = download.settings.get('max_pages') or 100 + settings = download.settings or {} + depth = settings.get('depth') or 1 + suffix = settings.get('suffix') + max_pages = settings.get('max_pages') or 100 destination = download.destination if 0 > depth > 10: @@ -64,16 +92,26 @@ class ScrapeHTMLDownloader(Downloader): if not destination.is_dir(): destination.mkdir(parents=True) - suffix = suffix.lower() + return PreparedScrape( + url=download.url, + depth=depth, + suffix=suffix.lower(), + max_pages=max_pages, + destination=destination, + ) + async def execute_download(self, prepared: PreparedScrape, ctx: DownloadContext) -> ExecutedScrape: + """Crawl HTML pages up to depth, collecting links that match the configured suffix.""" + urls = [prepared.url] + download_urls: List[str] = [] page_count = 0 - for i in range(depth): + for _ in range(prepared.depth): # Copy the found URLs at this depth. Accumulate all anchors () found. local_urls = urls.copy() urls = list() for url in local_urls: - if page_count >= max_pages: + if page_count >= prepared.max_pages: logger.warning('Reached max page count.') break @@ -99,7 +137,7 @@ class ScrapeHTMLDownloader(Downloader): logger.debug(f'Not a real anchor: {a}') continue child_url = resolve_url(url, href) - if child_url and child_url.lower().endswith(suffix): + if child_url and child_url.lower().endswith(prepared.suffix): # Found a file that the User requested. logger.info(f'ScrapeHTMLDownloader will download {child_url}') download_urls.append(child_url) @@ -107,20 +145,31 @@ class ScrapeHTMLDownloader(Downloader): logger.debug(f'ScrapeHTMLDownloader scraping {child_url}') urls.append(child_url) - if not download_urls: + return ExecutedScrape( + download_urls=download_urls, + page_count=page_count, + max_pages=prepared.max_pages, + suffix=prepared.suffix, + destination=prepared.destination, + ) + + def finalize_download(self, session: Session, download: Download, + executed: ExecutedScrape) -> DownloadResult: + """Build the DownloadResult. No DB work; session is unused.""" + if not executed.download_urls: return DownloadResult( success=False, - error=f'No files with {suffix} found in {page_count} pages!' + error=f'No files with {executed.suffix} found in {executed.page_count} pages!', ) - settings = copy(download.settings) - settings['destination'] = str(download.destination) # Use str for json conversion. + settings = copy(download.settings) if download.settings else {} + settings['destination'] = str(executed.destination) # Use str for json conversion. return DownloadResult( success=True, - downloads=download_urls, + downloads=executed.download_urls, settings=settings, - error='Reached max page count.' if page_count >= max_pages else None, - location=f'/files?folders={destination}' + error='Reached max page count.' if executed.page_count >= executed.max_pages else None, + location=f'/files?folders={executed.destination}', )