diff --git a/modules/videos/models.py b/modules/videos/models.py index 6c9552c7..60f31c61 100644 --- a/modules/videos/models.py +++ b/modules/videos/models.py @@ -1,6 +1,7 @@ import json import pathlib -from typing import Optional, Dict, List +from datetime import datetime, timezone +from typing import Optional, Dict, List, Tuple from sqlalchemy import Column, Integer, String, Boolean, Date, ForeignKey, BigInteger, Index, text, JSON from sqlalchemy.orm import Mapped, relationship, Session, deferred, undefer, joinedload, selectinload @@ -15,6 +16,7 @@ from wrolpi.downloader import Download from wrolpi.files.lib import split_path_stem_and_suffix from wrolpi.files.worker import file_worker from wrolpi.files.models import FileGroup +from wrolpi.files.progress import save_recently_viewed_config from wrolpi.tags import Tag, TagFile from wrolpi.vars import PYTEST, VIDEO_INFO_JSON_KEYS_TO_CLEAN @@ -534,35 +536,56 @@ class Video(ModelHelper, Base): logger.debug(f'No duplicates to delete: {url=} {source_id=}') return changes + def has_streams(video_: Video) -> Tuple[bool, bool]: + """(has audio, has video) from the stored ffprobe data. Unknown counts as complete; probing here would + hold this write transaction while ffprobe runs.""" + streams = (video_.ffprobe_json or dict()).get('streams') + if not streams: + return True, True + codec_types = {i.get('codec_type') for i in streams} + return 'audio' in codec_types, 'video' in codec_types + # Order videos by oldest first, we should keep the oldest if all files are the same size. duplicate_videos = sorted(duplicate_videos, key=lambda i: i.file_group.primary_path.stat().st_mtime) - # Find the largest video, if possible. If all videos are the same size then rename the oldest. - largest_video_idx = 0 - for idx, video in enumerate(duplicate_videos): - if video.file_group.size > duplicate_videos[largest_video_idx].file_group.size: - largest_video_idx = idx - largest_video = duplicate_videos.pop(largest_video_idx) + # Keep a complete video (a yt-dlp format file has only video, or only audio), then the largest. `max` returns + # the first of equals, so the oldest is kept when all are the same. + kept_video = max(duplicate_videos, key=lambda i: (*has_streams(i), i.file_group.size or 0)) + duplicate_videos.remove(kept_video) - # Delete the video at the destination, if it is not the largest. + # The kept video takes the most recent view, and the resume position of the most recently viewed duplicate + # when it has none of its own. + kept_group = kept_video.file_group + viewed = [i.file_group.viewed for i in duplicate_videos if i.file_group.viewed] + if viewed and (not kept_group.viewed or max(viewed) > kept_group.viewed): + kept_group.viewed = max(viewed) + save_recently_viewed_config.activate_switch() + if kept_group.position is None and kept_group.progress is None: + watched = [i.file_group for i in duplicate_videos + if i.file_group.position is not None or i.file_group.progress is not None] + if watched: + latest = max(watched, key=lambda i: i.viewed or datetime.min.replace(tzinfo=timezone.utc)) + kept_group.position, kept_group.progress = latest.position, latest.progress + + # Delete the video at the destination, if it is not the one kept. existing_video = Video.get_by_path(session, video_path) - if existing_video and largest_video != existing_video: + if existing_video and kept_video != existing_video: delete_video(existing_video) for idx, video in enumerate(duplicate_videos): if video == existing_video: duplicate_videos.pop(idx) # Rename the video, add any missing tag names. - if largest_video.video_path != video_path: + if kept_video.video_path != video_path: # Every deletion above unlinked its files immediately, but only queued its DELETE on the session. The # rename claims `video_path` as its `primary_path`, and SQLAlchemy emits UPDATEs before DELETEs within a # flush -- so without this flush the UPDATE can hit a not-yet-deleted row and violate the unique index on # `file_group.primary_path`, rolling back the entire download. session.flush() - largest_video.file_group.move(video_path) + kept_video.file_group.move(video_path) for tag_name in tag_names: - if tag_name not in largest_video.file_group.tag_names: - largest_video.add_tag(session, tag_name) + if tag_name not in kept_video.file_group.tag_names: + kept_video.add_tag(session, tag_name) logger.warning(f'Deleting duplicate videos: {duplicate_videos}') diff --git a/modules/videos/test/test_video.py b/modules/videos/test/test_video.py index 96db6833..93277ac1 100644 --- a/modules/videos/test/test_video.py +++ b/modules/videos/test/test_video.py @@ -286,6 +286,92 @@ async def test_delete_duplicate_video_smaller_copy_at_destination(async_client, assert set(channel.directory.iterdir()) == set(video.file_group.my_paths()) +VIDEO_STREAM = {'codec_type': 'video', 'codec_name': 'h264'} +AUDIO_STREAM = {'codec_type': 'audio', 'codec_name': 'aac'} + + +@pytest.mark.asyncio +@pytest.mark.parametrize('incomplete_streams', [[VIDEO_STREAM], [AUDIO_STREAM]]) +async def test_delete_duplicate_video_keeps_complete_copy(async_client, test_session, channel_factory, video_factory, + incomplete_streams): + """A larger copy without audio (or without video), like an unmerged yt-dlp format file, is deleted rather than + the complete copy.""" + channel = channel_factory(name='Channel Name') + video_path = channel.directory / f'{channel.name}_20000101_ABC123456_The video title.mp4' + channel.info_json = {'entries': [{'id': 'ABC123456', 'title': 'The video title'}]} + entry = channel.info_json['entries'][0] + + complete = video_factory(channel_id=channel.id, title=f'{channel.name}_20000101_ABC123456_The video title', + source_id='ABC123456', with_video_file=True) + incomplete = video_factory(channel_id=channel.id, title=f'{channel.name}_20000101_ABC123456_The video title.f313', + source_id='ABC123456', with_video_file=True) + complete.ffprobe_json = {'streams': [VIDEO_STREAM, AUDIO_STREAM]} + incomplete.ffprobe_json = {'streams': incomplete_streams} + incomplete.file_group.size = complete.file_group.size * 10 + complete_id, incomplete_path = complete.id, incomplete.video_path + test_session.commit() + + assert await Video.delete_duplicate_videos(test_session, 'https://example.com/video', entry['id'], video_path) + test_session.commit() + + video = test_session.query(Video).one() + assert video.id == complete_id, 'The complete Video was not the one kept' + assert video.video_path == video_path and video.video_path.is_file() + assert not incomplete_path.exists() + + +@pytest.mark.asyncio +async def test_delete_duplicate_video_keeps_viewing_history(async_client, test_session, channel_factory, + video_factory): + """The kept Video takes the most recent view, and the resume position of a deleted duplicate when it has none.""" + channel = channel_factory(name='Channel Name') + video_path = channel.directory / f'{channel.name}_20000101_ABC123456_The video title.mp4' + channel.info_json = {'entries': [{'id': 'ABC123456', 'title': 'The video title'}]} + entry = channel.info_json['entries'][0] + + kept = video_factory(channel_id=channel.id, title=f'{channel.name}_20000101_ABC123456_The video title', + source_id='ABC123456', with_video_file=True) + watched = video_factory(channel_id=channel.id, title=f'{channel.name}_20000101_ABC123456_The video title ', + source_id='ABC123456', with_video_file=True) + older = video_factory(channel_id=channel.id, title=f'{channel.name}_20000101_ABC123456_The video title ', + source_id='ABC123456', with_video_file=True) + kept.file_group.size = watched.file_group.size * 10 + watched.file_group.viewed = datetime(2026, 2, 1, tzinfo=timezone.utc) + watched.file_group.progress = 0.5 + watched.file_group.position = {'kind': 'time', 'seconds': 100.0} + older.file_group.viewed = datetime(2025, 1, 1, tzinfo=timezone.utc) + older.file_group.progress = 0.9 + older.file_group.position = {'kind': 'time', 'seconds': 900.0} + kept_id = kept.id + test_session.commit() + + assert await Video.delete_duplicate_videos(test_session, 'https://example.com/video', entry['id'], video_path) + test_session.commit() + + video = test_session.query(Video).one() + assert video.id == kept_id + assert video.file_group.viewed == datetime(2026, 2, 1, tzinfo=timezone.utc) + assert video.file_group.progress == 0.5 + assert video.file_group.position == {'kind': 'time', 'seconds': 100.0} + + # The kept Video's own position is not replaced. + other = video_factory(channel_id=channel.id, title=f'{channel.name}_20000101_ABC123456_The video title ', + source_id='ABC123456', with_video_file=True) + other.file_group.viewed = datetime(2026, 3, 1, tzinfo=timezone.utc) + other.file_group.progress = 0.2 + other.file_group.position = {'kind': 'time', 'seconds': 20.0} + test_session.commit() + + assert await Video.delete_duplicate_videos(test_session, 'https://example.com/video', entry['id'], video_path) + test_session.commit() + + video = test_session.query(Video).one() + assert video.id == kept_id + assert video.file_group.viewed == datetime(2026, 3, 1, tzinfo=timezone.utc) + assert video.file_group.progress == 0.5 + assert video.file_group.position == {'kind': 'time', 'seconds': 100.0} + + @pytest.mark.asyncio async def test_delete_renamed_video(async_client, test_session, channel_factory, video_factory, tag_factory): """If duplicate Video's exist, delete all the videos that do not have the new title."""