[theplatform] extract subtitles with multiple formats from the metadata
[youtube-dl] / youtube_dl / extractor / theplatform.py
1 # -*- coding: utf-8 -*-
2 from __future__ import unicode_literals
3
4 import re
5 import time
6 import hmac
7 import binascii
8 import hashlib
9
10
11 from .once import OnceIE
12 from .adobepass import AdobePassIE
13 from ..compat import (
14     compat_parse_qs,
15     compat_urllib_parse_urlparse,
16 )
17 from ..utils import (
18     determine_ext,
19     ExtractorError,
20     float_or_none,
21     int_or_none,
22     sanitized_Request,
23     unsmuggle_url,
24     update_url_query,
25     xpath_with_ns,
26     mimetype2ext,
27     find_xpath_attr,
28 )
29
30 default_ns = 'http://www.w3.org/2005/SMIL21/Language'
31 _x = lambda p: xpath_with_ns(p, {'smil': default_ns})
32
33
34 class ThePlatformBaseIE(OnceIE):
35     def _extract_theplatform_smil(self, smil_url, video_id, note='Downloading SMIL data'):
36         meta = self._download_xml(smil_url, video_id, note=note, query={'format': 'SMIL'})
37         error_element = find_xpath_attr(meta, _x('.//smil:ref'), 'src')
38         if error_element is not None and error_element.attrib['src'].startswith(
39                 'http://link.theplatform.com/s/errorFiles/Unavailable.'):
40             raise ExtractorError(error_element.attrib['abstract'], expected=True)
41
42         smil_formats = self._parse_smil_formats(
43             meta, smil_url, video_id, namespace=default_ns,
44             # the parameters are from syfy.com, other sites may use others,
45             # they also work for nbc.com
46             f4m_params={'g': 'UXWGVKRWHFSP', 'hdcore': '3.0.3'},
47             transform_rtmp_url=lambda streamer, src: (streamer, 'mp4:' + src))
48
49         formats = []
50         for _format in smil_formats:
51             if OnceIE.suitable(_format['url']):
52                 formats.extend(self._extract_once_formats(_format['url']))
53             else:
54                 media_url = _format['url']
55                 if determine_ext(media_url) == 'm3u8':
56                     hdnea2 = self._get_cookies(media_url).get('hdnea2')
57                     if hdnea2:
58                         _format['url'] = update_url_query(media_url, {'hdnea3': hdnea2.value})
59
60                 formats.append(_format)
61
62         subtitles = self._parse_smil_subtitles(meta, default_ns)
63
64         return formats, subtitles
65
66     def _download_theplatform_metadata(self, path, video_id):
67         info_url = 'http://link.theplatform.com/s/%s?format=preview' % path
68         return self._download_json(info_url, video_id)
69
70     def _parse_theplatform_metadata(self, info):
71         subtitles = {}
72         captions = info.get('captions')
73         if isinstance(captions, list):
74             for caption in captions:
75                 lang, src, mime = caption.get('lang', 'en'), caption.get('src'), caption.get('type')
76                 subtitles.setdefault(lang, []).append({
77                     'ext': mimetype2ext(mime),
78                     'url': src,
79                 })
80
81         return {
82             'title': info['title'],
83             'subtitles': subtitles,
84             'description': info['description'],
85             'thumbnail': info['defaultThumbnailUrl'],
86             'duration': int_or_none(info.get('duration'), 1000),
87             'timestamp': int_or_none(info.get('pubDate'), 1000) or None,
88             'uploader': info.get('billingCode'),
89         }
90
91     def _extract_theplatform_metadata(self, path, video_id):
92         info = self._download_theplatform_metadata(path, video_id)
93         return self._parse_theplatform_metadata(info)
94
95
96 class ThePlatformIE(ThePlatformBaseIE, AdobePassIE):
97     _VALID_URL = r'''(?x)
98         (?:https?://(?:link|player)\.theplatform\.com/[sp]/(?P<provider_id>[^/]+)/
99            (?:(?:(?:[^/]+/)+select/)?(?P<media>media/(?:guid/\d+/)?)|(?P<config>(?:[^/\?]+/(?:swf|config)|onsite)/select/))?
100          |theplatform:)(?P<id>[^/\?&]+)'''
101
102     _TESTS = [{
103         # from http://www.metacafe.com/watch/cb-e9I_cZgTgIPd/blackberrys_big_bold_z30/
104         'url': 'http://link.theplatform.com/s/dJ5BDC/e9I_cZgTgIPd/meta.smil?format=smil&Tracking=true&mbr=true',
105         'info_dict': {
106             'id': 'e9I_cZgTgIPd',
107             'ext': 'flv',
108             'title': 'Blackberry\'s big, bold Z30',
109             'description': 'The Z30 is Blackberry\'s biggest, baddest mobile messaging device yet.',
110             'duration': 247,
111             'timestamp': 1383239700,
112             'upload_date': '20131031',
113             'uploader': 'CBSI-NEW',
114         },
115         'params': {
116             # rtmp download
117             'skip_download': True,
118         },
119     }, {
120         # from http://www.cnet.com/videos/tesla-model-s-a-second-step-towards-a-cleaner-motoring-future/
121         'url': 'http://link.theplatform.com/s/kYEXFC/22d_qsQ6MIRT',
122         'info_dict': {
123             'id': '22d_qsQ6MIRT',
124             'ext': 'flv',
125             'description': 'md5:ac330c9258c04f9d7512cf26b9595409',
126             'title': 'Tesla Model S: A second step towards a cleaner motoring future',
127             'timestamp': 1426176191,
128             'upload_date': '20150312',
129             'uploader': 'CBSI-NEW',
130         },
131         'params': {
132             # rtmp download
133             'skip_download': True,
134         }
135     }, {
136         'url': 'https://player.theplatform.com/p/D6x-PC/pulse_preview/embed/select/media/yMBg9E8KFxZD',
137         'info_dict': {
138             'id': 'yMBg9E8KFxZD',
139             'ext': 'mp4',
140             'description': 'md5:644ad9188d655b742f942bf2e06b002d',
141             'title': 'HIGHLIGHTS: USA bag first ever series Cup win',
142             'uploader': 'EGSM',
143         }
144     }, {
145         'url': 'http://player.theplatform.com/p/NnzsPC/widget/select/media/4Y0TlYUr_ZT7',
146         'only_matching': True,
147     }, {
148         'url': 'http://player.theplatform.com/p/2E2eJC/nbcNewsOffsite?guid=tdy_or_siri_150701',
149         'md5': 'fb96bb3d85118930a5b055783a3bd992',
150         'info_dict': {
151             'id': 'tdy_or_siri_150701',
152             'ext': 'mp4',
153             'title': 'iPhone Siri’s sassy response to a math question has people talking',
154             'description': 'md5:a565d1deadd5086f3331d57298ec6333',
155             'duration': 83.0,
156             'thumbnail': 're:^https?://.*\.jpg$',
157             'timestamp': 1435752600,
158             'upload_date': '20150701',
159             'uploader': 'NBCU-NEWS',
160         },
161     }, {
162         # From http://www.nbc.com/the-blacklist/video/sir-crispin-crandall/2928790?onid=137781#vc137781=1
163         # geo-restricted (US), HLS encrypted with AES-128
164         'url': 'http://player.theplatform.com/p/NnzsPC/onsite_universal/select/media/guid/2410887629/2928790?fwsitesection=nbc_the_blacklist_video_library&autoPlay=true&carouselID=137781',
165         'only_matching': True,
166     }]
167
168     @classmethod
169     def _extract_urls(cls, webpage):
170         m = re.search(
171             r'''(?x)
172                     <meta\s+
173                         property=(["'])(?:og:video(?::(?:secure_)?url)?|twitter:player)\1\s+
174                         content=(["'])(?P<url>https?://player\.theplatform\.com/p/.+?)\2
175             ''', webpage)
176         if m:
177             return [m.group('url')]
178
179         matches = re.findall(
180             r'<(?:iframe|script)[^>]+src=(["\'])((?:https?:)?//player\.theplatform\.com/p/.+?)\1', webpage)
181         if matches:
182             return list(zip(*matches))[1]
183
184     @staticmethod
185     def _sign_url(url, sig_key, sig_secret, life=600, include_qs=False):
186         flags = '10' if include_qs else '00'
187         expiration_date = '%x' % (int(time.time()) + life)
188
189         def str_to_hex(str):
190             return binascii.b2a_hex(str.encode('ascii')).decode('ascii')
191
192         def hex_to_bytes(hex):
193             return binascii.a2b_hex(hex.encode('ascii'))
194
195         relative_path = re.match(r'https?://link.theplatform.com/s/([^?]+)', url).group(1)
196         clear_text = hex_to_bytes(flags + expiration_date + str_to_hex(relative_path))
197         checksum = hmac.new(sig_key.encode('ascii'), clear_text, hashlib.sha1).hexdigest()
198         sig = flags + expiration_date + checksum + str_to_hex(sig_secret)
199         return '%s&sig=%s' % (url, sig)
200
201     def _real_extract(self, url):
202         url, smuggled_data = unsmuggle_url(url, {})
203
204         mobj = re.match(self._VALID_URL, url)
205         provider_id = mobj.group('provider_id')
206         video_id = mobj.group('id')
207
208         if not provider_id:
209             provider_id = 'dJ5BDC'
210
211         path = provider_id + '/'
212         if mobj.group('media'):
213             path += mobj.group('media')
214         path += video_id
215
216         qs_dict = compat_parse_qs(compat_urllib_parse_urlparse(url).query)
217         if 'guid' in qs_dict:
218             webpage = self._download_webpage(url, video_id)
219             scripts = re.findall(r'<script[^>]+src="([^"]+)"', webpage)
220             feed_id = None
221             # feed id usually locates in the last script.
222             # Seems there's no pattern for the interested script filename, so
223             # I try one by one
224             for script in reversed(scripts):
225                 feed_script = self._download_webpage(
226                     self._proto_relative_url(script, 'http:'),
227                     video_id, 'Downloading feed script')
228                 feed_id = self._search_regex(
229                     r'defaultFeedId\s*:\s*"([^"]+)"', feed_script,
230                     'default feed id', default=None)
231                 if feed_id is not None:
232                     break
233             if feed_id is None:
234                 raise ExtractorError('Unable to find feed id')
235             return self.url_result('http://feed.theplatform.com/f/%s/%s?byGuid=%s' % (
236                 provider_id, feed_id, qs_dict['guid'][0]))
237
238         if smuggled_data.get('force_smil_url', False):
239             smil_url = url
240         # Explicitly specified SMIL (see https://github.com/rg3/youtube-dl/issues/7385)
241         elif '/guid/' in url:
242             headers = {}
243             source_url = smuggled_data.get('source_url')
244             if source_url:
245                 headers['Referer'] = source_url
246             request = sanitized_Request(url, headers=headers)
247             webpage = self._download_webpage(request, video_id)
248             smil_url = self._search_regex(
249                 r'<link[^>]+href=(["\'])(?P<url>.+?)\1[^>]+type=["\']application/smil\+xml',
250                 webpage, 'smil url', group='url')
251             path = self._search_regex(
252                 r'link\.theplatform\.com/s/((?:[^/?#&]+/)+[^/?#&]+)', smil_url, 'path')
253             smil_url += '?' if '?' not in smil_url else '&' + 'formats=m3u,mpeg4'
254         elif mobj.group('config'):
255             config_url = url + '&form=json'
256             config_url = config_url.replace('swf/', 'config/')
257             config_url = config_url.replace('onsite/', 'onsite/config/')
258             config = self._download_json(config_url, video_id, 'Downloading config')
259             if 'releaseUrl' in config:
260                 release_url = config['releaseUrl']
261             else:
262                 release_url = 'http://link.theplatform.com/s/%s?mbr=true' % path
263             smil_url = release_url + '&formats=MPEG4&manifest=f4m'
264         else:
265             smil_url = 'http://link.theplatform.com/s/%s?mbr=true' % path
266
267         sig = smuggled_data.get('sig')
268         if sig:
269             smil_url = self._sign_url(smil_url, sig['key'], sig['secret'])
270
271         formats, subtitles = self._extract_theplatform_smil(smil_url, video_id)
272         self._sort_formats(formats)
273
274         ret = self._extract_theplatform_metadata(path, video_id)
275         combined_subtitles = self._merge_subtitles(ret.get('subtitles', {}), subtitles)
276         ret.update({
277             'id': video_id,
278             'formats': formats,
279             'subtitles': combined_subtitles,
280         })
281
282         return ret
283
284
285 class ThePlatformFeedIE(ThePlatformBaseIE):
286     _URL_TEMPLATE = '%s//feed.theplatform.com/f/%s/%s?form=json&%s'
287     _VALID_URL = r'https?://feed\.theplatform\.com/f/(?P<provider_id>[^/]+)/(?P<feed_id>[^?/]+)\?(?:[^&]+&)*(?P<filter>by(?:Gui|I)d=(?P<id>[\w-]+))'
288     _TESTS = [{
289         # From http://player.theplatform.com/p/7wvmTC/MSNBCEmbeddedOffSite?guid=n_hardball_5biden_140207
290         'url': 'http://feed.theplatform.com/f/7wvmTC/msnbc_video-p-test?form=json&pretty=true&range=-40&byGuid=n_hardball_5biden_140207',
291         'md5': '6e32495b5073ab414471b615c5ded394',
292         'info_dict': {
293             'id': 'n_hardball_5biden_140207',
294             'ext': 'mp4',
295             'title': 'The Biden factor: will Joe run in 2016?',
296             'description': 'Could Vice President Joe Biden be preparing a 2016 campaign? Mark Halperin and Sam Stein weigh in.',
297             'thumbnail': 're:^https?://.*\.jpg$',
298             'upload_date': '20140208',
299             'timestamp': 1391824260,
300             'duration': 467.0,
301             'categories': ['MSNBC/Issues/Democrats', 'MSNBC/Issues/Elections/Election 2016'],
302             'uploader': 'NBCU-NEWS',
303         },
304     }]
305
306     def _extract_feed_info(self, provider_id, feed_id, filter_query, video_id, custom_fields=None, asset_types_query={}):
307         real_url = self._URL_TEMPLATE % (self.http_scheme(), provider_id, feed_id, filter_query)
308         entry = self._download_json(real_url, video_id)['entries'][0]
309
310         formats = []
311         subtitles = {}
312         first_video_id = None
313         duration = None
314         asset_types = []
315         for item in entry['media$content']:
316             smil_url = item['plfile$url']
317             cur_video_id = ThePlatformIE._match_id(smil_url)
318             if first_video_id is None:
319                 first_video_id = cur_video_id
320                 duration = float_or_none(item.get('plfile$duration'))
321             for asset_type in item['plfile$assetTypes']:
322                 if asset_type in asset_types:
323                     continue
324                 asset_types.append(asset_type)
325                 query = {
326                     'mbr': 'true',
327                     'formats': item['plfile$format'],
328                     'assetTypes': asset_type,
329                 }
330                 if asset_type in asset_types_query:
331                     query.update(asset_types_query[asset_type])
332                 cur_formats, cur_subtitles = self._extract_theplatform_smil(update_url_query(
333                     smil_url, query), video_id, 'Downloading SMIL data for %s' % asset_type)
334                 formats.extend(cur_formats)
335                 subtitles = self._merge_subtitles(subtitles, cur_subtitles)
336
337         self._sort_formats(formats)
338
339         thumbnails = [{
340             'url': thumbnail['plfile$url'],
341             'width': int_or_none(thumbnail.get('plfile$width')),
342             'height': int_or_none(thumbnail.get('plfile$height')),
343         } for thumbnail in entry.get('media$thumbnails', [])]
344
345         timestamp = int_or_none(entry.get('media$availableDate'), scale=1000)
346         categories = [item['media$name'] for item in entry.get('media$categories', [])]
347
348         ret = self._extract_theplatform_metadata('%s/%s' % (provider_id, first_video_id), video_id)
349         subtitles = self._merge_subtitles(subtitles, ret['subtitles'])
350         ret.update({
351             'id': video_id,
352             'formats': formats,
353             'subtitles': subtitles,
354             'thumbnails': thumbnails,
355             'duration': duration,
356             'timestamp': timestamp,
357             'categories': categories,
358         })
359         if custom_fields:
360             ret.update(custom_fields(entry))
361
362         return ret
363
364     def _real_extract(self, url):
365         mobj = re.match(self._VALID_URL, url)
366
367         video_id = mobj.group('id')
368         provider_id = mobj.group('provider_id')
369         feed_id = mobj.group('feed_id')
370         filter_query = mobj.group('filter')
371
372         return self._extract_feed_info(provider_id, feed_id, filter_query, video_id)