Merge branch 'bilibili' of https://github.com/PeterDing/youtube-dl into PeterDing...
[youtube-dl] / youtube_dl / extractor / nytimes.py
1 from __future__ import unicode_literals
2
3 import hmac
4 import hashlib
5 import base64
6
7 from .common import InfoExtractor
8 from ..utils import (
9     float_or_none,
10     int_or_none,
11     parse_iso8601,
12     mimetype2ext,
13     determine_ext,
14 )
15
16
17 class NYTimesBaseIE(InfoExtractor):
18     _SECRET = b'pX(2MbU2);4N{7J8)>YwKRJ+/pQ3JkiU2Q^V>mFYv6g6gYvt6v'
19
20     def _extract_video_from_id(self, video_id):
21         # Authorization generation algorithm is reverse engineered from `signer` in
22         # http://graphics8.nytimes.com/video/vhs/vhs-2.x.min.js
23         path = '/svc/video/api/v3/video/' + video_id
24         hm = hmac.new(self._SECRET, (path + ':vhs').encode(), hashlib.sha512).hexdigest()
25         video_data = self._download_json('http://www.nytimes.com' + path, video_id, 'Downloading video JSON', headers={
26             'Authorization': 'NYTV ' + base64.b64encode(hm.encode()).decode(),
27             'X-NYTV': 'vhs',
28         }, fatal=False)
29         if not video_data:
30             video_data = self._download_json(
31                 'http://www.nytimes.com/svc/video/api/v2/video/' + video_id,
32                 video_id, 'Downloading video JSON')
33
34         title = video_data['headline']
35
36         def get_file_size(file_size):
37             if isinstance(file_size, int):
38                 return file_size
39             elif isinstance(file_size, dict):
40                 return int(file_size.get('value', 0))
41             else:
42                 return None
43
44         urls = []
45         formats = []
46         for video in video_data.get('renditions', []):
47             video_url = video.get('url')
48             format_id = video.get('type')
49             if not video_url or format_id == 'thumbs' or video_url in urls:
50                 continue
51             urls.append(video_url)
52             ext = mimetype2ext(video.get('mimetype')) or determine_ext(video_url)
53             if ext == 'm3u8':
54                 formats.extend(self._extract_m3u8_formats(
55                     video_url, video_id, 'mp4', 'm3u8_native',
56                     m3u8_id=format_id or 'hls', fatal=False))
57             elif ext == 'mpd':
58                 continue
59             #     formats.extend(self._extract_mpd_formats(
60             #         video_url, video_id, format_id or 'dash', fatal=False))
61             else:
62                 formats.append({
63                     'url': video_url,
64                     'format_id': format_id,
65                     'vcodec': video.get('videoencoding') or video.get('video_codec'),
66                     'width': int_or_none(video.get('width')),
67                     'height': int_or_none(video.get('height')),
68                     'filesize': get_file_size(video.get('file_size') or video.get('fileSize')),
69                     'tbr': int_or_none(video.get('bitrate'), 1000),
70                     'ext': ext,
71                 })
72         self._sort_formats(formats)
73
74         thumbnails = []
75         for image in video_data.get('images', []):
76             image_url = image.get('url')
77             if not image_url:
78                 continue
79             thumbnails.append({
80                 'url': 'http://www.nytimes.com/' + image_url,
81                 'width': int_or_none(image.get('width')),
82                 'height': int_or_none(image.get('height')),
83             })
84
85         publication_date = video_data.get('publication_date')
86         timestamp = parse_iso8601(publication_date[:-8]) if publication_date else None
87
88         return {
89             'id': video_id,
90             'title': title,
91             'description': video_data.get('summary'),
92             'timestamp': timestamp,
93             'uploader': video_data.get('byline'),
94             'duration': float_or_none(video_data.get('duration'), 1000),
95             'formats': formats,
96             'thumbnails': thumbnails,
97         }
98
99
100 class NYTimesIE(NYTimesBaseIE):
101     _VALID_URL = r'https?://(?:(?:www\.)?nytimes\.com/video/(?:[^/]+/)+?|graphics8\.nytimes\.com/bcvideo/\d+(?:\.\d+)?/iframe/embed\.html\?videoId=)(?P<id>\d+)'
102
103     _TESTS = [{
104         'url': 'http://www.nytimes.com/video/opinion/100000002847155/verbatim-what-is-a-photocopier.html?playlistId=100000001150263',
105         'md5': 'd665342765db043f7e225cff19df0f2d',
106         'info_dict': {
107             'id': '100000002847155',
108             'ext': 'mov',
109             'title': 'Verbatim: What Is a Photocopier?',
110             'description': 'md5:93603dada88ddbda9395632fdc5da260',
111             'timestamp': 1398631707,
112             'upload_date': '20140427',
113             'uploader': 'Brett Weiner',
114             'duration': 419,
115         }
116     }, {
117         'url': 'http://www.nytimes.com/video/travel/100000003550828/36-hours-in-dubai.html',
118         'only_matching': True,
119     }]
120
121     def _real_extract(self, url):
122         video_id = self._match_id(url)
123
124         return self._extract_video_from_id(video_id)
125
126
127 class NYTimesArticleIE(NYTimesBaseIE):
128     _VALID_URL = r'https?://(?:www\.)?nytimes\.com/(.(?<!video))*?/(?:[^/]+/)*(?P<id>[^.]+)(?:\.html)?'
129     _TESTS = [{
130         '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',
131         'md5': 'e2076d58b4da18e6a001d53fd56db3c9',
132         'info_dict': {
133             'id': '100000003628438',
134             'ext': 'mov',
135             'title': 'New Minimum Wage: $70,000 a Year',
136             '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.',
137             'timestamp': 1429033037,
138             'upload_date': '20150414',
139             'uploader': 'Matthew Williams',
140         }
141     }, {
142         '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',
143         'only_matching': True,
144     }]
145
146     def _real_extract(self, url):
147         video_id = self._match_id(url)
148
149         webpage = self._download_webpage(url, video_id)
150
151         video_id = self._html_search_regex(r'data-videoid="(\d+)"', webpage, 'video id')
152
153         return self._extract_video_from_id(video_id)