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