]> jfr.im git - yt-dlp.git/blame - youtube_dl/extractor/mtv.py
[generic] Skip an invalid test
[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 (
15707c7e 7 compat_urllib_parse_urlencode,
e525d9a3 8 compat_str,
20a6a154 9 compat_xpath,
1cc79574
PH
10)
11from ..utils import (
fc287219 12 ExtractorError,
90834c78 13 find_xpath_attr,
5aafe895 14 fix_xml_ampersands,
8765151c 15 float_or_none,
0ef68e04 16 HEADRequest,
5c2266df 17 sanitized_Request,
7cdfc4c9 18 strip_or_none,
712c7530 19 timeconvert,
340b0468 20 unescapeHTML,
8d9453b9
JMF
21 url_basename,
22 RegexNotFoundError,
5767b4ee 23 xpath_text,
fc287219
PH
24)
25
90834c78 26
300fcad8
JMF
27def _media_xml_tag(tag):
28 return '{http://search.yahoo.com/mrss/}%s' % tag
fc287219 29
f7e02595 30
0af25f78 31class MTVServicesInfoExtractor(InfoExtractor):
340b0468 32 _MOBILE_TEMPLATE = None
a542e372 33 _LANG = None
8940c1c0 34
f7e02595
JMF
35 @staticmethod
36 def _id_from_uri(uri):
37 return uri.split(':')[-1]
38
39 # This was originally implemented for ComedyCentral, but it also works here
712c7530
YCH
40 @classmethod
41 def _transform_rtmp_url(cls, rtmp_video_url):
f7e02595
JMF
42 m = re.match(r'^rtmpe?://.*?/(?P<finalid>gsp\..+?/.*)$', rtmp_video_url)
43 if not m:
712c7530 44 return {'rtmp': rtmp_video_url}
2774852c 45 base = 'http://viacommtvstrmfs.fplive.net/'
712c7530 46 return {'http': base + m.group('finalid')}
ab2f744b 47
8940c1c0
JMF
48 def _get_feed_url(self, uri):
49 return self._FEED_URL
50
ab2f744b 51 def _get_thumbnail_url(self, uri, itemdoc):
84db8181
JMF
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 else:
57 return thumb_node.attrib['url']
f7e02595 58
340b0468
JMF
59 def _extract_mobile_video_formats(self, mtvn_id):
60 webpage_url = self._MOBILE_TEMPLATE % mtvn_id
5c2266df 61 req = sanitized_Request(webpage_url)
340b0468 62 # Otherwise we get a webpage that would execute some javascript
3fcfb8e9 63 req.add_header('User-Agent', 'curl/7')
340b0468 64 webpage = self._download_webpage(req, mtvn_id,
9e1a5b84 65 'Downloading mobile page')
0ef68e04
JMF
66 metrics_url = unescapeHTML(self._search_regex(r'<a href="(http://metrics.+?)"', webpage, 'url'))
67 req = HEADRequest(metrics_url)
68 response = self._request_webpage(req, mtvn_id, 'Resolving url')
69 url = response.geturl()
70 # Transform the url to get the best quality:
71 url = re.sub(r'.+pxE=mp4', 'http://mtvnmobile.vo.llnwd.net/kip0/_pxn=0+_pxK=18639+_pxE=mp4', url, 1)
5f6a1245 72 return [{'url': url, 'ext': 'mp4'}]
340b0468
JMF
73
74 def _extract_video_formats(self, mdoc, mtvn_id):
054d43bb 75 if re.match(r'.*/(error_country_block\.swf|geoblock\.mp4|copyright_error\.flv(?:\?geo\b.+?)?)$', mdoc.find('.//src').text) is not None:
340b0468 76 if mtvn_id is not None and self._MOBILE_TEMPLATE is not None:
0ef68e04 77 self.to_screen('The normal version is not available from your '
9e1a5b84 78 'country, trying with the mobile version')
340b0468 79 return self._extract_mobile_video_formats(mtvn_id)
cc1db7f9 80 raise ExtractorError('This video is not available from your country.',
9e1a5b84 81 expected=True)
f7e02595 82
f13d0933
PH
83 formats = []
84 for rendition in mdoc.findall('.//rendition'):
85 try:
86 _, _, ext = rendition.attrib['type'].partition('/')
87 rtmp_video_url = rendition.find('./src').text
ca0f500e
PH
88 if rtmp_video_url.endswith('siteunavail.png'):
89 continue
712c7530
YCH
90 new_urls = self._transform_rtmp_url(rtmp_video_url)
91 formats.extend([{
a72df5f3
YCH
92 'ext': 'flv' if new_url.startswith('rtmp') else ext,
93 'url': new_url,
10a1bb3a 94 'format_id': '-'.join(filter(None, [kind, rendition.get('bitrate')])),
ca0f500e
PH
95 'width': int(rendition.get('width')),
96 'height': int(rendition.get('height')),
712c7530 97 } for kind, new_url in new_urls.items()])
f13d0933
PH
98 except (KeyError, TypeError):
99 raise ExtractorError('Invalid rendition field.')
34d863f3 100 self._sort_formats(formats)
f13d0933 101 return formats
f7e02595 102
e525d9a3
S
103 def _extract_subtitles(self, mdoc, mtvn_id):
104 subtitles = {}
e525d9a3
S
105 for transcript in mdoc.findall('.//transcript'):
106 if transcript.get('kind') != 'captions':
107 continue
108 lang = transcript.get('srclang')
0af25f78
JMF
109 subtitles[lang] = [{
110 'url': compat_str(typographic.get('src')),
111 'ext': typographic.get('format')
112 } for typographic in transcript.findall('./typographic')]
113 return subtitles
e525d9a3 114
f7e02595
JMF
115 def _get_video_info(self, itemdoc):
116 uri = itemdoc.find('guid').text
117 video_id = self._id_from_uri(uri)
118 self.report_extraction(video_id)
04cbc498 119 content_el = itemdoc.find('%s/%s' % (_media_xml_tag('group'), _media_xml_tag('content')))
120 mediagen_url = content_el.attrib['url']
321a01f9 121 # Remove the templates, like &device={device}
32dac694 122 mediagen_url = re.sub(r'&[^=]*?={.*?}(?=(&|$))', '', mediagen_url)
f7e02595 123 if 'acceptMethods' not in mediagen_url:
56f447be
S
124 mediagen_url += '&' if '?' in mediagen_url else '?'
125 mediagen_url += 'acceptMethods=fms'
6562df76 126
e4f320a4 127 mediagen_doc = self._download_xml(mediagen_url, video_id,
9e1a5b84 128 'Downloading video urls')
f7e02595 129
0dfe9bc9
S
130 item = mediagen_doc.find('./video/item')
131 if item is not None and item.get('type') == 'text':
132 message = '%s returned error: ' % self.IE_NAME
133 if item.get('code') is not None:
134 message += '%s - ' % item.get('code')
135 message += item.text
136 raise ExtractorError(message, expected=True)
137
7cdfc4c9 138 description = strip_or_none(xpath_text(itemdoc, 'description'))
f13d0933 139
712c7530
YCH
140 timestamp = timeconvert(xpath_text(itemdoc, 'pubDate'))
141
90834c78
PH
142 title_el = None
143 if title_el is None:
144 title_el = find_xpath_attr(
145 itemdoc, './/{http://search.yahoo.com/mrss/}category',
146 'scheme', 'urn:mtvn:video_title')
90834c78 147 if title_el is None:
20a6a154 148 title_el = itemdoc.find(compat_xpath('.//{http://search.yahoo.com/mrss/}title'))
96cb10a5 149 if title_el is None:
20a6a154 150 title_el = itemdoc.find(compat_xpath('.//title'))
1df4229b
PH
151 if title_el.text is None:
152 title_el = None
1df4229b 153
90834c78
PH
154 title = title_el.text
155 if title is None:
156 raise ExtractorError('Could not find video title')
780ee4e5 157 title = title.strip()
90834c78 158
340b0468
JMF
159 # This a short id that's used in the webpage urls
160 mtvn_id = None
161 mtvn_id_node = find_xpath_attr(itemdoc, './/{http://search.yahoo.com/mrss/}category',
9e1a5b84 162 'scheme', 'urn:mtvn:id')
340b0468
JMF
163 if mtvn_id_node is not None:
164 mtvn_id = mtvn_id_node.text
165
fb7abb31 166 return {
90834c78 167 'title': title,
340b0468 168 'formats': self._extract_video_formats(mediagen_doc, mtvn_id),
e525d9a3 169 'subtitles': self._extract_subtitles(mediagen_doc, mtvn_id),
f13d0933
PH
170 'id': video_id,
171 'thumbnail': self._get_thumbnail_url(uri, itemdoc),
172 'description': description,
04cbc498 173 'duration': float_or_none(content_el.attrib.get('duration')),
712c7530 174 'timestamp': timestamp,
f13d0933
PH
175 }
176
c1e90619 177 def _get_feed_query(self, uri):
178 data = {'uri': uri}
179 if self._LANG:
180 data['lang'] = self._LANG
15707c7e 181 return compat_urllib_parse_urlencode(data)
c1e90619 182
f7e02595
JMF
183 def _get_videos_info(self, uri):
184 video_id = self._id_from_uri(uri)
8940c1c0 185 feed_url = self._get_feed_url(uri)
c1e90619 186 info_url = feed_url + '?' + self._get_feed_query(uri)
79fa9db0
S
187 return self._get_videos_info_from_url(info_url, video_id)
188
189 def _get_videos_info_from_url(self, url, video_id):
e2b38da9 190 idoc = self._download_xml(
79fa9db0 191 url, video_id,
32dac694 192 'Downloading info', transform_source=fix_xml_ampersands)
712c7530
YCH
193
194 title = xpath_text(idoc, './channel/title')
195 description = xpath_text(idoc, './channel/description')
196
5239075b 197 return self.playlist_result(
712c7530
YCH
198 [self._get_video_info(item) for item in idoc.findall('.//item')],
199 playlist_title=title, playlist_description=description)
fc287219 200
c1e90619 201 def _extract_mgid(self, webpage):
8d9453b9 202 try:
4bbf139a
JMF
203 # the url can be http://media.mtvnservices.com/fb/{mgid}.swf
204 # or http://media.mtvnservices.com/{mgid}
205 og_url = self._og_search_video_url(webpage)
206 mgid = url_basename(og_url)
207 if mgid.endswith('.swf'):
208 mgid = mgid[:-4]
8d9453b9 209 except RegexNotFoundError:
b1298d8e
AMW
210 mgid = None
211
212 if mgid is None or ':' not in mgid:
b9381e43
JMF
213 mgid = self._search_regex(
214 [r'data-mgid="(.*?)"', r'swfobject.embedSWF\(".*?(mgid:.*?)"'],
fc42bc6e
S
215 webpage, 'mgid', default=None)
216
217 if not mgid:
218 sm4_embed = self._html_search_meta(
219 'sm4:video:embed', webpage, 'sm4 embed', default='')
220 mgid = self._search_regex(
221 r'embed/(mgid:.+?)["\'&?/]', sm4_embed, 'mgid')
c1e90619 222 return mgid
e525d9a3 223
c1e90619 224 def _real_extract(self, url):
225 title = url_basename(url)
226 webpage = self._download_webpage(url, title)
227 mgid = self._extract_mgid(webpage)
e525d9a3 228 videos_info = self._get_videos_info(mgid)
e525d9a3 229 return videos_info
8d9453b9 230
84db8181 231
8940c1c0
JMF
232class MTVServicesEmbeddedIE(MTVServicesInfoExtractor):
233 IE_NAME = 'mtvservices:embedded'
234 _VALID_URL = r'https?://media\.mtvnservices\.com/embed/(?P<mgid>.+?)(\?|/|$)'
235
236 _TEST = {
237 # From http://www.thewrap.com/peter-dinklage-sums-up-game-of-thrones-in-45-seconds-video/
238 'url': 'http://media.mtvnservices.com/embed/mgid:uma:video:mtv.com:1043906/cp~vid%3D1043906%26uri%3Dmgid%3Auma%3Avideo%3Amtv.com%3A1043906',
239 'md5': 'cb349b21a7897164cede95bd7bf3fbb9',
240 'info_dict': {
241 'id': '1043906',
242 'ext': 'mp4',
243 'title': 'Peter Dinklage Sums Up \'Game Of Thrones\' In 45 Seconds',
244 '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
245 'timestamp': 1400126400,
246 'upload_date': '20140515',
8940c1c0
JMF
247 },
248 }
249
fe1d858e
S
250 @staticmethod
251 def _extract_url(webpage):
252 mobj = re.search(
253 r'<iframe[^>]+?src=(["\'])(?P<url>(?:https?:)?//media.mtvnservices.com/embed/.+?)\1', webpage)
254 if mobj:
255 return mobj.group('url')
256
8940c1c0
JMF
257 def _get_feed_url(self, uri):
258 video_id = self._id_from_uri(uri)
259 site_id = uri.replace(video_id, '')
71f8c7ce 260 config_url = ('http://media.mtvnservices.com/pmt/e1/players/{0}/'
9e1a5b84 261 'context4/context5/config.xml'.format(site_id))
8940c1c0
JMF
262 config_doc = self._download_xml(config_url, video_id)
263 feed_node = config_doc.find('.//feed')
264 feed_url = feed_node.text.strip().split('?')[0]
265 return feed_url
266
267 def _real_extract(self, url):
268 mobj = re.match(self._VALID_URL, url)
269 mgid = mobj.group('mgid')
270 return self._get_videos_info(mgid)
271
272
84db8181 273class MTVIE(MTVServicesInfoExtractor):
5c541b2c
JMF
274 _VALID_URL = r'''(?x)^https?://
275 (?:(?:www\.)?mtv\.com/videos/.+?/(?P<videoid>[0-9]+)/[^/]+$|
276 m\.mtv\.com/videos/video\.rbml\?.*?id=(?P<mgid>[^&]+))'''
84db8181
JMF
277
278 _FEED_URL = 'http://www.mtv.com/player/embed/AS3/rss/'
279
280 _TESTS = [
281 {
32dac694 282 'url': 'http://www.mtv.com/videos/misc/853555/ours-vh1-storytellers.jhtml',
32dac694
PH
283 'md5': '850f3f143316b1e71fa56a4edfd6e0f8',
284 'info_dict': {
ca0f500e
PH
285 'id': '853555',
286 'ext': 'mp4',
32dac694
PH
287 'title': 'Taylor Swift - "Ours (VH1 Storytellers)"',
288 'description': 'Album: Taylor Swift performs "Ours" for VH1 Storytellers at Harvey Mudd College.',
712c7530
YCH
289 'timestamp': 1352610000,
290 'upload_date': '20121111',
84db8181
JMF
291 },
292 },
84db8181
JMF
293 ]
294
295 def _get_thumbnail_url(self, uri, itemdoc):
296 return 'http://mtv.mtvnimages.com/uri/' + uri
297
fc287219
PH
298 def _real_extract(self, url):
299 mobj = re.match(self._VALID_URL, url)
fc287219 300 video_id = mobj.group('videoid')
c801b205 301 uri = mobj.groupdict().get('mgid')
5c541b2c
JMF
302 if uri is None:
303 webpage = self._download_webpage(url, video_id)
5f6a1245 304
5c541b2c 305 # Some videos come from Vevo.com
ca0f500e
PH
306 m_vevo = re.search(
307 r'(?s)isVevoVideo = true;.*?vevoVideoId = "(.*?)";', webpage)
5c541b2c 308 if m_vevo:
8bcc8756 309 vevo_id = m_vevo.group(1)
32dac694 310 self.to_screen('Vevo video detected: %s' % vevo_id)
5c541b2c 311 return self.url_result('vevo:%s' % vevo_id, ie='Vevo')
5f6a1245 312
32dac694 313 uri = self._html_search_regex(r'/uri/(.*?)\?', webpage, 'uri')
f7e02595 314 return self._get_videos_info(uri)
bc4ba05f
JMF
315
316
071c1013
PH
317class MTVDEIE(MTVServicesInfoExtractor):
318 IE_NAME = 'mtv.de'
65488b82 319 _VALID_URL = r'https?://(?:www\.)?mtv\.de/(?:artists|shows|news)/(?:[^/]+/)*(?P<id>\d+)-[^/#?]+/*(?:[#?].*)?$'
79fa9db0
S
320 _TESTS = [{
321 'url': 'http://www.mtv.de/artists/10571-cro/videos/61131-traum',
322 'info_dict': {
323 'id': 'music_video-a50bc5f0b3aa4b3190aa',
712c7530 324 'ext': 'flv',
79fa9db0
S
325 'title': 'MusicVideo_cro-traum',
326 'description': 'Cro - Traum',
071c1013 327 },
79fa9db0
S
328 'params': {
329 # rtmp download
330 'skip_download': True,
331 },
c3c9f879
S
332 }, {
333 # mediagen URL without query (e.g. http://videos.mtvnn.com/mediagen/e865da714c166d18d6f80893195fcb97)
334 'url': 'http://www.mtv.de/shows/933-teen-mom-2/staffeln/5353/folgen/63565-enthullungen',
335 'info_dict': {
336 'id': 'local_playlist-f5ae778b9832cc837189',
712c7530 337 'ext': 'flv',
c3c9f879
S
338 'title': 'Episode_teen-mom-2_shows_season-5_episode-1_full-episode_part1',
339 },
340 'params': {
341 # rtmp download
342 'skip_download': True,
343 },
65488b82 344 }, {
65488b82
S
345 'url': 'http://www.mtv.de/news/77491-mtv-movies-spotlight-pixels-teil-3',
346 'info_dict': {
347 'id': 'local_playlist-4e760566473c4c8c5344',
348 'ext': 'mp4',
349 'title': 'Article_mtv-movies-spotlight-pixels-teil-3_short-clips_part1',
350 'description': 'MTV Movies Supercut',
351 },
352 'params': {
353 # rtmp download
354 'skip_download': True,
355 },
712c7530 356 'skip': 'Das Video kann zur Zeit nicht abgespielt werden.',
79fa9db0 357 }]
071c1013
PH
358
359 def _real_extract(self, url):
79fa9db0
S
360 video_id = self._match_id(url)
361
362 webpage = self._download_webpage(url, video_id)
363
364 playlist = self._parse_json(
365 self._search_regex(
366 r'window\.pagePlaylist\s*=\s*(\[.+?\]);\n', webpage, 'page playlist'),
367 video_id)
071c1013 368
712c7530
YCH
369 def _mrss_url(item):
370 return item['mrss'] + item.get('mrssvars', '')
371
65488b82
S
372 # news pages contain single video in playlist with different id
373 if len(playlist) == 1:
712c7530 374 return self._get_videos_info_from_url(_mrss_url(playlist[0]), video_id)
65488b82 375
071c1013 376 for item in playlist:
79fa9db0
S
377 item_id = item.get('id')
378 if item_id and compat_str(item_id) == video_id:
712c7530 379 return self._get_videos_info_from_url(_mrss_url(item), video_id)