]> jfr.im git - yt-dlp.git/blame - youtube_dlc/extractor/pinterest.py
Update to release 2020.11.24 except youtube and skyit extractors
[yt-dlp.git] / youtube_dlc / extractor / pinterest.py
CommitLineData
70c5802b 1# coding: utf-8
2from __future__ import unicode_literals
3
4import json
5import re
6
7from .common import InfoExtractor
8from ..compat import compat_str
9from ..utils import (
10 determine_ext,
11 float_or_none,
12 int_or_none,
13 try_get,
14 unified_timestamp,
15 url_or_none,
16)
17
18
19class PinterestBaseIE(InfoExtractor):
20 _VALID_URL_BASE = r'https?://(?:[^/]+\.)?pinterest\.(?:com|fr|de|ch|jp|cl|ca|it|co\.uk|nz|ru|com\.au|at|pt|co\.kr|es|com\.mx|dk|ph|th|com\.uy|co|nl|info|kr|ie|vn|com\.vn|ec|mx|in|pe|co\.at|hu|co\.in|co\.nz|id|com\.ec|com\.py|tw|be|uk|com\.bo|com\.pe)'
21
22 def _call_api(self, resource, video_id, options):
23 return self._download_json(
24 'https://www.pinterest.com/resource/%sResource/get/' % resource,
25 video_id, 'Download %s JSON metadata' % resource, query={
26 'data': json.dumps({'options': options})
27 })['resource_response']
28
29 def _extract_video(self, data, extract_formats=True):
30 video_id = data['id']
31
32 title = (data.get('title') or data.get('grid_title') or video_id).strip()
33
34 formats = []
35 duration = None
36 if extract_formats:
37 for format_id, format_dict in data['videos']['video_list'].items():
38 if not isinstance(format_dict, dict):
39 continue
40 format_url = url_or_none(format_dict.get('url'))
41 if not format_url:
42 continue
43 duration = float_or_none(format_dict.get('duration'), scale=1000)
44 ext = determine_ext(format_url)
45 if 'hls' in format_id.lower() or ext == 'm3u8':
46 formats.extend(self._extract_m3u8_formats(
47 format_url, video_id, 'mp4', entry_protocol='m3u8_native',
48 m3u8_id=format_id, fatal=False))
49 else:
50 formats.append({
51 'url': format_url,
52 'format_id': format_id,
53 'width': int_or_none(format_dict.get('width')),
54 'height': int_or_none(format_dict.get('height')),
55 'duration': duration,
56 })
57 self._sort_formats(
58 formats, field_preference=('height', 'width', 'tbr', 'format_id'))
59
60 description = data.get('description') or data.get('description_html') or data.get('seo_description')
61 timestamp = unified_timestamp(data.get('created_at'))
62
63 def _u(field):
64 return try_get(data, lambda x: x['closeup_attribution'][field], compat_str)
65
66 uploader = _u('full_name')
67 uploader_id = _u('id')
68
69 repost_count = int_or_none(data.get('repin_count'))
70 comment_count = int_or_none(data.get('comment_count'))
71 categories = try_get(data, lambda x: x['pin_join']['visual_annotation'], list)
72 tags = data.get('hashtags')
73
74 thumbnails = []
75 images = data.get('images')
76 if isinstance(images, dict):
77 for thumbnail_id, thumbnail in images.items():
78 if not isinstance(thumbnail, dict):
79 continue
80 thumbnail_url = url_or_none(thumbnail.get('url'))
81 if not thumbnail_url:
82 continue
83 thumbnails.append({
84 'url': thumbnail_url,
85 'width': int_or_none(thumbnail.get('width')),
86 'height': int_or_none(thumbnail.get('height')),
87 })
88
89 return {
90 'id': video_id,
91 'title': title,
92 'description': description,
93 'duration': duration,
94 'timestamp': timestamp,
95 'thumbnails': thumbnails,
96 'uploader': uploader,
97 'uploader_id': uploader_id,
98 'repost_count': repost_count,
99 'comment_count': comment_count,
100 'categories': categories,
101 'tags': tags,
102 'formats': formats,
103 'extractor_key': PinterestIE.ie_key(),
104 }
105
106
107class PinterestIE(PinterestBaseIE):
108 _VALID_URL = r'%s/pin/(?P<id>\d+)' % PinterestBaseIE._VALID_URL_BASE
109 _TESTS = [{
110 'url': 'https://www.pinterest.com/pin/664281013778109217/',
111 'md5': '6550c2af85d6d9f3fe3b88954d1577fc',
112 'info_dict': {
113 'id': '664281013778109217',
114 'ext': 'mp4',
115 'title': 'Origami',
116 'description': 'md5:b9d90ddf7848e897882de9e73344f7dd',
117 'duration': 57.7,
118 'timestamp': 1593073622,
119 'upload_date': '20200625',
120 'uploader': 'Love origami -I am Dafei',
121 'uploader_id': '586523688879454212',
122 'repost_count': 50,
123 'comment_count': 0,
124 'categories': list,
125 'tags': list,
126 },
127 }, {
128 'url': 'https://co.pinterest.com/pin/824721750502199491/',
129 'only_matching': True,
130 }]
131
132 def _real_extract(self, url):
133 video_id = self._match_id(url)
134 data = self._call_api(
135 'Pin', video_id, {
136 'field_set_key': 'unauth_react_main_pin',
137 'id': video_id,
138 })['data']
139 return self._extract_video(data)
140
141
142class PinterestCollectionIE(PinterestBaseIE):
143 _VALID_URL = r'%s/(?P<username>[^/]+)/(?P<id>[^/?#&]+)' % PinterestBaseIE._VALID_URL_BASE
144 _TESTS = [{
145 'url': 'https://www.pinterest.ca/mashal0407/cool-diys/',
146 'info_dict': {
147 'id': '585890301462791043',
148 'title': 'cool diys',
149 },
150 'playlist_count': 8,
151 }, {
152 'url': 'https://www.pinterest.ca/fudohub/videos/',
153 'info_dict': {
154 'id': '682858430939307450',
155 'title': 'VIDEOS',
156 },
157 'playlist_mincount': 365,
158 'skip': 'Test with extract_formats=False',
159 }]
160
161 @classmethod
162 def suitable(cls, url):
163 return False if PinterestIE.suitable(url) else super(
164 PinterestCollectionIE, cls).suitable(url)
165
166 def _real_extract(self, url):
167 username, slug = re.match(self._VALID_URL, url).groups()
168 board = self._call_api(
169 'Board', slug, {
170 'slug': slug,
171 'username': username
172 })['data']
173 board_id = board['id']
174 options = {
175 'board_id': board_id,
176 'page_size': 250,
177 }
178 bookmark = None
179 entries = []
180 while True:
181 if bookmark:
182 options['bookmarks'] = [bookmark]
183 board_feed = self._call_api('BoardFeed', board_id, options)
184 for item in (board_feed.get('data') or []):
185 if not isinstance(item, dict) or item.get('type') != 'pin':
186 continue
187 video_id = item.get('id')
188 if video_id:
189 # Some pins may not be available anonymously via pin URL
190 # video = self._extract_video(item, extract_formats=False)
191 # video.update({
192 # '_type': 'url_transparent',
193 # 'url': 'https://www.pinterest.com/pin/%s/' % video_id,
194 # })
195 # entries.append(video)
196 entries.append(self._extract_video(item))
197 bookmark = board_feed.get('bookmark')
198 if not bookmark:
199 break
200 return self.playlist_result(
201 entries, playlist_id=board_id, playlist_title=board.get('name'))