Debian Codegraph @

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