]> Raphaƫl G. Git Repositories - youtubedl/blob - youtube_dl/extractor/mtv.py
Initiate new release.
[youtubedl] / youtube_dl / extractor / mtv.py
1 from __future__ import unicode_literals
2
3 import re
4
5 from .common import InfoExtractor
6 from ..compat import (
7 compat_str,
8 compat_xpath,
9 )
10 from ..utils import (
11 ExtractorError,
12 find_xpath_attr,
13 fix_xml_ampersands,
14 float_or_none,
15 HEADRequest,
16 RegexNotFoundError,
17 sanitized_Request,
18 strip_or_none,
19 timeconvert,
20 try_get,
21 unescapeHTML,
22 update_url_query,
23 url_basename,
24 xpath_text,
25 )
26
27
28 def _media_xml_tag(tag):
29 return '{http://search.yahoo.com/mrss/}%s' % tag
30
31
32 class MTVServicesInfoExtractor(InfoExtractor):
33 _MOBILE_TEMPLATE = None
34 _LANG = None
35
36 @staticmethod
37 def _id_from_uri(uri):
38 return uri.split(':')[-1]
39
40 @staticmethod
41 def _remove_template_parameter(url):
42 # Remove the templates, like &device={device}
43 return re.sub(r'&[^=]*?={.*?}(?=(&|$))', '', url)
44
45 def _get_feed_url(self, uri):
46 return self._FEED_URL
47
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:
52 return None
53 else:
54 return thumb_node.attrib['url']
55
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'}]
70
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.',
78 expected=True)
79
80 formats = []
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_m3u8_formats(
85 hls_url, video_id, ext='mp4', entry_protocol='m3u8_native',
86 m3u8_id='hls'))
87 else:
88 # fms
89 try:
90 _, _, ext = rendition.attrib['type'].partition('/')
91 rtmp_video_url = rendition.find('./src').text
92 if 'error_not_available.swf' in rtmp_video_url:
93 raise ExtractorError(
94 '%s said: video is not available' % self.IE_NAME,
95 expected=True)
96 if rtmp_video_url.endswith('siteunavail.png'):
97 continue
98 formats.extend([{
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')),
106 }])
107 except (KeyError, TypeError):
108 raise ExtractorError('Invalid rendition field.')
109 self._sort_formats(formats)
110 return formats
111
112 def _extract_subtitles(self, mdoc, mtvn_id):
113 subtitles = {}
114 for transcript in mdoc.findall('.//transcript'):
115 if transcript.get('kind') != 'captions':
116 continue
117 lang = transcript.get('srclang')
118 subtitles[lang] = [{
119 'url': compat_str(typographic.get('src')),
120 'ext': typographic.get('format')
121 } for typographic in transcript.findall('./typographic')]
122 return subtitles
123
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'
135
136 mediagen_doc = self._download_xml(mediagen_url, video_id,
137 'Downloading video urls')
138
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')
144 message += item.text
145 raise ExtractorError(message, expected=True)
146
147 description = strip_or_none(xpath_text(itemdoc, 'description'))
148
149 timestamp = timeconvert(xpath_text(itemdoc, 'pubDate'))
150
151 title_el = None
152 if title_el is None:
153 title_el = find_xpath_attr(
154 itemdoc, './/{http://search.yahoo.com/mrss/}category',
155 'scheme', 'urn:mtvn:video_title')
156 if title_el is None:
157 title_el = itemdoc.find(compat_xpath('.//{http://search.yahoo.com/mrss/}title'))
158 if title_el is None:
159 title_el = itemdoc.find(compat_xpath('.//title'))
160 if title_el.text is None:
161 title_el = None
162
163 title = title_el.text
164 if title is None:
165 raise ExtractorError('Could not find video title')
166 title = title.strip()
167
168 # This a short id that's used in the webpage urls
169 mtvn_id = None
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
174
175 formats = self._extract_video_formats(mediagen_doc, mtvn_id, video_id)
176
177 return {
178 'title': title,
179 'formats': formats,
180 'subtitles': self._extract_subtitles(mediagen_doc, mtvn_id),
181 'id': video_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,
186 }
187
188 def _get_feed_query(self, uri):
189 data = {'uri': uri}
190 if self._LANG:
191 data['lang'] = self._LANG
192 return data
193
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)
199
200 def _get_videos_info_from_url(self, url, video_id, use_hls=True):
201 idoc = self._download_xml(
202 url, video_id,
203 'Downloading info', transform_source=fix_xml_ampersands)
204
205 title = xpath_text(idoc, './channel/title')
206 description = xpath_text(idoc, './channel/description')
207
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)
211
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)
216
217 data_zone = self._search_regex(
218 r'data-zone=(["\'])(?P<zone>.+?_lc_promo.*?)\1', webpage,
219 'data zone', default=data_zone, group='zone')
220
221 feed_url = try_get(
222 triforce_feed, lambda x: x['manifest']['zones'][data_zone]['feed'],
223 compat_str)
224 if not feed_url:
225 return
226
227 feed = self._download_json(feed_url, video_id, fatal=False)
228 if not feed:
229 return
230
231 return try_get(feed, lambda x: x['result']['data']['id'], compat_str)
232
233 def _extract_mgid(self, webpage):
234 try:
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'):
240 mgid = mgid[:-4]
241 except RegexNotFoundError:
242 mgid = None
243
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)
248
249 if not mgid:
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)
254
255 if not mgid:
256 mgid = self._extract_triforce_mgid(webpage)
257
258 return mgid
259
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)
265 return videos_info
266
267
268 class MTVServicesEmbeddedIE(MTVServicesInfoExtractor):
269 IE_NAME = 'mtvservices:embedded'
270 _VALID_URL = r'https?://media\.mtvnservices\.com/embed/(?P<mgid>.+?)(\?|/|$)'
271
272 _TEST = {
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',
276 'info_dict': {
277 'id': '1043906',
278 'ext': 'mp4',
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',
283 },
284 }
285
286 @staticmethod
287 def _extract_url(webpage):
288 mobj = re.search(
289 r'<iframe[^>]+?src=(["\'])(?P<url>(?:https?:)?//media.mtvnservices.com/embed/.+?)\1', webpage)
290 if mobj:
291 return mobj.group('url')
292
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'])
298
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)
303
304
305 class MTVIE(MTVServicesInfoExtractor):
306 IE_NAME = 'mtv'
307 _VALID_URL = r'https?://(?:www\.)?mtv\.com/(?:video-clips|(?:full-)?episodes)/(?P<id>[^/?#.]+)'
308 _FEED_URL = 'http://www.mtv.com/feeds/mrss/'
309
310 _TESTS = [{
311 'url': 'http://www.mtv.com/video-clips/vl8qof/unlocking-the-truth-trailer',
312 'md5': '1edbcdf1e7628e414a8c5dcebca3d32b',
313 'info_dict': {
314 'id': '5e14040d-18a4-47c4-a582-43ff602de88e',
315 'ext': 'mp4',
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',
320 },
321 }, {
322 'url': 'http://www.mtv.com/full-episodes/94tujl/unlocking-the-truth-gates-of-hell-season-1-ep-101',
323 'only_matching': True,
324 }, {
325 'url': 'http://www.mtv.com/episodes/g8xu7q/teen-mom-2-breaking-the-wall-season-7-ep-713',
326 'only_matching': True,
327 }]
328
329
330 class MTV81IE(InfoExtractor):
331 IE_NAME = 'mtv81'
332 _VALID_URL = r'https?://(?:www\.)?mtv81\.com/videos/(?P<id>[^/?#.]+)'
333
334 _TEST = {
335 'url': 'http://www.mtv81.com/videos/artist-to-watch/the-godfather-of-japanese-hip-hop-segment-1/',
336 'md5': '1edbcdf1e7628e414a8c5dcebca3d32b',
337 'info_dict': {
338 'id': '5e14040d-18a4-47c4-a582-43ff602de88e',
339 'ext': 'mp4',
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',
344 },
345 }
346
347 def _extract_mgid(self, webpage):
348 return self._search_regex(
349 r'getTheVideo\((["\'])(?P<id>mgid:.+?)\1', webpage,
350 'mgid', group='id')
351
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)
357
358
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>[^&]+))'''
364
365 _FEED_URL = 'http://www.mtv.com/player/embed/AS3/rss/'
366
367 _TESTS = [
368 {
369 'url': 'http://www.mtv.com/videos/misc/853555/ours-vh1-storytellers.jhtml',
370 'md5': '850f3f143316b1e71fa56a4edfd6e0f8',
371 'info_dict': {
372 'id': '853555',
373 'ext': 'mp4',
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',
378 },
379 },
380 ]
381
382 def _get_thumbnail_url(self, uri, itemdoc):
383 return 'http://mtv.mtvnimages.com/uri/' + uri
384
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')
389 if uri is None:
390 webpage = self._download_webpage(url, video_id)
391
392 # Some videos come from Vevo.com
393 m_vevo = re.search(
394 r'(?s)isVevoVideo = true;.*?vevoVideoId = "(.*?)";', webpage)
395 if m_vevo:
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')
399
400 uri = self._html_search_regex(r'/uri/(.*?)\?', webpage, 'uri')
401 return self._get_videos_info(uri)
402
403
404 class MTVDEIE(MTVServicesInfoExtractor):
405 IE_NAME = 'mtv.de'
406 _VALID_URL = r'https?://(?:www\.)?mtv\.de/(?:artists|shows|news)/(?:[^/]+/)*(?P<id>\d+)-[^/#?]+/*(?:[#?].*)?$'
407 _TESTS = [{
408 'url': 'http://www.mtv.de/artists/10571-cro/videos/61131-traum',
409 'info_dict': {
410 'id': 'music_video-a50bc5f0b3aa4b3190aa',
411 'ext': 'flv',
412 'title': 'MusicVideo_cro-traum',
413 'description': 'Cro - Traum',
414 },
415 'params': {
416 # rtmp download
417 'skip_download': True,
418 },
419 'skip': 'Blocked at Travis CI',
420 }, {
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',
423 'info_dict': {
424 'id': 'local_playlist-f5ae778b9832cc837189',
425 'ext': 'flv',
426 'title': 'Episode_teen-mom-2_shows_season-5_episode-1_full-episode_part1',
427 },
428 'params': {
429 # rtmp download
430 'skip_download': True,
431 },
432 'skip': 'Blocked at Travis CI',
433 }, {
434 'url': 'http://www.mtv.de/news/77491-mtv-movies-spotlight-pixels-teil-3',
435 'info_dict': {
436 'id': 'local_playlist-4e760566473c4c8c5344',
437 'ext': 'mp4',
438 'title': 'Article_mtv-movies-spotlight-pixels-teil-3_short-clips_part1',
439 'description': 'MTV Movies Supercut',
440 },
441 'params': {
442 # rtmp download
443 'skip_download': True,
444 },
445 'skip': 'Das Video kann zur Zeit nicht abgespielt werden.',
446 }]
447
448 def _real_extract(self, url):
449 video_id = self._match_id(url)
450
451 webpage = self._download_webpage(url, video_id)
452
453 playlist = self._parse_json(
454 self._search_regex(
455 r'window\.pagePlaylist\s*=\s*(\[.+?\]);\n', webpage, 'page playlist'),
456 video_id)
457
458 def _mrss_url(item):
459 return item['mrss'] + item.get('mrssvars', '')
460
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)
464
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)