[cleanup] Misc (#8968)
[yt-dlp.git] / yt_dlp / extractor / pinterest.py
blob8361fbbc5f1bcf9be8012cc30076e1b59f8ed1da
1 import json
3 from .common import InfoExtractor
4 from ..utils import (
5 determine_ext,
6 float_or_none,
7 int_or_none,
8 str_or_none,
9 strip_or_none,
10 traverse_obj,
11 unified_timestamp,
12 url_or_none,
16 class PinterestBaseIE(InfoExtractor):
17 _VALID_URL_BASE = r'''(?x)
18 https?://(?:[^/]+\.)?pinterest\.(?:
19 com|fr|de|ch|jp|cl|ca|it|co\.uk|nz|ru|com\.au|at|pt|co\.kr|es|com\.mx|
20 dk|ph|th|com\.uy|co|nl|info|kr|ie|vn|com\.vn|ec|mx|in|pe|co\.at|hu|
21 co\.in|co\.nz|id|com\.ec|com\.py|tw|be|uk|com\.bo|com\.pe)'''
23 def _call_api(self, resource, video_id, options):
24 return self._download_json(
25 'https://www.pinterest.com/resource/%sResource/get/' % resource,
26 video_id, 'Download %s JSON metadata' % resource, query={
27 'data': json.dumps({'options': options})
28 })['resource_response']
30 def _extract_video(self, data, extract_formats=True):
31 video_id = data['id']
32 thumbnails = []
33 images = data.get('images')
34 if isinstance(images, dict):
35 for thumbnail_id, thumbnail in images.items():
36 if not isinstance(thumbnail, dict):
37 continue
38 thumbnail_url = url_or_none(thumbnail.get('url'))
39 if not thumbnail_url:
40 continue
41 thumbnails.append({
42 'url': thumbnail_url,
43 'width': int_or_none(thumbnail.get('width')),
44 'height': int_or_none(thumbnail.get('height')),
47 info = {
48 'title': strip_or_none(traverse_obj(data, 'title', 'grid_title', default='')),
49 'description': traverse_obj(data, 'seo_description', 'description'),
50 'timestamp': unified_timestamp(data.get('created_at')),
51 'thumbnails': thumbnails,
52 'uploader': traverse_obj(data, ('closeup_attribution', 'full_name')),
53 'uploader_id': str_or_none(traverse_obj(data, ('closeup_attribution', 'id'))),
54 'repost_count': int_or_none(data.get('repin_count')),
55 'comment_count': int_or_none(data.get('comment_count')),
56 'categories': traverse_obj(data, ('pin_join', 'visual_annotation'), expected_type=list),
57 'tags': traverse_obj(data, 'hashtags', expected_type=list),
60 urls = []
61 formats = []
62 duration = None
63 domain = data.get('domain', '')
64 if domain.lower() != 'uploaded by user' and traverse_obj(data, ('embed', 'src')):
65 if not info['title']:
66 info['title'] = None
67 return {
68 '_type': 'url_transparent',
69 'url': data['embed']['src'],
70 **info,
73 elif extract_formats:
74 video_list = traverse_obj(
75 data, ('videos', 'video_list'),
76 ('story_pin_data', 'pages', ..., 'blocks', ..., 'video', 'video_list'),
77 expected_type=dict, get_all=False, default={})
78 for format_id, format_dict in video_list.items():
79 if not isinstance(format_dict, dict):
80 continue
81 format_url = url_or_none(format_dict.get('url'))
82 if not format_url or format_url in urls:
83 continue
84 urls.append(format_url)
85 duration = float_or_none(format_dict.get('duration'), scale=1000)
86 ext = determine_ext(format_url)
87 if 'hls' in format_id.lower() or ext == 'm3u8':
88 formats.extend(self._extract_m3u8_formats(
89 format_url, video_id, 'mp4', entry_protocol='m3u8_native',
90 m3u8_id=format_id, fatal=False))
91 else:
92 formats.append({
93 'url': format_url,
94 'format_id': format_id,
95 'width': int_or_none(format_dict.get('width')),
96 'height': int_or_none(format_dict.get('height')),
97 'duration': duration,
100 return {
101 'id': video_id,
102 'formats': formats,
103 'duration': duration,
104 'webpage_url': f'https://www.pinterest.com/pin/{video_id}/',
105 'extractor_key': PinterestIE.ie_key(),
106 'extractor': PinterestIE.IE_NAME,
107 **info,
111 class PinterestIE(PinterestBaseIE):
112 _VALID_URL = r'%s/pin/(?P<id>\d+)' % PinterestBaseIE._VALID_URL_BASE
113 _TESTS = [{
114 # formats found in data['videos']
115 'url': 'https://www.pinterest.com/pin/664281013778109217/',
116 'md5': '6550c2af85d6d9f3fe3b88954d1577fc',
117 'info_dict': {
118 'id': '664281013778109217',
119 'ext': 'mp4',
120 'title': 'Origami',
121 'description': 'md5:e29801cab7d741ea8c741bc50c8d00ab',
122 'duration': 57.7,
123 'timestamp': 1593073622,
124 'upload_date': '20200625',
125 'repost_count': int,
126 'comment_count': int,
127 'categories': list,
128 'tags': list,
129 'thumbnail': r're:^https?://.*\.(?:jpg|png)$',
131 }, {
132 # formats found in data['story_pin_data']
133 'url': 'https://www.pinterest.com/pin/1084663891475263837/',
134 'md5': '069ac19919ab9e1e13fa60de46290b03',
135 'info_dict': {
136 'id': '1084663891475263837',
137 'ext': 'mp4',
138 'title': 'Gadget, Cool products, Amazon product, technology, Kitchen gadgets',
139 'description': 'md5:d0a4b6ae996ff0c6eed83bc869598d13',
140 'uploader': 'CoolCrazyGadgets',
141 'uploader_id': '1084664028912989237',
142 'upload_date': '20211003',
143 'timestamp': 1633246654.0,
144 'duration': 14.9,
145 'comment_count': int,
146 'repost_count': int,
147 'categories': 'count:9',
148 'tags': list,
149 'thumbnail': r're:^https?://.*\.(?:jpg|png)$',
151 }, {
152 # vimeo.com embed
153 'url': 'https://www.pinterest.ca/pin/441282463481903715/',
154 'info_dict': {
155 'id': '111691128',
156 'ext': 'mp4',
157 'title': 'Tonite Let\'s All Make Love In London (1967)',
158 'description': 'md5:8190f37b3926807809ec57ec21aa77b2',
159 'uploader': 'Vimeo',
160 'uploader_id': '473792960706651251',
161 'upload_date': '20180120',
162 'timestamp': 1516409040,
163 'duration': 3404,
164 'comment_count': int,
165 'repost_count': int,
166 'categories': 'count:9',
167 'tags': [],
168 'thumbnail': r're:^https?://.*\.(?:jpg|png)$',
169 'uploader_url': 'https://vimeo.com/willardandrade',
171 'params': {
172 'skip_download': 'm3u8',
174 }, {
175 'url': 'https://co.pinterest.com/pin/824721750502199491/',
176 'only_matching': True,
179 def _real_extract(self, url):
180 video_id = self._match_id(url)
181 data = self._call_api(
182 'Pin', video_id, {
183 'field_set_key': 'unauth_react_main_pin',
184 'id': video_id,
185 })['data']
186 return self._extract_video(data)
189 class PinterestCollectionIE(PinterestBaseIE):
190 _VALID_URL = r'%s/(?P<username>[^/]+)/(?P<id>[^/?#&]+)' % PinterestBaseIE._VALID_URL_BASE
191 _TESTS = [{
192 'url': 'https://www.pinterest.ca/mashal0407/cool-diys/',
193 'info_dict': {
194 'id': '585890301462791043',
195 'title': 'cool diys',
197 'playlist_count': 8,
198 }, {
199 'url': 'https://www.pinterest.ca/fudohub/videos/',
200 'info_dict': {
201 'id': '682858430939307450',
202 'title': 'VIDEOS',
204 'playlist_mincount': 365,
205 'skip': 'Test with extract_formats=False',
208 @classmethod
209 def suitable(cls, url):
210 return False if PinterestIE.suitable(url) else super(
211 PinterestCollectionIE, cls).suitable(url)
213 def _real_extract(self, url):
214 username, slug = self._match_valid_url(url).groups()
215 board = self._call_api(
216 'Board', slug, {
217 'slug': slug,
218 'username': username
219 })['data']
220 board_id = board['id']
221 options = {
222 'board_id': board_id,
223 'page_size': 250,
225 bookmark = None
226 entries = []
227 while True:
228 if bookmark:
229 options['bookmarks'] = [bookmark]
230 board_feed = self._call_api('BoardFeed', board_id, options)
231 for item in (board_feed.get('data') or []):
232 if not isinstance(item, dict) or item.get('type') != 'pin':
233 continue
234 video_id = item.get('id')
235 if video_id:
236 # Some pins may not be available anonymously via pin URL
237 # video = self._extract_video(item, extract_formats=False)
238 # video.update({
239 # '_type': 'url_transparent',
240 # 'url': 'https://www.pinterest.com/pin/%s/' % video_id,
241 # })
242 # entries.append(video)
243 entries.append(self._extract_video(item))
244 bookmark = board_feed.get('bookmark')
245 if not bookmark:
246 break
247 return self.playlist_result(
248 entries, playlist_id=board_id, playlist_title=board.get('name'))