aboutsummaryrefslogtreecommitdiffstats
path: root/gallery_dl/postprocessor/exec.py
blob: ef11bff7acaeda697a01732b7ba56bcca8a0376a (plain) (blame)
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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
# -*- coding: utf-8 -*-

# Copyright 2018-2023 Mike Fährmann
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 2 as
# published by the Free Software Foundation.

"""Execute processes"""

from .common import PostProcessor
from .. import util, formatter
import subprocess
import os


if util.WINDOWS:
    def quote(s):
        s = s.replace('"', '\\"')
        return f'"{s}"'
else:
    from shlex import quote


class ExecPP(PostProcessor):

    def __init__(self, job, options):
        PostProcessor.__init__(self, job)

        if cmds := options.get("commands"):
            self.cmds = [self._prepare_cmd(c) for c in cmds]
            execute = self.exec_many
        else:
            execute, self.args = self._prepare_cmd(options["command"])
            if options.get("async", False):
                self._exec = self._popen

        self.session = False
        self.creationflags = 0
        if options.get("session"):
            if util.WINDOWS:
                self.creationflags = subprocess.CREATE_NEW_PROCESS_GROUP
            else:
                self.session = True

        events = options.get("event")
        if events is None:
            events = ("after",)
        elif isinstance(events, str):
            events = events.split(",")
        job.register_hooks({event: execute for event in events}, options)

        if self._archive_init(job, options):
            self._archive_register(job)

    def _prepare_cmd(self, cmd):
        if isinstance(cmd, str):
            self._sub = util.re(r"\{(_directory|_filename|_path|)\}").sub
            return self.exec_string, cmd
        else:
            return self.exec_list, [formatter.parse(arg) for arg in cmd]

    def exec_list(self, pathfmt):
        archive = self.archive
        kwdict = pathfmt.kwdict

        if archive and archive.check(kwdict):
            return

        kwdict["_directory"] = pathfmt.realdirectory
        kwdict["_filename"] = pathfmt.filename
        kwdict["_path"] = pathfmt.realpath

        args = [arg.format_map(kwdict) for arg in self.args]
        args[0] = os.path.expanduser(args[0])
        retcode = self._exec(args, False)

        if archive:
            archive.add(kwdict)
        return retcode

    def exec_string(self, pathfmt):
        archive = self.archive
        if archive and archive.check(pathfmt.kwdict):
            return

        self.pathfmt = pathfmt
        args = self._sub(self._replace, self.args)
        retcode = self._exec(args, True)

        if archive:
            archive.add(pathfmt.kwdict)
        return retcode

    def exec_many(self, pathfmt):
        if archive := self.archive:
            if archive.check(pathfmt.kwdict):
                return
            self.archive = False

        retcode = 0
        for execute, args in self.cmds:
            self.args = args
            if retcode := execute(pathfmt):
                # non-zero exit status
                break

        if archive:
            self.archive = archive
            archive.add(pathfmt.kwdict)
        return retcode

    def _exec(self, args, shell):
        if retcode := self._popen(args, shell).wait():
            self.log.warning("'%s' returned with non-zero exit status (%d)",
                             args, retcode)
        return retcode

    def _popen(self, args, shell):
        self.log.debug("Running '%s'", args)
        return util.Popen(
            args,
            shell=shell,
            creationflags=self.creationflags,
            start_new_session=self.session,
        )

    def _replace(self, match):
        name = match[1]
        if name == "_directory":
            return quote(self.pathfmt.realdirectory)
        if name == "_filename":
            return quote(self.pathfmt.filename)
        return quote(self.pathfmt.realpath)


__postprocessor__ = ExecPP