]> jfr.im git - yt-dlp.git/blob - youtube_dlc/extractor/mtv.py
Fix `--windows-filenames` removing `/` from UNIX paths
[yt-dlp.git] / youtube_dlc / extractor / mtv.py
1 # coding: utf-8
2 from __future__ import unicode_literals
3
4 import re
5
6 from .common import InfoExtractor
7 from ..compat import (
8 compat_str,
9 compat_xpath,
10 compat_urlparse,
11 )
12 from ..utils import (
13 ExtractorError,
14 find_xpath_attr,
15 fix_xml_ampersands,
16 float_or_none,
17 HEADRequest,
18 RegexNotFoundError,
19 sanitized_Request,
20 strip_or_none,
21 timeconvert,
22 try_get,
23 unescapeHTML,
24 update_url_query,
25 url_basename,
26 get_domain,
27 xpath_text,
28 )
29
30
31 def _media_xml_tag(tag):
32 return '{http://search.yahoo.com/mrss/}%s' % tag
33
34
35 class MTVServicesInfoExtractor(InfoExtractor):
36 _MOBILE_TEMPLATE = None
37 _LANG = None
38
39 @staticmethod
40 def _id_from_uri(uri):
41 return uri.split(':')[-1]
42
43 @staticmethod
44 def _remove_template_parameter(url):
45 # Remove the templates, like &device={device}
46 return re.sub(r'&[^=]*?={.*?}(?=(&|$))', '', url)
47
48 def _get_feed_url(self, uri, url=None):
49 return self._FEED_URL
50
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:
55 return None
56 return thumb_node.get('url') or thumb_node.text or None
57
58 def _extract_mobile_video_formats(self, mtvn_id):
59 webpage_url = self._MOBILE_TEMPLATE % mtvn_id
60 req = sanitized_Request(webpage_url)
61 # Otherwise we get a webpage that would execute some javascript
62 req.add_header('User-Agent', 'curl/7')
63 webpage = self._download_webpage(req, mtvn_id,
64 'Downloading mobile page')
65 metrics_url = unescapeHTML(self._search_regex(r'<a href="(http://metrics.+?)"', webpage, 'url'))
66 req = HEADRequest(metrics_url)
67 response = self._request_webpage(req, mtvn_id, 'Resolving url')
68 url = response.geturl()
69 # Transform the url to get the best quality:
70 url = re.sub(r'.+pxE=mp4', 'http://mtvnmobile.vo.llnwd.net/kip0/_pxn=0+_pxK=18639+_pxE=mp4', url, 1)
71 return [{'url': url, 'ext': 'mp4'}]
72
73 def _extract_video_formats(self, mdoc, mtvn_id, video_id):
74 if re.match(r'.*/(error_country_block\.swf|geoblock\.mp4|copyright_error\.flv(?:\?geo\b.+?)?)$', mdoc.find('.//src').text) is not None:
75 if mtvn_id is not None and self._MOBILE_TEMPLATE is not None:
76 self.to_screen('The normal version is not available from your '
77 'country, trying with the mobile version')
78 return self._extract_mobile_video_formats(mtvn_id)
79 raise ExtractorError('This video is not available from your country.',
80 expected=True)
81
82 formats = []
83 for rendition in mdoc.findall('.//rendition'):
84 if rendition.get('method') == 'hls':
85 hls_url = rendition.find('./src').text
86 formats.extend(self._extract_m3u8_formats(
87 hls_url, video_id, ext='mp4', entry_protocol='m3u8_native',
88 m3u8_id='hls', fatal=False))
89 else:
90 # fms
91 try:
92 _, _, ext = rendition.attrib['type'].partition('/')
93 rtmp_video_url = rendition.find('./src').text
94 if 'error_not_available.swf' in rtmp_video_url:
95 raise ExtractorError(
96 '%s said: video is not available' % self.IE_NAME,
97 expected=True)
98 if rtmp_video_url.endswith('siteunavail.png'):
99 continue
100 formats.extend([{
101 'ext': 'flv' if rtmp_video_url.startswith('rtmp') else ext,
102 'url': rtmp_video_url,
103 'format_id': '-'.join(filter(None, [
104 'rtmp' if rtmp_video_url.startswith('rtmp') else None,
105 rendition.get('bitrate')])),
106 'width': int(rendition.get('width')),
107 'height': int(rendition.get('height')),
108 }])
109 except (KeyError, TypeError):
110 raise ExtractorError('Invalid rendition field.')
111 if formats:
112 self._sort_formats(formats)
113 return formats
114
115 def _extract_subtitles(self, mdoc, mtvn_id):
116 subtitles = {}
117 for transcript in mdoc.findall('.//transcript'):
118 if transcript.get('kind') != 'captions':
119 continue
120 lang = transcript.get('srclang')
121 for typographic in transcript.findall('./typographic'):
122 sub_src = typographic.get('src')
123 if not sub_src:
124 continue
125 ext = typographic.get('format')
126 if ext == 'cea-608':
127 ext = 'scc'
128 subtitles.setdefault(lang, []).append({
129 'url': compat_str(sub_src),
130 'ext': ext
131 })
132 return subtitles
133
134 def _get_video_info(self, itemdoc, use_hls=True):
135 uri = itemdoc.find('guid').text
136 video_id = self._id_from_uri(uri)
137 self.report_extraction(video_id)
138 content_el = itemdoc.find('%s/%s' % (_media_xml_tag('group'), _media_xml_tag('content')))
139 mediagen_url = self._remove_template_parameter(content_el.attrib['url'])
140 mediagen_url = mediagen_url.replace('device={device}', '')
141 if 'acceptMethods' not in mediagen_url:
142 mediagen_url += '&' if '?' in mediagen_url else '?'
143 mediagen_url += 'acceptMethods='
144 mediagen_url += 'hls' if use_hls else 'fms'
145
146 mediagen_doc = self._download_xml(
147 mediagen_url, video_id, 'Downloading video urls', fatal=False)
148
149 if mediagen_doc is False:
150 return None
151
152 item = mediagen_doc.find('./video/item')
153 if item is not None and item.get('type') == 'text':
154 message = '%s returned error: ' % self.IE_NAME
155 if item.get('code') is not None:
156 message += '%s - ' % item.get('code')
157 message += item.text
158 raise ExtractorError(message, expected=True)
159
160 description = strip_or_none(xpath_text(itemdoc, 'description'))
161
162 timestamp = timeconvert(xpath_text(itemdoc, 'pubDate'))
163
164 title_el = None
165 if title_el is None:
166 title_el = find_xpath_attr(
167 itemdoc, './/{http://search.yahoo.com/mrss/}category',
168 'scheme', 'urn:mtvn:video_title')
169 if title_el is None:
170 title_el = itemdoc.find(compat_xpath('.//{http://search.yahoo.com/mrss/}title'))
171 if title_el is None:
172 title_el = itemdoc.find(compat_xpath('.//title'))
173 if title_el.text is None:
174 title_el = None
175
176 title = title_el.text
177 if title is None:
178 raise ExtractorError('Could not find video title')
179 title = title.strip()
180
181 # This a short id that's used in the webpage urls
182 mtvn_id = None
183 mtvn_id_node = find_xpath_attr(itemdoc, './/{http://search.yahoo.com/mrss/}category',
184 'scheme', 'urn:mtvn:id')
185 if mtvn_id_node is not None:
186 mtvn_id = mtvn_id_node.text
187
188 formats = self._extract_video_formats(mediagen_doc, mtvn_id, video_id)
189
190 # Some parts of complete video may be missing (e.g. missing Act 3 in
191 # http://www.southpark.de/alle-episoden/s14e01-sexual-healing)
192 if not formats:
193 return None
194
195 self._sort_formats(formats)
196
197 return {
198 'title': title,
199 'formats': formats,
200 'subtitles': self._extract_subtitles(mediagen_doc, mtvn_id),
201 'id': video_id,
202 'thumbnail': self._get_thumbnail_url(uri, itemdoc),
203 'description': description,
204 'duration': float_or_none(content_el.attrib.get('duration')),
205 'timestamp': timestamp,
206 }
207
208 def _get_feed_query(self, uri):
209 data = {'uri': uri}
210 if self._LANG:
211 data['lang'] = self._LANG
212 return data
213
214 def _get_videos_info(self, uri, use_hls=True, url=None):
215 video_id = self._id_from_uri(uri)
216 feed_url = self._get_feed_url(uri, url)
217 info_url = update_url_query(feed_url, self._get_feed_query(uri))
218 return self._get_videos_info_from_url(info_url, video_id, use_hls)
219
220 def _get_videos_info_from_url(self, url, video_id, use_hls=True):
221 idoc = self._download_xml(
222 url, video_id,
223 'Downloading info', transform_source=fix_xml_ampersands)
224
225 title = xpath_text(idoc, './channel/title')
226 description = xpath_text(idoc, './channel/description')
227
228 entries = []
229 for item in idoc.findall('.//item'):
230 info = self._get_video_info(item, use_hls)
231 if info:
232 entries.append(info)
233
234 return self.playlist_result(
235 entries, playlist_title=title, playlist_description=description)
236
237 def _extract_triforce_mgid(self, webpage, data_zone=None, video_id=None):
238 triforce_feed = self._parse_json(self._search_regex(
239 r'triforceManifestFeed\s*=\s*({.+?})\s*;\s*\n', webpage,
240 'triforce feed', default='{}'), video_id, fatal=False)
241
242 data_zone = self._search_regex(
243 r'data-zone=(["\'])(?P<zone>.+?_lc_promo.*?)\1', webpage,
244 'data zone', default=data_zone, group='zone')
245
246 feed_url = try_get(
247 triforce_feed, lambda x: x['manifest']['zones'][data_zone]['feed'],
248 compat_str)
249 if not feed_url:
250 return
251
252 feed = self._download_json(feed_url, video_id, fatal=False)
253 if not feed:
254 return
255
256 return try_get(feed, lambda x: x['result']['data']['id'], compat_str)
257
258 @staticmethod
259 def _extract_child_with_type(parent, t):
260 return next(c for c in parent['children'] if c.get('type') == t)
261
262 def _extract_new_triforce_mgid(self, webpage, url='', video_id=None):
263 if url == '':
264 return
265 domain = get_domain(url)
266 if domain is None:
267 raise ExtractorError(
268 '[%s] could not get domain' % self.IE_NAME,
269 expected=True)
270 url = url.replace("https://", "http://")
271 enc_url = compat_urlparse.quote(url, safe='')
272 _TRIFORCE_V8_TEMPLATE = 'https://%s/feeds/triforce/manifest/v8?url=%s'
273 triforce_manifest_url = _TRIFORCE_V8_TEMPLATE % (domain, enc_url)
274
275 manifest = self._download_json(triforce_manifest_url, video_id, fatal=False)
276 if manifest:
277 if manifest.get('manifest').get('type') == 'redirect':
278 self.to_screen('Found a redirect. Downloading manifest from new location')
279 new_loc = manifest.get('manifest').get('newLocation')
280 new_loc = new_loc.replace("https://", "http://")
281 enc_new_loc = compat_urlparse.quote(new_loc, safe='')
282 triforce_manifest_new_loc = _TRIFORCE_V8_TEMPLATE % (domain, enc_new_loc)
283 manifest = self._download_json(triforce_manifest_new_loc, video_id, fatal=False)
284
285 item_id = try_get(manifest, lambda x: x['manifest']['reporting']['itemId'], compat_str)
286 if not item_id:
287 self.to_screen('No id found!')
288 return
289
290 # 'episode' can be anything. 'content' is used often as well
291 _MGID_TEMPLATE = 'mgid:arc:episode:%s:%s'
292 mgid = _MGID_TEMPLATE % (domain, item_id)
293
294 return mgid
295
296 def _extract_mgid(self, webpage, url, title=None, data_zone=None):
297 try:
298 # the url can be http://media.mtvnservices.com/fb/{mgid}.swf
299 # or http://media.mtvnservices.com/{mgid}
300 og_url = self._og_search_video_url(webpage)
301 mgid = url_basename(og_url)
302 if mgid.endswith('.swf'):
303 mgid = mgid[:-4]
304 except RegexNotFoundError:
305 mgid = None
306
307 if not title:
308 title = url_basename(url)
309
310 try:
311 window_data = self._parse_json(self._search_regex(
312 r'(?s)window.__DATA__ = (?P<json>{.+});', webpage,
313 'JSON Window Data', default=None, fatal=False, group='json'), title, fatal=False)
314 main_container = None
315 for i in range(len(window_data['children'])):
316 if window_data['children'][i]['type'] == 'MainContainer':
317 main_container = window_data['children'][i]
318 mgid = main_container['children'][0]['props']['media']['video']['config']['uri']
319 except (KeyError, IndexError, TypeError):
320 pass
321
322 if mgid is None or ':' not in mgid:
323 mgid = self._search_regex(
324 [r'data-mgid="(.*?)"', r'swfobject\.embedSWF\(".*?(mgid:.*?)"'],
325 webpage, 'mgid', default=None)
326
327 if not mgid:
328 sm4_embed = self._html_search_meta(
329 'sm4:video:embed', webpage, 'sm4 embed', default='')
330 mgid = self._search_regex(
331 r'embed/(mgid:.+?)["\'&?/]', sm4_embed, 'mgid', default=None)
332
333 if not mgid:
334 mgid = self._extract_new_triforce_mgid(webpage, url)
335
336 if not mgid:
337 mgid = self._extract_triforce_mgid(webpage, data_zone)
338
339 if not mgid:
340 data = self._parse_json(self._search_regex(
341 r'__DATA__\s*=\s*({.+?});', webpage, 'data'), None)
342 main_container = self._extract_child_with_type(data, 'MainContainer')
343 video_player = self._extract_child_with_type(main_container, 'VideoPlayer')
344 mgid = video_player['props']['media']['video']['config']['uri']
345
346 return mgid
347
348 def _real_extract(self, url):
349 title = url_basename(url)
350 webpage = self._download_webpage(url, title)
351 mgid = self._extract_mgid(webpage, url, title=title)
352 videos_info = self._get_videos_info(mgid, url=url)
353 return videos_info
354
355
356 class MTVServicesEmbeddedIE(MTVServicesInfoExtractor):
357 IE_NAME = 'mtvservices:embedded'
358 _VALID_URL = r'https?://media\.mtvnservices\.com/embed/(?P<mgid>.+?)(\?|/|$)'
359
360 _TEST = {
361 # From http://www.thewrap.com/peter-dinklage-sums-up-game-of-thrones-in-45-seconds-video/
362 'url': 'http://media.mtvnservices.com/embed/mgid:uma:video:mtv.com:1043906/cp~vid%3D1043906%26uri%3Dmgid%3Auma%3Avideo%3Amtv.com%3A1043906',
363 'md5': 'cb349b21a7897164cede95bd7bf3fbb9',
364 'info_dict': {
365 'id': '1043906',
366 'ext': 'mp4',
367 'title': 'Peter Dinklage Sums Up \'Game Of Thrones\' In 45 Seconds',
368 'description': '"Sexy sexy sexy, stabby stabby stabby, beautiful language," says Peter Dinklage as he tries summarizing "Game of Thrones" in under a minute.',
369 'timestamp': 1400126400,
370 'upload_date': '20140515',
371 },
372 }
373
374 @staticmethod
375 def _extract_url(webpage):
376 mobj = re.search(
377 r'<iframe[^>]+?src=(["\'])(?P<url>(?:https?:)?//media.mtvnservices.com/embed/.+?)\1', webpage)
378 if mobj:
379 return mobj.group('url')
380
381 def _get_feed_url(self, uri):
382 video_id = self._id_from_uri(uri)
383 config = self._download_json(
384 'http://media.mtvnservices.com/pmt/e1/access/index.html?uri=%s&configtype=edge' % uri, video_id)
385 return self._remove_template_parameter(config['feedWithQueryParams'])
386
387 def _real_extract(self, url):
388 mobj = re.match(self._VALID_URL, url)
389 mgid = mobj.group('mgid')
390 return self._get_videos_info(mgid)
391
392
393 class MTVIE(MTVServicesInfoExtractor):
394 IE_NAME = 'mtv'
395 _VALID_URL = r'https?://(?:www\.)?mtv\.com/(?:video-clips|(?:full-)?episodes)/(?P<id>[^/?#.]+)'
396 _FEED_URL = 'http://www.mtv.com/feeds/mrss/'
397
398 _TESTS = [{
399 'url': 'http://www.mtv.com/video-clips/vl8qof/unlocking-the-truth-trailer',
400 'md5': '1edbcdf1e7628e414a8c5dcebca3d32b',
401 'info_dict': {
402 'id': '5e14040d-18a4-47c4-a582-43ff602de88e',
403 'ext': 'mp4',
404 'title': 'Unlocking The Truth|July 18, 2016|1|101|Trailer',
405 'description': '"Unlocking the Truth" premieres August 17th at 11/10c.',
406 'timestamp': 1468846800,
407 'upload_date': '20160718',
408 },
409 }, {
410 'url': 'http://www.mtv.com/full-episodes/94tujl/unlocking-the-truth-gates-of-hell-season-1-ep-101',
411 'only_matching': True,
412 }, {
413 'url': 'http://www.mtv.com/episodes/g8xu7q/teen-mom-2-breaking-the-wall-season-7-ep-713',
414 'only_matching': True,
415 }]
416
417
418 class MTVJapanIE(MTVServicesInfoExtractor):
419 IE_NAME = 'mtvjapan'
420 _VALID_URL = r'https?://(?:www\.)?mtvjapan\.com/videos/(?P<id>[0-9a-z]+)'
421
422 _TEST = {
423 'url': 'http://www.mtvjapan.com/videos/prayht/fresh-info-cadillac-escalade',
424 'info_dict': {
425 'id': 'bc01da03-6fe5-4284-8880-f291f4e368f5',
426 'ext': 'mp4',
427 'title': '【Fresh Info】Cadillac ESCALADE Sport Edition',
428 },
429 'params': {
430 'skip_download': True,
431 },
432 }
433 _GEO_COUNTRIES = ['JP']
434 _FEED_URL = 'http://feeds.mtvnservices.com/od/feed/intl-mrss-player-feed'
435
436 def _get_feed_query(self, uri):
437 return {
438 'arcEp': 'mtvjapan.com',
439 'mgid': uri,
440 }
441
442
443 class MTVVideoIE(MTVServicesInfoExtractor):
444 IE_NAME = 'mtv:video'
445 _VALID_URL = r'''(?x)^https?://
446 (?:(?:www\.)?mtv\.com/videos/.+?/(?P<videoid>[0-9]+)/[^/]+$|
447 m\.mtv\.com/videos/video\.rbml\?.*?id=(?P<mgid>[^&]+))'''
448
449 _FEED_URL = 'http://www.mtv.com/player/embed/AS3/rss/'
450
451 _TESTS = [
452 {
453 'url': 'http://www.mtv.com/videos/misc/853555/ours-vh1-storytellers.jhtml',
454 'md5': '850f3f143316b1e71fa56a4edfd6e0f8',
455 'info_dict': {
456 'id': '853555',
457 'ext': 'mp4',
458 'title': 'Taylor Swift - "Ours (VH1 Storytellers)"',
459 'description': 'Album: Taylor Swift performs "Ours" for VH1 Storytellers at Harvey Mudd College.',
460 'timestamp': 1352610000,
461 'upload_date': '20121111',
462 },
463 },
464 ]
465
466 def _get_thumbnail_url(self, uri, itemdoc):
467 return 'http://mtv.mtvnimages.com/uri/' + uri
468
469 def _real_extract(self, url):
470 mobj = re.match(self._VALID_URL, url)
471 video_id = mobj.group('videoid')
472 uri = mobj.groupdict().get('mgid')
473 if uri is None:
474 webpage = self._download_webpage(url, video_id)
475
476 # Some videos come from Vevo.com
477 m_vevo = re.search(
478 r'(?s)isVevoVideo = true;.*?vevoVideoId = "(.*?)";', webpage)
479 if m_vevo:
480 vevo_id = m_vevo.group(1)
481 self.to_screen('Vevo video detected: %s' % vevo_id)
482 return self.url_result('vevo:%s' % vevo_id, ie='Vevo')
483
484 uri = self._html_search_regex(r'/uri/(.*?)\?', webpage, 'uri')
485 return self._get_videos_info(uri)
486
487
488 class MTVDEIE(MTVServicesInfoExtractor):
489 IE_NAME = 'mtv.de'
490 _VALID_URL = r'https?://(?:www\.)?mtv\.de/(?:musik/videoclips|folgen|news)/(?P<id>[0-9a-z]+)'
491 _TESTS = [{
492 'url': 'http://www.mtv.de/musik/videoclips/2gpnv7/Traum',
493 'info_dict': {
494 'id': 'd5d472bc-f5b7-11e5-bffd-a4badb20dab5',
495 'ext': 'mp4',
496 'title': 'Traum',
497 'description': 'Traum',
498 },
499 'params': {
500 # rtmp download
501 'skip_download': True,
502 },
503 'skip': 'Blocked at Travis CI',
504 }, {
505 # mediagen URL without query (e.g. http://videos.mtvnn.com/mediagen/e865da714c166d18d6f80893195fcb97)
506 'url': 'http://www.mtv.de/folgen/6b1ylu/teen-mom-2-enthuellungen-S5-F1',
507 'info_dict': {
508 'id': '1e5a878b-31c5-11e7-a442-0e40cf2fc285',
509 'ext': 'mp4',
510 'title': 'Teen Mom 2',
511 'description': 'md5:dc65e357ef7e1085ed53e9e9d83146a7',
512 },
513 'params': {
514 # rtmp download
515 'skip_download': True,
516 },
517 'skip': 'Blocked at Travis CI',
518 }, {
519 'url': 'http://www.mtv.de/news/glolix/77491-mtv-movies-spotlight--pixels--teil-3',
520 'info_dict': {
521 'id': 'local_playlist-4e760566473c4c8c5344',
522 'ext': 'mp4',
523 'title': 'Article_mtv-movies-spotlight-pixels-teil-3_short-clips_part1',
524 'description': 'MTV Movies Supercut',
525 },
526 'params': {
527 # rtmp download
528 'skip_download': True,
529 },
530 'skip': 'Das Video kann zur Zeit nicht abgespielt werden.',
531 }]
532 _GEO_COUNTRIES = ['DE']
533 _FEED_URL = 'http://feeds.mtvnservices.com/od/feed/intl-mrss-player-feed'
534
535 def _get_feed_query(self, uri):
536 return {
537 'arcEp': 'mtv.de',
538 'mgid': uri,
539 }