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