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