8 from .once
import OnceIE
9 from .adobepass
import AdobePassIE
10 from ..networking
import Request
26 from ..networking
import HEADRequest
28 default_ns
= 'http://www.w3.org/2005/SMIL21/Language'
29 _x
= lambda p
: xpath_with_ns(p
, {'smil': default_ns}
)
32 class ThePlatformBaseIE(OnceIE
):
35 def _extract_theplatform_smil(self
, smil_url
, video_id
, note
='Downloading SMIL data'):
36 meta
= self
._download
_xml
(
37 smil_url
, video_id
, note
=note
, query
={'format': 'SMIL'}
,
38 headers
=self
.geo_verification_headers())
39 error_element
= find_xpath_attr(meta
, _x('.//smil:ref'), 'src')
40 if error_element
is not None:
41 exception
= find_xpath_attr(
42 error_element
, _x('.//smil:param'), 'name', 'exception')
43 if exception
is not None:
44 if exception
.get('value') == 'GeoLocationBlocked':
45 self
.raise_geo_restricted(error_element
.attrib
['abstract'])
46 elif error_element
.attrib
['src'].startswith(
47 'http://link.theplatform.%s/s/errorFiles/Unavailable.'
50 error_element
.attrib
['abstract'], expected
=True)
52 smil_formats
, subtitles
= self
._parse
_smil
_formats
_and
_subtitles
(
53 meta
, smil_url
, video_id
, namespace
=default_ns
,
54 # the parameters are from syfy.com, other sites may use others,
55 # they also work for nbc.com
56 f4m_params
={'g': 'UXWGVKRWHFSP', 'hdcore': '3.0.3'}
,
57 transform_rtmp_url
=lambda streamer
, src
: (streamer
, 'mp4:' + src
))
60 for _format
in smil_formats
:
61 if OnceIE
.suitable(_format
['url']):
62 formats
.extend(self
._extract
_once
_formats
(_format
['url']))
64 media_url
= _format
['url']
65 if determine_ext(media_url
) == 'm3u8':
66 hdnea2
= self
._get
_cookies
(media_url
).get('hdnea2')
68 _format
['url'] = update_url_query(media_url
, {'hdnea3': hdnea2.value}
)
70 formats
.append(_format
)
72 return formats
, subtitles
74 def _download_theplatform_metadata(self
, path
, video_id
):
75 info_url
= 'http://link.theplatform.%s/s/%s?format=preview' % (self
._TP
_TLD
, path
)
76 return self
._download
_json
(info_url
, video_id
)
78 def _parse_theplatform_metadata(self
, info
):
80 captions
= info
.get('captions')
81 if isinstance(captions
, list):
82 for caption
in captions
:
83 lang
, src
, mime
= caption
.get('lang', 'en'), caption
.get('src'), caption
.get('type')
84 subtitles
.setdefault(lang
, []).append({
85 'ext': mimetype2ext(mime
),
89 duration
= info
.get('duration')
90 tp_chapters
= info
.get('chapters', [])
93 def _add_chapter(start_time
, end_time
):
94 start_time
= float_or_none(start_time
, 1000)
95 end_time
= float_or_none(end_time
, 1000)
96 if start_time
is None or end_time
is None:
99 'start_time': start_time
,
100 'end_time': end_time
,
103 for chapter
in tp_chapters
[:-1]:
104 _add_chapter(chapter
.get('startTime'), chapter
.get('endTime'))
105 _add_chapter(tp_chapters
[-1].get('startTime'), tp_chapters
[-1].get('endTime') or duration
)
107 def extract_site_specific_field(field
):
108 # A number of sites have custom-prefixed keys, e.g. 'cbc$seasonNumber'
109 return traverse_obj(info
, lambda k
, v
: v
and k
.endswith(f
'${field}'), get_all
=False)
112 'title': info
['title'],
113 'subtitles': subtitles
,
114 'description': info
['description'],
115 'thumbnail': info
['defaultThumbnailUrl'],
116 'duration': float_or_none(duration
, 1000),
117 'timestamp': int_or_none(info
.get('pubDate'), 1000) or None,
118 'uploader': info
.get('billingCode'),
119 'chapters': chapters
,
120 'creator': traverse_obj(info
, ('author', {str}
)) or None,
121 'categories': traverse_obj(info
, (
122 'categories', lambda _
, v
: v
.get('label') in ('category', None), 'name', {str}
)) or None,
123 'tags': traverse_obj(info
, ('keywords', {lambda x: re.split(r'[;,]\s?', x) if x else None}
)),
124 'location': extract_site_specific_field('region'),
125 'series': extract_site_specific_field('show'),
126 'season_number': int_or_none(extract_site_specific_field('seasonNumber')),
127 'media_type': extract_site_specific_field('programmingType') or extract_site_specific_field('type'),
130 def _extract_theplatform_metadata(self
, path
, video_id
):
131 info
= self
._download
_theplatform
_metadata
(path
, video_id
)
132 return self
._parse
_theplatform
_metadata
(info
)
135 class ThePlatformIE(ThePlatformBaseIE
, AdobePassIE
):
136 _VALID_URL
= r
'''(?x)
137 (?:https?://(?:link|player)\.theplatform\.com/[sp]/(?P<provider_id>[^/]+)/
138 (?:(?:(?:[^/]+/)+select/)?(?P<media>media/(?:guid/\d+/)?)?|(?P<config>(?:[^/\?]+/(?:swf|config)|onsite)/select/))?
139 |theplatform:)(?P<id>[^/\?&]+)'''
143 property=(["'])(?:og:video(?::(?:secure_)?url)?|twitter:player)\1\s+
144 content=(["'])(?P<url>https?://player\.theplatform\.com/p/.+?)\2''',
145 r
'(?s)<(?:iframe|script)[^>]+src=(["\'])(?P
<url
>(?
:https?
:)?
//player\
.theplatform\
.com
/p
/.+?
)\
1'
149 # from http://www.metacafe.com/watch/cb-e9I_cZgTgIPd/blackberrys_big_bold_z30/
150 'url
': 'http
://link
.theplatform
.com
/s
/dJ5BDC
/e9I_cZgTgIPd
/meta
.smil?format
=smil
&Tracking
=true
&mbr
=true
',
152 'id': 'e9I_cZgTgIPd
',
154 'title
': 'Blackberry
\'s big
, bold Z30
',
155 'description
': 'The Z30
is Blackberry
\'s biggest
, baddest mobile messaging device yet
.',
157 'timestamp
': 1383239700,
158 'upload_date
': '20131031',
159 'uploader
': 'CBSI
-NEW
',
163 'skip_download
': True,
165 'skip
': '404 Not Found
',
167 # from http://www.cnet.com/videos/tesla-model-s-a-second-step-towards-a-cleaner-motoring-future/
168 'url
': 'http
://link
.theplatform
.com
/s
/kYEXFC
/22d_qsQ6MIRT
',
170 'id': '22d_qsQ6MIRT
',
172 'description
': 'md5
:ac330c9258c04f9d7512cf26b9595409
',
173 'title
': 'Tesla Model S
: A second step towards a cleaner motoring future
',
174 'timestamp
': 1426176191,
175 'upload_date
': '20150312',
176 'uploader
': 'CBSI
-NEW
',
180 'skip_download
': True,
182 'skip
': 'CNet no longer uses ThePlatform
',
184 'url
': 'https
://player
.theplatform
.com
/p
/D6x
-PC
/pulse_preview
/embed
/select
/media
/yMBg9E8KFxZD
',
186 'id': 'yMBg9E8KFxZD
',
188 'description
': 'md5
:644ad9188d655b742f942bf2e06b002d
',
189 'title
': 'HIGHLIGHTS
: USA bag first ever series Cup win
',
194 'url
': 'http
://player
.theplatform
.com
/p
/NnzsPC
/widget
/select
/media
/4Y0TlYUr_ZT7
',
195 'only_matching
': True,
197 'url
': 'http
://player
.theplatform
.com
/p
/2E2eJC
/nbcNewsOffsite?guid
=tdy_or_siri_150701
',
198 'md5
': 'fb96bb3d85118930a5b055783a3bd992
',
200 'id': 'tdy_or_siri_150701
',
202 'title
': 'iPhone Siri’s sassy response to a math question has people talking
',
203 'description
': 'md5
:a565d1deadd5086f3331d57298ec6333
',
205 'thumbnail
': r're
:^https?
://.*\
.jpg$
',
206 'timestamp
': 1435752600,
207 'upload_date
': '20150701',
208 'uploader
': 'NBCU
-NEWS
',
210 'skip
': 'Error
: Player PID
"nbcNewsOffsite" is disabled
',
212 # From http://www.nbc.com/the-blacklist/video/sir-crispin-crandall/2928790?onid=137781#vc137781=1
213 # geo-restricted (US), HLS encrypted with AES-128
214 'url
': 'http
://player
.theplatform
.com
/p
/NnzsPC
/onsite_universal
/select
/media
/guid
/2410887629/2928790?fwsitesection
=nbc_the_blacklist_video_library
&autoPlay
=true
&carouselID
=137781',
215 'only_matching
': True,
219 def _extract_embed_urls(cls, url, webpage):
220 # Are whitespaces ignored in URLs?
221 # https://github.com/ytdl-org/youtube-dl/issues/12044
222 for embed_url in super()._extract_embed_urls(url, webpage):
223 yield re.sub(r'\s
', '', embed_url)
226 def _sign_url(url, sig_key, sig_secret, life=600, include_qs=False):
227 flags = '10' if include_qs else '00'
228 expiration_date = '%x' % (int(time.time()) + life)
231 return binascii.b2a_hex(str.encode('ascii
')).decode('ascii
')
233 def hex_to_bytes(hex):
234 return binascii.a2b_hex(hex.encode('ascii
'))
236 relative_path = re.match(r'https?
://link\
.theplatform\
.com
/s
/([^?
]+)', url).group(1)
237 clear_text = hex_to_bytes(flags + expiration_date + str_to_hex(relative_path))
238 checksum = hmac.new(sig_key.encode('ascii
'), clear_text, hashlib.sha1).hexdigest()
239 sig = flags + expiration_date + checksum + str_to_hex(sig_secret)
240 return '%s&sig
=%s' % (url, sig)
242 def _real_extract(self, url):
243 url, smuggled_data = unsmuggle_url(url, {})
244 self._initialize_geo_bypass({
245 'countries
': smuggled_data.get('geo_countries
'),
248 mobj = self._match_valid_url(url)
249 provider_id = mobj.group('provider_id
')
250 video_id = mobj.group('id')
253 provider_id = 'dJ5BDC
'
255 path = provider_id + '/'
256 if mobj.group('media
'):
257 path += mobj.group('media
')
260 qs_dict = parse_qs(url)
261 if 'guid
' in qs_dict:
262 webpage = self._download_webpage(url, video_id)
263 scripts = re.findall(r'<script
[^
>]+src
="([^"]+)"', webpage)
265 # feed id usually locates in the last script.
266 # Seems there's no pattern for the interested script filename, so
268 for script in reversed(scripts):
269 feed_script = self._download_webpage(
270 self._proto_relative_url(script, 'http:'),
271 video_id, 'Downloading feed script')
272 feed_id = self._search_regex(
273 r'defaultFeedId\s*:\s*"([^
"]+)"', feed_script,
274 'default feed
id', default=None)
275 if feed_id is not None:
278 raise ExtractorError('Unable to find feed
id')
279 return self.url_result('http
://feed
.theplatform
.com
/f
/%s/%s?byGuid
=%s' % (
280 provider_id, feed_id, qs_dict['guid
'][0]))
282 if smuggled_data.get('force_smil_url
', False):
284 # Explicitly specified SMIL (see https://github.com/ytdl-org/youtube-dl/issues/7385)
285 elif '/guid
/' in url:
287 source_url = smuggled_data.get('source_url
')
289 headers['Referer
'] = source_url
290 request = Request(url, headers=headers)
291 webpage = self._download_webpage(request, video_id)
292 smil_url = self._search_regex(
293 r'<link
[^
>]+href
=(["\'])(?P<url>.+?)\1[^>]+type=["\']application
/smil\
+xml
',
294 webpage, 'smil url
', group='url
')
295 path = self._search_regex(
296 r'link\
.theplatform\
.com
/s
/((?
:[^
/?
#&]+/)+[^/?#&]+)', smil_url, 'path')
297 smil_url
+= '?' if '?' not in smil_url
else '&' + 'formats=m3u,mpeg4'
298 elif mobj
.group('config'):
299 config_url
= url
+ '&form=json'
300 config_url
= config_url
.replace('swf/', 'config/')
301 config_url
= config_url
.replace('onsite/', 'onsite/config/')
302 config
= self
._download
_json
(config_url
, video_id
, 'Downloading config')
303 if 'releaseUrl' in config
:
304 release_url
= config
['releaseUrl']
306 release_url
= 'http://link.theplatform.com/s/%s?mbr=true' % path
307 smil_url
= release_url
+ '&formats=MPEG4&manifest=f4m'
309 smil_url
= 'http://link.theplatform.com/s/%s?mbr=true' % path
311 sig
= smuggled_data
.get('sig')
313 smil_url
= self
._sign
_url
(smil_url
, sig
['key'], sig
['secret'])
315 formats
, subtitles
= self
._extract
_theplatform
_smil
(smil_url
, video_id
)
317 # With some sites, manifest URL must be forced to extract HLS formats
318 if not traverse_obj(formats
, lambda _
, v
: v
['format_id'].startswith('hls')):
319 m3u8_url
= update_url(url
, query
='mbr=true&manifest=m3u', fragment
=None)
320 urlh
= self
._request
_webpage
(
321 HEADRequest(m3u8_url
), video_id
, 'Checking for HLS formats', 'No HLS formats found', fatal
=False)
322 if urlh
and urlhandle_detect_ext(urlh
) == 'm3u8':
323 m3u8_fmts
, m3u8_subs
= self
._extract
_m
3u8_formats
_and
_subtitles
(
324 m3u8_url
, video_id
, m3u8_id
='hls', fatal
=False)
325 formats
.extend(m3u8_fmts
)
326 self
._merge
_subtitles
(m3u8_subs
, target
=subtitles
)
328 ret
= self
._extract
_theplatform
_metadata
(path
, video_id
)
329 combined_subtitles
= self
._merge
_subtitles
(ret
.get('subtitles', {}), subtitles
)
333 'subtitles': combined_subtitles
,
339 class ThePlatformFeedIE(ThePlatformBaseIE
):
340 _URL_TEMPLATE
= '%s//feed.theplatform.com/f/%s/%s?form=json&%s'
341 _VALID_URL
= r
'https?://feed\.theplatform\.com/f/(?P<provider_id>[^/]+)/(?P<feed_id>[^?/]+)\?(?:[^&]+&)*(?P<filter>by(?:Gui|I)d=(?P<id>[^&]+))'
343 # From http://player.theplatform.com/p/7wvmTC/MSNBCEmbeddedOffSite?guid=n_hardball_5biden_140207
344 'url': 'http://feed.theplatform.com/f/7wvmTC/msnbc_video-p-test?form=json&pretty=true&range=-40&byGuid=n_hardball_5biden_140207',
345 'md5': '6e32495b5073ab414471b615c5ded394',
347 'id': 'n_hardball_5biden_140207',
349 'title': 'The Biden factor: will Joe run in 2016?',
350 'description': 'Could Vice President Joe Biden be preparing a 2016 campaign? Mark Halperin and Sam Stein weigh in.',
351 'thumbnail': r
're:^https?://.*\.jpg$',
352 'upload_date': '20140208',
353 'timestamp': 1391824260,
355 'categories': ['MSNBC/Issues/Democrats', 'MSNBC/Issues/Elections/Election 2016'],
356 'uploader': 'NBCU-NEWS',
359 'url': 'http://feed.theplatform.com/f/2E2eJC/nnd_NBCNews?byGuid=nn_netcast_180306.Copy.01',
360 'only_matching': True,
363 def _extract_feed_info(self
, provider_id
, feed_id
, filter_query
, video_id
, custom_fields
=None, asset_types_query
={}, account_id
=None):
364 real_url
= self
._URL
_TEMPLATE
% (self
.http_scheme(), provider_id
, feed_id
, filter_query
)
365 entry
= self
._download
_json
(real_url
, video_id
)['entries'][0]
366 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')
370 first_video_id
= None
373 for item
in entry
['media$content']:
374 smil_url
= item
['plfile$url']
375 cur_video_id
= ThePlatformIE
._match
_id
(smil_url
)
376 if first_video_id
is None:
377 first_video_id
= cur_video_id
378 duration
= float_or_none(item
.get('plfile$duration'))
379 file_asset_types
= item
.get('plfile$assetTypes') or parse_qs(smil_url
)['assetTypes']
380 for asset_type
in file_asset_types
:
381 if asset_type
in asset_types
:
383 asset_types
.append(asset_type
)
386 'formats': item
['plfile$format'],
387 'assetTypes': asset_type
,
389 if asset_type
in asset_types_query
:
390 query
.update(asset_types_query
[asset_type
])
391 cur_formats
, cur_subtitles
= self
._extract
_theplatform
_smil
(update_url_query(
392 main_smil_url
or smil_url
, query
), video_id
, 'Downloading SMIL data for %s' % asset_type
)
393 formats
.extend(cur_formats
)
394 subtitles
= self
._merge
_subtitles
(subtitles
, cur_subtitles
)
397 'url': thumbnail
['plfile$url'],
398 'width': int_or_none(thumbnail
.get('plfile$width')),
399 'height': int_or_none(thumbnail
.get('plfile$height')),
400 } for thumbnail
in entry
.get('media$thumbnails', [])]
402 timestamp
= int_or_none(entry
.get('media$availableDate'), scale
=1000)
403 categories
= [item
['media$name'] for item
in entry
.get('media$categories', [])]
405 ret
= self
._extract
_theplatform
_metadata
('%s/%s' % (provider_id
, first_video_id
), video_id
)
406 subtitles
= self
._merge
_subtitles
(subtitles
, ret
['subtitles'])
410 'subtitles': subtitles
,
411 'thumbnails': thumbnails
,
412 'duration': duration
,
413 'timestamp': timestamp
,
414 'categories': categories
,
417 ret
.update(custom_fields(entry
))
421 def _real_extract(self
, url
):
422 mobj
= self
._match
_valid
_url
(url
)
424 video_id
= mobj
.group('id')
425 provider_id
= mobj
.group('provider_id')
426 feed_id
= mobj
.group('feed_id')
427 filter_query
= mobj
.group('filter')
429 return self
._extract
_feed
_info
(provider_id
, feed_id
, filter_query
, video_id
)