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