Debian Codegraph @

gallery_dl/extractor/newgrounds.py

raw
1 # -*- coding: utf-8 -*-
2
3 # Copyright 2018-2026 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 """Extractors for https://www.newgrounds.com/"""
10
11 from .common import Extractor, Message, Dispatch
12 from .. import text, util
13 import itertools
14
15 BASE_PATTERN = r"(?:https?://)?(?:www\.)?newgrounds\.com"
16 USER_PATTERN = r"(?:https?://)?([\w-]+)\.newgrounds\.com"
17
18
19 class NewgroundsExtractor(Extractor):
20 """Base class for newgrounds extractors"""
21 category = "newgrounds"
22 directory_fmt = ("{category}", "{artist[:10]:J, }")
23 filename_fmt = "{category}_{_index}_{title}.{extension}"
24 archive_fmt = "{_type}{_index}"
25 root = "https://www.newgrounds.com"
26 cookies_domain = ".newgrounds.com"
27 cookies_names = ("ng_session",)
28 request_interval = (0.5, 1.5)
29
30 def __init__(self, match):
31 Extractor.__init__(self, match)
32 self.user = match[1]
33 self.user_root = f"https://{self.user}.newgrounds.com"
34
35 def _init(self):
36 self._extract_comment_urls = text.re(
37 r'(?:<img |data-smartload-)src="([^"]+)').findall
38 self.flash = self.config("flash", True)
39
40 fmt = self.config("format")
41 if not fmt or fmt == "original":
42 self.format = ("mp4", "webm", "m4v", "mov", "mkv",
43 1080, 720, 360)
44 elif isinstance(fmt, (list, tuple)):
45 self.format = fmt
46 else:
47 self._video_formats = self._video_formats_limit
48 self.format = (fmt if isinstance(fmt, int) else
49 text.parse_int(fmt.rstrip("p")))
50
51 def items(self):
52 self.login()
53
54 for post_url in self.posts():
55 try:
56 post = self.extract_post(post_url)
57 url = post.get("url")
58 except Exception as exc:
59 self.log.traceback(exc)
60 url = None
61
62 if url:
63 yield Message.Directory, "", post
64 post["num"] = 0
65 yield Message.Url, url, text.nameext_from_url(url, post)
66
67 if "_multi" in post:
68 for data in post["_multi"]:
69 post["num"] += 1
70 post["_index"] = f"{post['index']}_{post['num']:>02}"
71 post.update(data)
72 url = data["image"]
73
74 text.nameext_from_url(url, post)
75 yield Message.Url, url, post
76
77 if "_fallback" in post:
78 del post["_fallback"]
79
80 for url in self._extract_comment_urls(post["_comment"]):
81 post["num"] += 1
82 post["_index"] = f"{post['index']}_{post['num']:>02}"
83 url = text.ensure_http_scheme(url)
84 text.nameext_from_url(url, post)
85 yield Message.Url, url, post
86 else:
87 self.status |= 1
88 self.log.warning(
89 "Unable to get download URL for '%s'", post_url)
90
91 def posts(self):
92 """Return URLs of all relevant post pages"""
93 return self._pagination(self.__class__.subcategory, self.groups[1])
94
95 def login(self):
96 if self.cookies_check(self.cookies_names):
97 return
98
99 username, password = self._get_auth_info()
100 if username:
101 return self.cookies_update(self.cache(
102 self._login_impl, username, password,
103 _exp=365*86400, _mem=False))
104
105 def _login_impl(self, username, password):
106 self.log.info("Logging in as %s", username)
107
108 url = self.root + "/login"
109 response = self.request(url)
110 if response.history and response.url.endswith("/social"):
111 return self.cookies
112
113 page = response.text
114 headers = {
115 "Accept": "application/json, text/javascript, */*; q=0.01",
116 "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
117 "X-Requested-With": "XMLHttpRequest",
118 "Origin": self.root,
119 "Referer": url,
120 }
121 data = {
122 "_token" : text.extr(page, 'name="_token" value="', '"'),
123 "remember": "1",
124 "identity": username,
125 "password": str(password),
126 }
127
128 try:
129 response = self.request(
130 url, method="POST", headers=headers, data=data)
131 except Exception:
132 raise self.exc.AuthenticationError()
133
134 return {
135 cookie.name: cookie.value
136 for cookie in response.cookies
137 }
138
139 def extract_post(self, post_url):
140 url = post_url
141 if "/art/view/" in post_url:
142 extract_data = self._extract_image_data
143 elif "/audio/listen/" in post_url:
144 extract_data = self._extract_audio_data
145 else:
146 extract_data = self._extract_media_data
147 if self.flash:
148 url += "/format/flash"
149
150 response = self.request(url, fatal=False)
151 page = response.text
152
153 pos = page.find('id="adults_only"')
154 if pos >= 0:
155 msg = text.extract(page, 'class="highlight">', '<', pos)[0]
156 self.log.warning('"%s"', msg)
157 return {}
158
159 if response.status_code >= 400:
160 if "<title>Content Filtered</title>" not in page:
161 return {}
162 self.log.debug('"Content Filtered" response')
163
164 url_if = self.root + "/age-verification/ignore-filter"
165 headers = {"X-CSRF-TOKEN": text.extr(
166 page, 'name="csrf-token" content="', '"')}
167 data = {"url": url}
168 self.request(
169 url_if, method="POST", headers=headers, data=data, fatal=False)
170
171 response = self.request(url, fatal=False)
172 if response.history and "/login" in response.url:
173 self.log.warning("Redirected to 'login' page (%s)",
174 response.url)
175 return {}
176
177 extr = text.extract_from(page)
178 data = extract_data(extr, post_url)
179
180 data["comment_html"] = data["_comment"] = extr(
181 'id="author_comments"', '</div>').partition(">")[2].strip()
182 data["comment"] = text.unescape(text.remove_html(
183 data["_comment"]
184 .replace("<p><br></p>", "\n\n").replace("<br>", "\n"), "", ""))
185 data["favorites"] = text.parse_int(extr(
186 'id="faves_load">', '<').replace(",", ""))
187 data["score"] = text.parse_float(extr('id="score_number">', '<'))
188 data["tags"] = [
189 t for t in text.split_html(extr('<dd class="tags">', '</dd>'))
190 if "(function(" not in t
191 ]
192 data["artist"] = [
193 text.extr(user, '//', '.')
194 for user in text.extract_iter(page, '<div class="item-user">', '>')
195 ]
196
197 data["tags"].sort()
198 data["user"] = self.user or data["artist"][0]
199 data["slug"] = post_url[post_url.rfind("/")+1:]
200 data["post_url"] = post_url
201 return data
202
203 def _extract_image_data(self, extr, url):
204 full = text.extract_from(util.json_loads(extr(
205 '"full_image_text":', '});')))
206 data = {
207 "title" : text.unescape(extr('"og:title" content="', '"')),
208 "description": text.unescape(extr(':description" content="', '"')),
209 "type" : "art",
210 "_type" : "i",
211 "date" : self.parse_datetime_iso(extr(
212 'itemprop="datePublished" content="', '"')),
213 "rating" : extr('class="rated-', '"'),
214 "url" : full('src="', '"'),
215 "width" : text.parse_int(full('width="', '"')),
216 "height" : text.parse_int(full('height="', '"')),
217 }
218
219 if not data["url"]:
220 data["url"] = extr('<a href="', '"')
221
222 index = data["url"].rpartition("/")[2].partition("_")[0]
223 data["index"] = text.parse_int(index)
224 data["_index"] = index
225
226 if image_data := extr("let imageData =", "\n];"):
227 multi = self._extract_images_multi(image_data)
228 elif art_images := extr('<div class="art-images', '\n\t\t</div>'):
229 multi = self._extract_images_art(art_images)
230 else:
231 # single image post
232 return data
233
234 # multi image post
235 ext = text.ext_from_url(data["url"])
236 exts = ("jpg", "png", "gif")
237 if ext == "webp":
238 ext = "jpg"
239 for img in multi:
240 if text.ext_from_url(url := img["image"]) == "webp":
241 fallback = [url.replace(".webp", "." + e)
242 for e in exts if e != ext]
243 fallback.append(url)
244 img["image"] = url.replace(".webp", "." + ext)
245 img["_fallback"] = fallback
246 data["_multi"] = multi
247 return data
248
249 def _extract_images_multi(self, html):
250 images = util.json_loads(html + "]")
251 del images[0]
252 return images
253
254 def _extract_images_art(self, html):
255 return [
256 {"image": text.ensure_http_scheme(url.replace(
257 "/medium_views/", "/images/", 1))}
258 for url in text.extract_iter(html, 'data-smartload-src="', '"')
259 ]
260
261 def _extract_audio_data(self, extr, url):
262 index = url.split("/")[5]
263 return {
264 "title" : text.unescape(extr('"og:title" content="', '"')),
265 "description": text.unescape(extr(':description" content="', '"')),
266 "url" : text.unescape(extr('ty="og:audio" content="', '"')),
267 "type" : "audio",
268 "_type" : "a",
269 "date" : self.parse_datetime_iso(extr(
270 'itemprop="datePublished" content="', '"')),
271 "index" : text.parse_int(index),
272 "_index" : index,
273 "rating" : "",
274 }
275
276 def _extract_media_data(self, extr, url):
277 index = url.split("/")[5]
278 title = extr('"og:title" content="', '"')
279 type = extr('og:type" content="', '"')
280 descr = extr('"og:description" content="', '"')
281 src = extr('{"url":"', '"')
282 if not src and self.flash:
283 src = extr('swf: "', '"')
284
285 if src:
286 src = src.replace("\\/", "/")
287 formats = ()
288 type = extr(',"description":"', '"')
289 date = self.parse_datetime_iso(extr(
290 'itemprop="datePublished" content="', '"'))
291 if type:
292 type = type.rpartition(" ")[2].lower()
293 else:
294 type = "flash" if text.ext_from_url(url) == "swf" else "game"
295 else:
296 url = self.root + "/portal/video/" + index
297 headers = {
298 "Accept": "application/json, text/javascript, */*; q=0.01",
299 "X-Requested-With": "XMLHttpRequest",
300 }
301 sources = self.request_json(url, headers=headers)["sources"]
302 formats = self._video_formats(sources)
303 src = next(formats, "")
304 date = self.parse_timestamp(src.rpartition("?")[2])
305 type = "movie"
306
307 return {
308 "title" : text.unescape(title),
309 "url" : src,
310 "date" : date,
311 "type" : type,
312 "_type" : "",
313 "description": text.unescape(descr or extr(
314 'itemprop="description" content="', '"')),
315 "rating" : extr('class="rated-', '"'),
316 "index" : text.parse_int(index),
317 "_index" : index,
318 "_fallback" : formats,
319 }
320
321 def _video_formats(self, sources):
322 src = sources["360p"][0]["src"]
323 sub = text.re(r"\.360p\.\w+").sub
324
325 for fmt in self.format:
326 try:
327 if isinstance(fmt, int):
328 yield sources[str(fmt) + "p"][0]["src"]
329 elif fmt in sources:
330 yield sources[fmt][0]["src"]
331 else:
332 yield sub("." + fmt, src, 1)
333 except Exception as exc:
334 self.log.debug("Video format '%s' not available (%s: %s)",
335 fmt, exc.__class__.__name__, exc)
336
337 def _video_formats_limit(self, sources):
338 formats = []
339 for fmt, src in sources.items():
340 width = text.parse_int(fmt.rstrip("p"))
341 if width <= self.format:
342 formats.append((width, src))
343
344 formats.sort(reverse=True)
345 for fmt in formats:
346 yield fmt[1][0]["src"]
347
348 def _pagination(self, kind, pnum=1):
349 url = f"{self.user_root}/{kind}"
350 params = {
351 "page": text.parse_int(pnum, 1),
352 "isAjaxRequest": "1",
353 }
354 headers = {
355 "Referer": url,
356 "X-Requested-With": "XMLHttpRequest",
357 }
358
359 while True:
360 with self.request(
361 url, params=params, headers=headers,
362 fatal=False) as response:
363 try:
364 data = response.json()
365 except ValueError:
366 return
367 if not data:
368 return
369 if "errors" in data:
370 msg = ", ".join(text.unescape(e) for e in data["errors"])
371 raise self.exc.AbortExtraction(msg)
372
373 items = data.get("items")
374 if not items:
375 return
376
377 for year, items in items.items():
378 for item in items:
379 page_url = text.extr(item, 'href="', '"')
380 if page_url[0] == "/":
381 page_url = self.root + page_url
382 yield page_url
383
384 more = data.get("load_more")
385 if not more or len(more) < 8:
386 return
387 params["page"] += 1
388
389
390 class NewgroundsImageExtractor(NewgroundsExtractor):
391 """Extractor for a single image from newgrounds.com"""
392 subcategory = "image"
393 pattern = (r"(?:https?://)?(?:"
394 r"(?:www\.)?newgrounds\.com/art/view/([^/?#]+)/[^/?#]+"
395 r"|art\.ngfiles\.com/images/\d+/\d+_([^_]+)_([^.]+))")
396 example = "https://www.newgrounds.com/art/view/USER/TITLE"
397
398 def __init__(self, match):
399 NewgroundsExtractor.__init__(self, match)
400 if match[2]:
401 self.user = match[2]
402 self.post_url = f"{self.root}/art/view/{self.user}/{match[3]}"
403 else:
404 self.post_url = text.ensure_http_scheme(match[0])
405
406 def posts(self):
407 return (self.post_url,)
408
409
410 class NewgroundsMediaExtractor(NewgroundsExtractor):
411 """Extractor for a media file from newgrounds.com"""
412 subcategory = "media"
413 pattern = BASE_PATTERN + r"(/(?:portal/view|audio/listen)/\d+)"
414 example = "https://www.newgrounds.com/portal/view/12345"
415
416 def __init__(self, match):
417 NewgroundsExtractor.__init__(self, match)
418 self.user = ""
419 self.post_url = self.root + match[1]
420
421 def posts(self):
422 return (self.post_url,)
423
424
425 class NewgroundsArtExtractor(NewgroundsExtractor):
426 """Extractor for all images of a newgrounds user"""
427 subcategory = "art"
428 pattern = USER_PATTERN + r"/art(?:(?:/page/|/?\?page=)(\d+))?/?$"
429 example = "https://USER.newgrounds.com/art"
430
431
432 class NewgroundsAudioExtractor(NewgroundsExtractor):
433 """Extractor for all audio submissions of a newgrounds user"""
434 subcategory = "audio"
435 pattern = USER_PATTERN + r"/audio(?:(?:/page/|/?\?page=)(\d+))?/?$"
436 example = "https://USER.newgrounds.com/audio"
437
438
439 class NewgroundsMoviesExtractor(NewgroundsExtractor):
440 """Extractor for all movies of a newgrounds user"""
441 subcategory = "movies"
442 pattern = USER_PATTERN + r"/movies(?:(?:/page/|/?\?page=)(\d+))?/?$"
443 example = "https://USER.newgrounds.com/movies"
444
445
446 class NewgroundsGamesExtractor(NewgroundsExtractor):
447 """Extractor for a newgrounds user's games"""
448 subcategory = "games"
449 pattern = USER_PATTERN + r"/games(?:(?:/page/|/?\?page=)(\d+))?/?$"
450 example = "https://USER.newgrounds.com/games"
451
452
453 class NewgroundsUserExtractor(Dispatch, NewgroundsExtractor):
454 """Extractor for a newgrounds user profile"""
455 pattern = USER_PATTERN + r"/?$"
456 example = "https://USER.newgrounds.com"
457
458 def items(self):
459 base = self.user_root + "/"
460 return self._dispatch_extractors((
461 (NewgroundsArtExtractor , base + "art"),
462 (NewgroundsAudioExtractor , base + "audio"),
463 (NewgroundsGamesExtractor , base + "games"),
464 (NewgroundsMoviesExtractor, base + "movies"),
465 ), ("art",))
466
467
468 class NewgroundsFavoriteExtractor(NewgroundsExtractor):
469 """Extractor for posts favorited by a newgrounds user"""
470 subcategory = "favorite"
471 directory_fmt = ("{category}", "{user}", "Favorites")
472 pattern = (USER_PATTERN + r"/favorites(?!/following)(?:/(art|audio|movies)"
473 r"(?:(?:/page/|/?\?page=)(\d+))?)?")
474 example = "https://USER.newgrounds.com/favorites"
475
476 def posts(self):
477 _, kind, pnum = self.groups
478 if kind:
479 return self._pagination_favorites(kind, pnum)
480 return itertools.chain.from_iterable(
481 self._pagination_favorites(k) for k in ("art", "audio", "movies")
482 )
483
484 def _pagination_favorites(self, kind, pnum=1):
485 url = f"{self.user_root}/favorites/{kind}"
486 params = {
487 "page": text.parse_int(pnum, 1),
488 "isAjaxRequest": "1",
489 }
490 headers = {
491 "Referer": url,
492 "X-Requested-With": "XMLHttpRequest",
493 }
494
495 while True:
496 response = self.request(url, params=params, headers=headers)
497 if response.history:
498 return
499
500 data = response.json()
501 favs = self._extract_favorites(data.get("component") or "")
502 yield from favs
503
504 if len(favs) < 24:
505 return
506 params["page"] += 1
507
508 def _extract_favorites(self, page):
509 return [
510 self.root + path
511 for path in text.extract_iter(page, 'href="' + self.root, '"')
512 ]
513
514
515 class NewgroundsFollowingExtractor(NewgroundsFavoriteExtractor):
516 """Extractor for a newgrounds user's favorited users"""
517 subcategory = "following"
518 pattern = (USER_PATTERN + r"/favorites/(following)"
519 r"(?:(?:/page/|/?\?page=)(\d+))?")
520 example = "https://USER.newgrounds.com/favorites/following"
521
522 def items(self):
523 _, kind, pnum = self.groups
524 data = {"_extractor": NewgroundsUserExtractor}
525 for url in self._pagination_favorites(kind, pnum):
526 yield Message.Queue, url, data
527
528 def _extract_favorites(self, page):
529 return [
530 text.ensure_http_scheme(user.rpartition('"')[2])
531 for user in text.extract_iter(page, 'class="item-user', '"><img')
532 ]
533
534
535 class NewgroundsSearchExtractor(NewgroundsExtractor):
536 """Extractor for newgrounds.com search reesults"""
537 subcategory = "search"
538 directory_fmt = ("{category}", "search", "{search_tags}")
539 pattern = BASE_PATTERN + r"/search/conduct/([^/?#]+)/?\?([^#]+)"
540 example = "https://www.newgrounds.com/search/conduct/art?terms=QUERY"
541
542 def __init__(self, match):
543 NewgroundsExtractor.__init__(self, match)
544 self._path, query = self.groups
545 self.query = text.parse_query(query)
546
547 def posts(self):
548 self.kwdict["search_tags"] = self.query.get("terms", "")
549 if suitabilities := self.query.get("suitabilities"):
550 data = {"view_suitability_" + s: "on"
551 for s in suitabilities.split(",")}
552 self.request(self.root + "/suitabilities",
553 method="POST", data=data)
554 return self._pagination_search(
555 "/search/conduct/" + self._path, self.query)
556
557 def _pagination_search(self, path, params):
558 url = self.root + path
559 params["inner"] = "1"
560 params["page"] = text.parse_int(params.get("page"), 1)
561 headers = {
562 "Accept": "application/json, text/javascript, */*; q=0.01",
563 "X-Requested-With": "XMLHttpRequest",
564 }
565
566 while True:
567 data = self.request_json(url, params=params, headers=headers)
568
569 post_url = None
570 for post_url in text.extract_iter(data["content"], 'href="', '"'):
571 if not post_url.startswith("/search/"):
572 yield post_url
573
574 if post_url is None:
575 return
576 params["page"] += 1