-
-
Notifications
You must be signed in to change notification settings - Fork 996
/
job.py
310 lines (251 loc) · 9.69 KB
/
job.py
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
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
# -*- coding: utf-8 -*-
# Copyright 2015-2017 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.
import sys
import json
import hashlib
from . import extractor, downloader, config, util, output, exception
from .extractor.message import Message
class Job():
"""Base class for Job-types"""
ufile = None
def __init__(self, url):
self.url = url
self.extractor = extractor.find(url)
if self.extractor is None:
raise exception.NoExtractorError(url)
self.extractor.log.debug(
"Using %s for %s", self.extractor.__class__.__name__, url)
items = config.get(("images",))
if items:
pred = util.RangePredicate(items)
if pred.lower > 1:
pred.index += self.extractor.skip(pred.lower - 1)
self.pred_url = pred
else:
self.pred_url = True
items = config.get(("chapters",))
self.pred_queue = util.RangePredicate(items) if items else True
def run(self):
"""Execute or run the job"""
try:
log = self.extractor.log
for msg in self.extractor:
self.dispatch(msg)
except exception.AuthenticationError:
log.error("Authentication failed. Please provide a valid "
"username/password pair.")
except exception.AuthorizationError:
log.error("You do not have permission to access the resource "
"at '%s'", self.url)
except exception.NotFoundError as exc:
res = str(exc) or "resource (gallery/image/user)"
log.error("The %s at '%s' does not exist", res, self.url)
except exception.HttpError as exc:
log.error("HTTP request failed:\n%s", exc)
except exception.FormatError as exc:
err, obj = exc.args
log.error("Applying %s format string failed:\n%s: %s",
obj, err.__class__.__name__, err)
except exception.StopExtraction:
pass
except OSError as exc:
log.error("Unable to download data: %s", exc)
except Exception as exc:
log.error(("An unexpected error occurred: %s - %s. "
"Please run gallery-dl again with the --verbose flag, "
"copy its output and report this issue on "
"https://github.com/mikf/gallery-dl/issues ."),
exc.__class__.__name__, exc)
log.debug("Traceback", exc_info=True)
def dispatch(self, msg):
"""Call the appropriate message handler"""
if msg[0] == Message.Url:
if self.pred_url:
self.update_kwdict(msg[2])
self.handle_url(msg[1], msg[2])
elif msg[0] == Message.Directory:
self.update_kwdict(msg[1])
self.handle_directory(msg[1])
elif msg[0] == Message.Queue:
if self.pred_queue:
self.handle_queue(msg[1])
elif msg[0] == Message.Version:
if msg[1] != 1:
raise "unsupported message-version ({}, {})".format(
self.extractor.category, msg[1]
)
# TODO: support for multiple message versions
def handle_url(self, url, keywords):
"""Handle Message.Url"""
def handle_directory(self, keywords):
"""Handle Message.Directory"""
def handle_queue(self, url):
"""Handle Message.Queue"""
def update_kwdict(self, kwdict):
"""Add 'category' and 'subcategory' keywords"""
kwdict["category"] = self.extractor.category
kwdict["subcategory"] = self.extractor.subcategory
def _write_unsupported(self, url):
if self.ufile:
print(url, file=self.ufile, flush=True)
class DownloadJob(Job):
"""Download images into appropriate directory/filename locations"""
def __init__(self, url):
Job.__init__(self, url)
self.pathfmt = util.PathFormat(self.extractor)
self.downloaders = {}
self.out = output.select()
def handle_url(self, url, keywords):
"""Download the resource specified in 'url'"""
self.pathfmt.set_keywords(keywords)
if self.pathfmt.exists():
self.out.skip(self.pathfmt.path)
return
dlinstance = self.get_downloader(url)
dlinstance.download(url, self.pathfmt)
def handle_directory(self, keywords):
"""Set and create the target directory for downloads"""
self.pathfmt.set_directory(keywords)
def handle_queue(self, url):
try:
DownloadJob(url).run()
except exception.NoExtractorError:
self._write_unsupported(url)
def get_downloader(self, url):
"""Return, and possibly construct, a downloader suitable for 'url'"""
pos = url.find(":")
scheme = url[:pos] if pos != -1 else "http"
if scheme == "https":
scheme = "http"
instance = self.downloaders.get(scheme)
if instance is None:
klass = downloader.find(scheme)
instance = klass(self.extractor.session, self.out)
self.downloaders[scheme] = instance
return instance
class KeywordJob(Job):
"""Print available keywords"""
def handle_url(self, url, keywords):
print("\nKeywords for filenames:")
print("-----------------------")
self.print_keywords(keywords)
raise exception.StopExtraction()
def handle_directory(self, keywords):
print("Keywords for directory names:")
print("-----------------------------")
self.print_keywords(keywords)
def handle_queue(self, url):
print("This extractor transfers work to other extractors and does not "
"provide any keywords on its own. Try "
"'gallery-dl --list-keywords \"", url, "\"' instead.", sep="")
raise exception.StopExtraction()
@staticmethod
def print_keywords(keywords, prefix=""):
"""Print key-value pairs with formatting"""
suffix = "]" if prefix else ""
for key, value in sorted(keywords.items()):
key = prefix + key + suffix
if isinstance(value, dict):
KeywordJob.print_keywords(value, key + "[")
elif isinstance(value, list):
if value and isinstance(value[0], dict):
KeywordJob.print_keywords(value[0], key + "[][")
else:
print(key, "[]", sep="")
for val in value:
print(" -", val)
else:
# string or number
print(key, "\n ", value, sep="")
class UrlJob(Job):
"""Print download urls"""
maxdepth = -1
def __init__(self, url, depth=1):
Job.__init__(self, url)
self.depth = depth
if depth == self.maxdepth:
self.handle_queue = print
@staticmethod
def handle_url(url, _):
print(url)
def handle_queue(self, url):
try:
UrlJob(url, self.depth + 1).run()
except exception.NoExtractorError:
self._write_unsupported(url)
class TestJob(DownloadJob):
"""Generate test-results for extractor runs"""
class HashIO():
"""Minimal file-like interface"""
def __init__(self, hashobj):
self.hashobj = hashobj
self.path = ""
self.has_extension = True
def __enter__(self):
return self
def __exit__(self, *args):
pass
def open(self):
return self
def write(self, content):
"""Update SHA1 hash"""
self.hashobj.update(content)
def __init__(self, url, content=False):
DownloadJob.__init__(self, url)
self.content = content
self.hash_url = hashlib.sha1()
self.hash_keyword = hashlib.sha1()
self.hash_content = hashlib.sha1()
if content:
self.fileobj = self.HashIO(self.hash_content)
def run(self):
for msg in self.extractor:
self.dispatch(msg)
def handle_url(self, url, keywords):
self.update_url(url)
self.update_keyword(keywords)
self.update_content(url)
def handle_directory(self, keywords):
self.update_keyword(keywords)
def handle_queue(self, url):
self.update_url(url)
def update_url(self, url):
"""Update the URL hash"""
self.hash_url.update(url.encode())
def update_keyword(self, kwdict):
"""Update the keyword hash"""
self.hash_keyword.update(
json.dumps(kwdict, sort_keys=True).encode()
)
def update_content(self, url):
"""Update the content hash"""
if self.content:
self.get_downloader(url).download(url, self.fileobj)
class DataJob(Job):
"""Collect extractor results and dump them"""
def __init__(self, url, file=sys.stdout):
Job.__init__(self, url)
self.file = file
self.data = []
self.ensure_ascii = config.get(("output", "ascii"), True)
def run(self):
# collect data
try:
for msg in self.extractor:
copy = [
part.copy() if hasattr(part, "copy") else part
for part in msg
]
self.data.append(copy)
except Exception as exc:
self.data.append((exc.__class__.__name__, str(exc)))
# dump to 'file'
json.dump(
self.data, self.file,
sort_keys=True, indent=2, ensure_ascii=self.ensure_ascii
)
self.file.write("\n")