Compare commits

...

4 Commits

Author SHA1 Message Date
Kieran Eglin 0a3c5aceb5
Removed now-unneeded thumbnail/subtitle return values 2024-04-24 11:08:21 -07:00
Kieran Eglin 9c3b227db8
Removed files_to_move logic 2024-04-24 11:02:26 -07:00
Kieran Eglin ea2a085397
Fixed up tests and linting 2024-04-24 10:57:39 -07:00
Kieran Eglin 44bb6c2056
[WIP] got refactor of file mover basically working 2024-04-24 09:47:58 -07:00
5 changed files with 112 additions and 157 deletions

View File

@ -874,32 +874,33 @@ class TestYoutubeDL(unittest.TestCase):
}), r'^30fps$')
def test_postprocessors(self):
filename = 'post-processor-testfile.mp4'
audiofile = filename + '.mp3'
filename = 'post-processor-testfile'
video_file = filename + '.mp4'
audio_file = filename + '.mp3'
class SimplePP(PostProcessor):
def run(self, info):
with open(audiofile, 'w') as f:
with open(audio_file, 'w') as f:
f.write('EXAMPLE')
return [info['filepath']], info
def run_pp(params, PP):
with open(filename, 'w') as f:
with open(video_file, 'w') as f:
f.write('EXAMPLE')
ydl = YoutubeDL(params)
ydl.add_post_processor(PP())
ydl.post_process(filename, {'filepath': filename})
ydl.post_process(video_file, {'filepath': video_file})
run_pp({'keepvideo': True}, SimplePP)
self.assertTrue(os.path.exists(filename), '%s doesn\'t exist' % filename)
self.assertTrue(os.path.exists(audiofile), '%s doesn\'t exist' % audiofile)
os.unlink(filename)
os.unlink(audiofile)
run_pp({'keepvideo': True, 'outtmpl': filename}, SimplePP)
self.assertTrue(os.path.exists(video_file), '%s doesn\'t exist' % video_file)
self.assertTrue(os.path.exists(audio_file), '%s doesn\'t exist' % audio_file)
os.unlink(video_file)
os.unlink(audio_file)
run_pp({'keepvideo': False}, SimplePP)
self.assertFalse(os.path.exists(filename), '%s exists' % filename)
self.assertTrue(os.path.exists(audiofile), '%s doesn\'t exist' % audiofile)
os.unlink(audiofile)
run_pp({'keepvideo': False, 'outtmpl': filename}, SimplePP)
self.assertFalse(os.path.exists(video_file), '%s exists' % video_file)
self.assertTrue(os.path.exists(audio_file), '%s doesn\'t exist' % audio_file)
os.unlink(audio_file)
class ModifierPP(PostProcessor):
def run(self, info):
@ -907,9 +908,9 @@ class TestYoutubeDL(unittest.TestCase):
f.write('MODIFIED')
return [], info
run_pp({'keepvideo': False}, ModifierPP)
self.assertTrue(os.path.exists(filename), '%s doesn\'t exist' % filename)
os.unlink(filename)
run_pp({'keepvideo': False, 'outtmpl': filename}, ModifierPP)
self.assertTrue(os.path.exists(video_file), '%s doesn\'t exist' % video_file)
os.unlink(video_file)
def test_match_filter(self):
first = {

View File

@ -1808,7 +1808,7 @@ class YoutubeDL:
info_copy['id'] = ie.get_temp_id(ie_result['url'])
self.add_default_extra_info(info_copy, ie, ie_result['url'])
self.add_extra_info(info_copy, extra_info)
info_copy, _ = self.pre_process(info_copy)
info_copy = self.pre_process(info_copy)
self._fill_common_fields(info_copy, False)
self.__forced_printings(info_copy)
self._raise_pending_errors(info_copy)
@ -1982,8 +1982,9 @@ class YoutubeDL:
'playlist', ie_result, self.prepare_filename(ie_copy, 'pl_infojson'))
if _infojson_written is None:
return
if self._write_description('playlist', ie_result,
self.prepare_filename(ie_copy, 'pl_description')) is None:
description_file = self._write_description('playlist', ie_result, self.prepare_filename(ie_copy, 'pl_description'))
if description_file is None:
return
# TODO: This should be passed to ThumbnailsConvertor if necessary
self._write_thumbnails('playlist', ie_result, self.prepare_filename(ie_copy, 'pl_thumbnail'))
@ -2884,13 +2885,13 @@ class YoutubeDL:
# which can't be exported to json
info_dict['formats'] = formats
info_dict, _ = self.pre_process(info_dict)
info_dict = self.pre_process(info_dict)
if self._match_entry(info_dict, incomplete=self._format_fields) is not None:
return info_dict
self.post_extract(info_dict)
info_dict, _ = self.pre_process(info_dict, 'after_filter')
info_dict = self.pre_process(info_dict, 'after_filter')
# The pre-processors may have modified the formats
formats = self._get_formats(info_dict)
@ -3201,14 +3202,13 @@ class YoutubeDL:
info_dict.clear()
info_dict.update(new_info)
new_info, _ = self.pre_process(info_dict, 'video')
new_info = self.pre_process(info_dict, 'video')
replace_info_dict(new_info)
self._num_downloads += 1
# info_dict['_filename'] needs to be set for backward compatibility
info_dict['_filename'] = full_filename = self.prepare_filename(info_dict, warn=True)
temp_filename = self.prepare_filename(info_dict, 'temp')
files_to_move = {}
# Forced printings
self.__forced_printings(info_dict, full_filename, incomplete=('format' not in info_dict))
@ -3229,23 +3229,19 @@ class YoutubeDL:
if not self._ensure_dir_exists(encodeFilename(temp_filename)):
return
if self._write_description('video', info_dict,
self.prepare_filename(info_dict, 'description')) is None:
description_file = self._write_description('video', info_dict, self.prepare_filename(info_dict, 'description'))
if description_file is None:
return
sub_files = self._write_subtitles(info_dict, temp_filename)
if sub_files is None:
return
files_to_move['requested_subtitles'] = sub_files
thumb_files = self._write_thumbnails(
'video', info_dict, temp_filename, self.prepare_filename(info_dict, 'thumbnail'))
if thumb_files is None:
return
files_to_move['thumbnails'] = thumb_files
infofn = self.prepare_filename(info_dict, 'infojson')
_infojson_written = self._write_info_json('video', info_dict, infofn)
if _infojson_written:
@ -3318,13 +3314,12 @@ class YoutubeDL:
for link_type, should_write in write_links.items()):
return
new_info, files_to_move = self.pre_process(info_dict, 'before_dl', files_to_move)
new_info = self.pre_process(info_dict, 'before_dl')
replace_info_dict(new_info)
if self.params.get('skip_download'):
info_dict['filepath'] = temp_filename
info_dict['__finaldir'] = os.path.dirname(os.path.abspath(encodeFilename(full_filename)))
info_dict['__files_to_move'] = files_to_move
replace_info_dict(self.run_pp(MoveFilesAfterDownloadPP(self, False), info_dict))
info_dict['__write_download_archive'] = self.params.get('force_write_download_archive')
else:
@ -3438,9 +3433,6 @@ class YoutubeDL:
info_dict['__files_to_merge'] = downloaded
# Even if there were no downloads, it is being merged only now
info_dict['__real_download'] = True
else:
for file in downloaded:
files_to_move[file] = None
else:
# Just a single file
dl_filename = existing_video_file(full_filename, temp_filename)
@ -3524,7 +3516,7 @@ class YoutubeDL:
fixup()
try:
replace_info_dict(self.post_process(dl_filename, info_dict, files_to_move))
replace_info_dict(self.post_process(dl_filename, info_dict))
except PostProcessingError as err:
self.report_error('Postprocessing: %s' % str(err))
return
@ -3661,8 +3653,7 @@ class YoutubeDL:
def run_pp(self, pp, infodict):
files_to_delete = []
if '__files_to_move' not in infodict:
infodict['__files_to_move'] = {}
try:
files_to_delete, infodict = pp.run(infodict)
except PostProcessingError as e:
@ -3686,24 +3677,21 @@ class YoutubeDL:
info = self.run_pp(pp, info)
return info
def pre_process(self, ie_info, key='pre_process', files_to_move=None):
def pre_process(self, ie_info, key='pre_process'):
info = dict(ie_info)
info['__files_to_move'] = files_to_move or {}
try:
info = self.run_all_pps(key, info)
except PostProcessingError as err:
msg = f'Preprocessing: {err}'
info.setdefault('__pending_error', msg)
self.report_error(msg, is_error=False)
return info, info.pop('__files_to_move', None)
return info
def post_process(self, filename, info, files_to_move=None):
def post_process(self, filename, info):
"""Run all the postprocessors on the given file."""
info['filepath'] = filename
info['__files_to_move'] = files_to_move or {}
info = self.run_all_pps('post_process', info, additional_pps=info.get('__postprocessors'))
info = self.run_pp(MoveFilesAfterDownloadPP(self), info)
del info['__files_to_move']
return self.run_all_pps('after_move', info)
def _make_archive_id(self, info_dict):
@ -4245,27 +4233,27 @@ class YoutubeDL:
self.report_error(f'Cannot write {label} metadata to JSON file {infofn}')
return None
def _write_description(self, label, ie_result, descfn):
def _write_description(self, label, info_dict, filename):
''' Write description and returns True = written, False = skip, None = error '''
if not self.params.get('writedescription'):
return False
elif not descfn:
elif not filename:
self.write_debug(f'Skipping writing {label} description')
return False
elif not self._ensure_dir_exists(descfn):
elif not self._ensure_dir_exists(filename):
return None
elif not self.params.get('overwrites', True) and os.path.exists(descfn):
elif not self.params.get('overwrites', True) and os.path.exists(filename):
self.to_screen(f'[info] {label.title()} description is already present')
elif ie_result.get('description') is None:
elif info_dict.get('description') is None:
self.to_screen(f'[info] There\'s no {label} description to write')
return False
else:
try:
self.to_screen(f'[info] Writing {label} description to: {descfn}')
with open(encodeFilename(descfn), 'w', encoding='utf-8') as descfile:
descfile.write(ie_result['description'])
self.to_screen(f'[info] Writing {label} description to: {filename}')
with open(filename, 'w', encoding='utf-8') as descfile:
descfile.write(info_dict['description'])
except OSError:
self.report_error(f'Cannot write {label} description file {descfn}')
self.report_error(f'Cannot write {label} description file {filename}')
return None
return True
@ -4294,12 +4282,6 @@ class YoutubeDL:
if existing_sub:
self.to_screen(f'[info] Video subtitle {sub_lang}.{sub_format} is already present')
sub_info['filepath'] = existing_sub
ret.append({
'current_filepath': existing_sub,
'final_filepath': sub_filename_final,
'lang': sub_lang,
'ext': sub_info['ext']
})
continue
@ -4311,12 +4293,6 @@ class YoutubeDL:
with open(sub_filename, 'w', encoding='utf-8', newline='') as subfile:
subfile.write(sub_info['data'])
sub_info['filepath'] = sub_filename
ret.append({
'current_filepath': sub_filename,
'final_filepath': sub_filename_final,
'lang': sub_lang,
'ext': sub_info['ext']
})
continue
except OSError:
@ -4328,12 +4304,6 @@ class YoutubeDL:
sub_copy.setdefault('http_headers', info_dict.get('http_headers'))
self.dl(sub_filename, sub_copy, subtitle=True)
sub_info['filepath'] = sub_filename
ret.append({
'current_filepath': sub_filename,
'final_filepath': sub_filename_final,
'lang': sub_lang,
'ext': sub_info['ext']
})
except (DownloadError, ExtractorError, IOError, OSError, ValueError) + network_exceptions as err:
msg = f'Unable to download video subtitles for {sub_lang!r}: {err}'
@ -4375,11 +4345,6 @@ class YoutubeDL:
self.to_screen('[info] %s is already present' % (
thumb_display_id if multiple else f'{label} thumbnail').capitalize())
t['filepath'] = existing_thumb
ret.append({
'current_filepath': existing_thumb,
'final_filepath': thumb_filename_final,
'id': t['id']
})
else:
self.to_screen(f'[info] Downloading {thumb_display_id} ...')
@ -4389,12 +4354,6 @@ class YoutubeDL:
with open(encodeFilename(thumb_filename), 'wb') as thumbf:
shutil.copyfileobj(uf, thumbf)
ret.append({
'current_filepath': thumb_filename,
'final_filepath': thumb_filename_final,
'id': t['id']
})
t['filepath'] = thumb_filename
except network_exceptions as err:
if isinstance(err, HTTPError) and err.status == 404:

View File

@ -1016,11 +1016,6 @@ class FFmpegSubtitlesConvertorPP(FFmpegPostProcessor):
'filepath': new_file,
}
for sub_info in info['__files_to_move']['requested_subtitles']:
if sub_info['lang'] == lang and sub_info['ext'] == sub['ext']:
sub_info['current_filepath'] = replace_extension(sub_info['current_filepath'], new_ext)
sub_info['final_filepath'] = replace_extension(sub_info['final_filepath'], new_ext)
return sub_filenames, info
@ -1095,11 +1090,6 @@ class FFmpegThumbnailsConvertorPP(FFmpegPostProcessor):
os.replace(thumbnail_filename, webp_filename)
thumbnail['filepath'] = webp_filename
for thumb_info in info['__files_to_move']['thumbnails']:
if thumb_info['id'] == thumbnail['id']:
thumb_info['current_filepath'] = replace_extension(thumbnail_filename, 'webp')
thumb_info['final_filepath'] = replace_extension(thumb_info['final_filepath'], 'webp')
@staticmethod
def _options(target_ext):
yield from ('-update', '1')
@ -1137,11 +1127,6 @@ class FFmpegThumbnailsConvertorPP(FFmpegPostProcessor):
thumbnail_dict['filepath'] = self.convert_thumbnail(original_thumbnail, target_ext)
files_to_delete.append(original_thumbnail)
for thumb_info in info['__files_to_move']['thumbnails']:
if thumb_info['id'] == thumbnail_dict['id']:
thumb_info['current_filepath'] = replace_extension(thumb_info['current_filepath'], target_ext)
thumb_info['final_filepath'] = replace_extension(thumb_info['final_filepath'], target_ext)
if not has_thumbnail:
self.to_screen('There aren\'t any thumbnails to convert')
return files_to_delete, info

View File

@ -1,15 +1,23 @@
import os
from pathlib import Path
from .common import PostProcessor
from ..compat import shutil
from ..utils import (
PostProcessingError,
make_dir,
replace_extension
)
class MoveFilesAfterDownloadPP(PostProcessor):
FILETYPE_KEYS = ['media', 'thumbnails', 'requested_subtitles']
TOP_LEVEL_KEYS = ['filepath']
# Map of the keys that contain moveable files and the 'type' of the file
# for generating the output filename
CHILD_KEYS = {
'thumbnails': 'thumbnail',
'requested_subtitles': 'subtitle'
}
def __init__(self, downloader=None, downloaded=True):
PostProcessor.__init__(self, downloader)
@ -19,73 +27,73 @@ class MoveFilesAfterDownloadPP(PostProcessor):
def pp_key(cls):
return 'MoveFiles'
def expand_relative_paths(self, files_to_move, finaldir):
for filetype in self.FILETYPE_KEYS:
if filetype not in files_to_move:
files_to_move[filetype] = []
def move_file_and_write_to_info(self, info_dict, relevant_dict=None, output_file_type=None):
relevant_dict = relevant_dict or info_dict
if 'filepath' not in relevant_dict:
return
for file_attrs in files_to_move[filetype]:
if not os.path.isabs(file_attrs['final_filepath']):
file_attrs['final_filepath'] = os.path.join(finaldir, file_attrs['final_filepath'])
if not os.path.isabs(file_attrs['current_filepath']):
file_attrs['current_filepath'] = os.path.abspath(file_attrs['current_filepath'])
output_file_type = output_file_type or ''
current_filepath = relevant_dict['filepath']
# This approach is needed to preserved indexed thumbnail paths from `--write-all-thumbnails`
# and also to support user-defined extensions (eg: `%(title)s.temp.%(ext)s`)
extension = ''.join(Path(current_filepath).suffixes)
name_format = self._downloader.prepare_filename(info_dict, output_file_type)
final_filepath = replace_extension(name_format, extension)
move_result = self.move_file(info_dict, current_filepath, final_filepath)
return files_to_move
if move_result:
relevant_dict['filepath'] = move_result
else:
del relevant_dict['filepath']
def write_filepath_into_info(self, info, filetype, file_attrs):
if filetype == 'media':
info['filepath'] = file_attrs['final_filepath']
def move_file(self, info_dict, current_filepath, final_filepath):
if not current_filepath or not final_filepath:
return
elif filetype == 'thumbnails':
for filetype_dict in info[filetype]:
if filetype_dict['id'] == file_attrs['id']:
filetype_dict['filepath'] = file_attrs['final_filepath']
dl_parent_folder = os.path.split(info_dict['filepath'])[0]
finaldir = info_dict.get('__finaldir', os.path.abspath(dl_parent_folder))
elif filetype == 'requested_subtitles':
lang = file_attrs['lang']
if lang in info[filetype]:
info[filetype][lang]['filepath'] = file_attrs['final_filepath']
if not os.path.isabs(current_filepath):
current_filepath = os.path.join(finaldir, current_filepath)
if not os.path.isabs(final_filepath):
final_filepath = os.path.join(finaldir, final_filepath)
if current_filepath == final_filepath:
return final_filepath
if not os.path.exists(current_filepath):
self.report_warning('File "%s" cannot be found' % current_filepath)
return
if os.path.exists(final_filepath):
if self.get_param('overwrites', True):
self.report_warning('Replacing existing file "%s"' % final_filepath)
os.remove(final_filepath)
else:
self.report_warning(
'Cannot move file "%s" out of temporary directory since "%s" already exists. '
% (current_filepath, final_filepath))
return
make_dir(final_filepath, PostProcessingError)
self.to_screen(f'Moving file "{current_filepath}" to "{final_filepath}"')
shutil.move(current_filepath, final_filepath) # os.rename cannot move between volumes
return final_filepath
def run(self, info):
dl_path, dl_name = os.path.split(info['filepath'])
finaldir = info.get('__finaldir', os.path.abspath(dl_path))
# This represents the main media file (using the 'filepath' key)
self.move_file_and_write_to_info(info)
if self._downloaded:
info['__files_to_move']['media'] = [{'current_filepath': info['filepath'], 'final_filepath': dl_name}]
for key, output_file_type in self.CHILD_KEYS.items():
if key not in info:
continue
files_to_move = self.expand_relative_paths(info['__files_to_move'], finaldir)
if isinstance(info[key], list) or isinstance(info[key], dict):
iterable = info[key].values() if isinstance(info[key], dict) else info[key]
for filetype in self.FILETYPE_KEYS:
for file_attrs in files_to_move[filetype]:
current_filepath = file_attrs['current_filepath']
final_filepath = file_attrs['final_filepath']
if not current_filepath or not final_filepath:
continue
if current_filepath == final_filepath:
# This ensures the infojson contains the full filepath even
# when --no-overwrites is used
self.write_filepath_into_info(info, filetype, file_attrs)
continue
if not os.path.exists(current_filepath):
self.report_warning('File "%s" cannot be found' % current_filepath)
continue
if os.path.exists(final_filepath):
if self.get_param('overwrites', True):
self.report_warning('Replacing existing file "%s"' % final_filepath)
os.remove(final_filepath)
else:
self.report_warning(
'Cannot move file "%s" out of temporary directory since "%s" already exists. '
% (current_filepath, final_filepath))
continue
make_dir(final_filepath, PostProcessingError)
self.to_screen(f'Moving file "{current_filepath}" to "{final_filepath}"')
shutil.move(current_filepath, final_filepath) # os.rename cannot move between volumes
self.write_filepath_into_info(info, filetype, file_attrs)
for file_dict in iterable:
self.move_file_and_write_to_info(info, file_dict, output_file_type)
return [], info

View File

@ -2099,7 +2099,9 @@ def prepend_extension(filename, ext, expected_real_ext=None):
def replace_extension(filename, ext, expected_real_ext=None):
name, real_ext = os.path.splitext(filename)
return '{}.{}'.format(
ext = ext if ext.startswith('.') else '.' + ext
return '{}{}'.format(
name if not expected_real_ext or real_ext[1:] == expected_real_ext else filename,
ext)