]> jfr.im git - yt-dlp.git/blob - yt_dlp/extractor/nytimes.py
[vlive:channel] Fix extraction
[yt-dlp.git] / yt_dlp / extractor / nytimes.py
1 # coding: utf-8
2 from __future__ import unicode_literals
3
4 import hmac
5 import hashlib
6 import base64
7
8 from .common import InfoExtractor
9 from ..utils import (
10 determine_ext,
11 float_or_none,
12 int_or_none,
13 js_to_json,
14 mimetype2ext,
15 parse_iso8601,
16 remove_start,
17 )
18
19
20 class NYTimesBaseIE(InfoExtractor):
21 _SECRET = b'pX(2MbU2);4N{7J8)>YwKRJ+/pQ3JkiU2Q^V>mFYv6g6gYvt6v'
22
23 def _extract_video_from_id(self, video_id):
24 # Authorization generation algorithm is reverse engineered from `signer` in
25 # http://graphics8.nytimes.com/video/vhs/vhs-2.x.min.js
26 path = '/svc/video/api/v3/video/' + video_id
27 hm = hmac.new(self._SECRET, (path + ':vhs').encode(), hashlib.sha512).hexdigest()
28 video_data = self._download_json('http://www.nytimes.com' + path, video_id, 'Downloading video JSON', headers={
29 'Authorization': 'NYTV ' + base64.b64encode(hm.encode()).decode(),
30 'X-NYTV': 'vhs',
31 }, fatal=False)
32 if not video_data:
33 video_data = self._download_json(
34 'http://www.nytimes.com/svc/video/api/v2/video/' + video_id,
35 video_id, 'Downloading video JSON')
36
37 title = video_data['headline']
38
39 def get_file_size(file_size):
40 if isinstance(file_size, int):
41 return file_size
42 elif isinstance(file_size, dict):
43 return int(file_size.get('value', 0))
44 else:
45 return None
46
47 urls = []
48 formats = []
49 subtitles = {}
50 for video in video_data.get('renditions', []):
51 video_url = video.get('url')
52 format_id = video.get('type')
53 if not video_url or format_id == 'thumbs' or video_url in urls:
54 continue
55 urls.append(video_url)
56 ext = mimetype2ext(video.get('mimetype')) or determine_ext(video_url)
57 if ext == 'm3u8':
58 m3u8_fmts, m3u8_subs = self._extract_m3u8_formats_and_subtitles(
59 video_url, video_id, 'mp4', 'm3u8_native',
60 m3u8_id=format_id or 'hls', fatal=False)
61 formats.extend(m3u8_fmts)
62 subtitles = self._merge_subtitles(subtitles, m3u8_subs)
63 elif ext == 'mpd':
64 continue
65 # formats.extend(self._extract_mpd_formats(
66 # video_url, video_id, format_id or 'dash', fatal=False))
67 else:
68 formats.append({
69 'url': video_url,
70 'format_id': format_id,
71 'vcodec': video.get('videoencoding') or video.get('video_codec'),
72 'width': int_or_none(video.get('width')),
73 'height': int_or_none(video.get('height')),
74 'filesize': get_file_size(video.get('file_size') or video.get('fileSize')),
75 'tbr': int_or_none(video.get('bitrate'), 1000) or None,
76 'ext': ext,
77 })
78 self._sort_formats(formats)
79
80 thumbnails = []
81 for image in video_data.get('images', []):
82 image_url = image.get('url')
83 if not image_url:
84 continue
85 thumbnails.append({
86 'url': 'http://www.nytimes.com/' + image_url,
87 'width': int_or_none(image.get('width')),
88 'height': int_or_none(image.get('height')),
89 })
90
91 publication_date = video_data.get('publication_date')
92 timestamp = parse_iso8601(publication_date[:-8]) if publication_date else None
93
94 return {
95 'id': video_id,
96 'title': title,
97 'description': video_data.get('summary'),
98 'timestamp': timestamp,
99 'uploader': video_data.get('byline'),
100 'duration': float_or_none(video_data.get('duration'), 1000),
101 'formats': formats,
102 'subtitles': subtitles,
103 'thumbnails': thumbnails,
104 }
105
106
107 class NYTimesIE(NYTimesBaseIE):
108 _VALID_URL = r'https?://(?:(?:www\.)?nytimes\.com/video/(?:[^/]+/)+?|graphics8\.nytimes\.com/bcvideo/\d+(?:\.\d+)?/iframe/embed\.html\?videoId=)(?P<id>\d+)'
109
110 _TESTS = [{
111 'url': 'http://www.nytimes.com/video/opinion/100000002847155/verbatim-what-is-a-photocopier.html?playlistId=100000001150263',
112 'md5': 'd665342765db043f7e225cff19df0f2d',
113 'info_dict': {
114 'id': '100000002847155',
115 'ext': 'mov',
116 'title': 'Verbatim: What Is a Photocopier?',
117 'description': 'md5:93603dada88ddbda9395632fdc5da260',
118 'timestamp': 1398631707,
119 'upload_date': '20140427',
120 'uploader': 'Brett Weiner',
121 'duration': 419,
122 }
123 }, {
124 'url': 'http://www.nytimes.com/video/travel/100000003550828/36-hours-in-dubai.html',
125 'only_matching': True,
126 }]
127
128 def _real_extract(self, url):
129 video_id = self._match_id(url)
130
131 return self._extract_video_from_id(video_id)
132
133
134 class NYTimesArticleIE(NYTimesBaseIE):
135 _VALID_URL = r'https?://(?:www\.)?nytimes\.com/(.(?<!video))*?/(?:[^/]+/)*(?P<id>[^.]+)(?:\.html)?'
136 _TESTS = [{
137 'url': 'http://www.nytimes.com/2015/04/14/business/owner-of-gravity-payments-a-credit-card-processor-is-setting-a-new-minimum-wage-70000-a-year.html?_r=0',
138 'md5': 'e2076d58b4da18e6a001d53fd56db3c9',
139 'info_dict': {
140 'id': '100000003628438',
141 'ext': 'mov',
142 'title': 'New Minimum Wage: $70,000 a Year',
143 'description': 'Dan Price, C.E.O. of Gravity Payments, surprised his 120-person staff by announcing that he planned over the next three years to raise the salary of every employee to $70,000 a year.',
144 'timestamp': 1429033037,
145 'upload_date': '20150414',
146 'uploader': 'Matthew Williams',
147 }
148 }, {
149 'url': 'http://www.nytimes.com/2016/10/14/podcasts/revelations-from-the-final-weeks.html',
150 'md5': 'e0d52040cafb07662acf3c9132db3575',
151 'info_dict': {
152 'id': '100000004709062',
153 'title': 'The Run-Up: ‘He Was Like an Octopus’',
154 'ext': 'mp3',
155 'description': 'md5:fb5c6b93b12efc51649b4847fe066ee4',
156 'series': 'The Run-Up',
157 'episode': '‘He Was Like an Octopus’',
158 'episode_number': 20,
159 'duration': 2130,
160 }
161 }, {
162 'url': 'http://www.nytimes.com/2016/10/16/books/review/inside-the-new-york-times-book-review-the-rise-of-hitler.html',
163 'info_dict': {
164 'id': '100000004709479',
165 'title': 'The Rise of Hitler',
166 'ext': 'mp3',
167 'description': 'md5:bce877fd9e3444990cb141875fab0028',
168 'creator': 'Pamela Paul',
169 'duration': 3475,
170 },
171 'params': {
172 'skip_download': True,
173 },
174 }, {
175 'url': 'http://www.nytimes.com/news/minute/2014/03/17/times-minute-whats-next-in-crimea/?_php=true&_type=blogs&_php=true&_type=blogs&_r=1',
176 'only_matching': True,
177 }]
178
179 def _extract_podcast_from_json(self, json, page_id, webpage):
180 podcast_audio = self._parse_json(
181 json, page_id, transform_source=js_to_json)
182
183 audio_data = podcast_audio['data']
184 track = audio_data['track']
185
186 episode_title = track['title']
187 video_url = track['source']
188
189 description = track.get('description') or self._html_search_meta(
190 ['og:description', 'twitter:description'], webpage)
191
192 podcast_title = audio_data.get('podcast', {}).get('title')
193 title = ('%s: %s' % (podcast_title, episode_title)
194 if podcast_title else episode_title)
195
196 episode = audio_data.get('podcast', {}).get('episode') or ''
197 episode_number = int_or_none(self._search_regex(
198 r'[Ee]pisode\s+(\d+)', episode, 'episode number', default=None))
199
200 return {
201 'id': remove_start(podcast_audio.get('target'), 'FT') or page_id,
202 'url': video_url,
203 'title': title,
204 'description': description,
205 'creator': track.get('credit'),
206 'series': podcast_title,
207 'episode': episode_title,
208 'episode_number': episode_number,
209 'duration': int_or_none(track.get('duration')),
210 }
211
212 def _real_extract(self, url):
213 page_id = self._match_id(url)
214
215 webpage = self._download_webpage(url, page_id)
216
217 video_id = self._search_regex(
218 r'data-videoid=["\'](\d+)', webpage, 'video id',
219 default=None, fatal=False)
220 if video_id is not None:
221 return self._extract_video_from_id(video_id)
222
223 podcast_data = self._search_regex(
224 (r'NYTD\.FlexTypes\.push\s*\(\s*({.+?})\s*\)\s*;\s*</script',
225 r'NYTD\.FlexTypes\.push\s*\(\s*({.+})\s*\)\s*;'),
226 webpage, 'podcast data')
227 return self._extract_podcast_from_json(podcast_data, page_id, webpage)
228
229
230 class NYTimesCookingIE(NYTimesBaseIE):
231 _VALID_URL = r'https?://cooking\.nytimes\.com/(?:guid|recip)es/(?P<id>\d+)'
232 _TESTS = [{
233 'url': 'https://cooking.nytimes.com/recipes/1017817-cranberry-curd-tart',
234 'md5': 'dab81fa2eaeb3f9ed47498bdcfcdc1d3',
235 'info_dict': {
236 'id': '100000004756089',
237 'ext': 'mov',
238 'timestamp': 1479383008,
239 'uploader': 'By SHAW LASH, ADAM SAEWITZ and JAMES HERRON',
240 'title': 'Cranberry Tart',
241 'upload_date': '20161117',
242 'description': 'If you are a fan of lemon curd or the classic French tarte au citron, you will love this cranberry version.',
243 },
244 }, {
245 'url': 'https://cooking.nytimes.com/guides/13-how-to-cook-a-turkey',
246 'md5': '4b2e8c70530a89b8d905a2b572316eb8',
247 'info_dict': {
248 'id': '100000003951728',
249 'ext': 'mov',
250 'timestamp': 1445509539,
251 'description': 'Turkey guide',
252 'upload_date': '20151022',
253 'title': 'Turkey',
254 }
255 }]
256
257 def _real_extract(self, url):
258 page_id = self._match_id(url)
259
260 webpage = self._download_webpage(url, page_id)
261
262 video_id = self._search_regex(
263 r'data-video-id=["\'](\d+)', webpage, 'video id')
264
265 return self._extract_video_from_id(video_id)