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