]> Raphaƫl G. Git Repositories - youtubedl/blob - youtube_dl/extractor/mtv.py
debian/control: Update the repository to github.com.
[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 return thumb_node.get('url') or thumb_node.text or None
54
55 def _extract_mobile_video_formats(self, mtvn_id):
56 webpage_url = self._MOBILE_TEMPLATE % mtvn_id
57 req = sanitized_Request(webpage_url)
58 # Otherwise we get a webpage that would execute some javascript
59 req.add_header('User-Agent', 'curl/7')
60 webpage = self._download_webpage(req, mtvn_id,
61 'Downloading mobile page')
62 metrics_url = unescapeHTML(self._search_regex(r'<a href="(http://metrics.+?)"', webpage, 'url'))
63 req = HEADRequest(metrics_url)
64 response = self._request_webpage(req, mtvn_id, 'Resolving url')
65 url = response.geturl()
66 # Transform the url to get the best quality:
67 url = re.sub(r'.+pxE=mp4', 'http://mtvnmobile.vo.llnwd.net/kip0/_pxn=0+_pxK=18639+_pxE=mp4', url, 1)
68 return [{'url': url, 'ext': 'mp4'}]
69
70 def _extract_video_formats(self, mdoc, mtvn_id, video_id):
71 if re.match(r'.*/(error_country_block\.swf|geoblock\.mp4|copyright_error\.flv(?:\?geo\b.+?)?)$', mdoc.find('.//src').text) is not None:
72 if mtvn_id is not None and self._MOBILE_TEMPLATE is not None:
73 self.to_screen('The normal version is not available from your '
74 'country, trying with the mobile version')
75 return self._extract_mobile_video_formats(mtvn_id)
76 raise ExtractorError('This video is not available from your country.',
77 expected=True)
78
79 formats = []
80 for rendition in mdoc.findall('.//rendition'):
81 if rendition.get('method') == 'hls':
82 hls_url = rendition.find('./src').text
83 formats.extend(self._extract_m3u8_formats(
84 hls_url, video_id, ext='mp4', entry_protocol='m3u8_native',
85 m3u8_id='hls', fatal=False))
86 else:
87 # fms
88 try:
89 _, _, ext = rendition.attrib['type'].partition('/')
90 rtmp_video_url = rendition.find('./src').text
91 if 'error_not_available.swf' in rtmp_video_url:
92 raise ExtractorError(
93 '%s said: video is not available' % self.IE_NAME,
94 expected=True)
95 if rtmp_video_url.endswith('siteunavail.png'):
96 continue
97 formats.extend([{
98 'ext': 'flv' if rtmp_video_url.startswith('rtmp') else ext,
99 'url': rtmp_video_url,
100 'format_id': '-'.join(filter(None, [
101 'rtmp' if rtmp_video_url.startswith('rtmp') else None,
102 rendition.get('bitrate')])),
103 'width': int(rendition.get('width')),
104 'height': int(rendition.get('height')),
105 }])
106 except (KeyError, TypeError):
107 raise ExtractorError('Invalid rendition field.')
108 if formats:
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(
137 mediagen_url, video_id, 'Downloading video urls', fatal=False)
138
139 if mediagen_doc is False:
140 return None
141
142 item = mediagen_doc.find('./video/item')
143 if item is not None and item.get('type') == 'text':
144 message = '%s returned error: ' % self.IE_NAME
145 if item.get('code') is not None:
146 message += '%s - ' % item.get('code')
147 message += item.text
148 raise ExtractorError(message, expected=True)
149
150 description = strip_or_none(xpath_text(itemdoc, 'description'))
151
152 timestamp = timeconvert(xpath_text(itemdoc, 'pubDate'))
153
154 title_el = None
155 if title_el is None:
156 title_el = find_xpath_attr(
157 itemdoc, './/{http://search.yahoo.com/mrss/}category',
158 'scheme', 'urn:mtvn:video_title')
159 if title_el is None:
160 title_el = itemdoc.find(compat_xpath('.//{http://search.yahoo.com/mrss/}title'))
161 if title_el is None:
162 title_el = itemdoc.find(compat_xpath('.//title'))
163 if title_el.text is None:
164 title_el = None
165
166 title = title_el.text
167 if title is None:
168 raise ExtractorError('Could not find video title')
169 title = title.strip()
170
171 # This a short id that's used in the webpage urls
172 mtvn_id = None
173 mtvn_id_node = find_xpath_attr(itemdoc, './/{http://search.yahoo.com/mrss/}category',
174 'scheme', 'urn:mtvn:id')
175 if mtvn_id_node is not None:
176 mtvn_id = mtvn_id_node.text
177
178 formats = self._extract_video_formats(mediagen_doc, mtvn_id, video_id)
179
180 # Some parts of complete video may be missing (e.g. missing Act 3 in
181 # http://www.southpark.de/alle-episoden/s14e01-sexual-healing)
182 if not formats:
183 return None
184
185 self._sort_formats(formats)
186
187 return {
188 'title': title,
189 'formats': formats,
190 'subtitles': self._extract_subtitles(mediagen_doc, mtvn_id),
191 'id': video_id,
192 'thumbnail': self._get_thumbnail_url(uri, itemdoc),
193 'description': description,
194 'duration': float_or_none(content_el.attrib.get('duration')),
195 'timestamp': timestamp,
196 }
197
198 def _get_feed_query(self, uri):
199 data = {'uri': uri}
200 if self._LANG:
201 data['lang'] = self._LANG
202 return data
203
204 def _get_videos_info(self, uri, use_hls=True):
205 video_id = self._id_from_uri(uri)
206 feed_url = self._get_feed_url(uri)
207 info_url = update_url_query(feed_url, self._get_feed_query(uri))
208 return self._get_videos_info_from_url(info_url, video_id, use_hls)
209
210 def _get_videos_info_from_url(self, url, video_id, use_hls=True):
211 idoc = self._download_xml(
212 url, video_id,
213 'Downloading info', transform_source=fix_xml_ampersands)
214
215 title = xpath_text(idoc, './channel/title')
216 description = xpath_text(idoc, './channel/description')
217
218 entries = []
219 for item in idoc.findall('.//item'):
220 info = self._get_video_info(item, use_hls)
221 if info:
222 entries.append(info)
223
224 return self.playlist_result(
225 entries, playlist_title=title, playlist_description=description)
226
227 def _extract_triforce_mgid(self, webpage, data_zone=None, video_id=None):
228 triforce_feed = self._parse_json(self._search_regex(
229 r'triforceManifestFeed\s*=\s*({.+?})\s*;\s*\n', webpage,
230 'triforce feed', default='{}'), video_id, fatal=False)
231
232 data_zone = self._search_regex(
233 r'data-zone=(["\'])(?P<zone>.+?_lc_promo.*?)\1', webpage,
234 'data zone', default=data_zone, group='zone')
235
236 feed_url = try_get(
237 triforce_feed, lambda x: x['manifest']['zones'][data_zone]['feed'],
238 compat_str)
239 if not feed_url:
240 return
241
242 feed = self._download_json(feed_url, video_id, fatal=False)
243 if not feed:
244 return
245
246 return try_get(feed, lambda x: x['result']['data']['id'], compat_str)
247
248 def _extract_mgid(self, webpage):
249 try:
250 # the url can be http://media.mtvnservices.com/fb/{mgid}.swf
251 # or http://media.mtvnservices.com/{mgid}
252 og_url = self._og_search_video_url(webpage)
253 mgid = url_basename(og_url)
254 if mgid.endswith('.swf'):
255 mgid = mgid[:-4]
256 except RegexNotFoundError:
257 mgid = None
258
259 if mgid is None or ':' not in mgid:
260 mgid = self._search_regex(
261 [r'data-mgid="(.*?)"', r'swfobject\.embedSWF\(".*?(mgid:.*?)"'],
262 webpage, 'mgid', default=None)
263
264 if not mgid:
265 sm4_embed = self._html_search_meta(
266 'sm4:video:embed', webpage, 'sm4 embed', default='')
267 mgid = self._search_regex(
268 r'embed/(mgid:.+?)["\'&?/]', sm4_embed, 'mgid', default=None)
269
270 if not mgid:
271 mgid = self._extract_triforce_mgid(webpage)
272
273 return mgid
274
275 def _real_extract(self, url):
276 title = url_basename(url)
277 webpage = self._download_webpage(url, title)
278 mgid = self._extract_mgid(webpage)
279 videos_info = self._get_videos_info(mgid)
280 return videos_info
281
282
283 class MTVServicesEmbeddedIE(MTVServicesInfoExtractor):
284 IE_NAME = 'mtvservices:embedded'
285 _VALID_URL = r'https?://media\.mtvnservices\.com/embed/(?P<mgid>.+?)(\?|/|$)'
286
287 _TEST = {
288 # From http://www.thewrap.com/peter-dinklage-sums-up-game-of-thrones-in-45-seconds-video/
289 'url': 'http://media.mtvnservices.com/embed/mgid:uma:video:mtv.com:1043906/cp~vid%3D1043906%26uri%3Dmgid%3Auma%3Avideo%3Amtv.com%3A1043906',
290 'md5': 'cb349b21a7897164cede95bd7bf3fbb9',
291 'info_dict': {
292 'id': '1043906',
293 'ext': 'mp4',
294 'title': 'Peter Dinklage Sums Up \'Game Of Thrones\' In 45 Seconds',
295 'description': '"Sexy sexy sexy, stabby stabby stabby, beautiful language," says Peter Dinklage as he tries summarizing "Game of Thrones" in under a minute.',
296 'timestamp': 1400126400,
297 'upload_date': '20140515',
298 },
299 }
300
301 @staticmethod
302 def _extract_url(webpage):
303 mobj = re.search(
304 r'<iframe[^>]+?src=(["\'])(?P<url>(?:https?:)?//media.mtvnservices.com/embed/.+?)\1', webpage)
305 if mobj:
306 return mobj.group('url')
307
308 def _get_feed_url(self, uri):
309 video_id = self._id_from_uri(uri)
310 config = self._download_json(
311 'http://media.mtvnservices.com/pmt/e1/access/index.html?uri=%s&configtype=edge' % uri, video_id)
312 return self._remove_template_parameter(config['feedWithQueryParams'])
313
314 def _real_extract(self, url):
315 mobj = re.match(self._VALID_URL, url)
316 mgid = mobj.group('mgid')
317 return self._get_videos_info(mgid)
318
319
320 class MTVIE(MTVServicesInfoExtractor):
321 IE_NAME = 'mtv'
322 _VALID_URL = r'https?://(?:www\.)?mtv\.com/(?:video-clips|(?:full-)?episodes)/(?P<id>[^/?#.]+)'
323 _FEED_URL = 'http://www.mtv.com/feeds/mrss/'
324
325 _TESTS = [{
326 'url': 'http://www.mtv.com/video-clips/vl8qof/unlocking-the-truth-trailer',
327 'md5': '1edbcdf1e7628e414a8c5dcebca3d32b',
328 'info_dict': {
329 'id': '5e14040d-18a4-47c4-a582-43ff602de88e',
330 'ext': 'mp4',
331 'title': 'Unlocking The Truth|July 18, 2016|1|101|Trailer',
332 'description': '"Unlocking the Truth" premieres August 17th at 11/10c.',
333 'timestamp': 1468846800,
334 'upload_date': '20160718',
335 },
336 }, {
337 'url': 'http://www.mtv.com/full-episodes/94tujl/unlocking-the-truth-gates-of-hell-season-1-ep-101',
338 'only_matching': True,
339 }, {
340 'url': 'http://www.mtv.com/episodes/g8xu7q/teen-mom-2-breaking-the-wall-season-7-ep-713',
341 'only_matching': True,
342 }]
343
344
345 class MTV81IE(InfoExtractor):
346 IE_NAME = 'mtv81'
347 _VALID_URL = r'https?://(?:www\.)?mtv81\.com/videos/(?P<id>[^/?#.]+)'
348
349 _TEST = {
350 'url': 'http://www.mtv81.com/videos/artist-to-watch/the-godfather-of-japanese-hip-hop-segment-1/',
351 'md5': '1edbcdf1e7628e414a8c5dcebca3d32b',
352 'info_dict': {
353 'id': '5e14040d-18a4-47c4-a582-43ff602de88e',
354 'ext': 'mp4',
355 'title': 'Unlocking The Truth|July 18, 2016|1|101|Trailer',
356 'description': '"Unlocking the Truth" premieres August 17th at 11/10c.',
357 'timestamp': 1468846800,
358 'upload_date': '20160718',
359 },
360 }
361
362 def _extract_mgid(self, webpage):
363 return self._search_regex(
364 r'getTheVideo\((["\'])(?P<id>mgid:.+?)\1', webpage,
365 'mgid', group='id')
366
367 def _real_extract(self, url):
368 video_id = self._match_id(url)
369 webpage = self._download_webpage(url, video_id)
370 mgid = self._extract_mgid(webpage)
371 return self.url_result('http://media.mtvnservices.com/embed/%s' % mgid)
372
373
374 class MTVVideoIE(MTVServicesInfoExtractor):
375 IE_NAME = 'mtv:video'
376 _VALID_URL = r'''(?x)^https?://
377 (?:(?:www\.)?mtv\.com/videos/.+?/(?P<videoid>[0-9]+)/[^/]+$|
378 m\.mtv\.com/videos/video\.rbml\?.*?id=(?P<mgid>[^&]+))'''
379
380 _FEED_URL = 'http://www.mtv.com/player/embed/AS3/rss/'
381
382 _TESTS = [
383 {
384 'url': 'http://www.mtv.com/videos/misc/853555/ours-vh1-storytellers.jhtml',
385 'md5': '850f3f143316b1e71fa56a4edfd6e0f8',
386 'info_dict': {
387 'id': '853555',
388 'ext': 'mp4',
389 'title': 'Taylor Swift - "Ours (VH1 Storytellers)"',
390 'description': 'Album: Taylor Swift performs "Ours" for VH1 Storytellers at Harvey Mudd College.',
391 'timestamp': 1352610000,
392 'upload_date': '20121111',
393 },
394 },
395 ]
396
397 def _get_thumbnail_url(self, uri, itemdoc):
398 return 'http://mtv.mtvnimages.com/uri/' + uri
399
400 def _real_extract(self, url):
401 mobj = re.match(self._VALID_URL, url)
402 video_id = mobj.group('videoid')
403 uri = mobj.groupdict().get('mgid')
404 if uri is None:
405 webpage = self._download_webpage(url, video_id)
406
407 # Some videos come from Vevo.com
408 m_vevo = re.search(
409 r'(?s)isVevoVideo = true;.*?vevoVideoId = "(.*?)";', webpage)
410 if m_vevo:
411 vevo_id = m_vevo.group(1)
412 self.to_screen('Vevo video detected: %s' % vevo_id)
413 return self.url_result('vevo:%s' % vevo_id, ie='Vevo')
414
415 uri = self._html_search_regex(r'/uri/(.*?)\?', webpage, 'uri')
416 return self._get_videos_info(uri)
417
418
419 class MTVDEIE(MTVServicesInfoExtractor):
420 IE_NAME = 'mtv.de'
421 _VALID_URL = r'https?://(?:www\.)?mtv\.de/(?:artists|shows|news)/(?:[^/]+/)*(?P<id>\d+)-[^/#?]+/*(?:[#?].*)?$'
422 _TESTS = [{
423 'url': 'http://www.mtv.de/artists/10571-cro/videos/61131-traum',
424 'info_dict': {
425 'id': 'music_video-a50bc5f0b3aa4b3190aa',
426 'ext': 'flv',
427 'title': 'MusicVideo_cro-traum',
428 'description': 'Cro - Traum',
429 },
430 'params': {
431 # rtmp download
432 'skip_download': True,
433 },
434 'skip': 'Blocked at Travis CI',
435 }, {
436 # mediagen URL without query (e.g. http://videos.mtvnn.com/mediagen/e865da714c166d18d6f80893195fcb97)
437 'url': 'http://www.mtv.de/shows/933-teen-mom-2/staffeln/5353/folgen/63565-enthullungen',
438 'info_dict': {
439 'id': 'local_playlist-f5ae778b9832cc837189',
440 'ext': 'flv',
441 'title': 'Episode_teen-mom-2_shows_season-5_episode-1_full-episode_part1',
442 },
443 'params': {
444 # rtmp download
445 'skip_download': True,
446 },
447 'skip': 'Blocked at Travis CI',
448 }, {
449 'url': 'http://www.mtv.de/news/77491-mtv-movies-spotlight-pixels-teil-3',
450 'info_dict': {
451 'id': 'local_playlist-4e760566473c4c8c5344',
452 'ext': 'mp4',
453 'title': 'Article_mtv-movies-spotlight-pixels-teil-3_short-clips_part1',
454 'description': 'MTV Movies Supercut',
455 },
456 'params': {
457 # rtmp download
458 'skip_download': True,
459 },
460 'skip': 'Das Video kann zur Zeit nicht abgespielt werden.',
461 }]
462
463 def _real_extract(self, url):
464 video_id = self._match_id(url)
465
466 webpage = self._download_webpage(url, video_id)
467
468 playlist = self._parse_json(
469 self._search_regex(
470 r'window\.pagePlaylist\s*=\s*(\[.+?\]);\n', webpage, 'page playlist'),
471 video_id)
472
473 def _mrss_url(item):
474 return item['mrss'] + item.get('mrssvars', '')
475
476 # news pages contain single video in playlist with different id
477 if len(playlist) == 1:
478 return self._get_videos_info_from_url(_mrss_url(playlist[0]), video_id)
479
480 for item in playlist:
481 item_id = item.get('id')
482 if item_id and compat_str(item_id) == video_id:
483 return self._get_videos_info_from_url(_mrss_url(item), video_id)