2021-01-23 13:18:12 +01:00
|
|
|
import os
|
|
|
|
|
|
|
|
from .common import PostProcessor
|
2022-11-07 16:24:30 +01:00
|
|
|
from ..compat import shutil
|
2021-01-23 13:18:12 +01:00
|
|
|
from ..utils import (
|
2022-04-12 00:32:57 +02:00
|
|
|
PostProcessingError,
|
2021-01-23 13:18:12 +01:00
|
|
|
make_dir,
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
|
|
class MoveFilesAfterDownloadPP(PostProcessor):
|
|
|
|
|
2021-04-11 00:18:07 +02:00
|
|
|
def __init__(self, downloader=None, downloaded=True):
|
|
|
|
PostProcessor.__init__(self, downloader)
|
|
|
|
self._downloaded = downloaded
|
|
|
|
|
2021-01-23 13:18:12 +01:00
|
|
|
@classmethod
|
|
|
|
def pp_key(cls):
|
|
|
|
return 'MoveFiles'
|
|
|
|
|
|
|
|
def run(self, info):
|
2024-11-17 00:24:11 +01:00
|
|
|
dl_path, dl_name = os.path.split(info['filepath'])
|
2021-01-23 16:25:45 +01:00
|
|
|
finaldir = info.get('__finaldir', dl_path)
|
|
|
|
finalpath = os.path.join(finaldir, dl_name)
|
2021-04-11 00:18:07 +02:00
|
|
|
if self._downloaded:
|
2024-11-17 00:24:11 +01:00
|
|
|
info['__files_to_move'][info['filepath']] = finalpath
|
2021-01-23 13:18:12 +01:00
|
|
|
|
2024-11-17 00:24:11 +01:00
|
|
|
make_newfilename = lambda old: os.path.join(finaldir, os.path.basename(old))
|
2021-03-18 16:24:53 +01:00
|
|
|
for oldfile, newfile in info['__files_to_move'].items():
|
2021-01-23 13:18:12 +01:00
|
|
|
if not newfile:
|
2021-02-07 12:17:48 +01:00
|
|
|
newfile = make_newfilename(oldfile)
|
2024-11-17 00:24:11 +01:00
|
|
|
if os.path.abspath(oldfile) == os.path.abspath(newfile):
|
2021-01-23 13:18:12 +01:00
|
|
|
continue
|
2024-11-17 00:24:11 +01:00
|
|
|
if not os.path.exists(oldfile):
|
2024-06-12 01:09:58 +02:00
|
|
|
self.report_warning(f'File "{oldfile}" cannot be found')
|
2021-01-26 11:23:07 +01:00
|
|
|
continue
|
2024-11-17 00:24:11 +01:00
|
|
|
if os.path.exists(newfile):
|
2021-01-23 13:18:12 +01:00
|
|
|
if self.get_param('overwrites', True):
|
2024-06-12 01:09:58 +02:00
|
|
|
self.report_warning(f'Replacing existing file "{newfile}"')
|
2024-11-17 00:24:11 +01:00
|
|
|
os.remove(newfile)
|
2021-01-23 13:18:12 +01:00
|
|
|
else:
|
|
|
|
self.report_warning(
|
2024-06-12 01:09:58 +02:00
|
|
|
f'Cannot move file "{oldfile}" out of temporary directory since "{newfile}" already exists. ')
|
2021-01-23 13:18:12 +01:00
|
|
|
continue
|
|
|
|
make_dir(newfile, PostProcessingError)
|
2022-04-11 17:10:28 +02:00
|
|
|
self.to_screen(f'Moving file "{oldfile}" to "{newfile}"')
|
2021-01-23 13:18:12 +01:00
|
|
|
shutil.move(oldfile, newfile) # os.rename cannot move between volumes
|
|
|
|
|
2021-02-07 12:17:48 +01:00
|
|
|
info['filepath'] = finalpath
|
2021-01-23 13:18:12 +01:00
|
|
|
return [], info
|