]> jfr.im git - yt-dlp.git/blame - youtube_dl/extractor/mtv.py
[nick] Automate geo-restriction bypass (#13711)
[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 85 hls_url, video_id, ext='mp4', entry_protocol='m3u8_native',
e0f1fb0a 86 m3u8_id='hls', fatal=False))
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.')
e0f1fb0a
S
109 if formats:
110 self._sort_formats(formats)
f13d0933 111 return formats
f7e02595 112
e525d9a3
S
113 def _extract_subtitles(self, mdoc, mtvn_id):
114 subtitles = {}
e525d9a3
S
115 for transcript in mdoc.findall('.//transcript'):
116 if transcript.get('kind') != 'captions':
117 continue
118 lang = transcript.get('srclang')
0af25f78
JMF
119 subtitles[lang] = [{
120 'url': compat_str(typographic.get('src')),
121 'ext': typographic.get('format')
122 } for typographic in transcript.findall('./typographic')]
123 return subtitles
e525d9a3 124
67fc365b 125 def _get_video_info(self, itemdoc, use_hls=True):
f7e02595
JMF
126 uri = itemdoc.find('guid').text
127 video_id = self._id_from_uri(uri)
128 self.report_extraction(video_id)
04cbc498 129 content_el = itemdoc.find('%s/%s' % (_media_xml_tag('group'), _media_xml_tag('content')))
0c75abbb 130 mediagen_url = self._remove_template_parameter(content_el.attrib['url'])
dbaf6016 131 mediagen_url = mediagen_url.replace('device={device}', '')
f7e02595 132 if 'acceptMethods' not in mediagen_url:
56f447be 133 mediagen_url += '&' if '?' in mediagen_url else '?'
dbaf6016
PH
134 mediagen_url += 'acceptMethods='
135 mediagen_url += 'hls' if use_hls else 'fms'
6562df76 136
e0f1fb0a
S
137 mediagen_doc = self._download_xml(
138 mediagen_url, video_id, 'Downloading video urls', fatal=False)
139
140 if mediagen_doc is False:
141 return None
f7e02595 142
0dfe9bc9
S
143 item = mediagen_doc.find('./video/item')
144 if item is not None and item.get('type') == 'text':
145 message = '%s returned error: ' % self.IE_NAME
146 if item.get('code') is not None:
147 message += '%s - ' % item.get('code')
148 message += item.text
149 raise ExtractorError(message, expected=True)
150
7cdfc4c9 151 description = strip_or_none(xpath_text(itemdoc, 'description'))
f13d0933 152
712c7530
YCH
153 timestamp = timeconvert(xpath_text(itemdoc, 'pubDate'))
154
90834c78
PH
155 title_el = None
156 if title_el is None:
157 title_el = find_xpath_attr(
158 itemdoc, './/{http://search.yahoo.com/mrss/}category',
159 'scheme', 'urn:mtvn:video_title')
90834c78 160 if title_el is None:
20a6a154 161 title_el = itemdoc.find(compat_xpath('.//{http://search.yahoo.com/mrss/}title'))
96cb10a5 162 if title_el is None:
20a6a154 163 title_el = itemdoc.find(compat_xpath('.//title'))
1df4229b
PH
164 if title_el.text is None:
165 title_el = None
1df4229b 166
90834c78
PH
167 title = title_el.text
168 if title is None:
169 raise ExtractorError('Could not find video title')
780ee4e5 170 title = title.strip()
90834c78 171
340b0468
JMF
172 # This a short id that's used in the webpage urls
173 mtvn_id = None
174 mtvn_id_node = find_xpath_attr(itemdoc, './/{http://search.yahoo.com/mrss/}category',
9e1a5b84 175 'scheme', 'urn:mtvn:id')
340b0468
JMF
176 if mtvn_id_node is not None:
177 mtvn_id = mtvn_id_node.text
178
dbaf6016
PH
179 formats = self._extract_video_formats(mediagen_doc, mtvn_id, video_id)
180
e0f1fb0a
S
181 # Some parts of complete video may be missing (e.g. missing Act 3 in
182 # http://www.southpark.de/alle-episoden/s14e01-sexual-healing)
183 if not formats:
184 return None
185
186 self._sort_formats(formats)
187
fb7abb31 188 return {
90834c78 189 'title': title,
dbaf6016 190 'formats': formats,
e525d9a3 191 'subtitles': self._extract_subtitles(mediagen_doc, mtvn_id),
f13d0933
PH
192 'id': video_id,
193 'thumbnail': self._get_thumbnail_url(uri, itemdoc),
194 'description': description,
04cbc498 195 'duration': float_or_none(content_el.attrib.get('duration')),
712c7530 196 'timestamp': timestamp,
f13d0933
PH
197 }
198
c1e90619 199 def _get_feed_query(self, uri):
200 data = {'uri': uri}
201 if self._LANG:
202 data['lang'] = self._LANG
0c75abbb 203 return data
c1e90619 204
67fc365b 205 def _get_videos_info(self, uri, use_hls=True):
f7e02595 206 video_id = self._id_from_uri(uri)
8940c1c0 207 feed_url = self._get_feed_url(uri)
0c75abbb 208 info_url = update_url_query(feed_url, self._get_feed_query(uri))
dbaf6016 209 return self._get_videos_info_from_url(info_url, video_id, use_hls)
79fa9db0 210
67fc365b 211 def _get_videos_info_from_url(self, url, video_id, use_hls=True):
e2b38da9 212 idoc = self._download_xml(
79fa9db0 213 url, video_id,
32dac694 214 'Downloading info', transform_source=fix_xml_ampersands)
712c7530
YCH
215
216 title = xpath_text(idoc, './channel/title')
217 description = xpath_text(idoc, './channel/description')
218
e0f1fb0a
S
219 entries = []
220 for item in idoc.findall('.//item'):
221 info = self._get_video_info(item, use_hls)
222 if info:
223 entries.append(info)
224
5239075b 225 return self.playlist_result(
e0f1fb0a 226 entries, playlist_title=title, playlist_description=description)
fc287219 227
adf063da
S
228 def _extract_triforce_mgid(self, webpage, data_zone=None, video_id=None):
229 triforce_feed = self._parse_json(self._search_regex(
f1e70fc2 230 r'triforceManifestFeed\s*=\s*({.+?})\s*;\s*\n', webpage,
adf063da
S
231 'triforce feed', default='{}'), video_id, fatal=False)
232
233 data_zone = self._search_regex(
234 r'data-zone=(["\'])(?P<zone>.+?_lc_promo.*?)\1', webpage,
235 'data zone', default=data_zone, group='zone')
236
237 feed_url = try_get(
238 triforce_feed, lambda x: x['manifest']['zones'][data_zone]['feed'],
239 compat_str)
240 if not feed_url:
241 return
242
243 feed = self._download_json(feed_url, video_id, fatal=False)
244 if not feed:
245 return
246
247 return try_get(feed, lambda x: x['result']['data']['id'], compat_str)
248
249 def _extract_mgid(self, webpage):
8d9453b9 250 try:
4bbf139a
JMF
251 # the url can be http://media.mtvnservices.com/fb/{mgid}.swf
252 # or http://media.mtvnservices.com/{mgid}
253 og_url = self._og_search_video_url(webpage)
254 mgid = url_basename(og_url)
255 if mgid.endswith('.swf'):
256 mgid = mgid[:-4]
8d9453b9 257 except RegexNotFoundError:
b1298d8e
AMW
258 mgid = None
259
260 if mgid is None or ':' not in mgid:
b9381e43
JMF
261 mgid = self._search_regex(
262 [r'data-mgid="(.*?)"', r'swfobject.embedSWF\(".*?(mgid:.*?)"'],
fc42bc6e
S
263 webpage, 'mgid', default=None)
264
265 if not mgid:
266 sm4_embed = self._html_search_meta(
267 'sm4:video:embed', webpage, 'sm4 embed', default='')
268 mgid = self._search_regex(
adf063da
S
269 r'embed/(mgid:.+?)["\'&?/]', sm4_embed, 'mgid', default=None)
270
271 if not mgid:
272 mgid = self._extract_triforce_mgid(webpage)
273
c1e90619 274 return mgid
e525d9a3 275
c1e90619 276 def _real_extract(self, url):
277 title = url_basename(url)
278 webpage = self._download_webpage(url, title)
279 mgid = self._extract_mgid(webpage)
e525d9a3 280 videos_info = self._get_videos_info(mgid)
e525d9a3 281 return videos_info
8d9453b9 282
84db8181 283
8940c1c0
JMF
284class MTVServicesEmbeddedIE(MTVServicesInfoExtractor):
285 IE_NAME = 'mtvservices:embedded'
286 _VALID_URL = r'https?://media\.mtvnservices\.com/embed/(?P<mgid>.+?)(\?|/|$)'
287
288 _TEST = {
289 # From http://www.thewrap.com/peter-dinklage-sums-up-game-of-thrones-in-45-seconds-video/
290 'url': 'http://media.mtvnservices.com/embed/mgid:uma:video:mtv.com:1043906/cp~vid%3D1043906%26uri%3Dmgid%3Auma%3Avideo%3Amtv.com%3A1043906',
291 'md5': 'cb349b21a7897164cede95bd7bf3fbb9',
292 'info_dict': {
293 'id': '1043906',
294 'ext': 'mp4',
295 'title': 'Peter Dinklage Sums Up \'Game Of Thrones\' In 45 Seconds',
296 '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
297 'timestamp': 1400126400,
298 'upload_date': '20140515',
8940c1c0
JMF
299 },
300 }
301
fe1d858e
S
302 @staticmethod
303 def _extract_url(webpage):
304 mobj = re.search(
305 r'<iframe[^>]+?src=(["\'])(?P<url>(?:https?:)?//media.mtvnservices.com/embed/.+?)\1', webpage)
306 if mobj:
307 return mobj.group('url')
308
8940c1c0
JMF
309 def _get_feed_url(self, uri):
310 video_id = self._id_from_uri(uri)
0c75abbb
YCH
311 config = self._download_json(
312 'http://media.mtvnservices.com/pmt/e1/access/index.html?uri=%s&configtype=edge' % uri, video_id)
313 return self._remove_template_parameter(config['feedWithQueryParams'])
8940c1c0
JMF
314
315 def _real_extract(self, url):
316 mobj = re.match(self._VALID_URL, url)
317 mgid = mobj.group('mgid')
318 return self._get_videos_info(mgid)
319
320
84db8181 321class MTVIE(MTVServicesInfoExtractor):
a54ffb8a 322 IE_NAME = 'mtv'
cf0cabbe 323 _VALID_URL = r'https?://(?:www\.)?mtv\.com/(?:video-clips|(?:full-)?episodes)/(?P<id>[^/?#.]+)'
8add4bfe
RA
324 _FEED_URL = 'http://www.mtv.com/feeds/mrss/'
325
326 _TESTS = [{
327 'url': 'http://www.mtv.com/video-clips/vl8qof/unlocking-the-truth-trailer',
328 'md5': '1edbcdf1e7628e414a8c5dcebca3d32b',
329 'info_dict': {
330 'id': '5e14040d-18a4-47c4-a582-43ff602de88e',
331 'ext': 'mp4',
332 'title': 'Unlocking The Truth|July 18, 2016|1|101|Trailer',
333 'description': '"Unlocking the Truth" premieres August 17th at 11/10c.',
334 'timestamp': 1468846800,
335 'upload_date': '20160718',
336 },
337 }, {
338 'url': 'http://www.mtv.com/full-episodes/94tujl/unlocking-the-truth-gates-of-hell-season-1-ep-101',
339 'only_matching': True,
cf0cabbe
S
340 }, {
341 'url': 'http://www.mtv.com/episodes/g8xu7q/teen-mom-2-breaking-the-wall-season-7-ep-713',
342 'only_matching': True,
8add4bfe
RA
343 }]
344
345
008f2470
S
346class MTV81IE(InfoExtractor):
347 IE_NAME = 'mtv81'
348 _VALID_URL = r'https?://(?:www\.)?mtv81\.com/videos/(?P<id>[^/?#.]+)'
349
350 _TEST = {
351 'url': 'http://www.mtv81.com/videos/artist-to-watch/the-godfather-of-japanese-hip-hop-segment-1/',
352 'md5': '1edbcdf1e7628e414a8c5dcebca3d32b',
353 'info_dict': {
354 'id': '5e14040d-18a4-47c4-a582-43ff602de88e',
355 'ext': 'mp4',
356 'title': 'Unlocking The Truth|July 18, 2016|1|101|Trailer',
357 'description': '"Unlocking the Truth" premieres August 17th at 11/10c.',
358 'timestamp': 1468846800,
359 'upload_date': '20160718',
360 },
361 }
362
363 def _extract_mgid(self, webpage):
364 return self._search_regex(
365 r'getTheVideo\((["\'])(?P<id>mgid:.+?)\1', webpage,
366 'mgid', group='id')
367
368 def _real_extract(self, url):
369 video_id = self._match_id(url)
370 webpage = self._download_webpage(url, video_id)
371 mgid = self._extract_mgid(webpage)
372 return self.url_result('http://media.mtvnservices.com/embed/%s' % mgid)
373
374
8add4bfe 375class MTVVideoIE(MTVServicesInfoExtractor):
a54ffb8a 376 IE_NAME = 'mtv:video'
5c541b2c
JMF
377 _VALID_URL = r'''(?x)^https?://
378 (?:(?:www\.)?mtv\.com/videos/.+?/(?P<videoid>[0-9]+)/[^/]+$|
379 m\.mtv\.com/videos/video\.rbml\?.*?id=(?P<mgid>[^&]+))'''
84db8181
JMF
380
381 _FEED_URL = 'http://www.mtv.com/player/embed/AS3/rss/'
382
383 _TESTS = [
384 {
32dac694 385 'url': 'http://www.mtv.com/videos/misc/853555/ours-vh1-storytellers.jhtml',
32dac694
PH
386 'md5': '850f3f143316b1e71fa56a4edfd6e0f8',
387 'info_dict': {
ca0f500e
PH
388 'id': '853555',
389 'ext': 'mp4',
32dac694
PH
390 'title': 'Taylor Swift - "Ours (VH1 Storytellers)"',
391 'description': 'Album: Taylor Swift performs "Ours" for VH1 Storytellers at Harvey Mudd College.',
712c7530
YCH
392 'timestamp': 1352610000,
393 'upload_date': '20121111',
84db8181
JMF
394 },
395 },
84db8181
JMF
396 ]
397
398 def _get_thumbnail_url(self, uri, itemdoc):
399 return 'http://mtv.mtvnimages.com/uri/' + uri
400
fc287219
PH
401 def _real_extract(self, url):
402 mobj = re.match(self._VALID_URL, url)
fc287219 403 video_id = mobj.group('videoid')
c801b205 404 uri = mobj.groupdict().get('mgid')
5c541b2c
JMF
405 if uri is None:
406 webpage = self._download_webpage(url, video_id)
5f6a1245 407
5c541b2c 408 # Some videos come from Vevo.com
ca0f500e
PH
409 m_vevo = re.search(
410 r'(?s)isVevoVideo = true;.*?vevoVideoId = "(.*?)";', webpage)
5c541b2c 411 if m_vevo:
8bcc8756 412 vevo_id = m_vevo.group(1)
32dac694 413 self.to_screen('Vevo video detected: %s' % vevo_id)
5c541b2c 414 return self.url_result('vevo:%s' % vevo_id, ie='Vevo')
5f6a1245 415
32dac694 416 uri = self._html_search_regex(r'/uri/(.*?)\?', webpage, 'uri')
f7e02595 417 return self._get_videos_info(uri)
bc4ba05f
JMF
418
419
071c1013
PH
420class MTVDEIE(MTVServicesInfoExtractor):
421 IE_NAME = 'mtv.de'
65488b82 422 _VALID_URL = r'https?://(?:www\.)?mtv\.de/(?:artists|shows|news)/(?:[^/]+/)*(?P<id>\d+)-[^/#?]+/*(?:[#?].*)?$'
79fa9db0
S
423 _TESTS = [{
424 'url': 'http://www.mtv.de/artists/10571-cro/videos/61131-traum',
425 'info_dict': {
426 'id': 'music_video-a50bc5f0b3aa4b3190aa',
712c7530 427 'ext': 'flv',
79fa9db0
S
428 'title': 'MusicVideo_cro-traum',
429 'description': 'Cro - Traum',
071c1013 430 },
79fa9db0
S
431 'params': {
432 # rtmp download
433 'skip_download': True,
434 },
35f6e0ff 435 'skip': 'Blocked at Travis CI',
c3c9f879
S
436 }, {
437 # mediagen URL without query (e.g. http://videos.mtvnn.com/mediagen/e865da714c166d18d6f80893195fcb97)
438 'url': 'http://www.mtv.de/shows/933-teen-mom-2/staffeln/5353/folgen/63565-enthullungen',
439 'info_dict': {
440 'id': 'local_playlist-f5ae778b9832cc837189',
712c7530 441 'ext': 'flv',
c3c9f879
S
442 'title': 'Episode_teen-mom-2_shows_season-5_episode-1_full-episode_part1',
443 },
444 'params': {
445 # rtmp download
446 'skip_download': True,
447 },
35f6e0ff 448 'skip': 'Blocked at Travis CI',
65488b82 449 }, {
65488b82
S
450 'url': 'http://www.mtv.de/news/77491-mtv-movies-spotlight-pixels-teil-3',
451 'info_dict': {
452 'id': 'local_playlist-4e760566473c4c8c5344',
453 'ext': 'mp4',
454 'title': 'Article_mtv-movies-spotlight-pixels-teil-3_short-clips_part1',
455 'description': 'MTV Movies Supercut',
456 },
457 'params': {
458 # rtmp download
459 'skip_download': True,
460 },
712c7530 461 'skip': 'Das Video kann zur Zeit nicht abgespielt werden.',
79fa9db0 462 }]
071c1013
PH
463
464 def _real_extract(self, url):
79fa9db0
S
465 video_id = self._match_id(url)
466
467 webpage = self._download_webpage(url, video_id)
468
469 playlist = self._parse_json(
470 self._search_regex(
471 r'window\.pagePlaylist\s*=\s*(\[.+?\]);\n', webpage, 'page playlist'),
472 video_id)
071c1013 473
712c7530
YCH
474 def _mrss_url(item):
475 return item['mrss'] + item.get('mrssvars', '')
476
65488b82
S
477 # news pages contain single video in playlist with different id
478 if len(playlist) == 1:
712c7530 479 return self._get_videos_info_from_url(_mrss_url(playlist[0]), video_id)
65488b82 480
071c1013 481 for item in playlist:
79fa9db0
S
482 item_id = item.get('id')
483 if item_id and compat_str(item_id) == video_id:
712c7530 484 return self._get_videos_info_from_url(_mrss_url(item), video_id)