1 from __future__ import unicode_literals
5 from .common import InfoExtractor
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]
40 def _remove_template_parameter(url):
41 # Remove the templates, like &device={device}
42 return re.sub(r'&[^=]*?={.*?}(?=(&|$))', '', url)
44 # This was originally implemented for ComedyCentral, but it also works here
46 def _transform_rtmp_url(cls, rtmp_video_url):
47 m = re.match(r'^rtmpe?://.*?/(?P<finalid>gsp\..+?/.*)$', rtmp_video_url)
49 return {'rtmp': rtmp_video_url}
50 base = 'http://viacommtvstrmfs.fplive.net/'
51 return {'http': base + m.group('finalid')}
53 def _get_feed_url(self, uri):
56 def _get_thumbnail_url(self, uri, itemdoc):
57 search_path = '%s/%s' % (_media_xml_tag('group'), _media_xml_tag('thumbnail'))
58 thumb_node = itemdoc.find(search_path)
59 if thumb_node is None:
62 return thumb_node.attrib['url']
64 def _extract_mobile_video_formats(self, mtvn_id):
65 webpage_url = self._MOBILE_TEMPLATE % mtvn_id
66 req = sanitized_Request(webpage_url)
67 # Otherwise we get a webpage that would execute some javascript
68 req.add_header('User-Agent', 'curl/7')
69 webpage = self._download_webpage(req, mtvn_id,
70 'Downloading mobile page')
71 metrics_url = unescapeHTML(self._search_regex(r'<a href="(http://metrics.+?)"', webpage, 'url'))
72 req = HEADRequest(metrics_url)
73 response = self._request_webpage(req, mtvn_id, 'Resolving url')
74 url = response.geturl()
75 # Transform the url to get the best quality:
76 url = re.sub(r'.+pxE=mp4', 'http://mtvnmobile.vo.llnwd.net/kip0/_pxn=0+_pxK=18639+_pxE=mp4', url, 1)
77 return [{'url': url, 'ext': 'mp4'}]
79 def _extract_video_formats(self, mdoc, mtvn_id):
80 if re.match(r'.*/(error_country_block\.swf|geoblock\.mp4|copyright_error\.flv(?:\?geo\b.+?)?)$', mdoc.find('.//src').text) is not None:
81 if mtvn_id is not None and self._MOBILE_TEMPLATE is not None:
82 self.to_screen('The normal version is not available from your '
83 'country, trying with the mobile version')
84 return self._extract_mobile_video_formats(mtvn_id)
85 raise ExtractorError('This video is not available from your country.',
89 for rendition in mdoc.findall('.//rendition'):
91 _, _, ext = rendition.attrib['type'].partition('/')
92 rtmp_video_url = rendition.find('./src').text
93 if rtmp_video_url.endswith('siteunavail.png'):
95 new_urls = self._transform_rtmp_url(rtmp_video_url)
97 'ext': 'flv' if new_url.startswith('rtmp') else ext,
99 'format_id': '-'.join(filter(None, [kind, rendition.get('bitrate')])),
100 'width': int(rendition.get('width')),
101 'height': int(rendition.get('height')),
102 } for kind, new_url in new_urls.items()])
103 except (KeyError, TypeError):
104 raise ExtractorError('Invalid rendition field.')
105 self._sort_formats(formats)
108 def _extract_subtitles(self, mdoc, mtvn_id):
110 for transcript in mdoc.findall('.//transcript'):
111 if transcript.get('kind') != 'captions':
113 lang = transcript.get('srclang')
115 'url': compat_str(typographic.get('src')),
116 'ext': typographic.get('format')
117 } for typographic in transcript.findall('./typographic')]
120 def _get_video_info(self, itemdoc):
121 uri = itemdoc.find('guid').text
122 video_id = self._id_from_uri(uri)
123 self.report_extraction(video_id)
124 content_el = itemdoc.find('%s/%s' % (_media_xml_tag('group'), _media_xml_tag('content')))
125 mediagen_url = self._remove_template_parameter(content_el.attrib['url'])
126 if 'acceptMethods' not in mediagen_url:
127 mediagen_url += '&' if '?' in mediagen_url else '?'
128 mediagen_url += 'acceptMethods=fms'
130 mediagen_doc = self._download_xml(mediagen_url, video_id,
131 'Downloading video urls')
133 item = mediagen_doc.find('./video/item')
134 if item is not None and item.get('type') == 'text':
135 message = '%s returned error: ' % self.IE_NAME
136 if item.get('code') is not None:
137 message += '%s - ' % item.get('code')
139 raise ExtractorError(message, expected=True)
141 description = strip_or_none(xpath_text(itemdoc, 'description'))
143 timestamp = timeconvert(xpath_text(itemdoc, 'pubDate'))
147 title_el = find_xpath_attr(
148 itemdoc, './/{http://search.yahoo.com/mrss/}category',
149 'scheme', 'urn:mtvn:video_title')
151 title_el = itemdoc.find(compat_xpath('.//{http://search.yahoo.com/mrss/}title'))
153 title_el = itemdoc.find(compat_xpath('.//title'))
154 if title_el.text is None:
157 title = title_el.text
159 raise ExtractorError('Could not find video title')
160 title = title.strip()
162 # This a short id that's used in the webpage urls
164 mtvn_id_node = find_xpath_attr(itemdoc, './/{http://search.yahoo.com/mrss/}category',
165 'scheme', 'urn:mtvn:id')
166 if mtvn_id_node is not None:
167 mtvn_id = mtvn_id_node.text
171 'formats': self._extract_video_formats(mediagen_doc, mtvn_id),
172 'subtitles': self._extract_subtitles(mediagen_doc, mtvn_id),
174 'thumbnail': self._get_thumbnail_url(uri, itemdoc),
175 'description': description,
176 'duration': float_or_none(content_el.attrib.get('duration')),
177 'timestamp': timestamp,
180 def _get_feed_query(self, uri):
183 data['lang'] = self._LANG
186 def _get_videos_info(self, uri):
187 video_id = self._id_from_uri(uri)
188 feed_url = self._get_feed_url(uri)
189 info_url = update_url_query(feed_url, self._get_feed_query(uri))
190 return self._get_videos_info_from_url(info_url, video_id)
192 def _get_videos_info_from_url(self, url, video_id):
193 idoc = self._download_xml(
195 'Downloading info', transform_source=fix_xml_ampersands)
197 title = xpath_text(idoc, './channel/title')
198 description = xpath_text(idoc, './channel/description')
200 return self.playlist_result(
201 [self._get_video_info(item) for item in idoc.findall('.//item')],
202 playlist_title=title, playlist_description=description)
204 def _extract_mgid(self, webpage):
206 # the url can be http://media.mtvnservices.com/fb/{mgid}.swf
207 # or http://media.mtvnservices.com/{mgid}
208 og_url = self._og_search_video_url(webpage)
209 mgid = url_basename(og_url)
210 if mgid.endswith('.swf'):
212 except RegexNotFoundError:
215 if mgid is None or ':' not in mgid:
216 mgid = self._search_regex(
217 [r'data-mgid="(.*?)"', r'swfobject.embedSWF\(".*?(mgid:.*?)"'],
218 webpage, 'mgid', default=None)
221 sm4_embed = self._html_search_meta(
222 'sm4:video:embed', webpage, 'sm4 embed', default='')
223 mgid = self._search_regex(
224 r'embed/(mgid:.+?)["\'&?/]', sm4_embed, 'mgid')
227 def _real_extract(self, url):
228 title = url_basename(url)
229 webpage = self._download_webpage(url, title)
230 mgid = self._extract_mgid(webpage)
231 videos_info = self._get_videos_info(mgid)
235 class MTVServicesEmbeddedIE(MTVServicesInfoExtractor):
236 IE_NAME = 'mtvservices:embedded'
237 _VALID_URL = r'https?://media\.mtvnservices\.com/embed/(?P<mgid>.+?)(\?|/|$)'
240 # From http://www.thewrap.com/peter-dinklage-sums-up-game-of-thrones-in-45-seconds-video/
241 'url': 'http://media.mtvnservices.com/embed/mgid:uma:video:mtv.com:1043906/cp~vid%3D1043906%26uri%3Dmgid%3Auma%3Avideo%3Amtv.com%3A1043906',
242 'md5': 'cb349b21a7897164cede95bd7bf3fbb9',
246 'title': 'Peter Dinklage Sums Up \'Game Of Thrones\' In 45 Seconds',
247 'description': '"Sexy sexy sexy, stabby stabby stabby, beautiful language," says Peter Dinklage as he tries summarizing "Game of Thrones" in under a minute.',
248 'timestamp': 1400126400,
249 'upload_date': '20140515',
254 def _extract_url(webpage):
256 r'<iframe[^>]+?src=(["\'])(?P<url>(?:https?:)?//media.mtvnservices.com/embed/.+?)\1', webpage)
258 return mobj.group('url')
260 def _get_feed_url(self, uri):
261 video_id = self._id_from_uri(uri)
262 config = self._download_json(
263 'http://media.mtvnservices.com/pmt/e1/access/index.html?uri=%s&configtype=edge' % uri, video_id)
264 return self._remove_template_parameter(config['feedWithQueryParams'])
266 def _real_extract(self, url):
267 mobj = re.match(self._VALID_URL, url)
268 mgid = mobj.group('mgid')
269 return self._get_videos_info(mgid)
272 class MTVIE(MTVServicesInfoExtractor):
274 _VALID_URL = r'https?://(?:www\.)?mtv\.com/(?:video-clips|full-episodes)/(?P<id>[^/?#.]+)'
275 _FEED_URL = 'http://www.mtv.com/feeds/mrss/'
278 'url': 'http://www.mtv.com/video-clips/vl8qof/unlocking-the-truth-trailer',
279 'md5': '1edbcdf1e7628e414a8c5dcebca3d32b',
281 'id': '5e14040d-18a4-47c4-a582-43ff602de88e',
283 'title': 'Unlocking The Truth|July 18, 2016|1|101|Trailer',
284 'description': '"Unlocking the Truth" premieres August 17th at 11/10c.',
285 'timestamp': 1468846800,
286 'upload_date': '20160718',
289 'url': 'http://www.mtv.com/full-episodes/94tujl/unlocking-the-truth-gates-of-hell-season-1-ep-101',
290 'only_matching': True,
294 class MTVVideoIE(MTVServicesInfoExtractor):
295 IE_NAME = 'mtv:video'
296 _VALID_URL = r'''(?x)^https?://
297 (?:(?:www\.)?mtv\.com/videos/.+?/(?P<videoid>[0-9]+)/[^/]+$|
298 m\.mtv\.com/videos/video\.rbml\?.*?id=(?P<mgid>[^&]+))'''
300 _FEED_URL = 'http://www.mtv.com/player/embed/AS3/rss/'
304 'url': 'http://www.mtv.com/videos/misc/853555/ours-vh1-storytellers.jhtml',
305 'md5': '850f3f143316b1e71fa56a4edfd6e0f8',
309 'title': 'Taylor Swift - "Ours (VH1 Storytellers)"',
310 'description': 'Album: Taylor Swift performs "Ours" for VH1 Storytellers at Harvey Mudd College.',
311 'timestamp': 1352610000,
312 'upload_date': '20121111',
317 def _get_thumbnail_url(self, uri, itemdoc):
318 return 'http://mtv.mtvnimages.com/uri/' + uri
320 def _real_extract(self, url):
321 mobj = re.match(self._VALID_URL, url)
322 video_id = mobj.group('videoid')
323 uri = mobj.groupdict().get('mgid')
325 webpage = self._download_webpage(url, video_id)
327 # Some videos come from Vevo.com
329 r'(?s)isVevoVideo = true;.*?vevoVideoId = "(.*?)";', webpage)
331 vevo_id = m_vevo.group(1)
332 self.to_screen('Vevo video detected: %s' % vevo_id)
333 return self.url_result('vevo:%s' % vevo_id, ie='Vevo')
335 uri = self._html_search_regex(r'/uri/(.*?)\?', webpage, 'uri')
336 return self._get_videos_info(uri)
339 class MTVDEIE(MTVServicesInfoExtractor):
341 _VALID_URL = r'https?://(?:www\.)?mtv\.de/(?:artists|shows|news)/(?:[^/]+/)*(?P<id>\d+)-[^/#?]+/*(?:[#?].*)?$'
343 'url': 'http://www.mtv.de/artists/10571-cro/videos/61131-traum',
345 'id': 'music_video-a50bc5f0b3aa4b3190aa',
347 'title': 'MusicVideo_cro-traum',
348 'description': 'Cro - Traum',
352 'skip_download': True,
354 'skip': 'Blocked at Travis CI',
356 # mediagen URL without query (e.g. http://videos.mtvnn.com/mediagen/e865da714c166d18d6f80893195fcb97)
357 'url': 'http://www.mtv.de/shows/933-teen-mom-2/staffeln/5353/folgen/63565-enthullungen',
359 'id': 'local_playlist-f5ae778b9832cc837189',
361 'title': 'Episode_teen-mom-2_shows_season-5_episode-1_full-episode_part1',
365 'skip_download': True,
367 'skip': 'Blocked at Travis CI',
369 'url': 'http://www.mtv.de/news/77491-mtv-movies-spotlight-pixels-teil-3',
371 'id': 'local_playlist-4e760566473c4c8c5344',
373 'title': 'Article_mtv-movies-spotlight-pixels-teil-3_short-clips_part1',
374 'description': 'MTV Movies Supercut',
378 'skip_download': True,
380 'skip': 'Das Video kann zur Zeit nicht abgespielt werden.',
383 def _real_extract(self, url):
384 video_id = self._match_id(url)
386 webpage = self._download_webpage(url, video_id)
388 playlist = self._parse_json(
390 r'window\.pagePlaylist\s*=\s*(\[.+?\]);\n', webpage, 'page playlist'),
394 return item['mrss'] + item.get('mrssvars', '')
396 # news pages contain single video in playlist with different id
397 if len(playlist) == 1:
398 return self._get_videos_info_from_url(_mrss_url(playlist[0]), video_id)
400 for item in playlist:
401 item_id = item.get('id')
402 if item_id and compat_str(item_id) == video_id:
403 return self._get_videos_info_from_url(_mrss_url(item), video_id)