Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
mikf
GitHub Repository: mikf/gallery-dl
Path: blob/master/gallery_dl/actions.py
5457 views
1
# -*- coding: utf-8 -*-
2
3
# Copyright 2023-2025 Mike Fährmann
4
#
5
# This program is free software; you can redistribute it and/or modify
6
# it under the terms of the GNU General Public License version 2 as
7
# published by the Free Software Foundation.
8
9
""" """
10
11
import time
12
import logging
13
import operator
14
import functools
15
from . import util, exception
16
17
18
def parse_logging(actionspec):
19
if isinstance(actionspec, dict):
20
actionspec = actionspec.items()
21
22
actions = {}
23
actions[-logging.DEBUG] = actions_bd = []
24
actions[-logging.INFO] = actions_bi = []
25
actions[-logging.WARNING] = actions_bw = []
26
actions[-logging.ERROR] = actions_be = []
27
actions[logging.DEBUG] = actions_ad = []
28
actions[logging.INFO] = actions_ai = []
29
actions[logging.WARNING] = actions_aw = []
30
actions[logging.ERROR] = actions_ae = []
31
32
for event, spec in actionspec:
33
level, _, pattern = event.partition(":")
34
search = util.re(pattern).search if pattern else util.true
35
36
if isinstance(spec, str):
37
type, _, args = spec.partition(" ")
38
before, after = ACTIONS[type](args)
39
else:
40
actions_before = []
41
actions_after = []
42
for s in spec:
43
type, _, args = s.partition(" ")
44
before, after = ACTIONS[type](args)
45
if before:
46
actions_before.append(before)
47
if after:
48
actions_after.append(after)
49
before = _chain_actions(actions_before)
50
after = _chain_actions(actions_after)
51
52
level = level.strip()
53
if not level or level == "*":
54
if before:
55
action = (search, before)
56
actions_bd.append(action)
57
actions_bi.append(action)
58
actions_bw.append(action)
59
actions_be.append(action)
60
if after:
61
action = (search, after)
62
actions_ad.append(action)
63
actions_ai.append(action)
64
actions_aw.append(action)
65
actions_ae.append(action)
66
else:
67
level = _level_to_int(level)
68
if before:
69
actions[-level].append((search, before))
70
if after:
71
actions[level].append((search, after))
72
73
return actions
74
75
76
def parse_signals(actionspec):
77
import signal
78
79
if isinstance(actionspec, dict):
80
actionspec = actionspec.items()
81
82
for signal_name, spec in actionspec:
83
signal_num = getattr(signal, signal_name, None)
84
if signal_num is None:
85
log = logging.getLogger("gallery-dl")
86
log.warning("signal '%s' is not defined", signal_name)
87
continue
88
89
if isinstance(spec, str):
90
type, _, args = spec.partition(" ")
91
before, after = ACTIONS[type](args)
92
action = before if after is None else after
93
else:
94
actions_before = []
95
actions_after = []
96
for s in spec:
97
type, _, args = s.partition(" ")
98
before, after = ACTIONS[type](args)
99
if before is not None:
100
actions_before.append(before)
101
if after is not None:
102
actions_after.append(after)
103
104
actions = actions_before
105
actions.extend(actions_after)
106
action = _chain_actions(actions)
107
108
signal.signal(signal_num, signals_handler(action))
109
110
111
class LoggerAdapter():
112
113
def __init__(self, logger, job):
114
self.logger = logger
115
self.extra = job._logger_extra
116
self.actions = job._logger_actions
117
118
self.debug = functools.partial(self.log, logging.DEBUG)
119
self.info = functools.partial(self.log, logging.INFO)
120
self.warning = functools.partial(self.log, logging.WARNING)
121
self.error = functools.partial(self.log, logging.ERROR)
122
123
def log(self, level, msg, *args, **kwargs):
124
msg = str(msg)
125
if args:
126
msg = msg % args
127
128
before = self.actions[-level]
129
after = self.actions[level]
130
131
if before:
132
args = self.extra.copy()
133
args["level"] = level
134
135
for cond, action in before:
136
if cond(msg):
137
action(args)
138
139
level = args["level"]
140
141
if self.logger.isEnabledFor(level):
142
kwargs["extra"] = self.extra
143
self.logger._log(level, msg, (), **kwargs)
144
145
if after:
146
args = self.extra.copy()
147
for cond, action in after:
148
if cond(msg):
149
action(args)
150
151
152
def _level_to_int(level):
153
try:
154
return logging._nameToLevel[level]
155
except KeyError:
156
return int(level)
157
158
159
def _chain_actions(actions):
160
def _chain(args):
161
for action in actions:
162
action(args)
163
return _chain
164
165
166
def signals_handler(action, args={}):
167
def handler(signal_num, frame):
168
action(args)
169
return handler
170
171
172
# --------------------------------------------------------------------
173
174
def action_print(opts):
175
def _print(_):
176
print(opts)
177
return None, _print
178
179
180
def action_status(opts):
181
op, value = util.re(r"\s*([&|^=])=?\s*(\d+)").match(opts).groups()
182
183
op = {
184
"&": operator.and_,
185
"|": operator.or_,
186
"^": operator.xor,
187
"=": lambda x, y: y,
188
}[op]
189
190
value = int(value)
191
192
def _status(args):
193
args["job"].status = op(args["job"].status, value)
194
return _status, None
195
196
197
def action_level(opts):
198
level = _level_to_int(opts.lstrip(" ~="))
199
200
def _level(args):
201
args["level"] = level
202
return _level, None
203
204
205
def action_exec(opts):
206
def _exec(_):
207
util.Popen(opts, shell=True).wait()
208
return None, _exec
209
210
211
def action_wait(opts):
212
if opts:
213
seconds = util.build_duration_func(opts)
214
215
def _wait(args):
216
time.sleep(seconds())
217
else:
218
def _wait(args):
219
input("Press Enter to continue")
220
221
return None, _wait
222
223
224
def action_flag(opts):
225
flag, value = util.re(
226
r"(?i)(file|post|child|download)(?:\s*[= ]\s*(.+))?"
227
).match(opts).groups()
228
flag = flag.upper()
229
value = "stop" if value is None else value.lower()
230
231
def _flag(args):
232
util.FLAGS.__dict__[flag] = value
233
return _flag, None
234
235
236
def action_raise(opts):
237
name, _, arg = opts.partition(" ")
238
239
exc = getattr(exception, name, None)
240
if exc is None:
241
import builtins
242
exc = getattr(builtins, name, Exception)
243
244
if arg:
245
def _raise(args):
246
raise exc(arg)
247
else:
248
def _raise(args):
249
raise exc()
250
251
return None, _raise
252
253
254
def action_abort(opts):
255
return None, util.raises(exception.StopExtraction)
256
257
258
def action_terminate(opts):
259
return None, util.raises(exception.TerminateExtraction)
260
261
262
def action_restart(opts):
263
return None, util.raises(exception.RestartExtraction)
264
265
266
def action_exit(opts):
267
try:
268
opts = int(opts)
269
except ValueError:
270
pass
271
272
def _exit(args):
273
raise SystemExit(opts)
274
return None, _exit
275
276
277
ACTIONS = {
278
"abort" : action_abort,
279
"exec" : action_exec,
280
"exit" : action_exit,
281
"flag" : action_flag,
282
"level" : action_level,
283
"print" : action_print,
284
"raise" : action_raise,
285
"restart" : action_restart,
286
"status" : action_status,
287
"terminate": action_terminate,
288
"wait" : action_wait,
289
}
290
291