videos: address review — atomic caption write + strict YouTube host gate
Some checks are pending
CodeQL / Analyze (push) Waiting to run
Controller Tests / controller-tests (push) Waiting to run
Jest Tests / jest-tests (push) Waiting to run

- strip_youtube_caption_positioning now writes to a temp file in the same
  directory and os.replace()s the original, so a failed/partial write
  (e.g. disk full) can never truncate the existing caption file.
- Replace the substring `'youtube.com' in url` gate with is_youtube_url(),
  which parses the hostname and matches youtube.com / youtu.be (and
  subdomains), rejecting lookalikes like youtube.com.example.org and
  notyoutube.com. Add a parametrized test.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
Roland 2026-07-16 18:33:51 -06:00
parent 029f30c4c8
commit f5615440e5
No known key found for this signature in database
GPG key ID: 1BA620CE6C9A4680
3 changed files with 48 additions and 7 deletions

View file

@ -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:

View file

@ -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

View file

@ -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: