2 from __future__ 
import unicode_literals
 
  11 from .once 
import OnceIE
 
  12 from .adobepass 
import AdobePassIE
 
  13 from ..compat 
import ( 
  15     compat_urllib_parse_urlparse
, 
  30 default_ns 
= 'http://www.w3.org/2005/SMIL21/Language' 
  31 _x 
= lambda p
: xpath_with_ns(p
, {'smil': default_ns
}) 
  34 class ThePlatformBaseIE(OnceIE
): 
  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) 
  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
)) 
  54         for _format 
in smil_formats
: 
  55             if OnceIE
.suitable(_format
['url']): 
  56                 formats
.extend(self
._extract
_once
_formats
(_format
['url'])) 
  58                 media_url 
= _format
['url'] 
  59                 if determine_ext(media_url
) == 'm3u8': 
  60                     hdnea2 
= self
._get
_cookies
(media_url
).get('hdnea2') 
  62                         _format
['url'] = update_url_query(media_url
, {'hdnea3': hdnea2
.value
}) 
  64                 formats
.append(_format
) 
  66         subtitles 
= self
._parse
_smil
_subtitles
(meta
, default_ns
) 
  68         return formats
, subtitles
 
  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
) 
  74     def _parse_theplatform_metadata(self
, info
): 
  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
), 
  85         duration 
= info
.get('duration') 
  86         tp_chapters 
= info
.get('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: 
  95                     'start_time': start_time
, 
  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
) 
 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
, 
 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
) 
 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>[^/\?&]+)''' 
 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', 
 129             'id': 'e9I_cZgTgIPd', 
 131             'title': 'Blackberry\'s big, bold Z30', 
 132             'description': 'The Z30 is Blackberry\'s biggest, baddest mobile messaging device yet.', 
 134             'timestamp': 1383239700, 
 135             'upload_date': '20131031', 
 136             'uploader': 'CBSI-NEW', 
 140             'skip_download': True, 
 142         'skip': '404 Not Found', 
 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', 
 147             'id': '22d_qsQ6MIRT', 
 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', 
 157             'skip_download': True, 
 160         'url': 'https://player.theplatform.com/p/D6x-PC/pulse_preview/embed/select/media/yMBg9E8KFxZD', 
 162             'id': 'yMBg9E8KFxZD', 
 164             'description': 'md5:644ad9188d655b742f942bf2e06b002d', 
 165             'title': 'HIGHLIGHTS: USA bag first ever series Cup win', 
 169         'url': 'http://player.theplatform.com/p/NnzsPC/widget/select/media/4Y0TlYUr_ZT7', 
 170         'only_matching': True, 
 172         'url': 'http://player.theplatform.com/p/2E2eJC/nbcNewsOffsite?guid=tdy_or_siri_150701', 
 173         'md5': 'fb96bb3d85118930a5b055783a3bd992', 
 175             'id': 'tdy_or_siri_150701', 
 177             'title': 'iPhone Siri’s sassy response to a math question has people talking', 
 178             'description': 'md5:a565d1deadd5086f3331d57298ec6333', 
 180             'thumbnail': r
're:^https?://.*\.jpg$', 
 181             'timestamp': 1435752600, 
 182             'upload_date': '20150701', 
 183             'uploader': 'NBCU-NEWS', 
 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, 
 193     def _extract_urls(cls
, webpage
): 
 197                         property=(["'])(?:og:video(?::(?:secure_)?url)?|twitter:player)\1\s+ 
 198                         content=(["'])(?P<url>https?://player\.theplatform\.com/p/.+?)\2 
 201             return [m
.group('url')] 
 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) 
 208             return [re.sub(r'\s
', '', list(zip(*matches))[1][0])] 
 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) 
 216             return binascii.b2a_hex(str.encode('ascii
')).decode('ascii
') 
 218         def hex_to_bytes(hex): 
 219             return binascii.a2b_hex(hex.encode('ascii
')) 
 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) 
 227     def _real_extract(self, url): 
 228         url, smuggled_data = unsmuggle_url(url, {}) 
 230         mobj = re.match(self._VALID_URL, url) 
 231         provider_id = mobj.group('provider_id
') 
 232         video_id = mobj.group('id') 
 235             provider_id = 'dJ5BDC
' 
 237         path = provider_id + '/' 
 238         if mobj.group('media
'): 
 239             path += mobj.group('media
') 
 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) 
 247             # feed id usually locates in the last script. 
 248             # Seems there's no pattern for the interested script filename, so 
 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: 
 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])) 
 264         if smuggled_data.get('force_smil_url
', False): 
 266         # Explicitly specified SMIL (see https://github.com/rg3/youtube-dl/issues/7385) 
 267         elif '/guid
/' in url: 
 269             source_url = smuggled_data.get('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'] 
 288                 release_url 
= 'http://link.theplatform.com/s/%s?mbr=true' % path
 
 289             smil_url 
= release_url 
+ '&formats=MPEG4&manifest=f4m' 
 291             smil_url 
= 'http://link.theplatform.com/s/%s?mbr=true' % path
 
 293         sig 
= smuggled_data
.get('sig') 
 295             smil_url 
= self
._sign
_url
(smil_url
, sig
['key'], sig
['secret']) 
 297         formats
, subtitles 
= self
._extract
_theplatform
_smil
(smil_url
, video_id
) 
 298         self
._sort
_formats
(formats
) 
 300         ret 
= self
._extract
_theplatform
_metadata
(path
, video_id
) 
 301         combined_subtitles 
= self
._merge
_subtitles
(ret
.get('subtitles', {}), subtitles
) 
 305             'subtitles': combined_subtitles
, 
 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>[^&]+))' 
 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', 
 319             'id': 'n_hardball_5biden_140207', 
 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, 
 327             'categories': ['MSNBC/Issues/Democrats', 'MSNBC/Issues/Elections/Election 2016'], 
 328             'uploader': 'NBCU-NEWS', 
 331         'url': 'http://feed.theplatform.com/f/2E2eJC/nnd_NBCNews?byGuid=nn_netcast_180306.Copy.01', 
 332         'only_matching': True, 
 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 
 342         first_video_id 
= None 
 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
: 
 354                 asset_types
.append(asset_type
) 
 357                     'formats': item
['plfile$format'], 
 358                     'assetTypes': asset_type
, 
 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
) 
 367         self
._sort
_formats
(formats
) 
 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', [])] 
 375         timestamp 
= int_or_none(entry
.get('media$availableDate'), scale
=1000) 
 376         categories 
= [item
['media$name'] for item 
in entry
.get('media$categories', [])] 
 378         ret 
= self
._extract
_theplatform
_metadata
('%s/%s' % (provider_id
, first_video_id
), video_id
) 
 379         subtitles 
= self
._merge
_subtitles
(subtitles
, ret
['subtitles']) 
 383             'subtitles': subtitles
, 
 384             'thumbnails': thumbnails
, 
 385             'duration': duration
, 
 386             'timestamp': timestamp
, 
 387             'categories': categories
, 
 390             ret
.update(custom_fields(entry
)) 
 394     def _real_extract(self
, url
): 
 395         mobj 
= re
.match(self
._VALID
_URL
, url
) 
 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') 
 402         return self
._extract
_feed
_info
(provider_id
, feed_id
, filter_query
, video_id
)