| 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.artstation.com/""" |
| 10 |
|
| 11 |
from .common import Extractor, Message |
| 12 |
from .. import text, util |
| 13 |
import itertools |
| 14 |
|
| 15 |
|
| 16 |
class ArtstationExtractor(Extractor): |
| 17 |
"""Base class for artstation extractors""" |
| 18 |
category = "artstation" |
| 19 |
filename_fmt = "{category}_{id}_{asset[id]}_{title}.{extension}" |
| 20 |
directory_fmt = ("{category}", "{userinfo[username]}") |
| 21 |
archive_fmt = "{asset[id]}" |
| 22 |
browser = "firefox" |
| 23 |
tls12 = False |
| 24 |
root = "https://www.artstation.com" |
| 25 |
|
| 26 |
def __init__(self, match): |
| 27 |
Extractor.__init__(self, match) |
| 28 |
self.user = match[1] or match[2] |
| 29 |
|
| 30 |
def _init(self): |
| 31 |
self.session.headers["Cache-Control"] = "max-age=0" |
| 32 |
self.mviews = self.config("mviews", True) |
| 33 |
self.videos = self.config("videos", True) |
| 34 |
self.external = self.config("external", False) |
| 35 |
self.previews = self.config("previews", False) |
| 36 |
self.max_posts = self.config("max-posts") |
| 37 |
|
| 38 |
def items(self): |
| 39 |
data = self.metadata() |
| 40 |
projects = self.projects() |
| 41 |
|
| 42 |
if self.max_posts: |
| 43 |
projects = itertools.islice(projects, self.max_posts) |
| 44 |
for project in projects: |
| 45 |
for num, asset in enumerate( |
| 46 |
self.get_project_assets(project["hash_id"]), 1): |
| 47 |
asset.update(data) |
| 48 |
adict = asset["asset"] |
| 49 |
asset["num"] = num |
| 50 |
yield Message.Directory, "", asset |
| 51 |
|
| 52 |
if adict["has_embedded_player"]: |
| 53 |
if url := self._extract_embed(asset): |
| 54 |
text.nameext_from_url(url, asset) |
| 55 |
yield Message.Url, url, asset |
| 56 |
if not self.previews: |
| 57 |
continue |
| 58 |
|
| 59 |
if adict["has_image"]: |
| 60 |
url = adict["image_url"] |
| 61 |
text.nameext_from_url(url, asset) |
| 62 |
|
| 63 |
url = self._no_cache(url) |
| 64 |
if "/images/images/" in url: |
| 65 |
lhs, _, rhs = url.partition("/large/") |
| 66 |
if rhs: |
| 67 |
url = f"{lhs}/8k/{rhs}" |
| 68 |
asset["_fallback"] = self._image_fallback(lhs, rhs) |
| 69 |
|
| 70 |
yield Message.Url, url, asset |
| 71 |
|
| 72 |
def _extract_embed(self, asset): |
| 73 |
adict = asset["asset"] |
| 74 |
player = adict["player_embedded"] |
| 75 |
url = (text.extr(player, 'src="', '"') or |
| 76 |
text.extr(player, "src='", "'")) |
| 77 |
|
| 78 |
if url.startswith(self.root): |
| 79 |
# embed or video clip hosted on artstation |
| 80 |
type = text.extr(adict.get("image_url", ""), "/assets/", "/") |
| 81 |
if type == "marmosets": |
| 82 |
if not self.mviews: |
| 83 |
return |
| 84 |
page = self.request(url).text |
| 85 |
return text.extr(page, "marmoset.embed(", '",').strip("\"' ") |
| 86 |
|
| 87 |
elif type: |
| 88 |
if not self.videos: |
| 89 |
return |
| 90 |
page = self.request(url).text |
| 91 |
return text.extract( |
| 92 |
page, ' src="', '"', page.find('id="video"')+1)[0] |
| 93 |
|
| 94 |
if url: |
| 95 |
# external URL |
| 96 |
if not self.external: |
| 97 |
return |
| 98 |
asset["extension"] = "mp4" |
| 99 |
return "ytdl:" + url |
| 100 |
|
| 101 |
self.log.debug(player) |
| 102 |
self.log.warning("Failed to extract embedded player URL (%s)", |
| 103 |
adict.get("id")) |
| 104 |
|
| 105 |
def _image_fallback(self, lhs, rhs): |
| 106 |
yield f"{lhs}/4k/{rhs}" |
| 107 |
yield f"{lhs}/large/{rhs}" |
| 108 |
yield f"{lhs}/medium/{rhs}" |
| 109 |
yield f"{lhs}/small/{rhs}" |
| 110 |
|
| 111 |
def metadata(self): |
| 112 |
"""Return general metadata""" |
| 113 |
return {"userinfo": self.get_user_info(self.user)} |
| 114 |
|
| 115 |
def projects(self): |
| 116 |
"""Return an iterable containing all relevant project IDs""" |
| 117 |
|
| 118 |
def get_project_assets(self, project_id): |
| 119 |
"""Return all assets associated with 'project_id'""" |
| 120 |
url = f"{self.root}/projects/{project_id}.json" |
| 121 |
|
| 122 |
try: |
| 123 |
data = self.request_json(url) |
| 124 |
except self.exc.HttpError as exc: |
| 125 |
self.log.warning(exc) |
| 126 |
return |
| 127 |
|
| 128 |
data["title"] = text.unescape(data["title"]) |
| 129 |
data["description"] = text.unescape(text.remove_html( |
| 130 |
data["description"])) |
| 131 |
data["date"] = self.parse_datetime_iso(data["created_at"]) |
| 132 |
|
| 133 |
assets = data["assets"] |
| 134 |
del data["assets"] |
| 135 |
|
| 136 |
data["count"] = len(assets) |
| 137 |
if len(assets) == 1: |
| 138 |
data["asset"] = assets[0] |
| 139 |
yield data |
| 140 |
else: |
| 141 |
for asset in assets: |
| 142 |
data["asset"] = asset |
| 143 |
yield data.copy() |
| 144 |
|
| 145 |
def get_user_info(self, username): |
| 146 |
"""Return metadata for a specific user""" |
| 147 |
url = f"{self.root}/users/{username.lower()}/quick.json" |
| 148 |
response = self.request(url, notfound="user") |
| 149 |
return response.json() |
| 150 |
|
| 151 |
def _pagination(self, url, params=None, json=None): |
| 152 |
headers = {"Accept" : "application/json, text/plain, */*"} |
| 153 |
|
| 154 |
if json: |
| 155 |
params = json |
| 156 |
headers["PUBLIC-CSRF-TOKEN"] = self._init_csrf_token() |
| 157 |
kwargs = {"method": "POST", "headers": headers, "json": json} |
| 158 |
else: |
| 159 |
if not params: |
| 160 |
params = {} |
| 161 |
kwargs = {"params": params, "headers": headers} |
| 162 |
|
| 163 |
total = 0 |
| 164 |
params["page"] = 1 |
| 165 |
|
| 166 |
while True: |
| 167 |
data = self.request_json(url, **kwargs) |
| 168 |
yield from data["data"] |
| 169 |
|
| 170 |
total += len(data["data"]) |
| 171 |
if total >= data["total_count"]: |
| 172 |
return |
| 173 |
|
| 174 |
params["page"] += 1 |
| 175 |
|
| 176 |
def _init_csrf_token(self): |
| 177 |
url = self.root + "/api/v2/csrf_protection/token.json" |
| 178 |
return self.request_json( |
| 179 |
url, method="POST", json={})["public_csrf_token"] |
| 180 |
|
| 181 |
def _no_cache(self, url): |
| 182 |
"""Cause a cache miss to prevent Cloudflare 'optimizations' |
| 183 |
|
| 184 |
Cloudflare's 'Polish' optimization strips image metadata and may even |
| 185 |
recompress an image as lossy JPEG. This can be prevented by causing |
| 186 |
a cache miss when requesting an image by adding a random dummy query |
| 187 |
parameter. |
| 188 |
|
| 189 |
Ref: |
| 190 |
https://github.com/r888888888/danbooru/issues/3528 |
| 191 |
https://danbooru.donmai.us/forum_topics/14952 |
| 192 |
""" |
| 193 |
sep = "&" if "?" in url else "?" |
| 194 |
token = util.generate_token(8) |
| 195 |
return url + sep + token[:4] + "=" + token[4:] |
| 196 |
|
| 197 |
|
| 198 |
class ArtstationUserExtractor(ArtstationExtractor): |
| 199 |
"""Extractor for all projects of an artstation user""" |
| 200 |
subcategory = "user" |
| 201 |
pattern = (r"(?:https?://)?(?:(?:www\.)?artstation\.com" |
| 202 |
r"/(?!artwork|projects|search)([^/?#]+)(?:/albums/all)?" |
| 203 |
r"|((?!www)[\w-]+)\.artstation\.com(?:/projects)?)/?$") |
| 204 |
example = "https://www.artstation.com/USER" |
| 205 |
|
| 206 |
def projects(self): |
| 207 |
url = f"{self.root}/users/{self.user}/projects.json" |
| 208 |
params = {"album_id": "all"} |
| 209 |
return self._pagination(url, params) |
| 210 |
|
| 211 |
|
| 212 |
class ArtstationAlbumExtractor(ArtstationExtractor): |
| 213 |
"""Extractor for all projects in an artstation album""" |
| 214 |
subcategory = "album" |
| 215 |
directory_fmt = ("{category}", "{userinfo[username]}", "Albums", |
| 216 |
"{album[id]} - {album[title]}") |
| 217 |
archive_fmt = "a_{album[id]}_{asset[id]}" |
| 218 |
pattern = (r"(?:https?://)?(?:(?:www\.)?artstation\.com" |
| 219 |
r"/(?!artwork|projects|search)([^/?#]+)" |
| 220 |
r"|((?!www)[\w-]+)\.artstation\.com)/albums/(\d+)") |
| 221 |
example = "https://www.artstation.com/USER/albums/12345" |
| 222 |
|
| 223 |
def __init__(self, match): |
| 224 |
ArtstationExtractor.__init__(self, match) |
| 225 |
self.album_id = text.parse_int(match[3]) |
| 226 |
|
| 227 |
def metadata(self): |
| 228 |
userinfo = self.get_user_info(self.user) |
| 229 |
album = None |
| 230 |
|
| 231 |
for album in userinfo["albums_with_community_projects"]: |
| 232 |
if album["id"] == self.album_id: |
| 233 |
break |
| 234 |
else: |
| 235 |
raise self.exc.NotFoundError("album") |
| 236 |
|
| 237 |
return { |
| 238 |
"userinfo": userinfo, |
| 239 |
"album": album |
| 240 |
} |
| 241 |
|
| 242 |
def projects(self): |
| 243 |
url = f"{self.root}/users/{self.user}/projects.json" |
| 244 |
params = {"album_id": self.album_id} |
| 245 |
return self._pagination(url, params) |
| 246 |
|
| 247 |
|
| 248 |
class ArtstationLikesExtractor(ArtstationExtractor): |
| 249 |
"""Extractor for liked projects of an artstation user""" |
| 250 |
subcategory = "likes" |
| 251 |
directory_fmt = ("{category}", "{userinfo[username]}", "Likes") |
| 252 |
archive_fmt = "f_{userinfo[id]}_{asset[id]}" |
| 253 |
pattern = (r"(?:https?://)?(?:www\.)?artstation\.com" |
| 254 |
r"/(?!artwork|projects|search)([^/?#]+)/likes") |
| 255 |
example = "https://www.artstation.com/USER/likes" |
| 256 |
|
| 257 |
def projects(self): |
| 258 |
url = f"{self.root}/users/{self.user}/likes.json" |
| 259 |
return self._pagination(url) |
| 260 |
|
| 261 |
|
| 262 |
class ArtstationCollectionExtractor(ArtstationExtractor): |
| 263 |
"""Extractor for an artstation collection""" |
| 264 |
subcategory = "collection" |
| 265 |
directory_fmt = ("{category}", "{user}", |
| 266 |
"{collection[id]} {collection[name]}") |
| 267 |
archive_fmt = "c_{collection[id]}_{asset[id]}" |
| 268 |
pattern = (r"(?:https?://)?(?:www\.)?artstation\.com" |
| 269 |
r"/(?!artwork|projects|search)([^/?#]+)/collections/(\d+)") |
| 270 |
example = "https://www.artstation.com/USER/collections/12345" |
| 271 |
|
| 272 |
def __init__(self, match): |
| 273 |
ArtstationExtractor.__init__(self, match) |
| 274 |
self.collection_id = match[2] |
| 275 |
|
| 276 |
def metadata(self): |
| 277 |
url = f"{self.root}/collections/{self.collection_id}.json" |
| 278 |
params = {"username": self.user} |
| 279 |
collection = self.request_json( |
| 280 |
url, params=params, notfound=True) |
| 281 |
return {"collection": collection, "user": self.user} |
| 282 |
|
| 283 |
def projects(self): |
| 284 |
url = f"{self.root}/collections/{self.collection_id}/projects.json" |
| 285 |
params = {"collection_id": self.collection_id} |
| 286 |
return self._pagination(url, params) |
| 287 |
|
| 288 |
|
| 289 |
class ArtstationCollectionsExtractor(ArtstationExtractor): |
| 290 |
"""Extractor for an artstation user's collections""" |
| 291 |
subcategory = "collections" |
| 292 |
pattern = (r"(?:https?://)?(?:www\.)?artstation\.com" |
| 293 |
r"/(?!artwork|projects|search)([^/?#]+)/collections/?$") |
| 294 |
example = "https://www.artstation.com/USER/collections" |
| 295 |
|
| 296 |
def items(self): |
| 297 |
url = self.root + "/collections.json" |
| 298 |
params = {"username": self.user} |
| 299 |
|
| 300 |
for collection in self.request_json( |
| 301 |
url, params=params, notfound=True): |
| 302 |
url = f"{self.root}/{self.user}/collections/{collection['id']}" |
| 303 |
collection["_extractor"] = ArtstationCollectionExtractor |
| 304 |
yield Message.Queue, url, collection |
| 305 |
|
| 306 |
|
| 307 |
class ArtstationChallengeExtractor(ArtstationExtractor): |
| 308 |
"""Extractor for submissions of artstation challenges""" |
| 309 |
subcategory = "challenge" |
| 310 |
filename_fmt = "{submission_id}_{asset_id}_{filename}.{extension}" |
| 311 |
directory_fmt = ("{category}", "Challenges", |
| 312 |
"{challenge[id]} - {challenge[title]}") |
| 313 |
archive_fmt = "c_{challenge[id]}_{asset_id}" |
| 314 |
pattern = (r"(?:https?://)?(?:www\.)?artstation\.com" |
| 315 |
r"/c(?:hallenges|ontests)/[^/?#]+/c(?:ategori|halleng)es/(\d+)" |
| 316 |
r"/?(?:\?sorting=([a-z]+))?") |
| 317 |
example = "https://www.artstation.com/challenges/NAME/categories/12345" |
| 318 |
|
| 319 |
def __init__(self, match): |
| 320 |
ArtstationExtractor.__init__(self, match) |
| 321 |
self.challenge_id = match[1] |
| 322 |
self.sorting = match[2] or "popular" |
| 323 |
|
| 324 |
def items(self): |
| 325 |
base = self.root + "/api/v2/competition/" |
| 326 |
challenge_url = f"{base}challenges/{self.challenge_id}.json" |
| 327 |
submission_url = base + "submissions.json" |
| 328 |
|
| 329 |
challenge = self.request_json(challenge_url) |
| 330 |
yield Message.Directory, "", {"challenge": challenge} |
| 331 |
|
| 332 |
params = { |
| 333 |
"page" : 1, |
| 334 |
"per_page" : 50, |
| 335 |
"challenge_id": self.challenge_id, |
| 336 |
"sort_by" : self.sorting, |
| 337 |
} |
| 338 |
|
| 339 |
for submission in self._pagination(submission_url, params): |
| 340 |
update_url = (f"{base}submissions/{submission['id']}" |
| 341 |
f"/submission_updates.json") |
| 342 |
params = {"page": 1, "per_page": 50} |
| 343 |
for update in self._pagination(update_url, params=params): |
| 344 |
update["challenge"] = challenge |
| 345 |
for url in util.unique_sequence(text.extract_iter( |
| 346 |
update["body"], ' href="', '"')): |
| 347 |
update["asset_id"] = self._id_from_url(url) |
| 348 |
text.nameext_from_url(url, update) |
| 349 |
yield Message.Url, self._no_cache(url), update |
| 350 |
|
| 351 |
def _id_from_url(self, url): |
| 352 |
"""Get an image's submission ID from its URL""" |
| 353 |
parts = url.split("/") |
| 354 |
return text.parse_int("".join(parts[7:10])) |
| 355 |
|
| 356 |
|
| 357 |
class ArtstationSearchExtractor(ArtstationExtractor): |
| 358 |
"""Extractor for artstation search results""" |
| 359 |
subcategory = "search" |
| 360 |
directory_fmt = ("{category}", "Searches", "{search[query]}") |
| 361 |
archive_fmt = "s_{search[query]}_{asset[id]}" |
| 362 |
pattern = (r"(?:https?://)?(?:\w+\.)?artstation\.com" |
| 363 |
r"/search/?\?([^#]+)") |
| 364 |
example = "https://www.artstation.com/search?query=QUERY" |
| 365 |
|
| 366 |
def __init__(self, match): |
| 367 |
ArtstationExtractor.__init__(self, match) |
| 368 |
self.params = query = text.parse_query(match[1]) |
| 369 |
self.query = text.unquote(query.get("query") or query.get("q", "")) |
| 370 |
self.sorting = query.get("sort_by", "relevance").lower() |
| 371 |
self.tags = query.get("tags", "").split(",") |
| 372 |
|
| 373 |
def metadata(self): |
| 374 |
return {"search": { |
| 375 |
"query" : self.query, |
| 376 |
"sorting": self.sorting, |
| 377 |
"tags" : self.tags, |
| 378 |
}} |
| 379 |
|
| 380 |
def projects(self): |
| 381 |
filters = [] |
| 382 |
for key, value in self.params.items(): |
| 383 |
if key.endswith("_ids") or key == "tags": |
| 384 |
filters.append({ |
| 385 |
"field" : key, |
| 386 |
"method": "include", |
| 387 |
"value" : value.split(","), |
| 388 |
}) |
| 389 |
|
| 390 |
url = self.root + "/api/v2/search/projects.json" |
| 391 |
data = { |
| 392 |
"query" : self.query, |
| 393 |
"page" : None, |
| 394 |
"per_page" : 50, |
| 395 |
"sorting" : self.sorting, |
| 396 |
"pro_first" : ("1" if self.config("pro-first", True) else |
| 397 |
"0"), |
| 398 |
"filters" : filters, |
| 399 |
"additional_fields": (), |
| 400 |
} |
| 401 |
return self._pagination(url, json=data) |
| 402 |
|
| 403 |
|
| 404 |
class ArtstationArtworkExtractor(ArtstationExtractor): |
| 405 |
"""Extractor for projects on artstation's artwork page""" |
| 406 |
subcategory = "artwork" |
| 407 |
directory_fmt = ("{category}", "Artworks", "{artwork[sorting]!c}") |
| 408 |
archive_fmt = "A_{asset[id]}" |
| 409 |
pattern = (r"(?:https?://)?(?:\w+\.)?artstation\.com" |
| 410 |
r"/artwork/?\?([^#]+)") |
| 411 |
example = "https://www.artstation.com/artwork?sorting=SORT" |
| 412 |
|
| 413 |
def __init__(self, match): |
| 414 |
ArtstationExtractor.__init__(self, match) |
| 415 |
self.query = text.parse_query(match[1]) |
| 416 |
|
| 417 |
def metadata(self): |
| 418 |
return {"artwork": self.query} |
| 419 |
|
| 420 |
def projects(self): |
| 421 |
url = self.root + "/projects.json" |
| 422 |
return self._pagination(url, self.query.copy()) |
| 423 |
|
| 424 |
|
| 425 |
class ArtstationImageExtractor(ArtstationExtractor): |
| 426 |
"""Extractor for images from a single artstation project""" |
| 427 |
subcategory = "image" |
| 428 |
pattern = (r"(?:https?://)?(?:" |
| 429 |
r"(?:[\w-]+\.)?artstation\.com/(?:artwork|projects|search)" |
| 430 |
r"|artstn\.co/p)/(\w+)") |
| 431 |
example = "https://www.artstation.com/artwork/abcde" |
| 432 |
|
| 433 |
def __init__(self, match): |
| 434 |
ArtstationExtractor.__init__(self, match) |
| 435 |
self.project_id = match[1] |
| 436 |
self.assets = None |
| 437 |
|
| 438 |
def metadata(self): |
| 439 |
self.assets = list(ArtstationExtractor.get_project_assets( |
| 440 |
self, self.project_id)) |
| 441 |
try: |
| 442 |
self.user = self.assets[0]["user"]["username"] |
| 443 |
except IndexError: |
| 444 |
self.user = "" |
| 445 |
return ArtstationExtractor.metadata(self) |
| 446 |
|
| 447 |
def projects(self): |
| 448 |
return ({"hash_id": self.project_id},) |
| 449 |
|
| 450 |
def get_project_assets(self, project_id): |
| 451 |
return self.assets |
| 452 |
|
| 453 |
|
| 454 |
class ArtstationFollowingExtractor(ArtstationExtractor): |
| 455 |
"""Extractor for a user's followed users""" |
| 456 |
subcategory = "following" |
| 457 |
pattern = (r"(?:https?://)?(?:www\.)?artstation\.com" |
| 458 |
r"/(?!artwork|projects|search)([^/?#]+)/following") |
| 459 |
example = "https://www.artstation.com/USER/following" |
| 460 |
|
| 461 |
def items(self): |
| 462 |
url = f"{self.root}/users/{self.user}/following.json" |
| 463 |
for user in self._pagination(url): |
| 464 |
url = f"{self.root}/{user['username']}" |
| 465 |
user["_extractor"] = ArtstationUserExtractor |
| 466 |
yield Message.Queue, url, user |