1 from __future__ 
import unicode_literals
 
   5 from .common 
import InfoExtractor
 
  28 def _media_xml_tag(tag
): 
  29     return '{http://search.yahoo.com/mrss/}%s' % tag
 
  32 class MTVServicesInfoExtractor(InfoExtractor
): 
  33     _MOBILE_TEMPLATE 
= None 
  37     def _id_from_uri(uri
): 
  38         return uri
.split(':')[-1] 
  41     def _remove_template_parameter(url
): 
  42         # Remove the templates, like &device={device} 
  43         return re
.sub(r
'&[^=]*?={.*?}(?=(&|$))', '', url
) 
  45     def _get_feed_url(self
, uri
): 
  48     def _get_thumbnail_url(self
, uri
, itemdoc
): 
  49         search_path 
= '%s/%s' % (_media_xml_tag('group'), _media_xml_tag('thumbnail')) 
  50         thumb_node 
= itemdoc
.find(search_path
) 
  51         if thumb_node 
is None: 
  54             return thumb_node
.attrib
['url'] 
  56     def _extract_mobile_video_formats(self
, mtvn_id
): 
  57         webpage_url 
= self
._MOBILE
_TEMPLATE 
% mtvn_id
 
  58         req 
= sanitized_Request(webpage_url
) 
  59         # Otherwise we get a webpage that would execute some javascript 
  60         req
.add_header('User-Agent', 'curl/7') 
  61         webpage 
= self
._download
_webpage
(req
, mtvn_id
, 
  62                                          'Downloading mobile page') 
  63         metrics_url 
= unescapeHTML(self
._search
_regex
(r
'<a href="(http://metrics.+?)"', webpage
, 'url')) 
  64         req 
= HEADRequest(metrics_url
) 
  65         response 
= self
._request
_webpage
(req
, mtvn_id
, 'Resolving url') 
  66         url 
= response
.geturl() 
  67         # Transform the url to get the best quality: 
  68         url 
= re
.sub(r
'.+pxE=mp4', 'http://mtvnmobile.vo.llnwd.net/kip0/_pxn=0+_pxK=18639+_pxE=mp4', url
, 1) 
  69         return [{'url': url
, 'ext': 'mp4'}] 
  71     def _extract_video_formats(self
, mdoc
, mtvn_id
, video_id
): 
  72         if re
.match(r
'.*/(error_country_block\.swf|geoblock\.mp4|copyright_error\.flv(?:\?geo\b.+?)?)$', mdoc
.find('.//src').text
) is not None: 
  73             if mtvn_id 
is not None and self
._MOBILE
_TEMPLATE 
is not None: 
  74                 self
.to_screen('The normal version is not available from your ' 
  75                                'country, trying with the mobile version') 
  76                 return self
._extract
_mobile
_video
_formats
(mtvn_id
) 
  77             raise ExtractorError('This video is not available from your country.', 
  81         for rendition 
in mdoc
.findall('.//rendition'): 
  82             if rendition
.get('method') == 'hls': 
  83                 hls_url 
= rendition
.find('./src').text
 
  84                 formats
.extend(self
._extract
_m
3u8_formats
( 
  85                     hls_url
, video_id
, ext
='mp4', entry_protocol
='m3u8_native', 
  90                     _
, _
, ext 
= rendition
.attrib
['type'].partition('/') 
  91                     rtmp_video_url 
= rendition
.find('./src').text
 
  92                     if 'error_not_available.swf' in rtmp_video_url
: 
  94                             '%s said: video is not available' % self
.IE_NAME
, 
  96                     if rtmp_video_url
.endswith('siteunavail.png'): 
  99                         'ext': 'flv' if rtmp_video_url
.startswith('rtmp') else ext
, 
 100                         'url': rtmp_video_url
, 
 101                         'format_id': '-'.join(filter(None, [ 
 102                             'rtmp' if rtmp_video_url
.startswith('rtmp') else None, 
 103                             rendition
.get('bitrate')])), 
 104                         'width': int(rendition
.get('width')), 
 105                         'height': int(rendition
.get('height')), 
 107                 except (KeyError, TypeError): 
 108                     raise ExtractorError('Invalid rendition field.') 
 109         self
._sort
_formats
(formats
) 
 112     def _extract_subtitles(self
, mdoc
, mtvn_id
): 
 114         for transcript 
in mdoc
.findall('.//transcript'): 
 115             if transcript
.get('kind') != 'captions': 
 117             lang 
= transcript
.get('srclang') 
 119                 'url': compat_str(typographic
.get('src')), 
 120                 'ext': typographic
.get('format') 
 121             } for typographic 
in transcript
.findall('./typographic')] 
 124     def _get_video_info(self
, itemdoc
, use_hls
=True): 
 125         uri 
= itemdoc
.find('guid').text
 
 126         video_id 
= self
._id
_from
_uri
(uri
) 
 127         self
.report_extraction(video_id
) 
 128         content_el 
= itemdoc
.find('%s/%s' % (_media_xml_tag('group'), _media_xml_tag('content'))) 
 129         mediagen_url 
= self
._remove
_template
_parameter
(content_el
.attrib
['url']) 
 130         mediagen_url 
= mediagen_url
.replace('device={device}', '') 
 131         if 'acceptMethods' not in mediagen_url
: 
 132             mediagen_url 
+= '&' if '?' in mediagen_url 
else '?' 
 133             mediagen_url 
+= 'acceptMethods=' 
 134             mediagen_url 
+= 'hls' if use_hls 
else 'fms' 
 136         mediagen_doc 
= self
._download
_xml
(mediagen_url
, video_id
, 
 137                                           'Downloading video urls') 
 139         item 
= mediagen_doc
.find('./video/item') 
 140         if item 
is not None and item
.get('type') == 'text': 
 141             message 
= '%s returned error: ' % self
.IE_NAME
 
 142             if item
.get('code') is not None: 
 143                 message 
+= '%s - ' % item
.get('code') 
 145             raise ExtractorError(message
, expected
=True) 
 147         description 
= strip_or_none(xpath_text(itemdoc
, 'description')) 
 149         timestamp 
= timeconvert(xpath_text(itemdoc
, 'pubDate')) 
 153             title_el 
= find_xpath_attr( 
 154                 itemdoc
, './/{http://search.yahoo.com/mrss/}category', 
 155                 'scheme', 'urn:mtvn:video_title') 
 157             title_el 
= itemdoc
.find(compat_xpath('.//{http://search.yahoo.com/mrss/}title')) 
 159             title_el 
= itemdoc
.find(compat_xpath('.//title')) 
 160             if title_el
.text 
is None: 
 163         title 
= title_el
.text
 
 165             raise ExtractorError('Could not find video title') 
 166         title 
= title
.strip() 
 168         # This a short id that's used in the webpage urls 
 170         mtvn_id_node 
= find_xpath_attr(itemdoc
, './/{http://search.yahoo.com/mrss/}category', 
 171                                        'scheme', 'urn:mtvn:id') 
 172         if mtvn_id_node 
is not None: 
 173             mtvn_id 
= mtvn_id_node
.text
 
 175         formats 
= self
._extract
_video
_formats
(mediagen_doc
, mtvn_id
, video_id
) 
 180             'subtitles': self
._extract
_subtitles
(mediagen_doc
, mtvn_id
), 
 182             'thumbnail': self
._get
_thumbnail
_url
(uri
, itemdoc
), 
 183             'description': description
, 
 184             'duration': float_or_none(content_el
.attrib
.get('duration')), 
 185             'timestamp': timestamp
, 
 188     def _get_feed_query(self
, uri
): 
 191             data
['lang'] = self
._LANG
 
 194     def _get_videos_info(self
, uri
, use_hls
=True): 
 195         video_id 
= self
._id
_from
_uri
(uri
) 
 196         feed_url 
= self
._get
_feed
_url
(uri
) 
 197         info_url 
= update_url_query(feed_url
, self
._get
_feed
_query
(uri
)) 
 198         return self
._get
_videos
_info
_from
_url
(info_url
, video_id
, use_hls
) 
 200     def _get_videos_info_from_url(self
, url
, video_id
, use_hls
=True): 
 201         idoc 
= self
._download
_xml
( 
 203             'Downloading info', transform_source
=fix_xml_ampersands
) 
 205         title 
= xpath_text(idoc
, './channel/title') 
 206         description 
= xpath_text(idoc
, './channel/description') 
 208         return self
.playlist_result( 
 209             [self
._get
_video
_info
(item
, use_hls
) for item 
in idoc
.findall('.//item')], 
 210             playlist_title
=title
, playlist_description
=description
) 
 212     def _extract_triforce_mgid(self
, webpage
, data_zone
=None, video_id
=None): 
 213         triforce_feed 
= self
._parse
_json
(self
._search
_regex
( 
 214             r
'triforceManifestFeed\s*=\s*({.+?})\s*;\s*\n', webpage
, 
 215             'triforce feed', default
='{}'), video_id
, fatal
=False) 
 217         data_zone 
= self
._search
_regex
( 
 218             r
'data-zone=(["\'])(?P
<zone
>.+?_lc_promo
.*?
)\
1', webpage, 
 219             'data zone
', default=data_zone, group='zone
') 
 222             triforce_feed, lambda x: x['manifest
']['zones
'][data_zone]['feed
'], 
 227         feed = self._download_json(feed_url, video_id, fatal=False) 
 231         return try_get(feed, lambda x: x['result
']['data
']['id'], compat_str) 
 233     def _extract_mgid(self, webpage): 
 235             # the url can be http://media.mtvnservices.com/fb/{mgid}.swf 
 236             # or http://media.mtvnservices.com/{mgid} 
 237             og_url = self._og_search_video_url(webpage) 
 238             mgid = url_basename(og_url) 
 239             if mgid.endswith('.swf
'): 
 241         except RegexNotFoundError: 
 244         if mgid is None or ':' not in mgid: 
 245             mgid = self._search_regex( 
 246                 [r'data
-mgid
="(.*?)"', r'swfobject
.embedSWF\
(".*?(mgid:.*?)"'], 
 247                 webpage, 'mgid
', default=None) 
 250             sm4_embed = self._html_search_meta( 
 251                 'sm4
:video
:embed
', webpage, 'sm4 embed
', default='') 
 252             mgid = self._search_regex( 
 253                 r'embed
/(mgid
:.+?
)["\'&?/]', sm4_embed, 'mgid', default=None) 
 256             mgid = self._extract_triforce_mgid(webpage) 
 260     def _real_extract(self, url): 
 261         title = url_basename(url) 
 262         webpage = self._download_webpage(url, title) 
 263         mgid = self._extract_mgid(webpage) 
 264         videos_info = self._get_videos_info(mgid) 
 268 class MTVServicesEmbeddedIE(MTVServicesInfoExtractor): 
 269     IE_NAME = 'mtvservices:embedded' 
 270     _VALID_URL = r'https?://media\.mtvnservices\.com/embed/(?P<mgid>.+?)(\?|/|$)' 
 273         # From http://www.thewrap.com/peter-dinklage-sums-up-game-of-thrones-in-45-seconds-video/ 
 274         'url': 'http://media.mtvnservices.com/embed/mgid:uma:video:mtv.com:1043906/cp~vid%3D1043906%26uri%3Dmgid%3Auma%3Avideo%3Amtv.com%3A1043906', 
 275         'md5': 'cb349b21a7897164cede95bd7bf3fbb9', 
 279             'title': 'Peter Dinklage Sums Up \'Game Of Thrones\' In 45 Seconds', 
 280             'description': '"Sexy sexy sexy
, stabby stabby stabby
, beautiful language
," says Peter Dinklage as he tries summarizing "Game of Thrones
" in under a minute.', 
 281             'timestamp': 1400126400, 
 282             'upload_date': '20140515', 
 287     def _extract_url(webpage): 
 289             r'<iframe[^>]+?src=(["\'])(?P
<url
>(?
:https?
:)?
//media
.mtvnservices
.com
/embed
/.+?
)\
1', webpage) 
 291             return mobj.group('url
') 
 293     def _get_feed_url(self, uri): 
 294         video_id = self._id_from_uri(uri) 
 295         config = self._download_json( 
 296             'http
://media
.mtvnservices
.com
/pmt
/e1
/access
/index
.html?uri
=%s&configtype
=edge
' % uri, video_id) 
 297         return self._remove_template_parameter(config['feedWithQueryParams
']) 
 299     def _real_extract(self, url): 
 300         mobj = re.match(self._VALID_URL, url) 
 301         mgid = mobj.group('mgid
') 
 302         return self._get_videos_info(mgid) 
 305 class MTVIE(MTVServicesInfoExtractor): 
 307     _VALID_URL = r'https?
://(?
:www\
.)?mtv\
.com
/(?
:video
-clips|
(?
:full
-)?episodes
)/(?P
<id>[^
/?
#.]+)' 
 308     _FEED_URL 
= 'http://www.mtv.com/feeds/mrss/' 
 311         'url': 'http://www.mtv.com/video-clips/vl8qof/unlocking-the-truth-trailer', 
 312         'md5': '1edbcdf1e7628e414a8c5dcebca3d32b', 
 314             'id': '5e14040d-18a4-47c4-a582-43ff602de88e', 
 316             'title': 'Unlocking The Truth|July 18, 2016|1|101|Trailer', 
 317             'description': '"Unlocking the Truth" premieres August 17th at 11/10c.', 
 318             'timestamp': 1468846800, 
 319             'upload_date': '20160718', 
 322         'url': 'http://www.mtv.com/full-episodes/94tujl/unlocking-the-truth-gates-of-hell-season-1-ep-101', 
 323         'only_matching': True, 
 325         'url': 'http://www.mtv.com/episodes/g8xu7q/teen-mom-2-breaking-the-wall-season-7-ep-713', 
 326         'only_matching': True, 
 330 class MTV81IE(InfoExtractor
): 
 332     _VALID_URL 
= r
'https?://(?:www\.)?mtv81\.com/videos/(?P<id>[^/?#.]+)' 
 335         'url': 'http://www.mtv81.com/videos/artist-to-watch/the-godfather-of-japanese-hip-hop-segment-1/', 
 336         'md5': '1edbcdf1e7628e414a8c5dcebca3d32b', 
 338             'id': '5e14040d-18a4-47c4-a582-43ff602de88e', 
 340             'title': 'Unlocking The Truth|July 18, 2016|1|101|Trailer', 
 341             'description': '"Unlocking the Truth" premieres August 17th at 11/10c.', 
 342             'timestamp': 1468846800, 
 343             'upload_date': '20160718', 
 347     def _extract_mgid(self
, webpage
): 
 348         return self
._search
_regex
( 
 349             r
'getTheVideo\((["\'])(?P
<id>mgid
:.+?
)\
1', webpage, 
 352     def _real_extract(self, url): 
 353         video_id = self._match_id(url) 
 354         webpage = self._download_webpage(url, video_id) 
 355         mgid = self._extract_mgid(webpage) 
 356         return self.url_result('http
://media
.mtvnservices
.com
/embed
/%s' % mgid) 
 359 class MTVVideoIE(MTVServicesInfoExtractor): 
 360     IE_NAME = 'mtv
:video
' 
 361     _VALID_URL = r'''(?x)^https?:// 
 362         (?:(?:www\.)?mtv\.com/videos/.+?/(?P<videoid>[0-9]+)/[^/]+$| 
 363            m\.mtv\.com/videos/video\.rbml\?.*?id=(?P<mgid>[^&]+))''' 
 365     _FEED_URL = 'http
://www
.mtv
.com
/player
/embed
/AS3
/rss
/' 
 369             'url
': 'http
://www
.mtv
.com
/videos
/misc
/853555/ours
-vh1
-storytellers
.jhtml
', 
 370             'md5
': '850f3f143316b1e71fa56a4edfd6e0f8
', 
 374                 'title
': 'Taylor Swift 
- "Ours (VH1 Storytellers)"', 
 375                 'description
': 'Album
: Taylor Swift performs 
"Ours" for VH1 Storytellers at Harvey Mudd College
.', 
 376                 'timestamp
': 1352610000, 
 377                 'upload_date
': '20121111', 
 382     def _get_thumbnail_url(self, uri, itemdoc): 
 383         return 'http
://mtv
.mtvnimages
.com
/uri
/' + uri 
 385     def _real_extract(self, url): 
 386         mobj = re.match(self._VALID_URL, url) 
 387         video_id = mobj.group('videoid
') 
 388         uri = mobj.groupdict().get('mgid
') 
 390             webpage = self._download_webpage(url, video_id) 
 392             # Some videos come from Vevo.com 
 394                 r'(?s
)isVevoVideo 
= true
;.*?vevoVideoId 
= "(.*?)";', webpage) 
 396                 vevo_id = m_vevo.group(1) 
 397                 self.to_screen('Vevo video detected
: %s' % vevo_id) 
 398                 return self.url_result('vevo
:%s' % vevo_id, ie='Vevo
') 
 400             uri = self._html_search_regex(r'/uri
/(.*?
)\?', webpage, 'uri
') 
 401         return self._get_videos_info(uri) 
 404 class MTVDEIE(MTVServicesInfoExtractor): 
 406     _VALID_URL = r'https?
://(?
:www\
.)?mtv\
.de
/(?
:artists|shows|news
)/(?
:[^
/]+/)*(?P
<id>\d
+)-[^
/#?]+/*(?:[#?].*)?$' 
 408         'url': 'http://www.mtv.de/artists/10571-cro/videos/61131-traum', 
 410             'id': 'music_video-a50bc5f0b3aa4b3190aa', 
 412             'title': 'MusicVideo_cro-traum', 
 413             'description': 'Cro - Traum', 
 417             'skip_download': True, 
 419         'skip': 'Blocked at Travis CI', 
 421         # mediagen URL without query (e.g. http://videos.mtvnn.com/mediagen/e865da714c166d18d6f80893195fcb97) 
 422         'url': 'http://www.mtv.de/shows/933-teen-mom-2/staffeln/5353/folgen/63565-enthullungen', 
 424             'id': 'local_playlist-f5ae778b9832cc837189', 
 426             'title': 'Episode_teen-mom-2_shows_season-5_episode-1_full-episode_part1', 
 430             'skip_download': True, 
 432         'skip': 'Blocked at Travis CI', 
 434         'url': 'http://www.mtv.de/news/77491-mtv-movies-spotlight-pixels-teil-3', 
 436             'id': 'local_playlist-4e760566473c4c8c5344', 
 438             'title': 'Article_mtv-movies-spotlight-pixels-teil-3_short-clips_part1', 
 439             'description': 'MTV Movies Supercut', 
 443             'skip_download': True, 
 445         'skip': 'Das Video kann zur Zeit nicht abgespielt werden.', 
 448     def _real_extract(self
, url
): 
 449         video_id 
= self
._match
_id
(url
) 
 451         webpage 
= self
._download
_webpage
(url
, video_id
) 
 453         playlist 
= self
._parse
_json
( 
 455                 r
'window\.pagePlaylist\s*=\s*(\[.+?\]);\n', webpage
, 'page playlist'), 
 459             return item
['mrss'] + item
.get('mrssvars', '') 
 461         # news pages contain single video in playlist with different id 
 462         if len(playlist
) == 1: 
 463             return self
._get
_videos
_info
_from
_url
(_mrss_url(playlist
[0]), video_id
) 
 465         for item 
in playlist
: 
 466             item_id 
= item
.get('id') 
 467             if item_id 
and compat_str(item_id
) == video_id
: 
 468                 return self
._get
_videos
_info
_from
_url
(_mrss_url(item
), video_id
)