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