movefilesafterdownload.py 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  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(f'File "{oldfile}" cannot be found')
  31. continue
  32. if os.path.exists(encodeFilename(newfile)):
  33. if self.get_param('overwrites', True):
  34. self.report_warning(f'Replacing existing file "{newfile}"')
  35. os.remove(encodeFilename(newfile))
  36. else:
  37. self.report_warning(
  38. f'Cannot move file "{oldfile}" out of temporary directory since "{newfile}" already exists. ')
  39. continue
  40. make_dir(newfile, PostProcessingError)
  41. self.to_screen(f'Moving file "{oldfile}" to "{newfile}"')
  42. shutil.move(oldfile, newfile) # os.rename cannot move between volumes
  43. info['filepath'] = finalpath
  44. return [], info