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