]> jfr.im git - yt-dlp.git/blame - youtube_dl/extractor/mtv.py
[YoutubeDL] Improve default format specification (closes #13704)
[yt-dlp.git] / youtube_dl / extractor / mtv.py
CommitLineData
32dac694
PH
1from __future__ import unicode_literals
2
fc287219 3import re
fc287219 4
0af25f78 5from .common import InfoExtractor
1cc79574 6from ..compat import (
e525d9a3 7 compat_str,
20a6a154 8 compat_xpath,
1cc79574
PH
9)
10from ..utils import (
fc287219 11 ExtractorError,
90834c78 12 find_xpath_attr,
5aafe895 13 fix_xml_ampersands,
8765151c 14 float_or_none,
0ef68e04 15 HEADRequest,
0c75abbb 16 RegexNotFoundError,
5c2266df 17 sanitized_Request,
7cdfc4c9 18 strip_or_none,
712c7530 19 timeconvert,
adf063da 20 try_get,
340b0468 21 unescapeHTML,
0c75abbb 22 update_url_query,
8d9453b9 23 url_basename,
5767b4ee 24 xpath_text,
fc287219
PH
25)
26
90834c78 27
300fcad8
JMF
28def _media_xml_tag(tag):
29 return '{http://search.yahoo.com/mrss/}%s' % tag
fc287219 30
f7e02595 31
0af25f78 32class MTVServicesInfoExtractor(InfoExtractor):
340b0468 33 _MOBILE_TEMPLATE = None
a542e372 34 _LANG = None
8940c1c0 35
f7e02595
JMF
36 @staticmethod
37 def _id_from_uri(uri):
38 return uri.split(':')[-1]
39
0c75abbb
YCH
40 @staticmethod
41 def _remove_template_parameter(url):
42 # Remove the templates, like &device={device}
43 return re.sub(r'&[^=]*?={.*?}(?=(&|$))', '', url)
44
8940c1c0
JMF
45 def _get_feed_url(self, uri):
46 return self._FEED_URL
47
ab2f744b 48 def _get_thumbnail_url(self, uri, itemdoc):
84db8181
JMF
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']
f7e02595 55
340b0468
JMF
56 def _extract_mobile_video_formats(self, mtvn_id):
57 webpage_url = self._MOBILE_TEMPLATE % mtvn_id
5c2266df 58 req = sanitized_Request(webpage_url)
340b0468 59 # Otherwise we get a webpage that would execute some javascript
3fcfb8e9 60 req.add_header('User-Agent', 'curl/7')
340b0468 61 webpage = self._download_webpage(req, mtvn_id,
9e1a5b84 62 'Downloading mobile page')
0ef68e04
JMF
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)
5f6a1245 69 return [{'url': url, 'ext': 'mp4'}]
340b0468 70
dbaf6016 71 def _extract_video_formats(self, mdoc, mtvn_id, video_id):
054d43bb 72 if re.match(r'.*/(error_country_block\.swf|geoblock\.mp4|copyright_error\.flv(?:\?geo\b.+?)?)$', mdoc.find('.//src').text) is not None:
340b0468 73 if mtvn_id is not None and self._MOBILE_TEMPLATE is not None:
0ef68e04 74 self.to_screen('The normal version is not available from your '
9e1a5b84 75 'country, trying with the mobile version')
340b0468 76 return self._extract_mobile_video_formats(mtvn_id)
cc1db7f9 77 raise ExtractorError('This video is not available from your country.',
9e1a5b84 78 expected=True)
f7e02595 79
f13d0933
PH
80 formats = []
81 for rendition in mdoc.findall('.//rendition'):
20faad74 82 if rendition.get('method') == 'hls':
dbaf6016 83 hls_url = rendition.find('./src').text
cdd11c05 84 formats.extend(self._extract_m3u8_formats(
adf063da
S
85 hls_url, video_id, ext='mp4', entry_protocol='m3u8_native',
86 m3u8_id='hls'))
dbaf6016
PH
87 else:
88 # fms
89 try:
90 _, _, ext = rendition.attrib['type'].partition('/')
91 rtmp_video_url = rendition.find('./src').text
adf063da
S
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)
dbaf6016
PH
96 if rtmp_video_url.endswith('siteunavail.png'):
97 continue
dbaf6016 98 formats.extend([{
adf063da
S
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')])),
dbaf6016
PH
104 'width': int(rendition.get('width')),
105 'height': int(rendition.get('height')),
adf063da 106 }])
dbaf6016
PH
107 except (KeyError, TypeError):
108 raise ExtractorError('Invalid rendition field.')
34d863f3 109 self._sort_formats(formats)
f13d0933 110 return formats
f7e02595 111
e525d9a3
S
112 def _extract_subtitles(self, mdoc, mtvn_id):
113 subtitles = {}
e525d9a3
S
114 for transcript in mdoc.findall('.//transcript'):
115 if transcript.get('kind') != 'captions':
116 continue
117 lang = transcript.get('srclang')
0af25f78
JMF
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
e525d9a3 123
67fc365b 124 def _get_video_info(self, itemdoc, use_hls=True):
f7e02595
JMF
125 uri = itemdoc.find('guid').text
126 video_id = self._id_from_uri(uri)
127 self.report_extraction(video_id)
04cbc498 128 content_el = itemdoc.find('%s/%s' % (_media_xml_tag('group'), _media_xml_tag('content')))
0c75abbb 129 mediagen_url = self._remove_template_parameter(content_el.attrib['url'])
dbaf6016 130 mediagen_url = mediagen_url.replace('device={device}', '')
f7e02595 131 if 'acceptMethods' not in mediagen_url:
56f447be 132 mediagen_url += '&' if '?' in mediagen_url else '?'
dbaf6016
PH
133 mediagen_url += 'acceptMethods='
134 mediagen_url += 'hls' if use_hls else 'fms'
6562df76 135
e4f320a4 136 mediagen_doc = self._download_xml(mediagen_url, video_id,
9e1a5b84 137 'Downloading video urls')
f7e02595 138
0dfe9bc9
S
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
7cdfc4c9 147 description = strip_or_none(xpath_text(itemdoc, 'description'))
f13d0933 148
712c7530
YCH
149 timestamp = timeconvert(xpath_text(itemdoc, 'pubDate'))
150
90834c78
PH
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')
90834c78 156 if title_el is None:
20a6a154 157 title_el = itemdoc.find(compat_xpath('.//{http://search.yahoo.com/mrss/}title'))
96cb10a5 158 if title_el is None:
20a6a154 159 title_el = itemdoc.find(compat_xpath('.//title'))
1df4229b
PH
160 if title_el.text is None:
161 title_el = None
1df4229b 162
90834c78
PH
163 title = title_el.text
164 if title is None:
165 raise ExtractorError('Could not find video title')
780ee4e5 166 title = title.strip()
90834c78 167
340b0468
JMF
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',
9e1a5b84 171 'scheme', 'urn:mtvn:id')
340b0468
JMF
172 if mtvn_id_node is not None:
173 mtvn_id = mtvn_id_node.text
174
dbaf6016
PH
175 formats = self._extract_video_formats(mediagen_doc, mtvn_id, video_id)
176
fb7abb31 177 return {
90834c78 178 'title': title,
dbaf6016 179 'formats': formats,
e525d9a3 180 'subtitles': self._extract_subtitles(mediagen_doc, mtvn_id),
f13d0933
PH
181 'id': video_id,
182 'thumbnail': self._get_thumbnail_url(uri, itemdoc),
183 'description': description,
04cbc498 184 'duration': float_or_none(content_el.attrib.get('duration')),
712c7530 185 'timestamp': timestamp,
f13d0933
PH
186 }
187
c1e90619 188 def _get_feed_query(self, uri):
189 data = {'uri': uri}
190 if self._LANG:
191 data['lang'] = self._LANG
0c75abbb 192 return data
c1e90619 193
67fc365b 194 def _get_videos_info(self, uri, use_hls=True):
f7e02595 195 video_id = self._id_from_uri(uri)
8940c1c0 196 feed_url = self._get_feed_url(uri)
0c75abbb 197 info_url = update_url_query(feed_url, self._get_feed_query(uri))
dbaf6016 198 return self._get_videos_info_from_url(info_url, video_id, use_hls)
79fa9db0 199
67fc365b 200 def _get_videos_info_from_url(self, url, video_id, use_hls=True):
e2b38da9 201 idoc = self._download_xml(
79fa9db0 202 url, video_id,
32dac694 203 'Downloading info', transform_source=fix_xml_ampersands)
712c7530
YCH
204
205 title = xpath_text(idoc, './channel/title')
206 description = xpath_text(idoc, './channel/description')
207
5239075b 208 return self.playlist_result(
dbaf6016 209 [self._get_video_info(item, use_hls) for item in idoc.findall('.//item')],
712c7530 210 playlist_title=title, playlist_description=description)
fc287219 211
adf063da
S
212 def _extract_triforce_mgid(self, webpage, data_zone=None, video_id=None):
213 triforce_feed = self._parse_json(self._search_regex(
f1e70fc2 214 r'triforceManifestFeed\s*=\s*({.+?})\s*;\s*\n', webpage,
adf063da
S
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):
8d9453b9 234 try:
4bbf139a
JMF
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]
8d9453b9 241 except RegexNotFoundError:
b1298d8e
AMW
242 mgid = None
243
244 if mgid is None or ':' not in mgid:
b9381e43
JMF
245 mgid = self._search_regex(
246 [r'data-mgid="(.*?)"', r'swfobject.embedSWF\(".*?(mgid:.*?)"'],
fc42bc6e
S
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(
adf063da
S
253 r'embed/(mgid:.+?)["\'&?/]', sm4_embed, 'mgid', default=None)
254
255 if not mgid:
256 mgid = self._extract_triforce_mgid(webpage)
257
c1e90619 258 return mgid
e525d9a3 259
c1e90619 260 def _real_extract(self, url):
261 title = url_basename(url)
262 webpage = self._download_webpage(url, title)
263 mgid = self._extract_mgid(webpage)
e525d9a3 264 videos_info = self._get_videos_info(mgid)
e525d9a3 265 return videos_info
8d9453b9 266
84db8181 267
8940c1c0
JMF
268class 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.',
712c7530
YCH
281 'timestamp': 1400126400,
282 'upload_date': '20140515',
8940c1c0
JMF
283 },
284 }
285
fe1d858e
S
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
8940c1c0
JMF
293 def _get_feed_url(self, uri):
294 video_id = self._id_from_uri(uri)
0c75abbb
YCH
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'])
8940c1c0
JMF
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
84db8181 305class MTVIE(MTVServicesInfoExtractor):
a54ffb8a 306 IE_NAME = 'mtv'
cf0cabbe 307 _VALID_URL = r'https?://(?:www\.)?mtv\.com/(?:video-clips|(?:full-)?episodes)/(?P<id>[^/?#.]+)'
8add4bfe
RA
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,
cf0cabbe
S
324 }, {
325 'url': 'http://www.mtv.com/episodes/g8xu7q/teen-mom-2-breaking-the-wall-season-7-ep-713',
326 'only_matching': True,
8add4bfe
RA
327 }]
328
329
008f2470
S
330class 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
8add4bfe 359class MTVVideoIE(MTVServicesInfoExtractor):
a54ffb8a 360 IE_NAME = 'mtv:video'
5c541b2c
JMF
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>[^&]+))'''
84db8181
JMF
364
365 _FEED_URL = 'http://www.mtv.com/player/embed/AS3/rss/'
366
367 _TESTS = [
368 {
32dac694 369 'url': 'http://www.mtv.com/videos/misc/853555/ours-vh1-storytellers.jhtml',
32dac694
PH
370 'md5': '850f3f143316b1e71fa56a4edfd6e0f8',
371 'info_dict': {
ca0f500e
PH
372 'id': '853555',
373 'ext': 'mp4',
32dac694
PH
374 'title': 'Taylor Swift - "Ours (VH1 Storytellers)"',
375 'description': 'Album: Taylor Swift performs "Ours" for VH1 Storytellers at Harvey Mudd College.',
712c7530
YCH
376 'timestamp': 1352610000,
377 'upload_date': '20121111',
84db8181
JMF
378 },
379 },
84db8181
JMF
380 ]
381
382 def _get_thumbnail_url(self, uri, itemdoc):
383 return 'http://mtv.mtvnimages.com/uri/' + uri
384
fc287219
PH
385 def _real_extract(self, url):
386 mobj = re.match(self._VALID_URL, url)
fc287219 387 video_id = mobj.group('videoid')
c801b205 388 uri = mobj.groupdict().get('mgid')
5c541b2c
JMF
389 if uri is None:
390 webpage = self._download_webpage(url, video_id)
5f6a1245 391
5c541b2c 392 # Some videos come from Vevo.com
ca0f500e
PH
393 m_vevo = re.search(
394 r'(?s)isVevoVideo = true;.*?vevoVideoId = "(.*?)";', webpage)
5c541b2c 395 if m_vevo:
8bcc8756 396 vevo_id = m_vevo.group(1)
32dac694 397 self.to_screen('Vevo video detected: %s' % vevo_id)
5c541b2c 398 return self.url_result('vevo:%s' % vevo_id, ie='Vevo')
5f6a1245 399
32dac694 400 uri = self._html_search_regex(r'/uri/(.*?)\?', webpage, 'uri')
f7e02595 401 return self._get_videos_info(uri)
bc4ba05f
JMF
402
403
071c1013
PH
404class MTVDEIE(MTVServicesInfoExtractor):
405 IE_NAME = 'mtv.de'
65488b82 406 _VALID_URL = r'https?://(?:www\.)?mtv\.de/(?:artists|shows|news)/(?:[^/]+/)*(?P<id>\d+)-[^/#?]+/*(?:[#?].*)?$'
79fa9db0
S
407 _TESTS = [{
408 'url': 'http://www.mtv.de/artists/10571-cro/videos/61131-traum',
409 'info_dict': {
410 'id': 'music_video-a50bc5f0b3aa4b3190aa',
712c7530 411 'ext': 'flv',
79fa9db0
S
412 'title': 'MusicVideo_cro-traum',
413 'description': 'Cro - Traum',
071c1013 414 },
79fa9db0
S
415 'params': {
416 # rtmp download
417 'skip_download': True,
418 },
35f6e0ff 419 'skip': 'Blocked at Travis CI',
c3c9f879
S
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',
712c7530 425 'ext': 'flv',
c3c9f879
S
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 },
35f6e0ff 432 'skip': 'Blocked at Travis CI',
65488b82 433 }, {
65488b82
S
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 },
712c7530 445 'skip': 'Das Video kann zur Zeit nicht abgespielt werden.',
79fa9db0 446 }]
071c1013
PH
447
448 def _real_extract(self, url):
79fa9db0
S
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)
071c1013 457
712c7530
YCH
458 def _mrss_url(item):
459 return item['mrss'] + item.get('mrssvars', '')
460
65488b82
S
461 # news pages contain single video in playlist with different id
462 if len(playlist) == 1:
712c7530 463 return self._get_videos_info_from_url(_mrss_url(playlist[0]), video_id)
65488b82 464
071c1013 465 for item in playlist:
79fa9db0
S
466 item_id = item.get('id')
467 if item_id and compat_str(item_id) == video_id:
712c7530 468 return self._get_videos_info_from_url(_mrss_url(item), video_id)