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