]> jfr.im git - yt-dlp.git/blob - yt_dlp/extractor/theplatform.py
bf7efc0134da41f8fad6a999b68741dc98d5f89e
[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
127 _TESTS = [{
128 # from http://www.metacafe.com/watch/cb-e9I_cZgTgIPd/blackberrys_big_bold_z30/
129 'url': 'http://link.theplatform.com/s/dJ5BDC/e9I_cZgTgIPd/meta.smil?format=smil&Tracking=true&mbr=true',
130 'info_dict': {
131 'id': 'e9I_cZgTgIPd',
132 'ext': 'flv',
133 'title': 'Blackberry\'s big, bold Z30',
134 'description': 'The Z30 is Blackberry\'s biggest, baddest mobile messaging device yet.',
135 'duration': 247,
136 'timestamp': 1383239700,
137 'upload_date': '20131031',
138 'uploader': 'CBSI-NEW',
139 },
140 'params': {
141 # rtmp download
142 'skip_download': True,
143 },
144 'skip': '404 Not Found',
145 }, {
146 # from http://www.cnet.com/videos/tesla-model-s-a-second-step-towards-a-cleaner-motoring-future/
147 'url': 'http://link.theplatform.com/s/kYEXFC/22d_qsQ6MIRT',
148 'info_dict': {
149 'id': '22d_qsQ6MIRT',
150 'ext': 'flv',
151 'description': 'md5:ac330c9258c04f9d7512cf26b9595409',
152 'title': 'Tesla Model S: A second step towards a cleaner motoring future',
153 'timestamp': 1426176191,
154 'upload_date': '20150312',
155 'uploader': 'CBSI-NEW',
156 },
157 'params': {
158 # rtmp download
159 'skip_download': True,
160 }
161 }, {
162 'url': 'https://player.theplatform.com/p/D6x-PC/pulse_preview/embed/select/media/yMBg9E8KFxZD',
163 'info_dict': {
164 'id': 'yMBg9E8KFxZD',
165 'ext': 'mp4',
166 'description': 'md5:644ad9188d655b742f942bf2e06b002d',
167 'title': 'HIGHLIGHTS: USA bag first ever series Cup win',
168 'uploader': 'EGSM',
169 }
170 }, {
171 'url': 'http://player.theplatform.com/p/NnzsPC/widget/select/media/4Y0TlYUr_ZT7',
172 'only_matching': True,
173 }, {
174 'url': 'http://player.theplatform.com/p/2E2eJC/nbcNewsOffsite?guid=tdy_or_siri_150701',
175 'md5': 'fb96bb3d85118930a5b055783a3bd992',
176 'info_dict': {
177 'id': 'tdy_or_siri_150701',
178 'ext': 'mp4',
179 'title': 'iPhone Siri’s sassy response to a math question has people talking',
180 'description': 'md5:a565d1deadd5086f3331d57298ec6333',
181 'duration': 83.0,
182 'thumbnail': r're:^https?://.*\.jpg$',
183 'timestamp': 1435752600,
184 'upload_date': '20150701',
185 'uploader': 'NBCU-NEWS',
186 },
187 }, {
188 # From http://www.nbc.com/the-blacklist/video/sir-crispin-crandall/2928790?onid=137781#vc137781=1
189 # geo-restricted (US), HLS encrypted with AES-128
190 'url': 'http://player.theplatform.com/p/NnzsPC/onsite_universal/select/media/guid/2410887629/2928790?fwsitesection=nbc_the_blacklist_video_library&autoPlay=true&carouselID=137781',
191 'only_matching': True,
192 }]
193
194 @classmethod
195 def _extract_urls(cls, webpage):
196 m = re.search(
197 r'''(?x)
198 <meta\s+
199 property=(["'])(?:og:video(?::(?:secure_)?url)?|twitter:player)\1\s+
200 content=(["'])(?P<url>https?://player\.theplatform\.com/p/.+?)\2
201 ''', webpage)
202 if m:
203 return [m.group('url')]
204
205 # Are whitespaces ignored in URLs?
206 # https://github.com/ytdl-org/youtube-dl/issues/12044
207 matches = re.findall(
208 r'(?s)<(?:iframe|script)[^>]+src=(["\'])((?:https?:)?//player\.theplatform\.com/p/.+?)\1', webpage)
209 if matches:
210 return [re.sub(r'\s', '', list(zip(*matches))[1][0])]
211
212 @staticmethod
213 def _sign_url(url, sig_key, sig_secret, life=600, include_qs=False):
214 flags = '10' if include_qs else '00'
215 expiration_date = '%x' % (int(time.time()) + life)
216
217 def str_to_hex(str):
218 return binascii.b2a_hex(str.encode('ascii')).decode('ascii')
219
220 def hex_to_bytes(hex):
221 return binascii.a2b_hex(hex.encode('ascii'))
222
223 relative_path = re.match(r'https?://link\.theplatform\.com/s/([^?]+)', url).group(1)
224 clear_text = hex_to_bytes(flags + expiration_date + str_to_hex(relative_path))
225 checksum = hmac.new(sig_key.encode('ascii'), clear_text, hashlib.sha1).hexdigest()
226 sig = flags + expiration_date + checksum + str_to_hex(sig_secret)
227 return '%s&sig=%s' % (url, sig)
228
229 def _real_extract(self, url):
230 url, smuggled_data = unsmuggle_url(url, {})
231 self._initialize_geo_bypass({
232 'countries': smuggled_data.get('geo_countries'),
233 })
234
235 mobj = self._match_valid_url(url)
236 provider_id = mobj.group('provider_id')
237 video_id = mobj.group('id')
238
239 if not provider_id:
240 provider_id = 'dJ5BDC'
241
242 path = provider_id + '/'
243 if mobj.group('media'):
244 path += mobj.group('media')
245 path += video_id
246
247 qs_dict = parse_qs(url)
248 if 'guid' in qs_dict:
249 webpage = self._download_webpage(url, video_id)
250 scripts = re.findall(r'<script[^>]+src="([^"]+)"', webpage)
251 feed_id = None
252 # feed id usually locates in the last script.
253 # Seems there's no pattern for the interested script filename, so
254 # I try one by one
255 for script in reversed(scripts):
256 feed_script = self._download_webpage(
257 self._proto_relative_url(script, 'http:'),
258 video_id, 'Downloading feed script')
259 feed_id = self._search_regex(
260 r'defaultFeedId\s*:\s*"([^"]+)"', feed_script,
261 'default feed id', default=None)
262 if feed_id is not None:
263 break
264 if feed_id is None:
265 raise ExtractorError('Unable to find feed id')
266 return self.url_result('http://feed.theplatform.com/f/%s/%s?byGuid=%s' % (
267 provider_id, feed_id, qs_dict['guid'][0]))
268
269 if smuggled_data.get('force_smil_url', False):
270 smil_url = url
271 # Explicitly specified SMIL (see https://github.com/ytdl-org/youtube-dl/issues/7385)
272 elif '/guid/' in url:
273 headers = {}
274 source_url = smuggled_data.get('source_url')
275 if source_url:
276 headers['Referer'] = source_url
277 request = sanitized_Request(url, headers=headers)
278 webpage = self._download_webpage(request, video_id)
279 smil_url = self._search_regex(
280 r'<link[^>]+href=(["\'])(?P<url>.+?)\1[^>]+type=["\']application/smil\+xml',
281 webpage, 'smil url', group='url')
282 path = self._search_regex(
283 r'link\.theplatform\.com/s/((?:[^/?#&]+/)+[^/?#&]+)', smil_url, 'path')
284 smil_url += '?' if '?' not in smil_url else '&' + 'formats=m3u,mpeg4'
285 elif mobj.group('config'):
286 config_url = url + '&form=json'
287 config_url = config_url.replace('swf/', 'config/')
288 config_url = config_url.replace('onsite/', 'onsite/config/')
289 config = self._download_json(config_url, video_id, 'Downloading config')
290 if 'releaseUrl' in config:
291 release_url = config['releaseUrl']
292 else:
293 release_url = 'http://link.theplatform.com/s/%s?mbr=true' % path
294 smil_url = release_url + '&formats=MPEG4&manifest=f4m'
295 else:
296 smil_url = 'http://link.theplatform.com/s/%s?mbr=true' % path
297
298 sig = smuggled_data.get('sig')
299 if sig:
300 smil_url = self._sign_url(smil_url, sig['key'], sig['secret'])
301
302 formats, subtitles = self._extract_theplatform_smil(smil_url, video_id)
303 self._sort_formats(formats)
304
305 ret = self._extract_theplatform_metadata(path, video_id)
306 combined_subtitles = self._merge_subtitles(ret.get('subtitles', {}), subtitles)
307 ret.update({
308 'id': video_id,
309 'formats': formats,
310 'subtitles': combined_subtitles,
311 })
312
313 return ret
314
315
316 class ThePlatformFeedIE(ThePlatformBaseIE):
317 _URL_TEMPLATE = '%s//feed.theplatform.com/f/%s/%s?form=json&%s'
318 _VALID_URL = r'https?://feed\.theplatform\.com/f/(?P<provider_id>[^/]+)/(?P<feed_id>[^?/]+)\?(?:[^&]+&)*(?P<filter>by(?:Gui|I)d=(?P<id>[^&]+))'
319 _TESTS = [{
320 # From http://player.theplatform.com/p/7wvmTC/MSNBCEmbeddedOffSite?guid=n_hardball_5biden_140207
321 'url': 'http://feed.theplatform.com/f/7wvmTC/msnbc_video-p-test?form=json&pretty=true&range=-40&byGuid=n_hardball_5biden_140207',
322 'md5': '6e32495b5073ab414471b615c5ded394',
323 'info_dict': {
324 'id': 'n_hardball_5biden_140207',
325 'ext': 'mp4',
326 'title': 'The Biden factor: will Joe run in 2016?',
327 'description': 'Could Vice President Joe Biden be preparing a 2016 campaign? Mark Halperin and Sam Stein weigh in.',
328 'thumbnail': r're:^https?://.*\.jpg$',
329 'upload_date': '20140208',
330 'timestamp': 1391824260,
331 'duration': 467.0,
332 'categories': ['MSNBC/Issues/Democrats', 'MSNBC/Issues/Elections/Election 2016'],
333 'uploader': 'NBCU-NEWS',
334 },
335 }, {
336 'url': 'http://feed.theplatform.com/f/2E2eJC/nnd_NBCNews?byGuid=nn_netcast_180306.Copy.01',
337 'only_matching': True,
338 }]
339
340 def _extract_feed_info(self, provider_id, feed_id, filter_query, video_id, custom_fields=None, asset_types_query={}, account_id=None):
341 real_url = self._URL_TEMPLATE % (self.http_scheme(), provider_id, feed_id, filter_query)
342 entry = self._download_json(real_url, video_id)['entries'][0]
343 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')
344
345 formats = []
346 subtitles = {}
347 first_video_id = None
348 duration = None
349 asset_types = []
350 for item in entry['media$content']:
351 smil_url = item['plfile$url']
352 cur_video_id = ThePlatformIE._match_id(smil_url)
353 if first_video_id is None:
354 first_video_id = cur_video_id
355 duration = float_or_none(item.get('plfile$duration'))
356 file_asset_types = item.get('plfile$assetTypes') or parse_qs(smil_url)['assetTypes']
357 for asset_type in file_asset_types:
358 if asset_type in asset_types:
359 continue
360 asset_types.append(asset_type)
361 query = {
362 'mbr': 'true',
363 'formats': item['plfile$format'],
364 'assetTypes': asset_type,
365 }
366 if asset_type in asset_types_query:
367 query.update(asset_types_query[asset_type])
368 cur_formats, cur_subtitles = self._extract_theplatform_smil(update_url_query(
369 main_smil_url or smil_url, query), video_id, 'Downloading SMIL data for %s' % asset_type)
370 formats.extend(cur_formats)
371 subtitles = self._merge_subtitles(subtitles, cur_subtitles)
372
373 self._sort_formats(formats)
374
375 thumbnails = [{
376 'url': thumbnail['plfile$url'],
377 'width': int_or_none(thumbnail.get('plfile$width')),
378 'height': int_or_none(thumbnail.get('plfile$height')),
379 } for thumbnail in entry.get('media$thumbnails', [])]
380
381 timestamp = int_or_none(entry.get('media$availableDate'), scale=1000)
382 categories = [item['media$name'] for item in entry.get('media$categories', [])]
383
384 ret = self._extract_theplatform_metadata('%s/%s' % (provider_id, first_video_id), video_id)
385 subtitles = self._merge_subtitles(subtitles, ret['subtitles'])
386 ret.update({
387 'id': video_id,
388 'formats': formats,
389 'subtitles': subtitles,
390 'thumbnails': thumbnails,
391 'duration': duration,
392 'timestamp': timestamp,
393 'categories': categories,
394 })
395 if custom_fields:
396 ret.update(custom_fields(entry))
397
398 return ret
399
400 def _real_extract(self, url):
401 mobj = self._match_valid_url(url)
402
403 video_id = mobj.group('id')
404 provider_id = mobj.group('provider_id')
405 feed_id = mobj.group('feed_id')
406 filter_query = mobj.group('filter')
407
408 return self._extract_feed_info(provider_id, feed_id, filter_query, video_id)