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