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