Debian Codegraph @

gallery_dl/extractor/pinterest.py

raw symbols SCIP
1 # -*- coding: utf-8 -*-
2
3 # Copyright 2016-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.pinterest.com/"""
10
11 from .common import Extractor, Message
12 from .. import text, util
13 import itertools
14
15 BASE_PATTERN = r"(?:https?://)?(?:\w+\.)?pinterest\.[\w.]+"
16
17
18 class PinterestExtractor(Extractor):
19 """Base class for pinterest extractors"""
20 category = "pinterest"
21 filename_fmt = "{category}_{id}{media_id|page_id:?_//}.{extension}"
22 archive_fmt = "{id}{media_id|page_id}"
23 root = "https://www.pinterest.com"
24
25 def _init(self):
26 domain = self.config("domain")
27 if not domain or domain == "auto" :
28 self.root = text.root_from_url(self.url)
29 else:
30 self.root = text.ensure_http_scheme(domain)
31
32 self.api = PinterestAPI(self)
33 self.stories = self.config("stories", True)
34 self.videos = self.config("videos", True)
35
36 def items(self):
37 data = self.metadata()
38
39 for pin in self.pins():
40
41 if isinstance(pin, tuple):
42 url, data = pin
43 yield Message.Queue, url, data
44 continue
45
46 try:
47 files = self._extract_files(pin)
48 except Exception as exc:
49 self.log.traceback(exc)
50 self.log.warning(
51 "%s: Error when extracting download URLs (%s: %s)",
52 pin.get("id"), exc.__class__.__name__, exc)
53 continue
54
55 pin.update(data)
56 pin["count"] = len(files)
57
58 for key in (
59 "description",
60 "closeup_description",
61 "closeup_unified_description",
62 ):
63 if value := pin.get(key):
64 pin[key] = value.strip()
65
66 yield Message.Directory, "", pin
67 for pin["num"], file in enumerate(files, 1):
68 url = file["url"]
69 text.nameext_from_url(url, pin)
70 pin.update(file)
71
72 if "media_id" not in file:
73 pin["media_id"] = ""
74 if "page_id" not in file:
75 pin["page_id"] = ""
76
77 if pin["extension"] == "m3u8":
78 url = "ytdl:" + url
79 pin["_ytdl_manifest"] = "hls"
80 pin["extension"] = "mp4"
81
82 yield Message.Url, url, pin
83
84 def metadata(self):
85 """Return general metadata"""
86
87 def pins(self):
88 """Return all relevant pin objects"""
89
90 def _extract_files(self, pin):
91 story_pin_data = pin.get("story_pin_data")
92 if story_pin_data and self.stories:
93 return self._extract_story(pin, story_pin_data)
94
95 if carousel_data := pin.get("carousel_data"):
96 return self._extract_carousel(pin, carousel_data)
97
98 videos = pin.get("videos")
99 if videos and self.videos:
100 return (self._extract_video(videos),)
101
102 try:
103 return (pin["images"]["orig"],)
104 except Exception:
105 self.log.debug("%s: No files found", pin.get("id"))
106 return ()
107
108 def _extract_story(self, pin, story):
109 files = []
110 story_id = story.get("id")
111
112 for page in story["pages"]:
113 page_id = page.get("id")
114
115 for block in page["blocks"]:
116 type = block.get("type")
117
118 if type == "story_pin_image_block":
119 if 1 == len(page["blocks"]) == len(story["pages"]):
120 try:
121 media = pin["images"]["orig"]
122 except Exception:
123 media = self._extract_image(page, block)
124 else:
125 media = self._extract_image(page, block)
126
127 elif type == "story_pin_video_block" or "video" in block:
128 video = block["video"]
129 media = self._extract_video(video)
130 media["media_id"] = video.get("id") or ""
131
132 elif type == "story_pin_music_block" or "audio" in block:
133 media = block["audio"]
134 media["url"] = media["audio_url"]
135 media["media_id"] = media.get("id") or ""
136
137 elif type == "story_pin_paragraph_block":
138 media = {"url": "text:" + block["text"],
139 "extension": "txt",
140 "media_id": block.get("id")}
141
142 elif type == "story_pin_product_sticker_block":
143 continue
144
145 elif type == "story_pin_static_sticker_block":
146 continue
147
148 else:
149 self.log.warning("%s: Unsupported story block '%s'",
150 pin.get("id"), type)
151 try:
152 media = self._extract_image(page, block)
153 except Exception:
154 continue
155
156 media["story_id"] = story_id
157 media["page_id"] = page_id
158 files.append(media)
159
160 return files
161
162 def _extract_carousel(self, pin, carousel_data):
163 files = []
164 for slot in carousel_data["carousel_slots"]:
165 size, image = next(iter(slot["images"].items()))
166 slot["media_id"] = slot.pop("id")
167 slot["url"] = image["url"].replace(
168 "/" + size + "/", "/originals/", 1)
169 files.append(slot)
170 return files
171
172 def _extract_image(self, page, block):
173 sig = block.get("image_signature") or page["image_signature"]
174 url_base = (f"https://i.pinimg.com/originals"
175 f"/{sig[0:2]}/{sig[2:4]}/{sig[4:6]}/{sig}.")
176 url_jpg = url_base + "jpg"
177 url_png = url_base + "png"
178 url_webp = url_base + "webp"
179
180 try:
181 media = block["image"]["images"]["originals"]
182 except Exception:
183 media = {"url": url_jpg, "_fallback": (url_png, url_webp,)}
184
185 if media["url"] == url_jpg:
186 media["_fallback"] = (url_png, url_webp,)
187 else:
188 media["_fallback"] = (url_jpg, url_png, url_webp,)
189 media["media_id"] = sig
190
191 return media
192
193 def _extract_video(self, video):
194 video_formats = video["video_list"]
195 for fmt in ("V_HLSV4", "V_HLSV3_WEB", "V_HLSV3_MOBILE"):
196 if fmt in video_formats:
197 media = video_formats[fmt]
198 break
199 else:
200 media = max(video_formats.values(),
201 key=lambda x: x.get("width", 0))
202 if "V_720P" in video_formats:
203 media["_fallback"] = (video_formats["V_720P"]["url"],)
204 return media
205
206
207 class PinterestUserExtractor(PinterestExtractor):
208 """Extractor for a user's boards"""
209 subcategory = "user"
210 pattern = BASE_PATTERN + r"/(?!pin/)([^/?#]+)(?:/_saved)?/?$"
211 example = "https://www.pinterest.com/USER/"
212
213 def __init__(self, match):
214 PinterestExtractor.__init__(self, match)
215 self.user = text.unquote(match[1])
216
217 def items(self):
218 for board in self.api.boards(self.user):
219 if url := board.get("url"):
220 board["_extractor"] = PinterestBoardExtractor
221 yield Message.Queue, self.root + url, board
222
223
224 class PinterestAllpinsExtractor(PinterestExtractor):
225 """Extractor for a user's 'All Pins' feed"""
226 subcategory = "allpins"
227 directory_fmt = ("{category}", "{user}")
228 pattern = BASE_PATTERN + r"/(?!pin/)([^/?#]+)/pins/?$"
229 example = "https://www.pinterest.com/USER/pins/"
230
231 def __init__(self, match):
232 PinterestExtractor.__init__(self, match)
233 self.user = text.unquote(match[1])
234
235 def metadata(self):
236 return {"user": self.user}
237
238 def pins(self):
239 return self.api.user_pins(self.user)
240
241
242 class PinterestCreatedExtractor(PinterestExtractor):
243 """Extractor for a user's created pins"""
244 subcategory = "created"
245 directory_fmt = ("{category}", "{user}")
246 pattern = BASE_PATTERN + r"/(?!pin/)([^/?#]+)/_created/?$"
247 example = "https://www.pinterest.com/USER/_created/"
248
249 def __init__(self, match):
250 PinterestExtractor.__init__(self, match)
251 self.user = text.unquote(match[1])
252
253 def metadata(self):
254 return {"user": self.user}
255
256 def pins(self):
257 return self.api.user_activity_pins(self.user)
258
259
260 class PinterestSectionExtractor(PinterestExtractor):
261 """Extractor for board sections on pinterest.com"""
262 subcategory = "section"
263 directory_fmt = ("{category}", "{board[owner][username]}",
264 "{board[name]}", "{section[title]}")
265 archive_fmt = "{board[id]}_{id}"
266 pattern = BASE_PATTERN + r"/(?!pin/)([^/?#]+)/([^/?#]+)/([^/?#]+)"
267 example = "https://www.pinterest.com/USER/BOARD/SECTION"
268
269 def __init__(self, match):
270 PinterestExtractor.__init__(self, match)
271 self.user = text.unquote(match[1])
272 self.board_slug = text.unquote(match[2])
273 self.section_slug = text.unquote(match[3])
274 self.section = None
275
276 def metadata(self):
277 if self.section_slug.startswith("id:"):
278 section = self.section = self.api.board_section(
279 self.section_slug[3:])
280 else:
281 section = self.section = self.api.board_section_by_name(
282 self.user, self.board_slug, self.section_slug)
283 section.pop("preview_pins", None)
284 return {"board": section.pop("board"), "section": section}
285
286 def pins(self):
287 return self.api.board_section_pins(self.section["id"])
288
289
290 class PinterestSearchExtractor(PinterestExtractor):
291 """Extractor for Pinterest search results"""
292 subcategory = "search"
293 directory_fmt = ("{category}", "Search", "{search}")
294 pattern = BASE_PATTERN + r"/search/pins/?\?q=([^&#]+)"
295 example = "https://www.pinterest.com/search/pins/?q=QUERY"
296
297 def __init__(self, match):
298 PinterestExtractor.__init__(self, match)
299 self.search = text.unquote(match[1])
300
301 def metadata(self):
302 return {"search": self.search}
303
304 def pins(self):
305 return self.api.search(self.search)
306
307
308 class PinterestPinExtractor(PinterestExtractor):
309 """Extractor for images from a single pin from pinterest.com"""
310 subcategory = "pin"
311 pattern = BASE_PATTERN + r"/pin/([^/?#]+)(?!.*#related$)"
312 example = "https://www.pinterest.com/pin/12345/"
313
314 def __init__(self, match):
315 PinterestExtractor.__init__(self, match)
316 self.pin_id = match[1]
317 self.pin = None
318
319 def metadata(self):
320 self.pin = self.api.pin(self.pin_id)
321 return self.pin
322
323 def pins(self):
324 return (self.pin,)
325
326
327 class PinterestBoardExtractor(PinterestExtractor):
328 """Extractor for images from a board from pinterest.com"""
329 subcategory = "board"
330 directory_fmt = ("{category}", "{board[owner][username]}", "{board[name]}")
331 archive_fmt = "{board[id]}_{id}"
332 pattern = (BASE_PATTERN + r"/(?!pin/)([^/?#]+)"
333 r"/([^/?#]+)/?(?!.*#related$)")
334 example = "https://www.pinterest.com/USER/BOARD/"
335
336 def __init__(self, match):
337 PinterestExtractor.__init__(self, match)
338 self.user = text.unquote(match[1])
339 self.board_name = text.unquote(match[2])
340 self.board = None
341
342 def metadata(self):
343 self.board = self.api.board(self.user, self.board_name)
344 return {"board": self.board}
345
346 def pins(self):
347 board = self.board
348 pins = self.api.board_pins(board["id"])
349
350 if board["section_count"] and self.config("sections", True):
351 base = f"{self.root}{board['url']}id:"
352 data = {"_extractor": PinterestSectionExtractor}
353 sections = [(base + section["id"], data)
354 for section in self.api.board_sections(board["id"])]
355 pins = itertools.chain(pins, sections)
356
357 return pins
358
359
360 class PinterestRelatedPinExtractor(PinterestPinExtractor):
361 """Extractor for related pins of another pin from pinterest.com"""
362 subcategory = "related-pin"
363 directory_fmt = ("{category}", "related {original_pin[id]}")
364 pattern = BASE_PATTERN + r"/pin/([^/?#]+).*#related$"
365 example = "https://www.pinterest.com/pin/12345/#related"
366
367 def metadata(self):
368 return {"original_pin": self.api.pin(self.pin_id)}
369
370 def pins(self):
371 return self.api.pin_related(self.pin_id)
372
373
374 class PinterestRelatedBoardExtractor(PinterestBoardExtractor):
375 """Extractor for related pins of a board from pinterest.com"""
376 subcategory = "related-board"
377 directory_fmt = ("{category}", "{board[owner][username]}",
378 "{board[name]}", "related")
379 pattern = BASE_PATTERN + r"/(?!pin/)([^/?#]+)/([^/?#]+)/?#related$"
380 example = "https://www.pinterest.com/USER/BOARD/#related"
381
382 def pins(self):
383 return self.api.board_content_recommendation(self.board["id"])
384
385
386 class PinterestPinitExtractor(PinterestExtractor):
387 """Extractor for images from a pin.it URL"""
388 subcategory = "pinit"
389 pattern = r"(?:https?://)?pin\.it/([^/?#]+)"
390 example = "https://pin.it/abcde"
391
392 def items(self):
393 url = (f"https://api.pinterest.com/url_shortener"
394 f"/{self.groups[0]}/redirect/")
395 location = self.request_location(url)
396 if not location:
397 raise self.exc.NotFoundError("pin")
398 elif PinterestPinExtractor.pattern.match(location):
399 yield Message.Queue, location, {
400 "_extractor": PinterestPinExtractor}
401 elif PinterestBoardExtractor.pattern.match(location):
402 yield Message.Queue, location, {
403 "_extractor": PinterestBoardExtractor}
404 else:
405 raise self.exc.NotFoundError("pin")
406
407
408 class PinterestAPI():
409 """Minimal interface for the Pinterest Web API
410
411 For a better and more complete implementation in PHP, see
412 - https://github.com/seregazhuk/php-pinterest-bot
413 """
414
415 def __init__(self, extractor):
416 csrf_token = util.generate_token()
417
418 self.extractor = extractor
419 self.root = extractor.root
420 self.cookies = {"csrftoken": csrf_token}
421 self.headers = {
422 "Accept" : "application/json, text/javascript, "
423 "*/*, q=0.01",
424 "X-Requested-With" : "XMLHttpRequest",
425 "X-APP-VERSION" : "a89153f",
426 "X-Pinterest-AppState" : "active",
427 "X-Pinterest-Source-Url" : None,
428 "X-Pinterest-PWS-Handler": "www/[username].js",
429 "Alt-Used" : "www.pinterest.com",
430 "Connection" : "keep-alive",
431 "Cookie" : None,
432 "Sec-Fetch-Dest" : "empty",
433 "Sec-Fetch-Mode" : "cors",
434 "Sec-Fetch-Site" : "same-origin",
435 }
436
437 def pin(self, pin_id):
438 """Query information about a pin"""
439 options = {"id": pin_id, "field_set_key": "detailed"}
440 return self._call("Pin", options)["resource_response"]["data"]
441
442 def pin_related(self, pin_id):
443 """Yield related pins of another pin"""
444 options = {"pin": pin_id, "add_vase": True, "pins_only": True}
445 return self._pagination("RelatedPinFeed", options)
446
447 def board(self, user, board_name):
448 """Query information about a board"""
449 options = {"slug": board_name, "username": user,
450 "field_set_key": "detailed"}
451 return self._call("Board", options)["resource_response"]["data"]
452
453 def boards(self, user):
454 """Yield all boards from 'user'"""
455 options = {
456 "sort" : "last_pinned_to",
457 "field_set_key" : "profile_grid_item",
458 "filter_stories" : False,
459 "username" : user,
460 "page_size" : 25,
461 "include_archived": True,
462 }
463 return self._pagination("Boards", options)
464
465 def board_pins(self, board_id):
466 """Yield all pins of a specific board"""
467 options = {
468 "board_id": board_id,
469 "field_set_key": "react_grid_pin",
470 "prepend": False,
471 "bookmarks": None,
472 }
473 return self._pagination("BoardFeed", options)
474
475 def board_section(self, section_id):
476 """Yield a specific board section"""
477 options = {"section_id": section_id}
478 return self._call("BoardSection", options)["resource_response"]["data"]
479
480 def board_section_by_name(self, user, board_slug, section_slug):
481 """Yield a board section by name"""
482 options = {"board_slug": board_slug, "section_slug": section_slug,
483 "username": user}
484 return self._call("BoardSection", options)["resource_response"]["data"]
485
486 def board_sections(self, board_id):
487 """Yield all sections of a specific board"""
488 options = {"board_id": board_id}
489 return self._pagination("BoardSections", options)
490
491 def board_section_pins(self, section_id):
492 """Yield all pins from a board section"""
493 options = {"section_id": section_id}
494 return self._pagination("BoardSectionPins", options)
495
496 def board_content_recommendation(self, board_id):
497 """Yield related pins of a specific board"""
498 options = {"id": board_id, "type": "board", "add_vase": True}
499 return self._pagination("BoardContentRecommendation", options)
500
501 def user_pins(self, user):
502 """Yield all pins from 'user'"""
503 options = {
504 "is_own_profile_pins": False,
505 "username" : user,
506 "field_set_key" : "grid_item",
507 "pin_filter" : None,
508 }
509 return self._pagination("UserPins", options)
510
511 def user_activity_pins(self, user):
512 """Yield pins created by 'user'"""
513 options = {
514 "exclude_add_pin_rep": True,
515 "field_set_key" : "grid_item",
516 "is_own_profile_pins": False,
517 "username" : user,
518 }
519 return self._pagination("UserActivityPins", options)
520
521 def search(self, query):
522 """Yield pins from searches"""
523 options = {"query": query, "scope": "pins", "rs": "typed"}
524 return self._pagination("BaseSearch", options)
525
526 def _call(self, resource, options):
527 url = f"{self.root}/resource/{resource}Resource/get/"
528 params = {
529 "data" : util.json_dumps({"options": options}),
530 "source_url": "",
531 }
532
533 response = self.extractor.request(
534 url, params=params, headers=self.headers,
535 cookies=self.cookies, fatal=False)
536
537 try:
538 data = response.json()
539 except ValueError:
540 data = {}
541
542 if response.history:
543 self.root = text.root_from_url(response.url)
544 if response.status_code < 400:
545 return data
546 if response.status_code == 404:
547 resource = self.extractor.subcategory.rpartition("-")[2]
548 raise self.extractor.exc.NotFoundError(resource)
549 self.extractor.log.debug("Server response: %s", response.text)
550 raise self.extractor.exc.AbortExtraction("API request failed")
551
552 def _pagination(self, resource, options):
553 while True:
554 data = self._call(resource, options)
555 results = data["resource_response"]["data"]
556 if isinstance(results, dict):
557 results = results["results"]
558 yield from results
559
560 try:
561 bookmarks = data["resource"]["options"]["bookmarks"]
562 if (not bookmarks or bookmarks[0] == "-end-" or
563 bookmarks[0].startswith("Y2JOb25lO")):
564 return
565 options["bookmarks"] = bookmarks
566 except KeyError:
567 return