Failing all downloads of a domain if cookies errors are received.

This commit is contained in:
Roland 2026-03-08 11:08:08 -06:00
parent da8a9bb923
commit b2185ad7c3
No known key found for this signature in database
GPG key ID: 1BA620CE6C9A4680
4 changed files with 89 additions and 4 deletions

View file

@ -24,7 +24,7 @@ from wrolpi.common import logger, get_media_directory, escape_file_name, resolve
from wrolpi.dates import now
from wrolpi.db import get_db_session
from wrolpi.downloader import Downloader, Download, DownloadResult
from wrolpi.errors import UnrecoverableDownloadError
from wrolpi.errors import UnrecoverableDownloadError, BotBlockedDownloadError
from wrolpi.files.lib import glob_shared_stem, split_path_stem_and_suffix
from wrolpi.files.models import FileGroup
from wrolpi.files.worker import file_worker
@ -321,7 +321,12 @@ class ChannelDownloader(Downloader, ABC):
async def do_download(self, download: Download) -> DownloadResult:
"""Update a Channel's catalog, then schedule downloads of every missing video."""
info = extract_info(download.url, process=False)
try:
info = extract_info(download.url, process=False)
except Exception as e:
if _bot_blocked(e):
raise BotBlockedDownloadError(str(e)) from e
raise
# Resolve the "entries" generator.
info: dict = resolve_generators(info)
entries = info.get('entries')
@ -518,6 +523,8 @@ class VideoDownloader(Downloader, ABC):
try:
download.info_json = download.info_json or extract_info(url)
except yt_dlp.utils.DownloadError as e:
if _bot_blocked(e):
raise BotBlockedDownloadError(str(e)) from e
# Video may be private.
try:
raise RuntimeError('Failed to extract_info') from e
@ -617,6 +624,8 @@ class VideoDownloader(Downloader, ABC):
if result.return_code != 0:
error = f'{stdout}\n\n\n{stderr}\n\nvideo downloader process exited with {result.return_code}'
if _bot_blocked(error):
raise BotBlockedDownloadError(f'Bot detection or invalid cookies: {error}')
return DownloadResult(
success=False,
error=error,
@ -723,12 +732,16 @@ class VideoDownloader(Downloader, ABC):
with get_db_session(commit=True) as session:
await Video.delete_duplicate_videos(session, download.url, entry['id'], video_path)
except BotBlockedDownloadError:
raise
except UnrecoverableDownloadError:
raise
except yt_dlp.utils.UnsupportedError as e:
raise UnrecoverableDownloadError('URL is not supported by yt-dlp') from e
except Exception as e:
logger.warning(f'VideoDownloader failed to download: {url}', exc_info=e)
if _bot_blocked(e):
raise BotBlockedDownloadError(str(e)) from e
if _skip_download(e):
# The video failed to download, and the error will never be fixed. Skip it forever.
try:
@ -1085,9 +1098,28 @@ UNRECOVERABLE_ERRORS = {
"You've asked yt-dlp to download the URL",
}
# Errors that indicate bot detection or invalid cookies. All pending downloads should be stopped.
BOT_BLOCKED_ERRORS = {
"Sign in to confirm you're not a bot",
'Sign in to confirm you\u2019re not a bot',
'cookies are no longer valid',
}
def _bot_blocked(error):
"""Return True if the error indicates bot detection or invalid cookies."""
error_str = str(error)
for msg in BOT_BLOCKED_ERRORS:
if msg in error_str:
return True
return False
def _skip_download(error):
"""Return True if the error is unrecoverable and the video should be skipped in the future."""
if _bot_blocked(error):
# Bot detection errors should stop all downloads, not skip individual videos.
return False
error_str = str(error)
for msg in UNRECOVERABLE_ERRORS:
if msg in error_str:

View file

@ -9,7 +9,7 @@ import pytest
from modules.videos.downloader import VideoDownloader, \
get_or_create_channel, channel_downloader, video_downloader, preview_filename, \
prepare_filename, convert_wrolpi_filename_format
prepare_filename, convert_wrolpi_filename_format, _bot_blocked, _skip_download
from modules.videos.lib import get_videos_downloader_config
from modules.videos.models import Channel, Video
from wrolpi.conftest import test_directory, await_switches
@ -853,3 +853,30 @@ async def test_live_video_retry_seconds(test_session, test_directory, mock_video
assert result.success is False
assert result.retry_seconds == 3600
assert 'live' in result.error.lower()
def test_bot_blocked_detection():
"""Bot detection errors should be identified by _bot_blocked."""
assert _bot_blocked("Sign in to confirm you're not a bot") is True
assert _bot_blocked("Sign in to confirm you\u2019re not a bot") is True
assert _bot_blocked("cookies are no longer valid") is True
assert _bot_blocked("ERROR: Sign in to confirm you're not a bot. Use --cookies") is True
# These should NOT be detected as bot-blocked.
assert _bot_blocked("404: Not Found") is False
assert _bot_blocked("requires payment") is False
assert _bot_blocked("some random error") is False
def test_skip_download_excludes_bot_blocked():
"""Bot-blocked errors should NOT cause a video to be skipped (added to skip list)."""
# Bot-blocked errors should not be skipped (they should stop all downloads instead).
assert _skip_download("Sign in to confirm you're not a bot") is False
assert _skip_download("cookies are no longer valid") is False
# Regular "Sign in" errors that are NOT bot-related should still be skipped.
assert _skip_download("Sign in to view this video") is True
# Other unrecoverable errors should still be skipped.
assert _skip_download("404: Not Found") is True
assert _skip_download("requires payment") is True

View file

@ -35,7 +35,8 @@ from wrolpi.common import Base, ModelHelper, logger, wrol_mode_check, zig_zag, C
get_download_info, trim_file_name, get_wrolpi_config, TRACE_LEVEL
from wrolpi.dates import TZDateTime, now, Seconds
from wrolpi.db import get_db_session, get_db_curs
from wrolpi.errors import InvalidDownload, UnrecoverableDownloadError, UnknownDownload, ValidationError, DownloadError
from wrolpi.errors import InvalidDownload, UnrecoverableDownloadError, BotBlockedDownloadError, UnknownDownload, \
ValidationError, DownloadError
from wrolpi.events import Events
from wrolpi.media_path import MediaPathType
from wrolpi.switches import register_switch_handler, ActivateSwitchMethod, await_switches
@ -1262,6 +1263,25 @@ async def signal_download_download(download_id: int, download_url: str):
raise RuntimeError(f'Coroutine expected from {downloader} do_download method.')
coro = downloader.do_download(download)
result = await downloader.cancel_wrapper(coro, download)
except BotBlockedDownloadError as e:
# Bot detection or invalid cookies - stop all pending downloads from this domain.
worker_logger.warning(f'BotBlockedDownloadError for {url}', exc_info=e)
result = DownloadResult(success=False, error=str(traceback.format_exc()))
try_again = False
# Fail all pending/new downloads from the same domain.
with get_db_session(commit=True) as fail_session:
domain = urlparse(url).netloc
siblings = fail_session.query(Download).filter(
Download.status.in_(('new', 'pending')),
Download.url.contains(f'://{domain}'),
Download.id != download_id,
).all()
for sibling in siblings:
sibling.error = f'Stopped: bot detection or invalid cookies on {domain}'
sibling.fail()
if siblings:
worker_logger.warning(
f'Failed {len(siblings)} pending downloads from {domain} due to bot detection')
except UnrecoverableDownloadError as e:
# Download failed and should not be retried.
worker_logger.warning(f'UnrecoverableDownloadError for {url}', exc_info=e)

View file

@ -63,6 +63,12 @@ class UnrecoverableDownloadError(APIError):
status_code = HTTPStatus.BAD_REQUEST
class BotBlockedDownloadError(UnrecoverableDownloadError):
code = 'BOT_BLOCKED_DOWNLOAD_ERROR'
summary = 'Download was blocked by bot detection or invalid cookies. All pending downloads will be stopped.'
status_code = HTTPStatus.BAD_REQUEST
class InvalidFile(APIError):
code = 'INVALID_FILE'
summary = 'File does not exist or is a directory'