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