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