From 82af9a0d3c03c12d46b944735cdfc1954493f1b6 Mon Sep 17 00:00:00 2001 From: Roland Date: Mon, 22 Jul 2024 17:56:41 -0600 Subject: [PATCH] Fixing bug where download.downloader would be replaced for all Channel Downloads. --- modules/videos/models.py | 16 +++++++++++----- wrolpi/api_utils.py | 1 - wrolpi/conftest.py | 2 +- wrolpi/downloader.py | 15 ++++++++------- wrolpi/root_api.py | 4 ++-- wrolpi/test/test_downloader.py | 11 ++++++++--- wrolpi/test/test_root_api.py | 9 +++++---- 7 files changed, 35 insertions(+), 23 deletions(-) diff --git a/modules/videos/models.py b/modules/videos/models.py index 7f135f36..ac061adf 100644 --- a/modules/videos/models.py +++ b/modules/videos/models.py @@ -707,12 +707,18 @@ class Channel(ModelHelper, Base): if not isinstance(url, str) or not url: raise RuntimeError(f'Cannot get Download without url') - download = download_manager.get_or_create_download(url, session=session, reset_attempts=reset_attempts) - download.channel_id = self.id - download.settings = download.settings or dict(destination=str(self.directory)) from modules.videos.downloader import ChannelDownloader, VideoDownloader - download.downloader = ChannelDownloader.name - download.sub_downloader = VideoDownloader.name + + download = download_manager.get_download(session, url) + if not download: + download = download_manager.create_download(url, ChannelDownloader.name, session=session, + sub_downloader_name=VideoDownloader.name, + settings=dict(destination=str(self.directory)), + reset_attempts=reset_attempts, + ) + if reset_attempts: + download.attempts = 0 + download.channel_id = self.id return download diff --git a/wrolpi/api_utils.py b/wrolpi/api_utils.py index 700734bd..de12a523 100644 --- a/wrolpi/api_utils.py +++ b/wrolpi/api_utils.py @@ -9,7 +9,6 @@ from sanic import response, HTTPResponse, Request, Sanic, SanicException from wrolpi.common import Base, get_media_directory, logger, LOGGING_CONFIG from wrolpi.errors import APIError -from wrolpi.vars import PYTEST logger = logger.getChild(__name__) diff --git a/wrolpi/conftest.py b/wrolpi/conftest.py index 0fb31038..adb521eb 100644 --- a/wrolpi/conftest.py +++ b/wrolpi/conftest.py @@ -162,7 +162,7 @@ def test_client(test_directory) -> ReusableClient: @pytest.fixture -def test_async_client(test_directory) -> SanicASGITestClient: +async def test_async_client(test_directory) -> SanicASGITestClient: """Get an Async Sanic Test Client with all default routes attached.""" attach_shared_contexts(api_app) diff --git a/wrolpi/downloader.py b/wrolpi/downloader.py index 11acfbfa..b3152534 100644 --- a/wrolpi/downloader.py +++ b/wrolpi/downloader.py @@ -192,7 +192,7 @@ class Download(ModelHelper, Base): # noqa def get_downloader(self): if self.downloader: - return download_manager.get_downloader_by_name(self.downloader) + return download_manager.find_downloader_by_name(self.downloader) raise UnrecoverableDownloadError(f'Cannot find downloader for {repr(str(self.url))}') @@ -485,8 +485,8 @@ class DownloadManager: task = loop.create_task(coro) self.workers.append(task) - def get_downloader_by_name(self, name: str) -> Optional[Downloader]: - """Attempt to find a registered Downloader by its name. Returns None if it cannot be found.""" + def find_downloader_by_name(self, name: str) -> Optional[Downloader]: + """Attempt to find a registered Downloader by its name. Raises error if it cannot be found.""" if downloader := self._instances.get(name): return downloader raise InvalidDownload(f'Cannot find downloader with name {name}') @@ -516,19 +516,18 @@ class DownloadManager: """Schedule all URLs for download. If one cannot be downloaded, none will be added.""" if not urls or not all(urls): raise ValueError(f'Download must have a URL: {urls=}') + logger.debug(f'Attempting to create {len(urls)} new downloads') downloads = [] # Throws an error if no downloader is found. - self.get_downloader_by_name(downloader_name) + self.find_downloader_by_name(downloader_name) - skipped = list() for url in urls: if url in get_download_manager_config().skip_urls and reset_attempts: # User manually entered this download, remove it from the skip list. self.remove_from_skip_list(url) elif url in get_download_manager_config().skip_urls: self.log_warning(f'Skipping {url} because it is in the download_manager.yaml skip list.') - skipped.append(url) continue download = self.get_or_create_download(url, session, reset_attempts=reset_attempts) @@ -547,6 +546,8 @@ class DownloadManager: downloads.append(download) + logger.debug(f'Created {len(downloads)} new downloads') + session.flush(downloads) try: # Start downloading ASAP. @@ -1323,7 +1324,7 @@ class RSSDownloader(Downloader, ABC): # Only download URLs that have not yet been downloaded. urls = [] - sub_downloader = download_manager.get_downloader_by_name(download.sub_downloader) + sub_downloader = download_manager.find_downloader_by_name(download.sub_downloader) if not sub_downloader: raise ValueError(f'Unable to find sub_downloader for {download.url}') diff --git a/wrolpi/root_api.py b/wrolpi/root_api.py index 65da626e..3a34ab97 100644 --- a/wrolpi/root_api.py +++ b/wrolpi/root_api.py @@ -249,7 +249,7 @@ def valid_regex(_: Request, body: schema.RegexRequest): @validate(schema.DownloadRequest) @wrol_mode_check async def post_download(_: Request, body: schema.DownloadRequest): - downloader = download_manager.get_downloader_by_name(body.downloader) + downloader = download_manager.find_downloader_by_name(body.downloader) if not downloader: raise InvalidDownload(f'Cannot find downloader with name {body.downloader}') @@ -272,7 +272,7 @@ async def post_download(_: Request, body: schema.DownloadRequest): @validate(schema.DownloadRequest) @wrol_mode_check async def put_download(_: Request, download_id: int, body: schema.DownloadRequest): - downloader = download_manager.get_downloader_by_name(body.downloader) + downloader = download_manager.find_downloader_by_name(body.downloader) if not downloader: raise InvalidDownload(f'Cannot find downloader with name {body.downloader}') diff --git a/wrolpi/test/test_downloader.py b/wrolpi/test/test_downloader.py index 0c20355a..b1148227 100644 --- a/wrolpi/test/test_downloader.py +++ b/wrolpi/test/test_downloader.py @@ -5,6 +5,7 @@ from datetime import datetime from http import HTTPStatus from itertools import zip_longest from unittest import mock +from unittest.mock import AsyncMock import pytest import pytz @@ -61,11 +62,15 @@ async def test_delete_old_once_downloads(test_session, test_download_manager, te @pytest.mark.asyncio -async def test_create_downloads(test_session, test_download_manager, test_downloader, assert_download_urls): +async def test_create_downloads(test_async_client, test_session, test_download_manager, test_downloader, + assert_download_urls): """Multiple downloads can be scheduled using DownloadManager.create_downloads.""" + mock_save_downloads_config = AsyncMock() # Both URLs are scheduled. - test_download_manager.create_downloads(['https://example.com/1', 'https://example.com/2'], test_downloader.name) - assert_download_urls({'https://example.com/1', 'https://example.com/2'}) + with mock.patch('wrolpi.downloader.save_downloads_config', mock_save_downloads_config): + test_download_manager.create_downloads(['https://example.com/1', 'https://example.com/2'], test_downloader.name) + assert_download_urls({'https://example.com/1', 'https://example.com/2'}) + mock_save_downloads_config.assert_called_once() @pytest.mark.asyncio diff --git a/wrolpi/test/test_root_api.py b/wrolpi/test/test_root_api.py index 85eaba52..76c7e0d2 100644 --- a/wrolpi/test/test_root_api.py +++ b/wrolpi/test/test_root_api.py @@ -389,7 +389,8 @@ async def test_get_status(test_async_client, test_session): assert 'flags' in response.json and isinstance(response.json['flags'], dict) -def test_download_crud(test_session, test_client, test_download_manager_config, tag_factory): +@pytest.mark.asyncio +async def test_download_crud(test_session, test_async_client, test_download_manager_config, tag_factory): """Test creating once-downloads and recurring downloads.""" tag1, tag2 = tag_factory(), tag_factory() @@ -403,7 +404,7 @@ def test_download_crud(test_session, test_client, test_download_manager_config, frequency=1_000, downloader='archive', ) - request, response = test_client.post('/api/download', content=json.dumps(content)) + request, response = await test_async_client.post('/api/download', content=json.dumps(content)) assert response.status_code == HTTPStatus.NO_CONTENT assert {i.url for i in test_session.query(Download)} == {'https://example.com/1', } @@ -413,7 +414,7 @@ def test_download_crud(test_session, test_client, test_download_manager_config, urls=['https://example.com/2', 'https://example.com/3'], downloader='archive', ) - request, response = test_client.post('/api/download', json=content) + request, response = await test_async_client.post('/api/download', json=content) assert response.status_code == HTTPStatus.NO_CONTENT assert {i.url for i in test_session.query(Download)} == {f'https://example.com/{i}' for i in range(1, 4)} @@ -429,7 +430,7 @@ def test_download_crud(test_session, test_client, test_download_manager_config, settings={'tag_names': [tag1.name, tag2.name]}, ) expected_download1.update({'url': 'https://example.com/1', 'settings': {'tag_names': [tag1.name, tag2.name]}}) - request, response = test_client.put(f'/api/download/{download1.id}', json=content) + request, response = await test_async_client.put(f'/api/download/{download1.id}', json=content) assert response.status_code == HTTPStatus.NO_CONTENT test_session.flush([download2]) download2 = test_session.query(Download).filter_by(id=expected_download1['id']).first()