movefilesafterdownload.py 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. import os
  2. from .common import PostProcessor
  3. from ..compat import shutil
  4. from ..utils import (
  5. PostProcessingError,
  6. decodeFilename,
  7. encodeFilename,
  8. make_dir,
  9. )
  10. class MoveFilesAfterDownloadPP(PostProcessor):
  11. def __init__(self, downloader=None, downloaded=True):
  12. PostProcessor.__init__(self, downloader)
  13. self._downloaded = downloaded
  14. @classmethod
  15. def pp_key(cls):
  16. return 'MoveFiles'
  17. def run(self, info):
  18. dl_path, dl_name = os.path.split(encodeFilename(info['filepath']))
  19. finaldir = info.get('__finaldir', dl_path)
  20. finalpath = os.path.join(finaldir, dl_name)
  21. if self._downloaded:
  22. info['__files_to_move'][info['filepath']] = decodeFilename(finalpath)
  23. make_newfilename = lambda old: decodeFilename(os.path.join(finaldir, os.path.basename(encodeFilename(old))))
  24. for oldfile, newfile in info['__files_to_move'].items():
  25. if not newfile:
  26. newfile = make_newfilename(oldfile)
  27. if os.path.abspath(encodeFilename(oldfile)) == os.path.abspath(encodeFilename(newfile)):
  28. continue
  29. if not os.path.exists(encodeFilename(oldfile)):
  30. self.report_warning('File "%s" cannot be found' % oldfile)
  31. continue
  32. if os.path.exists(encodeFilename(newfile)):
  33. if self.get_param('overwrites', True):
  34. self.report_warning('Replacing existing file "%s"' % newfile)
  35. os.remove(encodeFilename(newfile))
  36. else:
  37. self.report_warning(
  38. 'Cannot move file "%s" out of temporary directory since "%s" already exists. '
  39. % (oldfile, newfile))
  40. continue
  41. make_dir(newfile, PostProcessingError)
  42. self.to_screen(f'Moving file "{oldfile}" to "{newfile}"')
  43. shutil.move(oldfile, newfile) # os.rename cannot move between volumes
  44. info['filepath'] = finalpath
  45. return [], info