diff --git a/modules/videos/downloader.py b/modules/videos/downloader.py index c2216bac..f4f1ae04 100755 --- a/modules/videos/downloader.py +++ b/modules/videos/downloader.py @@ -186,6 +186,19 @@ def get_youtube_video_id(url: str) -> Optional[str]: return None +YOUTUBE_HOSTS = ('youtube.com', 'youtu.be') + + +def is_youtube_url(url: str) -> bool: + """Return True if the URL's host is a YouTube domain (youtube.com / youtu.be) or a subdomain of one. + + Parses the hostname so unrelated hosts like `youtube.com.example.org` or `notyoutube.com` are rejected.""" + if not url: + return False + host = (urlparse(url).hostname or '').lower() + return any(host == h or host.endswith(f'.{h}') for h in YOUTUBE_HOSTS) + + async def get_youtube_duration(video_url: str) -> Optional[int]: """Get video duration using YouTube's internal API. Returns None if URL is not YouTube or API fails.""" video_id = get_youtube_video_id(video_url) @@ -1038,7 +1051,7 @@ class VideoDownloader(Downloader, ABC): video_paths = self._delete_part_files(video_path, video_paths) video_paths = self.normalize_video_file_names(video_path, video_paths) - if url and ('youtube.com' in url or 'youtu.be' in url): + if is_youtube_url(url): # YouTube auto-captions pin the text to the bottom-left; center them at the source. Runs # before the FileGroup is created, so the first index reads the corrected file. for path in video_paths: diff --git a/modules/videos/test/test_downloader.py b/modules/videos/test/test_downloader.py index fea7a8d6..f52de392 100644 --- a/modules/videos/test/test_downloader.py +++ b/modules/videos/test/test_downloader.py @@ -10,7 +10,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, _bot_blocked, _skip_download, \ - parse_ytdlp_progress, is_youtube_rss_feed_url + parse_ytdlp_progress, is_youtube_rss_feed_url, is_youtube_url from modules.videos.lib import get_videos_downloader_config from modules.videos.models import Channel, Video from wrolpi.conftest import test_directory, await_switches @@ -1405,3 +1405,22 @@ def test_prepare_uses_existing_video_location(test_session, video_factory): assert prepared.location == existing.location assert prepared.location is not None + + +@pytest.mark.parametrize('url,expected', [ + ('https://www.youtube.com/watch?v=abc123', True), + ('https://youtube.com/watch?v=abc123', True), + ('https://m.youtube.com/watch?v=abc123', True), + ('https://music.youtube.com/watch?v=abc123', True), + ('https://youtu.be/abc123', True), + # Lookalike / malicious hosts must be rejected. + ('https://youtube.com.example.org/watch?v=abc123', False), + ('https://notyoutube.com/watch?v=abc123', False), + ('https://vimeo.com/12345', False), + ('https://example.com/youtube.com', False), + ('', False), + (None, False), +]) +def test_is_youtube_url(url, expected): + """is_youtube_url matches YouTube hosts (and subdomains) but rejects lookalike hosts.""" + assert is_youtube_url(url) is expected diff --git a/wrolpi/captions.py b/wrolpi/captions.py index 6b8964c1..443f0d0a 100755 --- a/wrolpi/captions.py +++ b/wrolpi/captions.py @@ -1,4 +1,5 @@ #! /usr/bin/env python3 +import os import pathlib import re import subprocess @@ -36,11 +37,19 @@ def strip_youtube_caption_positioning(caption_path: Union[str, Path]) -> bool: caption_path = pathlib.Path(caption_path) text = caption_path.read_text() new_text = YOUTUBE_CUE_SETTINGS.sub(r'\1', text) - if new_text != text: - caption_path.write_text(new_text) - logger.info(f'Centered YouTube captions in {caption_path}') - return True - return False + if new_text == text: + return False + # Write to a temp file in the same directory, then atomically replace the original. A failed or partial + # write (e.g. the volume runs out of space) can never truncate/corrupt the existing caption file. + tmp_path = caption_path.with_name(f'{caption_path.name}.tmp') + try: + tmp_path.write_text(new_text) + os.replace(tmp_path, caption_path) + except Exception: + tmp_path.unlink(missing_ok=True) + raise + logger.info(f'Centered YouTube captions in {caption_path}') + return True def _parse_vtt_timestamp(timestamp: str) -> float: