| 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.behance.net/""" |
| 10 |
|
| 11 |
from .common import Extractor, Message |
| 12 |
from .. import text, util |
| 13 |
|
| 14 |
|
| 15 |
class BehanceExtractor(Extractor): |
| 16 |
"""Base class for behance extractors""" |
| 17 |
category = "behance" |
| 18 |
root = "https://www.behance.net" |
| 19 |
request_interval = (2.0, 4.0) |
| 20 |
browser = "firefox" |
| 21 |
tls12 = False |
| 22 |
|
| 23 |
def _init(self): |
| 24 |
self._bcp = self.cookies.get("bcp", domain="www.behance.net") |
| 25 |
if not self._bcp: |
| 26 |
self._bcp = "4c34489d-914c-46cd-b44c-dfd0e661136d" |
| 27 |
self.cookies.set("bcp", self._bcp, domain="www.behance.net") |
| 28 |
|
| 29 |
def items(self): |
| 30 |
for gallery in self.galleries(): |
| 31 |
gallery["_extractor"] = BehanceGalleryExtractor |
| 32 |
yield Message.Queue, gallery["url"], self._update(gallery) |
| 33 |
|
| 34 |
def galleries(self): |
| 35 |
"""Return all relevant gallery URLs""" |
| 36 |
|
| 37 |
def _request_graphql(self, endpoint, variables): |
| 38 |
url = self.root + "/v3/graphql" |
| 39 |
headers = { |
| 40 |
"X-BCP" : self._bcp, |
| 41 |
"X-Requested-With": "XMLHttpRequest", |
| 42 |
} |
| 43 |
data = { |
| 44 |
"query" : self.utils("graphql", endpoint), |
| 45 |
"variables": variables, |
| 46 |
} |
| 47 |
|
| 48 |
return self.request_json( |
| 49 |
url, method="POST", headers=headers, json=data)["data"] |
| 50 |
|
| 51 |
def _update(self, data): |
| 52 |
# compress data to simple lists |
| 53 |
if (fields := data.get("fields")) and isinstance(fields[0], dict): |
| 54 |
data["fields"] = [ |
| 55 |
field.get("name") or field.get("label") |
| 56 |
for field in fields |
| 57 |
] |
| 58 |
|
| 59 |
data["owners"] = [ |
| 60 |
owner.get("display_name") or owner.get("displayName") |
| 61 |
for owner in data["owners"] |
| 62 |
] |
| 63 |
|
| 64 |
tags = data.get("tags") or () |
| 65 |
if tags and isinstance(tags[0], dict): |
| 66 |
tags = [tag["title"] for tag in tags] |
| 67 |
data["tags"] = tags |
| 68 |
|
| 69 |
data["date"] = self.parse_timestamp( |
| 70 |
data.get("publishedOn") or data.get("conceived_on") or 0) |
| 71 |
|
| 72 |
if creator := data.get("creator"): |
| 73 |
creator["name"] = creator["url"].rpartition("/")[2] |
| 74 |
|
| 75 |
# backwards compatibility |
| 76 |
data["gallery_id"] = data["id"] |
| 77 |
data["title"] = data["name"] |
| 78 |
data["user"] = ", ".join(data["owners"]) |
| 79 |
|
| 80 |
return data |
| 81 |
|
| 82 |
|
| 83 |
class BehanceGalleryExtractor(BehanceExtractor): |
| 84 |
"""Extractor for image galleries from www.behance.net""" |
| 85 |
subcategory = "gallery" |
| 86 |
directory_fmt = ("{category}", "{owners:J, }", "{id} {name}") |
| 87 |
filename_fmt = "{category}_{id}_{num:>02}.{extension}" |
| 88 |
archive_fmt = "{id}_{num}" |
| 89 |
pattern = r"(?:https?://)?(?:www\.)?behance\.net/gallery/(\d+)" |
| 90 |
example = "https://www.behance.net/gallery/12345/TITLE" |
| 91 |
|
| 92 |
def __init__(self, match): |
| 93 |
BehanceExtractor.__init__(self, match) |
| 94 |
self.gallery_id = match[1] |
| 95 |
|
| 96 |
def _init(self): |
| 97 |
BehanceExtractor._init(self) |
| 98 |
|
| 99 |
if modules := self.config("modules"): |
| 100 |
if isinstance(modules, str): |
| 101 |
modules = modules.split(",") |
| 102 |
self.modules = set(modules) |
| 103 |
else: |
| 104 |
self.modules = {"image", "video", "mediacollection", "embed"} |
| 105 |
|
| 106 |
def items(self): |
| 107 |
data = self.get_gallery_data() |
| 108 |
imgs = self.get_images(data) |
| 109 |
data["count"] = len(imgs) |
| 110 |
|
| 111 |
yield Message.Directory, "", data |
| 112 |
for data["num"], (url, module) in enumerate(imgs, 1): |
| 113 |
data["module"] = module |
| 114 |
data["extension"] = (module.get("extension") or |
| 115 |
text.ext_from_url(url)) |
| 116 |
yield Message.Url, url, data |
| 117 |
|
| 118 |
def get_gallery_data(self): |
| 119 |
"""Collect gallery info dict""" |
| 120 |
url = f"{self.root}/gallery/{self.gallery_id}/a" |
| 121 |
cookies = { |
| 122 |
"gk_suid": "14118261", |
| 123 |
"gki": "feature_3_in_1_checkout_test:false,hire_browse_get_quote_c" |
| 124 |
"ta_ab_test:false,feature_hire_dashboard_services_ab_test:f" |
| 125 |
"alse,feature_show_details_jobs_row_ab_test:false,feature_a" |
| 126 |
"i_freelance_project_create_flow:false,", |
| 127 |
"ilo0": "true", |
| 128 |
"originalReferrer": "", |
| 129 |
} |
| 130 |
page = self.request(url, cookies=cookies).text |
| 131 |
|
| 132 |
data = util.json_loads(text.extr( |
| 133 |
page, 'id="beconfig-store_state">', '</script>')) |
| 134 |
return self._update(data["project"]["project"]) |
| 135 |
|
| 136 |
def get_images(self, data): |
| 137 |
"""Extract image results from an API response""" |
| 138 |
if not data["modules"]: |
| 139 |
access = data.get("matureAccess") |
| 140 |
if access == "logged-out": |
| 141 |
raise self.exc.AuthorizationError( |
| 142 |
"Mature content galleries require logged-in cookies") |
| 143 |
if access == "restricted-safe": |
| 144 |
raise self.exc.AuthorizationError( |
| 145 |
"Mature content blocked in account settings") |
| 146 |
if access and access != "allowed": |
| 147 |
raise self.exc.AuthorizationError() |
| 148 |
return () |
| 149 |
|
| 150 |
results = [] |
| 151 |
for module in data["modules"]: |
| 152 |
mtype = module["__typename"][:-6].lower() |
| 153 |
|
| 154 |
if mtype not in self.modules: |
| 155 |
self.log.debug("Skipping '%s' module", mtype) |
| 156 |
continue |
| 157 |
|
| 158 |
if mtype == "image": |
| 159 |
sizes = { |
| 160 |
size["url"].rsplit("/", 2)[1]: size |
| 161 |
for size in module["imageSizes"]["allAvailable"] |
| 162 |
} |
| 163 |
size = (sizes.get("source") or |
| 164 |
sizes.get("max_3840") or |
| 165 |
sizes.get("fs") or |
| 166 |
sizes.get("hd") or |
| 167 |
sizes.get("disp")) |
| 168 |
results.append((size["url"], module)) |
| 169 |
|
| 170 |
elif mtype == "video": |
| 171 |
try: |
| 172 |
url = text.extr(module["embed"], 'src="', '"') |
| 173 |
page = self.request(text.unescape(url)).text |
| 174 |
|
| 175 |
url = text.extr(page, '<source src="', '"') |
| 176 |
if text.ext_from_url(url) == "m3u8": |
| 177 |
url = "ytdl:" + url |
| 178 |
module["_ytdl_manifest"] = "hls" |
| 179 |
module["extension"] = "mp4" |
| 180 |
results.append((url, module)) |
| 181 |
continue |
| 182 |
except Exception as exc: |
| 183 |
self.log.debug("%s: %s", exc.__class__.__name__, exc) |
| 184 |
|
| 185 |
try: |
| 186 |
renditions = module["videoData"]["renditions"] |
| 187 |
except Exception: |
| 188 |
self.log.warning("No download URLs for video %s", |
| 189 |
module.get("id") or "???") |
| 190 |
continue |
| 191 |
|
| 192 |
try: |
| 193 |
url = [ |
| 194 |
r["url"] for r in renditions |
| 195 |
if text.ext_from_url(r["url"]) != "m3u8" |
| 196 |
][-1] |
| 197 |
except Exception as exc: |
| 198 |
self.log.debug("%s: %s", exc.__class__.__name__, exc) |
| 199 |
url = "ytdl:" + renditions[-1]["url"] |
| 200 |
|
| 201 |
results.append((url, module)) |
| 202 |
|
| 203 |
elif mtype == "mediacollection": |
| 204 |
for component in module["components"]: |
| 205 |
for size in component["imageSizes"].values(): |
| 206 |
if size: |
| 207 |
parts = size["url"].split("/") |
| 208 |
parts[4] = "source" |
| 209 |
results.append(("/".join(parts), module)) |
| 210 |
break |
| 211 |
|
| 212 |
elif mtype == "embed": |
| 213 |
if embed := (module.get("originalEmbed") or |
| 214 |
module.get("fluidEmbed")): |
| 215 |
embed = text.unescape(text.extr(embed, 'src="', '"')) |
| 216 |
module["extension"] = "mp4" |
| 217 |
results.append(("ytdl:" + embed, module)) |
| 218 |
|
| 219 |
elif mtype == "text": |
| 220 |
module["extension"] = "txt" |
| 221 |
results.append(("text:" + module["text"], module)) |
| 222 |
|
| 223 |
return results |
| 224 |
|
| 225 |
|
| 226 |
class BehanceUserExtractor(BehanceExtractor): |
| 227 |
"""Extractor for a user's galleries from www.behance.net""" |
| 228 |
subcategory = "user" |
| 229 |
categorytransfer = True |
| 230 |
pattern = r"(?:https?://)?(?:www\.)?behance\.net/([^/?#]+)/?$" |
| 231 |
example = "https://www.behance.net/USER" |
| 232 |
|
| 233 |
def __init__(self, match): |
| 234 |
BehanceExtractor.__init__(self, match) |
| 235 |
self.user = match[1] |
| 236 |
|
| 237 |
def galleries(self): |
| 238 |
endpoint = "GetProfileProjects" |
| 239 |
variables = { |
| 240 |
"username": self.user, |
| 241 |
"after" : "MAo=", # "0" in base64 |
| 242 |
} |
| 243 |
|
| 244 |
while True: |
| 245 |
data = self._request_graphql(endpoint, variables) |
| 246 |
items = data["user"]["profileProjects"] |
| 247 |
yield from items["nodes"] |
| 248 |
|
| 249 |
if not items["pageInfo"]["hasNextPage"]: |
| 250 |
return |
| 251 |
variables["after"] = items["pageInfo"]["endCursor"] |
| 252 |
|
| 253 |
|
| 254 |
class BehanceCollectionExtractor(BehanceExtractor): |
| 255 |
"""Extractor for a collection's galleries from www.behance.net""" |
| 256 |
subcategory = "collection" |
| 257 |
categorytransfer = True |
| 258 |
pattern = r"(?:https?://)?(?:www\.)?behance\.net/collection/(\d+)" |
| 259 |
example = "https://www.behance.net/collection/12345/TITLE" |
| 260 |
|
| 261 |
def __init__(self, match): |
| 262 |
BehanceExtractor.__init__(self, match) |
| 263 |
self.collection_id = match[1] |
| 264 |
|
| 265 |
def galleries(self): |
| 266 |
endpoint = "GetMoodboardItemsAndRecommendations" |
| 267 |
variables = { |
| 268 |
"afterItem": "MAo=", # "0" in base64 |
| 269 |
"firstItem": 40, |
| 270 |
"id" : int(self.collection_id), |
| 271 |
"shouldGetItems" : True, |
| 272 |
"shouldGetMoodboardFields": False, |
| 273 |
"shouldGetRecommendations": False, |
| 274 |
} |
| 275 |
|
| 276 |
while True: |
| 277 |
data = self._request_graphql(endpoint, variables) |
| 278 |
items = data["moodboard"]["items"] |
| 279 |
|
| 280 |
for node in items["nodes"]: |
| 281 |
yield node["entity"] |
| 282 |
|
| 283 |
if not items["pageInfo"]["hasNextPage"]: |
| 284 |
return |
| 285 |
variables["afterItem"] = items["pageInfo"]["endCursor"] |