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