From d1f9837ac8e6440a9153dda39cb3875062278993 Mon Sep 17 00:00:00 2001 From: Roland Date: Sun, 12 Jan 2025 17:20:29 -0700 Subject: [PATCH] Deleting leftover .part files after a video has been successfully downloaded. --- modules/videos/common.py | 2 ++ modules/videos/downloader.py | 13 +++++++++++++ modules/videos/test/test_downloader.py | 6 ++++++ wrolpi/files/lib.py | 8 ++++++-- 4 files changed, 27 insertions(+), 2 deletions(-) diff --git a/modules/videos/common.py b/modules/videos/common.py index 4663ba89..9345b729 100644 --- a/modules/videos/common.py +++ b/modules/videos/common.py @@ -142,6 +142,8 @@ def ffmpeg_video_complete(video_path: Path, seconds: int = None) -> bool: """ if not video_path.is_file(): raise FileNotFoundError(f'Video file not found: {video_path}') + if not video_path.stat().st_size: + raise RuntimeError(f'Video file is empty: {video_path}') with tempfile.NamedTemporaryFile(suffix='.jpg', delete=False) as fh: path = Path(fh.name) diff --git a/modules/videos/downloader.py b/modules/videos/downloader.py index 8ce764bf..64ea423e 100755 --- a/modules/videos/downloader.py +++ b/modules/videos/downloader.py @@ -435,6 +435,12 @@ class VideoDownloader(Downloader, ABC): video_path = preferred_path logger.info(f'Using preferred video file which exists: {preferred_path}') + if video_path.suffix == '.part': + return DownloadResult( + success=False, + error=f'Video file that completed was a .part file: {video_path}', + ) + if not video_path.is_file(): error = f'{stdout}\n\n\n{stderr}\n\n' \ f'Video file could not be found! {video_path}' @@ -458,6 +464,13 @@ class VideoDownloader(Downloader, ABC): with get_db_session(commit=True) as session: # Find any files downloaded with the video (poster, caption, etc.). video_paths = glob_shared_stem(video_path) + # Delete any leftover .part files because the video has been verified complete + # by `ffmpeg_video_complete`. + for part_file in [i for i in video_paths if i.name.endswith(f'{video_path.suffix}.part')]: + logger.warning(f'Deleting leftover .part file: {part_file}') + part_file.unlink() + video_paths.remove(part_file) + # Create the Video record. video = Video.from_paths(session, *video_paths) video.source_id = entry['id'] video.channel_id = channel_id diff --git a/modules/videos/test/test_downloader.py b/modules/videos/test/test_downloader.py index 54c34978..8664e3be 100644 --- a/modules/videos/test/test_downloader.py +++ b/modules/videos/test/test_downloader.py @@ -283,6 +283,9 @@ async def test_video_download(test_session, test_directory, mock_video_extract_i # `formats` should be cleaned from info json. info_json_path = video_path.with_suffix('.info.json') info_json_path.write_text(json.dumps({'duration': 5, 'formats': [1, 2, 3]})) + # .part file should be deleted + part_path = video_path.with_suffix('.mp4.part') + part_path.touch() url = 'https://www.youtube.com/watch?v=31jPEBiAC3c' with mock.patch('modules.videos.downloader.VideoDownloader.prepare_filename') as mock_prepare_filename: @@ -302,6 +305,9 @@ async def test_video_download(test_session, test_directory, mock_video_extract_i video: Video = test_session.query(Video).one() assert video.video_path.is_absolute() and video.video_path == video_path, 'Video path is not absolute' assert video.video_path.is_absolute() and video.poster_path == poster_path, 'Video poster was not discovered' + assert not any([i for i in video.file_group.my_paths() if i.name.endswith('.part')]), \ + 'Part file should not be in group' + assert not part_path.exists(), 'Part file should be deleted.' # Some info json data is deleted during download. assert video.get_info_json(), 'Download should keep info json file' assert 'duration' in video.get_info_json(), 'Duration should stay in info json' diff --git a/wrolpi/files/lib.py b/wrolpi/files/lib.py index f4a8b6a2..d7ce392e 100644 --- a/wrolpi/files/lib.py +++ b/wrolpi/files/lib.py @@ -26,7 +26,7 @@ from wrolpi.common import get_media_directory, wrol_mode_check, logger, limit_co partition, cancelable_wrapper, \ get_files_and_directories, chunks_by_stem, apply_modelers, apply_refresh_cleanup, background_task, walk, \ get_wrolpi_config, \ - timer, chunks, unique_by_predicate, get_paths_in_media_directory + timer, chunks, unique_by_predicate, get_paths_in_media_directory, TRACE_LEVEL from wrolpi.dates import now, from_timestamp, months_selector_to_where, date_range_to_where from wrolpi.db import get_db_session, get_db_curs, mogrify, optional_session from wrolpi.downloader import download_manager @@ -328,7 +328,11 @@ def split_path_stem_and_suffix(path: Union[pathlib.Path, str], full: bool = Fals def get_unique_files_by_stem(files: List[pathlib.Path] | Tuple[pathlib.Path, ...] | Set[pathlib.Path]) \ -> List[pathlib.Path]: """Returns the first of each Path with a unique stem. Used to detect if a group of files share a stem.""" - return unique_by_predicate(files, lambda i: split_path_stem_and_suffix(i)[0]) + results = unique_by_predicate(files, lambda i: split_path_stem_and_suffix(i)[0]) + if logger.isEnabledFor(TRACE_LEVEL): + logger.trace(f'get_unique_files_by_stem {files=}') + logger.trace(f'get_unique_files_by_stem {results=}') + return results refresh_logger = logger.getChild('refresh')