1 from __future__ import unicode_literals
5 from .common import InfoExtractor
24 def _media_xml_tag(tag):
25 return '{http://search.yahoo.com/mrss/}%s' % tag
28 class MTVServicesInfoExtractor(InfoExtractor):
29 _MOBILE_TEMPLATE = None
33 def _id_from_uri(uri):
34 return uri.split(':')[-1]
36 # This was originally implemented for ComedyCentral, but it also works here
38 def _transform_rtmp_url(rtmp_video_url):
39 m = re.match(r'^rtmpe?://.*?/(?P<finalid>gsp\..+?/.*)$', rtmp_video_url)
42 base = 'http://viacommtvstrmfs.fplive.net/'
43 return base + m.group('finalid')
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):
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'):
83 _, _, ext = rendition.attrib['type'].partition('/')
84 rtmp_video_url = rendition.find('./src').text
85 if rtmp_video_url.endswith('siteunavail.png'):
89 'url': self._transform_rtmp_url(rtmp_video_url),
90 'format_id': rendition.get('bitrate'),
91 'width': int(rendition.get('width')),
92 'height': int(rendition.get('height')),
94 except (KeyError, TypeError):
95 raise ExtractorError('Invalid rendition field.')
96 self._sort_formats(formats)
99 def _extract_subtitles(self, mdoc, mtvn_id):
101 for transcript in mdoc.findall('.//transcript'):
102 if transcript.get('kind') != 'captions':
104 lang = transcript.get('srclang')
106 'url': compat_str(typographic.get('src')),
107 'ext': typographic.get('format')
108 } for typographic in transcript.findall('./typographic')]
111 def _get_video_info(self, itemdoc):
112 uri = itemdoc.find('guid').text
113 video_id = self._id_from_uri(uri)
114 self.report_extraction(video_id)
115 content_el = itemdoc.find('%s/%s' % (_media_xml_tag('group'), _media_xml_tag('content')))
116 mediagen_url = content_el.attrib['url']
117 # Remove the templates, like &device={device}
118 mediagen_url = re.sub(r'&[^=]*?={.*?}(?=(&|$))', '', mediagen_url)
119 if 'acceptMethods' not in mediagen_url:
120 mediagen_url += '&' if '?' in mediagen_url else '?'
121 mediagen_url += 'acceptMethods=fms'
123 mediagen_doc = self._download_xml(mediagen_url, video_id,
124 'Downloading video urls')
126 item = mediagen_doc.find('./video/item')
127 if item is not None and item.get('type') == 'text':
128 message = '%s returned error: ' % self.IE_NAME
129 if item.get('code') is not None:
130 message += '%s - ' % item.get('code')
132 raise ExtractorError(message, expected=True)
134 description = xpath_text(itemdoc, 'description')
138 title_el = find_xpath_attr(
139 itemdoc, './/{http://search.yahoo.com/mrss/}category',
140 'scheme', 'urn:mtvn:video_title')
142 title_el = itemdoc.find('.//{http://search.yahoo.com/mrss/}title')
144 title_el = itemdoc.find('.//title') or itemdoc.find('./title')
145 if title_el.text is None:
148 title = title_el.text
150 raise ExtractorError('Could not find video title')
151 title = title.strip()
153 # This a short id that's used in the webpage urls
155 mtvn_id_node = find_xpath_attr(itemdoc, './/{http://search.yahoo.com/mrss/}category',
156 'scheme', 'urn:mtvn:id')
157 if mtvn_id_node is not None:
158 mtvn_id = mtvn_id_node.text
162 'formats': self._extract_video_formats(mediagen_doc, mtvn_id),
163 'subtitles': self._extract_subtitles(mediagen_doc, mtvn_id),
165 'thumbnail': self._get_thumbnail_url(uri, itemdoc),
166 'description': description,
167 'duration': float_or_none(content_el.attrib.get('duration')),
170 def _get_feed_query(self, uri):
173 data['lang'] = self._LANG
174 return compat_urllib_parse.urlencode(data)
176 def _get_videos_info(self, uri):
177 video_id = self._id_from_uri(uri)
178 feed_url = self._get_feed_url(uri)
179 info_url = feed_url + '?' + self._get_feed_query(uri)
180 return self._get_videos_info_from_url(info_url, video_id)
182 def _get_videos_info_from_url(self, url, video_id):
183 idoc = self._download_xml(
185 'Downloading info', transform_source=fix_xml_ampersands)
186 return self.playlist_result(
187 [self._get_video_info(item) for item in idoc.findall('.//item')])
189 def _extract_mgid(self, webpage):
191 # the url can be http://media.mtvnservices.com/fb/{mgid}.swf
192 # or http://media.mtvnservices.com/{mgid}
193 og_url = self._og_search_video_url(webpage)
194 mgid = url_basename(og_url)
195 if mgid.endswith('.swf'):
197 except RegexNotFoundError:
200 if mgid is None or ':' not in mgid:
201 mgid = self._search_regex(
202 [r'data-mgid="(.*?)"', r'swfobject.embedSWF\(".*?(mgid:.*?)"'],
203 webpage, 'mgid', default=None)
206 sm4_embed = self._html_search_meta(
207 'sm4:video:embed', webpage, 'sm4 embed', default='')
208 mgid = self._search_regex(
209 r'embed/(mgid:.+?)["\'&?/]', sm4_embed, 'mgid')
212 def _real_extract(self, url):
213 title = url_basename(url)
214 webpage = self._download_webpage(url, title)
215 mgid = self._extract_mgid(webpage)
216 videos_info = self._get_videos_info(mgid)
220 class MTVServicesEmbeddedIE(MTVServicesInfoExtractor):
221 IE_NAME = 'mtvservices:embedded'
222 _VALID_URL = r'https?://media\.mtvnservices\.com/embed/(?P<mgid>.+?)(\?|/|$)'
225 # From http://www.thewrap.com/peter-dinklage-sums-up-game-of-thrones-in-45-seconds-video/
226 'url': 'http://media.mtvnservices.com/embed/mgid:uma:video:mtv.com:1043906/cp~vid%3D1043906%26uri%3Dmgid%3Auma%3Avideo%3Amtv.com%3A1043906',
227 'md5': 'cb349b21a7897164cede95bd7bf3fbb9',
231 'title': 'Peter Dinklage Sums Up \'Game Of Thrones\' In 45 Seconds',
232 'description': '"Sexy sexy sexy, stabby stabby stabby, beautiful language," says Peter Dinklage as he tries summarizing "Game of Thrones" in under a minute.',
237 def _extract_url(webpage):
239 r'<iframe[^>]+?src=(["\'])(?P<url>(?:https?:)?//media.mtvnservices.com/embed/.+?)\1', webpage)
241 return mobj.group('url')
243 def _get_feed_url(self, uri):
244 video_id = self._id_from_uri(uri)
245 site_id = uri.replace(video_id, '')
246 config_url = ('http://media.mtvnservices.com/pmt/e1/players/{0}/'
247 'context4/context5/config.xml'.format(site_id))
248 config_doc = self._download_xml(config_url, video_id)
249 feed_node = config_doc.find('.//feed')
250 feed_url = feed_node.text.strip().split('?')[0]
253 def _real_extract(self, url):
254 mobj = re.match(self._VALID_URL, url)
255 mgid = mobj.group('mgid')
256 return self._get_videos_info(mgid)
259 class MTVIE(MTVServicesInfoExtractor):
260 _VALID_URL = r'''(?x)^https?://
261 (?:(?:www\.)?mtv\.com/videos/.+?/(?P<videoid>[0-9]+)/[^/]+$|
262 m\.mtv\.com/videos/video\.rbml\?.*?id=(?P<mgid>[^&]+))'''
264 _FEED_URL = 'http://www.mtv.com/player/embed/AS3/rss/'
268 'url': 'http://www.mtv.com/videos/misc/853555/ours-vh1-storytellers.jhtml',
269 'md5': '850f3f143316b1e71fa56a4edfd6e0f8',
273 'title': 'Taylor Swift - "Ours (VH1 Storytellers)"',
274 'description': 'Album: Taylor Swift performs "Ours" for VH1 Storytellers at Harvey Mudd College.',
279 def _get_thumbnail_url(self, uri, itemdoc):
280 return 'http://mtv.mtvnimages.com/uri/' + uri
282 def _real_extract(self, url):
283 mobj = re.match(self._VALID_URL, url)
284 video_id = mobj.group('videoid')
285 uri = mobj.groupdict().get('mgid')
287 webpage = self._download_webpage(url, video_id)
289 # Some videos come from Vevo.com
291 r'(?s)isVevoVideo = true;.*?vevoVideoId = "(.*?)";', webpage)
293 vevo_id = m_vevo.group(1)
294 self.to_screen('Vevo video detected: %s' % vevo_id)
295 return self.url_result('vevo:%s' % vevo_id, ie='Vevo')
297 uri = self._html_search_regex(r'/uri/(.*?)\?', webpage, 'uri')
298 return self._get_videos_info(uri)
301 class MTVIggyIE(MTVServicesInfoExtractor):
302 IE_NAME = 'mtviggy.com'
303 _VALID_URL = r'https?://www\.mtviggy\.com/videos/.+'
305 'url': 'http://www.mtviggy.com/videos/arcade-fire-behind-the-scenes-at-the-biggest-music-experiment-yet/',
309 'title': 'Arcade Fire: Behind the Scenes at the Biggest Music Experiment Yet',
312 _FEED_URL = 'http://all.mtvworldverticals.com/feed-xml/'
315 class MTVDEIE(MTVServicesInfoExtractor):
317 _VALID_URL = r'https?://(?:www\.)?mtv\.de/(?:artists|shows|news)/(?:[^/]+/)*(?P<id>\d+)-[^/#?]+/*(?:[#?].*)?$'
319 'url': 'http://www.mtv.de/artists/10571-cro/videos/61131-traum',
321 'id': 'music_video-a50bc5f0b3aa4b3190aa',
323 'title': 'MusicVideo_cro-traum',
324 'description': 'Cro - Traum',
328 'skip_download': True,
331 # mediagen URL without query (e.g. http://videos.mtvnn.com/mediagen/e865da714c166d18d6f80893195fcb97)
332 'url': 'http://www.mtv.de/shows/933-teen-mom-2/staffeln/5353/folgen/63565-enthullungen',
334 'id': 'local_playlist-f5ae778b9832cc837189',
336 'title': 'Episode_teen-mom-2_shows_season-5_episode-1_full-episode_part1',
340 'skip_download': True,
343 # single video in pagePlaylist with different id
344 'url': 'http://www.mtv.de/news/77491-mtv-movies-spotlight-pixels-teil-3',
346 'id': 'local_playlist-4e760566473c4c8c5344',
348 'title': 'Article_mtv-movies-spotlight-pixels-teil-3_short-clips_part1',
349 'description': 'MTV Movies Supercut',
353 'skip_download': True,
357 def _real_extract(self, url):
358 video_id = self._match_id(url)
360 webpage = self._download_webpage(url, video_id)
362 playlist = self._parse_json(
364 r'window\.pagePlaylist\s*=\s*(\[.+?\]);\n', webpage, 'page playlist'),
367 # news pages contain single video in playlist with different id
368 if len(playlist) == 1:
369 return self._get_videos_info_from_url(playlist[0]['mrss'], video_id)
371 for item in playlist:
372 item_id = item.get('id')
373 if item_id and compat_str(item_id) == video_id:
374 return self._get_videos_info_from_url(item['mrss'], video_id)