]> jfr.im git - yt-dlp.git/blob - youtube_dl/extractor/mtv.py
[mtv,cc] Use hls by default (closes #11641)
[yt-dlp.git] / 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 NO_DEFAULT,
17 RegexNotFoundError,
18 sanitized_Request,
19 strip_or_none,
20 timeconvert,
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 # This was originally implemented for ComedyCentral, but it also works here
46 @classmethod
47 def _transform_rtmp_url(cls, rtmp_video_url):
48 m = re.match(r'^rtmpe?://.*?/(?P<finalid>gsp\..+?/.*)$', rtmp_video_url)
49 if not m:
50 return {'rtmp': rtmp_video_url}
51 base = 'http://viacommtvstrmfs.fplive.net/'
52 return {'http': base + m.group('finalid')}
53
54 def _get_feed_url(self, uri):
55 return self._FEED_URL
56
57 def _get_thumbnail_url(self, uri, itemdoc):
58 search_path = '%s/%s' % (_media_xml_tag('group'), _media_xml_tag('thumbnail'))
59 thumb_node = itemdoc.find(search_path)
60 if thumb_node is None:
61 return None
62 else:
63 return thumb_node.attrib['url']
64
65 def _extract_mobile_video_formats(self, mtvn_id):
66 webpage_url = self._MOBILE_TEMPLATE % mtvn_id
67 req = sanitized_Request(webpage_url)
68 # Otherwise we get a webpage that would execute some javascript
69 req.add_header('User-Agent', 'curl/7')
70 webpage = self._download_webpage(req, mtvn_id,
71 'Downloading mobile page')
72 metrics_url = unescapeHTML(self._search_regex(r'<a href="(http://metrics.+?)"', webpage, 'url'))
73 req = HEADRequest(metrics_url)
74 response = self._request_webpage(req, mtvn_id, 'Resolving url')
75 url = response.geturl()
76 # Transform the url to get the best quality:
77 url = re.sub(r'.+pxE=mp4', 'http://mtvnmobile.vo.llnwd.net/kip0/_pxn=0+_pxK=18639+_pxE=mp4', url, 1)
78 return [{'url': url, 'ext': 'mp4'}]
79
80 def _extract_video_formats(self, mdoc, mtvn_id, video_id):
81 if re.match(r'.*/(error_country_block\.swf|geoblock\.mp4|copyright_error\.flv(?:\?geo\b.+?)?)$', mdoc.find('.//src').text) is not None:
82 if mtvn_id is not None and self._MOBILE_TEMPLATE is not None:
83 self.to_screen('The normal version is not available from your '
84 'country, trying with the mobile version')
85 return self._extract_mobile_video_formats(mtvn_id)
86 raise ExtractorError('This video is not available from your country.',
87 expected=True)
88
89 formats = []
90 for rendition in mdoc.findall('.//rendition'):
91 if rendition.get('method') == 'hls':
92 hls_url = rendition.find('./src').text
93 formats.extend(self._extract_m3u8_formats(hls_url, video_id, ext='mp4'))
94 else:
95 # fms
96 try:
97 _, _, ext = rendition.attrib['type'].partition('/')
98 rtmp_video_url = rendition.find('./src').text
99 if rtmp_video_url.endswith('siteunavail.png'):
100 continue
101 new_urls = self._transform_rtmp_url(rtmp_video_url)
102 formats.extend([{
103 'ext': 'flv' if new_url.startswith('rtmp') else ext,
104 'url': new_url,
105 'format_id': '-'.join(filter(None, [kind, rendition.get('bitrate')])),
106 'width': int(rendition.get('width')),
107 'height': int(rendition.get('height')),
108 } for kind, new_url in new_urls.items()])
109 except (KeyError, TypeError):
110 raise ExtractorError('Invalid rendition field.')
111 self._sort_formats(formats)
112 return formats
113
114 def _extract_subtitles(self, mdoc, mtvn_id):
115 subtitles = {}
116 for transcript in mdoc.findall('.//transcript'):
117 if transcript.get('kind') != 'captions':
118 continue
119 lang = transcript.get('srclang')
120 subtitles[lang] = [{
121 'url': compat_str(typographic.get('src')),
122 'ext': typographic.get('format')
123 } for typographic in transcript.findall('./typographic')]
124 return subtitles
125
126 def _get_video_info(self, itemdoc, use_hls=True):
127 uri = itemdoc.find('guid').text
128 video_id = self._id_from_uri(uri)
129 self.report_extraction(video_id)
130 content_el = itemdoc.find('%s/%s' % (_media_xml_tag('group'), _media_xml_tag('content')))
131 mediagen_url = self._remove_template_parameter(content_el.attrib['url'])
132 mediagen_url = mediagen_url.replace('device={device}', '')
133 if 'acceptMethods' not in mediagen_url:
134 mediagen_url += '&' if '?' in mediagen_url else '?'
135 mediagen_url += 'acceptMethods='
136 mediagen_url += 'hls' if use_hls else 'fms'
137
138 mediagen_doc = self._download_xml(mediagen_url, video_id,
139 'Downloading video urls')
140
141 item = mediagen_doc.find('./video/item')
142 if item is not None and item.get('type') == 'text':
143 message = '%s returned error: ' % self.IE_NAME
144 if item.get('code') is not None:
145 message += '%s - ' % item.get('code')
146 message += item.text
147 raise ExtractorError(message, expected=True)
148
149 description = strip_or_none(xpath_text(itemdoc, 'description'))
150
151 timestamp = timeconvert(xpath_text(itemdoc, 'pubDate'))
152
153 title_el = None
154 if title_el is None:
155 title_el = find_xpath_attr(
156 itemdoc, './/{http://search.yahoo.com/mrss/}category',
157 'scheme', 'urn:mtvn:video_title')
158 if title_el is None:
159 title_el = itemdoc.find(compat_xpath('.//{http://search.yahoo.com/mrss/}title'))
160 if title_el is None:
161 title_el = itemdoc.find(compat_xpath('.//title'))
162 if title_el.text is None:
163 title_el = None
164
165 title = title_el.text
166 if title is None:
167 raise ExtractorError('Could not find video title')
168 title = title.strip()
169
170 # This a short id that's used in the webpage urls
171 mtvn_id = None
172 mtvn_id_node = find_xpath_attr(itemdoc, './/{http://search.yahoo.com/mrss/}category',
173 'scheme', 'urn:mtvn:id')
174 if mtvn_id_node is not None:
175 mtvn_id = mtvn_id_node.text
176
177 formats = self._extract_video_formats(mediagen_doc, mtvn_id, video_id)
178
179 return {
180 'title': title,
181 'formats': formats,
182 'subtitles': self._extract_subtitles(mediagen_doc, mtvn_id),
183 'id': video_id,
184 'thumbnail': self._get_thumbnail_url(uri, itemdoc),
185 'description': description,
186 'duration': float_or_none(content_el.attrib.get('duration')),
187 'timestamp': timestamp,
188 }
189
190 def _get_feed_query(self, uri):
191 data = {'uri': uri}
192 if self._LANG:
193 data['lang'] = self._LANG
194 return data
195
196 def _get_videos_info(self, uri, use_hls=True):
197 video_id = self._id_from_uri(uri)
198 feed_url = self._get_feed_url(uri)
199 info_url = update_url_query(feed_url, self._get_feed_query(uri))
200 return self._get_videos_info_from_url(info_url, video_id, use_hls)
201
202 def _get_videos_info_from_url(self, url, video_id, use_hls=True):
203 idoc = self._download_xml(
204 url, video_id,
205 'Downloading info', transform_source=fix_xml_ampersands)
206
207 title = xpath_text(idoc, './channel/title')
208 description = xpath_text(idoc, './channel/description')
209
210 return self.playlist_result(
211 [self._get_video_info(item, use_hls) for item in idoc.findall('.//item')],
212 playlist_title=title, playlist_description=description)
213
214 def _extract_mgid(self, webpage, default=NO_DEFAULT):
215 try:
216 # the url can be http://media.mtvnservices.com/fb/{mgid}.swf
217 # or http://media.mtvnservices.com/{mgid}
218 og_url = self._og_search_video_url(webpage)
219 mgid = url_basename(og_url)
220 if mgid.endswith('.swf'):
221 mgid = mgid[:-4]
222 except RegexNotFoundError:
223 mgid = None
224
225 if mgid is None or ':' not in mgid:
226 mgid = self._search_regex(
227 [r'data-mgid="(.*?)"', r'swfobject.embedSWF\(".*?(mgid:.*?)"'],
228 webpage, 'mgid', default=None)
229
230 if not mgid:
231 sm4_embed = self._html_search_meta(
232 'sm4:video:embed', webpage, 'sm4 embed', default='')
233 mgid = self._search_regex(
234 r'embed/(mgid:.+?)["\'&?/]', sm4_embed, 'mgid', default=default)
235 return mgid
236
237 def _real_extract(self, url):
238 title = url_basename(url)
239 webpage = self._download_webpage(url, title)
240 mgid = self._extract_mgid(webpage)
241 videos_info = self._get_videos_info(mgid)
242 return videos_info
243
244
245 class MTVServicesEmbeddedIE(MTVServicesInfoExtractor):
246 IE_NAME = 'mtvservices:embedded'
247 _VALID_URL = r'https?://media\.mtvnservices\.com/embed/(?P<mgid>.+?)(\?|/|$)'
248
249 _TEST = {
250 # From http://www.thewrap.com/peter-dinklage-sums-up-game-of-thrones-in-45-seconds-video/
251 'url': 'http://media.mtvnservices.com/embed/mgid:uma:video:mtv.com:1043906/cp~vid%3D1043906%26uri%3Dmgid%3Auma%3Avideo%3Amtv.com%3A1043906',
252 'md5': 'cb349b21a7897164cede95bd7bf3fbb9',
253 'info_dict': {
254 'id': '1043906',
255 'ext': 'mp4',
256 'title': 'Peter Dinklage Sums Up \'Game Of Thrones\' In 45 Seconds',
257 'description': '"Sexy sexy sexy, stabby stabby stabby, beautiful language," says Peter Dinklage as he tries summarizing "Game of Thrones" in under a minute.',
258 'timestamp': 1400126400,
259 'upload_date': '20140515',
260 },
261 }
262
263 @staticmethod
264 def _extract_url(webpage):
265 mobj = re.search(
266 r'<iframe[^>]+?src=(["\'])(?P<url>(?:https?:)?//media.mtvnservices.com/embed/.+?)\1', webpage)
267 if mobj:
268 return mobj.group('url')
269
270 def _get_feed_url(self, uri):
271 video_id = self._id_from_uri(uri)
272 config = self._download_json(
273 'http://media.mtvnservices.com/pmt/e1/access/index.html?uri=%s&configtype=edge' % uri, video_id)
274 return self._remove_template_parameter(config['feedWithQueryParams'])
275
276 def _real_extract(self, url):
277 mobj = re.match(self._VALID_URL, url)
278 mgid = mobj.group('mgid')
279 return self._get_videos_info(mgid)
280
281
282 class MTVIE(MTVServicesInfoExtractor):
283 IE_NAME = 'mtv'
284 _VALID_URL = r'https?://(?:www\.)?mtv\.com/(?:video-clips|full-episodes)/(?P<id>[^/?#.]+)'
285 _FEED_URL = 'http://www.mtv.com/feeds/mrss/'
286
287 _TESTS = [{
288 'url': 'http://www.mtv.com/video-clips/vl8qof/unlocking-the-truth-trailer',
289 'md5': '1edbcdf1e7628e414a8c5dcebca3d32b',
290 'info_dict': {
291 'id': '5e14040d-18a4-47c4-a582-43ff602de88e',
292 'ext': 'mp4',
293 'title': 'Unlocking The Truth|July 18, 2016|1|101|Trailer',
294 'description': '"Unlocking the Truth" premieres August 17th at 11/10c.',
295 'timestamp': 1468846800,
296 'upload_date': '20160718',
297 },
298 }, {
299 'url': 'http://www.mtv.com/full-episodes/94tujl/unlocking-the-truth-gates-of-hell-season-1-ep-101',
300 'only_matching': True,
301 }]
302
303
304 class MTVVideoIE(MTVServicesInfoExtractor):
305 IE_NAME = 'mtv:video'
306 _VALID_URL = r'''(?x)^https?://
307 (?:(?:www\.)?mtv\.com/videos/.+?/(?P<videoid>[0-9]+)/[^/]+$|
308 m\.mtv\.com/videos/video\.rbml\?.*?id=(?P<mgid>[^&]+))'''
309
310 _FEED_URL = 'http://www.mtv.com/player/embed/AS3/rss/'
311
312 _TESTS = [
313 {
314 'url': 'http://www.mtv.com/videos/misc/853555/ours-vh1-storytellers.jhtml',
315 'md5': '850f3f143316b1e71fa56a4edfd6e0f8',
316 'info_dict': {
317 'id': '853555',
318 'ext': 'mp4',
319 'title': 'Taylor Swift - "Ours (VH1 Storytellers)"',
320 'description': 'Album: Taylor Swift performs "Ours" for VH1 Storytellers at Harvey Mudd College.',
321 'timestamp': 1352610000,
322 'upload_date': '20121111',
323 },
324 },
325 ]
326
327 def _get_thumbnail_url(self, uri, itemdoc):
328 return 'http://mtv.mtvnimages.com/uri/' + uri
329
330 def _real_extract(self, url):
331 mobj = re.match(self._VALID_URL, url)
332 video_id = mobj.group('videoid')
333 uri = mobj.groupdict().get('mgid')
334 if uri is None:
335 webpage = self._download_webpage(url, video_id)
336
337 # Some videos come from Vevo.com
338 m_vevo = re.search(
339 r'(?s)isVevoVideo = true;.*?vevoVideoId = "(.*?)";', webpage)
340 if m_vevo:
341 vevo_id = m_vevo.group(1)
342 self.to_screen('Vevo video detected: %s' % vevo_id)
343 return self.url_result('vevo:%s' % vevo_id, ie='Vevo')
344
345 uri = self._html_search_regex(r'/uri/(.*?)\?', webpage, 'uri')
346 return self._get_videos_info(uri)
347
348
349 class MTVDEIE(MTVServicesInfoExtractor):
350 IE_NAME = 'mtv.de'
351 _VALID_URL = r'https?://(?:www\.)?mtv\.de/(?:artists|shows|news)/(?:[^/]+/)*(?P<id>\d+)-[^/#?]+/*(?:[#?].*)?$'
352 _TESTS = [{
353 'url': 'http://www.mtv.de/artists/10571-cro/videos/61131-traum',
354 'info_dict': {
355 'id': 'music_video-a50bc5f0b3aa4b3190aa',
356 'ext': 'flv',
357 'title': 'MusicVideo_cro-traum',
358 'description': 'Cro - Traum',
359 },
360 'params': {
361 # rtmp download
362 'skip_download': True,
363 },
364 'skip': 'Blocked at Travis CI',
365 }, {
366 # mediagen URL without query (e.g. http://videos.mtvnn.com/mediagen/e865da714c166d18d6f80893195fcb97)
367 'url': 'http://www.mtv.de/shows/933-teen-mom-2/staffeln/5353/folgen/63565-enthullungen',
368 'info_dict': {
369 'id': 'local_playlist-f5ae778b9832cc837189',
370 'ext': 'flv',
371 'title': 'Episode_teen-mom-2_shows_season-5_episode-1_full-episode_part1',
372 },
373 'params': {
374 # rtmp download
375 'skip_download': True,
376 },
377 'skip': 'Blocked at Travis CI',
378 }, {
379 'url': 'http://www.mtv.de/news/77491-mtv-movies-spotlight-pixels-teil-3',
380 'info_dict': {
381 'id': 'local_playlist-4e760566473c4c8c5344',
382 'ext': 'mp4',
383 'title': 'Article_mtv-movies-spotlight-pixels-teil-3_short-clips_part1',
384 'description': 'MTV Movies Supercut',
385 },
386 'params': {
387 # rtmp download
388 'skip_download': True,
389 },
390 'skip': 'Das Video kann zur Zeit nicht abgespielt werden.',
391 }]
392
393 def _real_extract(self, url):
394 video_id = self._match_id(url)
395
396 webpage = self._download_webpage(url, video_id)
397
398 playlist = self._parse_json(
399 self._search_regex(
400 r'window\.pagePlaylist\s*=\s*(\[.+?\]);\n', webpage, 'page playlist'),
401 video_id)
402
403 def _mrss_url(item):
404 return item['mrss'] + item.get('mrssvars', '')
405
406 # news pages contain single video in playlist with different id
407 if len(playlist) == 1:
408 return self._get_videos_info_from_url(_mrss_url(playlist[0]), video_id)
409
410 for item in playlist:
411 item_id = item.get('id')
412 if item_id and compat_str(item_id) == video_id:
413 return self._get_videos_info_from_url(_mrss_url(item), video_id)