aboutsummaryrefslogtreecommitdiffstats
path: root/youtube_dlc/postprocessor/movefilesafterdownload.py
blob: 4146a9549c43ee2b770a5d4c2cf84d0372f1aba5 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
from __future__ import unicode_literals
import os
import shutil

from .common import PostProcessor
from ..utils import (
    encodeFilename,
    make_dir,
    PostProcessingError,
)
from ..compat import compat_str


class MoveFilesAfterDownloadPP(PostProcessor):

    def __init__(self, downloader, files_to_move):
        PostProcessor.__init__(self, downloader)
        self.files_to_move = files_to_move

    @classmethod
    def pp_key(cls):
        return 'MoveFiles'

    def run(self, info):
        dl_path, dl_name = os.path.split(encodeFilename(info['filepath']))
        finaldir = info.get('__finaldir', dl_path)
        finalpath = os.path.join(finaldir, dl_name)
        self.files_to_move[info['filepath']] = finalpath

        for oldfile, newfile in self.files_to_move.items():
            if not os.path.exists(encodeFilename(oldfile)):
                self.report_warning('File "%s" cannot be found' % oldfile)
                continue
            if not newfile:
                newfile = os.path.join(finaldir, os.path.basename(encodeFilename(oldfile)))
            oldfile, newfile = compat_str(oldfile), compat_str(newfile)
            if os.path.abspath(encodeFilename(oldfile)) == os.path.abspath(encodeFilename(newfile)):
                continue
            if os.path.exists(encodeFilename(newfile)):
                if self.get_param('overwrites', True):
                    self.report_warning('Replacing existing file "%s"' % newfile)
                    os.path.remove(encodeFilename(newfile))
                else:
                    self.report_warning(
                        'Cannot move file "%s" out of temporary directory since "%s" already exists. '
                        % (oldfile, newfile))
                    continue
            make_dir(newfile, PostProcessingError)
            self.to_screen('Moving file "%s" to "%s"' % (oldfile, newfile))
            shutil.move(oldfile, newfile)  # os.rename cannot move between volumes

        info['filepath'] = compat_str(finalpath)
        return [], info