1 from __future__ 
import unicode_literals
 
   5 from .common 
import InfoExtractor
 
   7     compat_urllib_parse_urlencode
, 
  27 def _media_xml_tag(tag
): 
  28     return '{http://search.yahoo.com/mrss/}%s' % tag
 
  31 class MTVServicesInfoExtractor(InfoExtractor
): 
  32     _MOBILE_TEMPLATE 
= None 
  36     def _id_from_uri(uri
): 
  37         return uri
.split(':')[-1] 
  39     # This was originally implemented for ComedyCentral, but it also works here 
  41     def _transform_rtmp_url(cls
, rtmp_video_url
): 
  42         m 
= re
.match(r
'^rtmpe?://.*?/(?P<finalid>gsp\..+?/.*)$', rtmp_video_url
) 
  44             return {'rtmp': rtmp_video_url
} 
  45         base 
= 'http://viacommtvstrmfs.fplive.net/' 
  46         return {'http': base 
+ m
.group('finalid')} 
  48     def _get_feed_url(self
, uri
): 
  51     def _get_thumbnail_url(self
, uri
, itemdoc
): 
  52         search_path 
= '%s/%s' % (_media_xml_tag('group'), _media_xml_tag('thumbnail')) 
  53         thumb_node 
= itemdoc
.find(search_path
) 
  54         if thumb_node 
is None: 
  57             return thumb_node
.attrib
['url'] 
  59     def _extract_mobile_video_formats(self
, mtvn_id
): 
  60         webpage_url 
= self
._MOBILE
_TEMPLATE 
% mtvn_id
 
  61         req 
= sanitized_Request(webpage_url
) 
  62         # Otherwise we get a webpage that would execute some javascript 
  63         req
.add_header('User-Agent', 'curl/7') 
  64         webpage 
= self
._download
_webpage
(req
, mtvn_id
, 
  65                                          'Downloading mobile page') 
  66         metrics_url 
= unescapeHTML(self
._search
_regex
(r
'<a href="(http://metrics.+?)"', webpage
, 'url')) 
  67         req 
= HEADRequest(metrics_url
) 
  68         response 
= self
._request
_webpage
(req
, mtvn_id
, 'Resolving url') 
  69         url 
= response
.geturl() 
  70         # Transform the url to get the best quality: 
  71         url 
= re
.sub(r
'.+pxE=mp4', 'http://mtvnmobile.vo.llnwd.net/kip0/_pxn=0+_pxK=18639+_pxE=mp4', url
, 1) 
  72         return [{'url': url
, 'ext': 'mp4'}] 
  74     def _extract_video_formats(self
, mdoc
, mtvn_id
): 
  75         if re
.match(r
'.*/(error_country_block\.swf|geoblock\.mp4|copyright_error\.flv(?:\?geo\b.+?)?)$', mdoc
.find('.//src').text
) is not None: 
  76             if mtvn_id 
is not None and self
._MOBILE
_TEMPLATE 
is not None: 
  77                 self
.to_screen('The normal version is not available from your ' 
  78                                'country, trying with the mobile version') 
  79                 return self
._extract
_mobile
_video
_formats
(mtvn_id
) 
  80             raise ExtractorError('This video is not available from your country.', 
  84         for rendition 
in mdoc
.findall('.//rendition'): 
  86                 _
, _
, ext 
= rendition
.attrib
['type'].partition('/') 
  87                 rtmp_video_url 
= rendition
.find('./src').text
 
  88                 if rtmp_video_url
.endswith('siteunavail.png'): 
  90                 new_urls 
= self
._transform
_rtmp
_url
(rtmp_video_url
) 
  92                     'ext': 'flv' if new_url
.startswith('rtmp') else ext
, 
  94                     'format_id': '-'.join(filter(None, [kind
, rendition
.get('bitrate')])), 
  95                     'width': int(rendition
.get('width')), 
  96                     'height': int(rendition
.get('height')), 
  97                 } for kind
, new_url 
in new_urls
.items()]) 
  98             except (KeyError, TypeError): 
  99                 raise ExtractorError('Invalid rendition field.') 
 100         self
._sort
_formats
(formats
) 
 103     def _extract_subtitles(self
, mdoc
, mtvn_id
): 
 105         for transcript 
in mdoc
.findall('.//transcript'): 
 106             if transcript
.get('kind') != 'captions': 
 108             lang 
= transcript
.get('srclang') 
 110                 'url': compat_str(typographic
.get('src')), 
 111                 'ext': typographic
.get('format') 
 112             } for typographic 
in transcript
.findall('./typographic')] 
 115     def _get_video_info(self
, itemdoc
): 
 116         uri 
= itemdoc
.find('guid').text
 
 117         video_id 
= self
._id
_from
_uri
(uri
) 
 118         self
.report_extraction(video_id
) 
 119         content_el 
= itemdoc
.find('%s/%s' % (_media_xml_tag('group'), _media_xml_tag('content'))) 
 120         mediagen_url 
= content_el
.attrib
['url'] 
 121         # Remove the templates, like &device={device} 
 122         mediagen_url 
= re
.sub(r
'&[^=]*?={.*?}(?=(&|$))', '', mediagen_url
) 
 123         if 'acceptMethods' not in mediagen_url
: 
 124             mediagen_url 
+= '&' if '?' in mediagen_url 
else '?' 
 125             mediagen_url 
+= 'acceptMethods=fms' 
 127         mediagen_doc 
= self
._download
_xml
(mediagen_url
, video_id
, 
 128                                           'Downloading video urls') 
 130         item 
= mediagen_doc
.find('./video/item') 
 131         if item 
is not None and item
.get('type') == 'text': 
 132             message 
= '%s returned error: ' % self
.IE_NAME
 
 133             if item
.get('code') is not None: 
 134                 message 
+= '%s - ' % item
.get('code') 
 136             raise ExtractorError(message
, expected
=True) 
 138         description 
= strip_or_none(xpath_text(itemdoc
, 'description')) 
 140         timestamp 
= timeconvert(xpath_text(itemdoc
, 'pubDate')) 
 144             title_el 
= find_xpath_attr( 
 145                 itemdoc
, './/{http://search.yahoo.com/mrss/}category', 
 146                 'scheme', 'urn:mtvn:video_title') 
 148             title_el 
= itemdoc
.find(compat_xpath('.//{http://search.yahoo.com/mrss/}title')) 
 150             title_el 
= itemdoc
.find(compat_xpath('.//title')) 
 151             if title_el
.text 
is None: 
 154         title 
= title_el
.text
 
 156             raise ExtractorError('Could not find video title') 
 157         title 
= title
.strip() 
 159         # This a short id that's used in the webpage urls 
 161         mtvn_id_node 
= find_xpath_attr(itemdoc
, './/{http://search.yahoo.com/mrss/}category', 
 162                                        'scheme', 'urn:mtvn:id') 
 163         if mtvn_id_node 
is not None: 
 164             mtvn_id 
= mtvn_id_node
.text
 
 168             'formats': self
._extract
_video
_formats
(mediagen_doc
, mtvn_id
), 
 169             'subtitles': self
._extract
_subtitles
(mediagen_doc
, mtvn_id
), 
 171             'thumbnail': self
._get
_thumbnail
_url
(uri
, itemdoc
), 
 172             'description': description
, 
 173             'duration': float_or_none(content_el
.attrib
.get('duration')), 
 174             'timestamp': timestamp
, 
 177     def _get_feed_query(self
, uri
): 
 180             data
['lang'] = self
._LANG
 
 181         return compat_urllib_parse_urlencode(data
) 
 183     def _get_videos_info(self
, uri
): 
 184         video_id 
= self
._id
_from
_uri
(uri
) 
 185         feed_url 
= self
._get
_feed
_url
(uri
) 
 186         info_url 
= feed_url 
+ '?' + self
._get
_feed
_query
(uri
) 
 187         return self
._get
_videos
_info
_from
_url
(info_url
, video_id
) 
 189     def _get_videos_info_from_url(self
, url
, video_id
): 
 190         idoc 
= self
._download
_xml
( 
 192             'Downloading info', transform_source
=fix_xml_ampersands
) 
 194         title 
= xpath_text(idoc
, './channel/title') 
 195         description 
= xpath_text(idoc
, './channel/description') 
 197         return self
.playlist_result( 
 198             [self
._get
_video
_info
(item
) for item 
in idoc
.findall('.//item')], 
 199             playlist_title
=title
, playlist_description
=description
) 
 201     def _extract_mgid(self
, webpage
): 
 203             # the url can be http://media.mtvnservices.com/fb/{mgid}.swf 
 204             # or http://media.mtvnservices.com/{mgid} 
 205             og_url 
= self
._og
_search
_video
_url
(webpage
) 
 206             mgid 
= url_basename(og_url
) 
 207             if mgid
.endswith('.swf'): 
 209         except RegexNotFoundError
: 
 212         if mgid 
is None or ':' not in mgid
: 
 213             mgid 
= self
._search
_regex
( 
 214                 [r
'data-mgid="(.*?)"', r
'swfobject.embedSWF\(".*?(mgid:.*?)"'], 
 215                 webpage
, 'mgid', default
=None) 
 218             sm4_embed 
= self
._html
_search
_meta
( 
 219                 'sm4:video:embed', webpage
, 'sm4 embed', default
='') 
 220             mgid 
= self
._search
_regex
( 
 221                 r
'embed/(mgid:.+?)["\'&?
/]', sm4_embed, 'mgid
') 
 224     def _real_extract(self, url): 
 225         title = url_basename(url) 
 226         webpage = self._download_webpage(url, title) 
 227         mgid = self._extract_mgid(webpage) 
 228         videos_info = self._get_videos_info(mgid) 
 232 class MTVServicesEmbeddedIE(MTVServicesInfoExtractor): 
 233     IE_NAME = 'mtvservices
:embedded
' 
 234     _VALID_URL = r'https?
://media\
.mtvnservices\
.com
/embed
/(?P
<mgid
>.+?
)(\?|
/|$
)' 
 237         # From http://www.thewrap.com/peter-dinklage-sums-up-game-of-thrones-in-45-seconds-video/ 
 238         'url
': 'http
://media
.mtvnservices
.com
/embed
/mgid
:uma
:video
:mtv
.com
:1043906/cp~vid
%3D1043906
%26uri
%3Dmgid
%3Auma
%3Avideo
%3Amtv
.com
%3A1043906
', 
 239         'md5
': 'cb349b21a7897164cede95bd7bf3fbb9
', 
 243             'title
': 'Peter Dinklage Sums Up 
\'Game Of Thrones
\' In 
45 Seconds
', 
 244             'description
': '"Sexy sexy sexy, stabby stabby stabby, beautiful language," says Peter Dinklage 
as he tries summarizing 
"Game of Thrones" in under a minute
.', 
 245             'timestamp
': 1400126400, 
 246             'upload_date
': '20140515', 
 251     def _extract_url(webpage): 
 253             r'<iframe
[^
>]+?src
=(["\'])(?P<url>(?:https?:)?//media.mtvnservices.com/embed/.+?)\1', webpage) 
 255             return mobj.group('url') 
 257     def _get_feed_url(self, uri): 
 258         video_id = self._id_from_uri(uri) 
 259         site_id = uri.replace(video_id, '') 
 260         config_url = ('http://media.mtvnservices.com/pmt/e1/players/{0}/' 
 261                       'context4/context5/config.xml'.format(site_id)) 
 262         config_doc = self._download_xml(config_url, video_id) 
 263         feed_node = config_doc.find('.//feed') 
 264         feed_url = feed_node.text.strip().split('?')[0] 
 267     def _real_extract(self, url): 
 268         mobj = re.match(self._VALID_URL, url) 
 269         mgid = mobj.group('mgid') 
 270         return self._get_videos_info(mgid) 
 273 class MTVIE(MTVServicesInfoExtractor): 
 274     _VALID_URL = r'''(?x)^https?:// 
 275         (?:(?:www\.)?mtv\.com/videos/.+?/(?P<videoid>[0-9]+)/[^/]+$| 
 276            m\.mtv\.com/videos/video\.rbml\?.*?id=(?P<mgid>[^&]+))''' 
 278     _FEED_URL = 'http://www.mtv.com/player/embed/AS3/rss/' 
 282             'url': 'http://www.mtv.com/videos/misc/853555/ours-vh1-storytellers.jhtml', 
 283             'md5': '850f3f143316b1e71fa56a4edfd6e0f8', 
 287                 'title': 'Taylor Swift - "Ours (VH1 Storytellers
)"', 
 288                 'description': 'Album: Taylor Swift performs "Ours
" for VH1 Storytellers at Harvey Mudd College.', 
 289                 'timestamp': 1352610000, 
 290                 'upload_date': '20121111', 
 295     def _get_thumbnail_url(self, uri, itemdoc): 
 296         return 'http://mtv.mtvnimages.com/uri/' + uri 
 298     def _real_extract(self, url): 
 299         mobj = re.match(self._VALID_URL, url) 
 300         video_id = mobj.group('videoid') 
 301         uri = mobj.groupdict().get('mgid') 
 303             webpage = self._download_webpage(url, video_id) 
 305             # Some videos come from Vevo.com 
 307                 r'(?s)isVevoVideo = true;.*?vevoVideoId = "(.*?
)";', webpage) 
 309                 vevo_id = m_vevo.group(1) 
 310                 self.to_screen('Vevo video detected: %s' % vevo_id) 
 311                 return self.url_result('vevo:%s' % vevo_id, ie='Vevo') 
 313             uri = self._html_search_regex(r'/uri/(.*?)\?', webpage, 'uri') 
 314         return self._get_videos_info(uri) 
 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, 
 332         'skip': 'Blocked at Travis CI', 
 334         # mediagen URL without query (e.g. http://videos.mtvnn.com/mediagen/e865da714c166d18d6f80893195fcb97) 
 335         'url': 'http://www.mtv.de/shows/933-teen-mom-2/staffeln/5353/folgen/63565-enthullungen', 
 337             'id': 'local_playlist-f5ae778b9832cc837189', 
 339             'title': 'Episode_teen-mom-2_shows_season-5_episode-1_full-episode_part1', 
 343             'skip_download': True, 
 345         'skip': 'Blocked at Travis CI', 
 347         'url': 'http://www.mtv.de/news/77491-mtv-movies-spotlight-pixels-teil-3', 
 349             'id': 'local_playlist-4e760566473c4c8c5344', 
 351             'title': 'Article_mtv-movies-spotlight-pixels-teil-3_short-clips_part1', 
 352             'description': 'MTV Movies Supercut', 
 356             'skip_download': True, 
 358         'skip': 'Das Video kann zur Zeit nicht abgespielt werden.', 
 361     def _real_extract(self, url): 
 362         video_id = self._match_id(url) 
 364         webpage = self._download_webpage(url, video_id) 
 366         playlist = self._parse_json( 
 368                 r'window\.pagePlaylist\s*=\s*(\[.+?\]);\n', webpage, 'page playlist'), 
 372             return item['mrss'] + item.get('mrssvars', '') 
 374         # news pages contain single video in playlist with different id 
 375         if len(playlist) == 1: 
 376             return self._get_videos_info_from_url(_mrss_url(playlist[0]), video_id) 
 378         for item in playlist: 
 379             item_id = item.get('id') 
 380             if item_id and compat_str(item_id) == video_id: 
 381                 return self._get_videos_info_from_url(_mrss_url(item), video_id)