1 from __future__ 
import unicode_literals
 
   5 from .common 
import InfoExtractor
 
   7     compat_urllib_parse_urlencode
, 
  25 def _media_xml_tag(tag
): 
  26     return '{http://search.yahoo.com/mrss/}%s' % tag
 
  29 class MTVServicesInfoExtractor(InfoExtractor
): 
  30     _MOBILE_TEMPLATE 
= None 
  34     def _id_from_uri(uri
): 
  35         return uri
.split(':')[-1] 
  37     # This was originally implemented for ComedyCentral, but it also works here 
  39     def _transform_rtmp_url(rtmp_video_url
): 
  40         m 
= re
.match(r
'^rtmpe?://.*?/(?P<finalid>gsp\..+?/.*)$', rtmp_video_url
) 
  43         base 
= 'http://viacommtvstrmfs.fplive.net/' 
  44         return base 
+ m
.group('finalid') 
  46     def _get_feed_url(self
, uri
): 
  49     def _get_thumbnail_url(self
, uri
, itemdoc
): 
  50         search_path 
= '%s/%s' % (_media_xml_tag('group'), _media_xml_tag('thumbnail')) 
  51         thumb_node 
= itemdoc
.find(search_path
) 
  52         if thumb_node 
is None: 
  55             return thumb_node
.attrib
['url'] 
  57     def _extract_mobile_video_formats(self
, mtvn_id
): 
  58         webpage_url 
= self
._MOBILE
_TEMPLATE 
% mtvn_id
 
  59         req 
= sanitized_Request(webpage_url
) 
  60         # Otherwise we get a webpage that would execute some javascript 
  61         req
.add_header('User-Agent', 'curl/7') 
  62         webpage 
= self
._download
_webpage
(req
, mtvn_id
, 
  63                                          'Downloading mobile page') 
  64         metrics_url 
= unescapeHTML(self
._search
_regex
(r
'<a href="(http://metrics.+?)"', webpage
, 'url')) 
  65         req 
= HEADRequest(metrics_url
) 
  66         response 
= self
._request
_webpage
(req
, mtvn_id
, 'Resolving url') 
  67         url 
= response
.geturl() 
  68         # Transform the url to get the best quality: 
  69         url 
= re
.sub(r
'.+pxE=mp4', 'http://mtvnmobile.vo.llnwd.net/kip0/_pxn=0+_pxK=18639+_pxE=mp4', url
, 1) 
  70         return [{'url': url
, 'ext': 'mp4'}] 
  72     def _extract_video_formats(self
, mdoc
, mtvn_id
): 
  73         if re
.match(r
'.*/(error_country_block\.swf|geoblock\.mp4|copyright_error\.flv(?:\?geo\b.+?)?)$', mdoc
.find('.//src').text
) is not None: 
  74             if mtvn_id 
is not None and self
._MOBILE
_TEMPLATE 
is not None: 
  75                 self
.to_screen('The normal version is not available from your ' 
  76                                'country, trying with the mobile version') 
  77                 return self
._extract
_mobile
_video
_formats
(mtvn_id
) 
  78             raise ExtractorError('This video is not available from your country.', 
  82         for rendition 
in mdoc
.findall('.//rendition'): 
  84                 _
, _
, ext 
= rendition
.attrib
['type'].partition('/') 
  85                 rtmp_video_url 
= rendition
.find('./src').text
 
  86                 if rtmp_video_url
.endswith('siteunavail.png'): 
  88                 new_url 
= self
._transform
_rtmp
_url
(rtmp_video_url
) 
  90                     'ext': 'flv' if new_url
.startswith('rtmp') else ext
, 
  92                     'format_id': rendition
.get('bitrate'), 
  93                     'width': int(rendition
.get('width')), 
  94                     'height': int(rendition
.get('height')), 
  96             except (KeyError, TypeError): 
  97                 raise ExtractorError('Invalid rendition field.') 
  98         self
._sort
_formats
(formats
) 
 101     def _extract_subtitles(self
, mdoc
, mtvn_id
): 
 103         for transcript 
in mdoc
.findall('.//transcript'): 
 104             if transcript
.get('kind') != 'captions': 
 106             lang 
= transcript
.get('srclang') 
 108                 'url': compat_str(typographic
.get('src')), 
 109                 'ext': typographic
.get('format') 
 110             } for typographic 
in transcript
.findall('./typographic')] 
 113     def _get_video_info(self
, itemdoc
): 
 114         uri 
= itemdoc
.find('guid').text
 
 115         video_id 
= self
._id
_from
_uri
(uri
) 
 116         self
.report_extraction(video_id
) 
 117         content_el 
= itemdoc
.find('%s/%s' % (_media_xml_tag('group'), _media_xml_tag('content'))) 
 118         mediagen_url 
= content_el
.attrib
['url'] 
 119         # Remove the templates, like &device={device} 
 120         mediagen_url 
= re
.sub(r
'&[^=]*?={.*?}(?=(&|$))', '', mediagen_url
) 
 121         if 'acceptMethods' not in mediagen_url
: 
 122             mediagen_url 
+= '&' if '?' in mediagen_url 
else '?' 
 123             mediagen_url 
+= 'acceptMethods=fms' 
 125         mediagen_doc 
= self
._download
_xml
(mediagen_url
, video_id
, 
 126                                           'Downloading video urls') 
 128         item 
= mediagen_doc
.find('./video/item') 
 129         if item 
is not None and item
.get('type') == 'text': 
 130             message 
= '%s returned error: ' % self
.IE_NAME
 
 131             if item
.get('code') is not None: 
 132                 message 
+= '%s - ' % item
.get('code') 
 134             raise ExtractorError(message
, expected
=True) 
 136         description 
= xpath_text(itemdoc
, 'description') 
 140             title_el 
= find_xpath_attr( 
 141                 itemdoc
, './/{http://search.yahoo.com/mrss/}category', 
 142                 'scheme', 'urn:mtvn:video_title') 
 144             title_el 
= itemdoc
.find(compat_xpath('.//{http://search.yahoo.com/mrss/}title')) 
 146             title_el 
= itemdoc
.find(compat_xpath('.//title')) 
 147             if title_el
.text 
is None: 
 150         title 
= title_el
.text
 
 152             raise ExtractorError('Could not find video title') 
 153         title 
= title
.strip() 
 155         # This a short id that's used in the webpage urls 
 157         mtvn_id_node 
= find_xpath_attr(itemdoc
, './/{http://search.yahoo.com/mrss/}category', 
 158                                        'scheme', 'urn:mtvn:id') 
 159         if mtvn_id_node 
is not None: 
 160             mtvn_id 
= mtvn_id_node
.text
 
 164             'formats': self
._extract
_video
_formats
(mediagen_doc
, mtvn_id
), 
 165             'subtitles': self
._extract
_subtitles
(mediagen_doc
, mtvn_id
), 
 167             'thumbnail': self
._get
_thumbnail
_url
(uri
, itemdoc
), 
 168             'description': description
, 
 169             'duration': float_or_none(content_el
.attrib
.get('duration')), 
 172     def _get_feed_query(self
, uri
): 
 175             data
['lang'] = self
._LANG
 
 176         return compat_urllib_parse_urlencode(data
) 
 178     def _get_videos_info(self
, uri
): 
 179         video_id 
= self
._id
_from
_uri
(uri
) 
 180         feed_url 
= self
._get
_feed
_url
(uri
) 
 181         info_url 
= feed_url 
+ '?' + self
._get
_feed
_query
(uri
) 
 182         return self
._get
_videos
_info
_from
_url
(info_url
, video_id
) 
 184     def _get_videos_info_from_url(self
, url
, video_id
): 
 185         idoc 
= self
._download
_xml
( 
 187             'Downloading info', transform_source
=fix_xml_ampersands
) 
 188         return self
.playlist_result( 
 189             [self
._get
_video
_info
(item
) for item 
in idoc
.findall('.//item')]) 
 191     def _extract_mgid(self
, webpage
): 
 193             # the url can be http://media.mtvnservices.com/fb/{mgid}.swf 
 194             # or http://media.mtvnservices.com/{mgid} 
 195             og_url 
= self
._og
_search
_video
_url
(webpage
) 
 196             mgid 
= url_basename(og_url
) 
 197             if mgid
.endswith('.swf'): 
 199         except RegexNotFoundError
: 
 202         if mgid 
is None or ':' not in mgid
: 
 203             mgid 
= self
._search
_regex
( 
 204                 [r
'data-mgid="(.*?)"', r
'swfobject.embedSWF\(".*?(mgid:.*?)"'], 
 205                 webpage
, 'mgid', default
=None) 
 208             sm4_embed 
= self
._html
_search
_meta
( 
 209                 'sm4:video:embed', webpage
, 'sm4 embed', default
='') 
 210             mgid 
= self
._search
_regex
( 
 211                 r
'embed/(mgid:.+?)["\'&?
/]', sm4_embed, 'mgid
') 
 214     def _real_extract(self, url): 
 215         title = url_basename(url) 
 216         webpage = self._download_webpage(url, title) 
 217         mgid = self._extract_mgid(webpage) 
 218         videos_info = self._get_videos_info(mgid) 
 222 class MTVServicesEmbeddedIE(MTVServicesInfoExtractor): 
 223     IE_NAME = 'mtvservices
:embedded
' 
 224     _VALID_URL = r'https?
://media\
.mtvnservices\
.com
/embed
/(?P
<mgid
>.+?
)(\?|
/|$
)' 
 227         # From http://www.thewrap.com/peter-dinklage-sums-up-game-of-thrones-in-45-seconds-video/ 
 228         'url
': 'http
://media
.mtvnservices
.com
/embed
/mgid
:uma
:video
:mtv
.com
:1043906/cp~vid
%3D1043906
%26uri
%3Dmgid
%3Auma
%3Avideo
%3Amtv
.com
%3A1043906
', 
 229         'md5
': 'cb349b21a7897164cede95bd7bf3fbb9
', 
 233             'title
': 'Peter Dinklage Sums Up 
\'Game Of Thrones
\' In 
45 Seconds
', 
 234             'description
': '"Sexy sexy sexy, stabby stabby stabby, beautiful language," says Peter Dinklage 
as he tries summarizing 
"Game of Thrones" in under a minute
.', 
 239     def _extract_url(webpage): 
 241             r'<iframe
[^
>]+?src
=(["\'])(?P<url>(?:https?:)?//media.mtvnservices.com/embed/.+?)\1', webpage) 
 243             return mobj.group('url') 
 245     def _get_feed_url(self, uri): 
 246         video_id = self._id_from_uri(uri) 
 247         site_id = uri.replace(video_id, '') 
 248         config_url = ('http://media.mtvnservices.com/pmt/e1/players/{0}/' 
 249                       'context4/context5/config.xml'.format(site_id)) 
 250         config_doc = self._download_xml(config_url, video_id) 
 251         feed_node = config_doc.find('.//feed') 
 252         feed_url = feed_node.text.strip().split('?')[0] 
 255     def _real_extract(self, url): 
 256         mobj = re.match(self._VALID_URL, url) 
 257         mgid = mobj.group('mgid') 
 258         return self._get_videos_info(mgid) 
 261 class MTVIE(MTVServicesInfoExtractor): 
 262     _VALID_URL = r'''(?x)^https?:// 
 263         (?:(?:www\.)?mtv\.com/videos/.+?/(?P<videoid>[0-9]+)/[^/]+$| 
 264            m\.mtv\.com/videos/video\.rbml\?.*?id=(?P<mgid>[^&]+))''' 
 266     _FEED_URL = 'http://www.mtv.com/player/embed/AS3/rss/' 
 270             'url': 'http://www.mtv.com/videos/misc/853555/ours-vh1-storytellers.jhtml', 
 271             'md5': '850f3f143316b1e71fa56a4edfd6e0f8', 
 275                 'title': 'Taylor Swift - "Ours (VH1 Storytellers
)"', 
 276                 'description': 'Album: Taylor Swift performs "Ours
" for VH1 Storytellers at Harvey Mudd College.', 
 281     def _get_thumbnail_url(self, uri, itemdoc): 
 282         return 'http://mtv.mtvnimages.com/uri/' + uri 
 284     def _real_extract(self, url): 
 285         mobj = re.match(self._VALID_URL, url) 
 286         video_id = mobj.group('videoid') 
 287         uri = mobj.groupdict().get('mgid') 
 289             webpage = self._download_webpage(url, video_id) 
 291             # Some videos come from Vevo.com 
 293                 r'(?s)isVevoVideo = true;.*?vevoVideoId = "(.*?
)";', webpage) 
 295                 vevo_id = m_vevo.group(1) 
 296                 self.to_screen('Vevo video detected: %s' % vevo_id) 
 297                 return self.url_result('vevo:%s' % vevo_id, ie='Vevo') 
 299             uri = self._html_search_regex(r'/uri/(.*?)\?', webpage, 'uri') 
 300         return self._get_videos_info(uri) 
 303 class MTVIggyIE(MTVServicesInfoExtractor): 
 304     IE_NAME = 'mtviggy.com' 
 305     _VALID_URL = r'https?://www\.mtviggy\.com/videos/.+' 
 307         'url': 'http://www.mtviggy.com/videos/arcade-fire-behind-the-scenes-at-the-biggest-music-experiment-yet/', 
 311             'title': 'Arcade Fire: Behind the Scenes at the Biggest Music Experiment Yet', 
 314     _FEED_URL = 'http://all.mtvworldverticals.com/feed-xml/' 
 317 class MTVDEIE(MTVServicesInfoExtractor): 
 319     _VALID_URL = r'https?://(?:www\.)?mtv\.de/(?:artists|shows|news)/(?:[^/]+/)*(?P<id>\d+)-[^/#?]+/*(?:[#?].*)?$' 
 321         'url': 'http://www.mtv.de/artists/10571-cro/videos/61131-traum', 
 323             'id': 'music_video-a50bc5f0b3aa4b3190aa', 
 325             'title': 'MusicVideo_cro-traum', 
 326             'description': 'Cro - Traum', 
 330             'skip_download': True, 
 333         # mediagen URL without query (e.g. http://videos.mtvnn.com/mediagen/e865da714c166d18d6f80893195fcb97) 
 334         'url': 'http://www.mtv.de/shows/933-teen-mom-2/staffeln/5353/folgen/63565-enthullungen', 
 336             'id': 'local_playlist-f5ae778b9832cc837189', 
 338             'title': 'Episode_teen-mom-2_shows_season-5_episode-1_full-episode_part1', 
 342             'skip_download': True, 
 345         # single video in pagePlaylist with different id 
 346         'url': 'http://www.mtv.de/news/77491-mtv-movies-spotlight-pixels-teil-3', 
 348             'id': 'local_playlist-4e760566473c4c8c5344', 
 350             'title': 'Article_mtv-movies-spotlight-pixels-teil-3_short-clips_part1', 
 351             'description': 'MTV Movies Supercut', 
 355             'skip_download': True, 
 359     def _real_extract(self, url): 
 360         video_id = self._match_id(url) 
 362         webpage = self._download_webpage(url, video_id) 
 364         playlist = self._parse_json( 
 366                 r'window\.pagePlaylist\s*=\s*(\[.+?\]);\n', webpage, 'page playlist'), 
 369         # news pages contain single video in playlist with different id 
 370         if len(playlist) == 1: 
 371             return self._get_videos_info_from_url(playlist[0]['mrss'], video_id) 
 373         for item in playlist: 
 374             item_id = item.get('id') 
 375             if item_id and compat_str(item_id) == video_id: 
 376                 return self._get_videos_info_from_url(item['mrss'], video_id)