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