]> jfr.im git - yt-dlp.git/blob - yt_dlp/extractor/mtv.py
[fragments] Pad fragments before decrypting (#1298)
[yt-dlp.git] / yt_dlp / extractor / mtv.py
1 # coding: utf-8
2 from __future__ import unicode_literals
3
4 import re
5
6 from .common import InfoExtractor
7 from ..compat import (
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 int_or_none,
18 RegexNotFoundError,
19 sanitized_Request,
20 strip_or_none,
21 timeconvert,
22 try_get,
23 unescapeHTML,
24 update_url_query,
25 url_basename,
26 xpath_text,
27 )
28
29
30 def _media_xml_tag(tag):
31 return '{http://search.yahoo.com/mrss/}%s' % tag
32
33
34 class MTVServicesInfoExtractor(InfoExtractor):
35 _MOBILE_TEMPLATE = None
36 _LANG = None
37
38 @staticmethod
39 def _id_from_uri(uri):
40 return uri.split(':')[-1]
41
42 @staticmethod
43 def _remove_template_parameter(url):
44 # Remove the templates, like &device={device}
45 return re.sub(r'&[^=]*?={.*?}(?=(&|$))', '', url)
46
47 def _get_feed_url(self, uri, url=None):
48 return self._FEED_URL
49
50 def _get_thumbnail_url(self, uri, itemdoc):
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 return thumb_node.get('url') or thumb_node.text or None
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, video_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 if rendition.get('method') == 'hls':
84 hls_url = rendition.find('./src').text
85 formats.extend(self._extract_m3u8_formats(
86 hls_url, video_id, ext='mp4', entry_protocol='m3u8_native',
87 m3u8_id='hls', fatal=False))
88 else:
89 # fms
90 try:
91 _, _, ext = rendition.attrib['type'].partition('/')
92 rtmp_video_url = rendition.find('./src').text
93 if 'error_not_available.swf' in rtmp_video_url:
94 raise ExtractorError(
95 '%s said: video is not available' % self.IE_NAME,
96 expected=True)
97 if rtmp_video_url.endswith('siteunavail.png'):
98 continue
99 formats.extend([{
100 'ext': 'flv' if rtmp_video_url.startswith('rtmp') else ext,
101 'url': rtmp_video_url,
102 'format_id': '-'.join(filter(None, [
103 'rtmp' if rtmp_video_url.startswith('rtmp') else None,
104 rendition.get('bitrate')])),
105 'width': int(rendition.get('width')),
106 'height': int(rendition.get('height')),
107 }])
108 except (KeyError, TypeError):
109 raise ExtractorError('Invalid rendition field.')
110 if formats:
111 self._sort_formats(formats)
112 return formats
113
114 def _extract_subtitles(self, mdoc, mtvn_id):
115 subtitles = {}
116 for transcript in mdoc.findall('.//transcript'):
117 if transcript.get('kind') != 'captions':
118 continue
119 lang = transcript.get('srclang')
120 for typographic in transcript.findall('./typographic'):
121 sub_src = typographic.get('src')
122 if not sub_src:
123 continue
124 ext = typographic.get('format')
125 if ext == 'cea-608':
126 ext = 'scc'
127 subtitles.setdefault(lang, []).append({
128 'url': compat_str(sub_src),
129 'ext': ext
130 })
131 return subtitles
132
133 def _get_video_info(self, itemdoc, use_hls=True):
134 uri = itemdoc.find('guid').text
135 video_id = self._id_from_uri(uri)
136 self.report_extraction(video_id)
137 content_el = itemdoc.find('%s/%s' % (_media_xml_tag('group'), _media_xml_tag('content')))
138 mediagen_url = self._remove_template_parameter(content_el.attrib['url'])
139 mediagen_url = mediagen_url.replace('device={device}', '')
140 if 'acceptMethods' not in mediagen_url:
141 mediagen_url += '&' if '?' in mediagen_url else '?'
142 mediagen_url += 'acceptMethods='
143 mediagen_url += 'hls' if use_hls else 'fms'
144
145 mediagen_doc = self._download_xml(
146 mediagen_url, video_id, 'Downloading video urls', fatal=False)
147
148 if mediagen_doc is False:
149 return None
150
151 item = mediagen_doc.find('./video/item')
152 if item is not None and item.get('type') == 'text':
153 message = '%s returned error: ' % self.IE_NAME
154 if item.get('code') is not None:
155 message += '%s - ' % item.get('code')
156 message += item.text
157 raise ExtractorError(message, expected=True)
158
159 description = strip_or_none(xpath_text(itemdoc, 'description'))
160
161 timestamp = timeconvert(xpath_text(itemdoc, 'pubDate'))
162
163 title_el = None
164 if title_el is None:
165 title_el = find_xpath_attr(
166 itemdoc, './/{http://search.yahoo.com/mrss/}category',
167 'scheme', 'urn:mtvn:video_title')
168 if title_el is None:
169 title_el = itemdoc.find(compat_xpath('.//{http://search.yahoo.com/mrss/}title'))
170 if title_el is None:
171 title_el = itemdoc.find(compat_xpath('.//title'))
172 if title_el.text is None:
173 title_el = None
174
175 title = title_el.text
176 if title is None:
177 raise ExtractorError('Could not find video title')
178 title = title.strip()
179
180 series = find_xpath_attr(
181 itemdoc, './/{http://search.yahoo.com/mrss/}category',
182 'scheme', 'urn:mtvn:franchise')
183 season = find_xpath_attr(
184 itemdoc, './/{http://search.yahoo.com/mrss/}category',
185 'scheme', 'urn:mtvn:seasonN')
186 episode = find_xpath_attr(
187 itemdoc, './/{http://search.yahoo.com/mrss/}category',
188 'scheme', 'urn:mtvn:episodeN')
189 series = series.text if series is not None else None
190 season = season.text if season is not None else None
191 episode = episode.text if episode is not None else None
192 if season and episode:
193 # episode number includes season, so remove it
194 episode = re.sub(r'^%s' % season, '', episode)
195
196 # This a short id that's used in the webpage urls
197 mtvn_id = None
198 mtvn_id_node = find_xpath_attr(itemdoc, './/{http://search.yahoo.com/mrss/}category',
199 'scheme', 'urn:mtvn:id')
200 if mtvn_id_node is not None:
201 mtvn_id = mtvn_id_node.text
202
203 formats = self._extract_video_formats(mediagen_doc, mtvn_id, video_id)
204
205 # Some parts of complete video may be missing (e.g. missing Act 3 in
206 # http://www.southpark.de/alle-episoden/s14e01-sexual-healing)
207 if not formats:
208 return None
209
210 self._sort_formats(formats)
211
212 return {
213 'title': title,
214 'formats': formats,
215 'subtitles': self._extract_subtitles(mediagen_doc, mtvn_id),
216 'id': video_id,
217 'thumbnail': self._get_thumbnail_url(uri, itemdoc),
218 'description': description,
219 'duration': float_or_none(content_el.attrib.get('duration')),
220 'timestamp': timestamp,
221 'series': series,
222 'season_number': int_or_none(season),
223 'episode_number': int_or_none(episode),
224 }
225
226 def _get_feed_query(self, uri):
227 data = {'uri': uri}
228 if self._LANG:
229 data['lang'] = self._LANG
230 return data
231
232 def _get_videos_info(self, uri, use_hls=True, url=None):
233 video_id = self._id_from_uri(uri)
234 feed_url = self._get_feed_url(uri, url)
235 info_url = update_url_query(feed_url, self._get_feed_query(uri))
236 return self._get_videos_info_from_url(info_url, video_id, use_hls)
237
238 def _get_videos_info_from_url(self, url, video_id, use_hls=True):
239 idoc = self._download_xml(
240 url, video_id,
241 'Downloading info', transform_source=fix_xml_ampersands)
242
243 title = xpath_text(idoc, './channel/title')
244 description = xpath_text(idoc, './channel/description')
245
246 entries = []
247 for item in idoc.findall('.//item'):
248 info = self._get_video_info(item, use_hls)
249 if info:
250 entries.append(info)
251
252 # TODO: should be multi-video
253 return self.playlist_result(
254 entries, playlist_title=title, playlist_description=description)
255
256 def _extract_triforce_mgid(self, webpage, data_zone=None, video_id=None):
257 triforce_feed = self._parse_json(self._search_regex(
258 r'triforceManifestFeed\s*=\s*({.+?})\s*;\s*\n', webpage,
259 'triforce feed', default='{}'), video_id, fatal=False)
260
261 data_zone = self._search_regex(
262 r'data-zone=(["\'])(?P<zone>.+?_lc_promo.*?)\1', webpage,
263 'data zone', default=data_zone, group='zone')
264
265 feed_url = try_get(
266 triforce_feed, lambda x: x['manifest']['zones'][data_zone]['feed'],
267 compat_str)
268 if not feed_url:
269 return
270
271 feed = self._download_json(feed_url, video_id, fatal=False)
272 if not feed:
273 return
274
275 return try_get(feed, lambda x: x['result']['data']['id'], compat_str)
276
277 @staticmethod
278 def _extract_child_with_type(parent, t):
279 for c in parent['children']:
280 if c.get('type') == t:
281 return c
282
283 def _extract_mgid(self, webpage):
284 try:
285 # the url can be http://media.mtvnservices.com/fb/{mgid}.swf
286 # or http://media.mtvnservices.com/{mgid}
287 og_url = self._og_search_video_url(webpage)
288 mgid = url_basename(og_url)
289 if mgid.endswith('.swf'):
290 mgid = mgid[:-4]
291 except RegexNotFoundError:
292 mgid = None
293
294 if mgid is None or ':' not in mgid:
295 mgid = self._search_regex(
296 [r'data-mgid="(.*?)"', r'swfobject\.embedSWF\(".*?(mgid:.*?)"'],
297 webpage, 'mgid', default=None)
298
299 if not mgid:
300 sm4_embed = self._html_search_meta(
301 'sm4:video:embed', webpage, 'sm4 embed', default='')
302 mgid = self._search_regex(
303 r'embed/(mgid:.+?)["\'&?/]', sm4_embed, 'mgid', default=None)
304
305 if not mgid:
306 mgid = self._extract_triforce_mgid(webpage)
307
308 if not mgid:
309 data = self._parse_json(self._search_regex(
310 r'__DATA__\s*=\s*({.+?});', webpage, 'data'), None)
311 main_container = self._extract_child_with_type(data, 'MainContainer')
312 ab_testing = self._extract_child_with_type(main_container, 'ABTesting')
313 video_player = self._extract_child_with_type(ab_testing or main_container, 'VideoPlayer')
314 mgid = video_player['props']['media']['video']['config']['uri']
315
316 if not mgid:
317 mgid = self._search_regex(
318 r'"media":{"video":{"config":{"uri":"(mgid:.*?)"', webpage, 'mgid', default=None)
319
320 return mgid
321
322 def _real_extract(self, url):
323 title = url_basename(url)
324 webpage = self._download_webpage(url, title)
325 mgid = self._extract_mgid(webpage)
326 videos_info = self._get_videos_info(mgid, url=url)
327 return videos_info
328
329
330 class MTVServicesEmbeddedIE(MTVServicesInfoExtractor):
331 IE_NAME = 'mtvservices:embedded'
332 _VALID_URL = r'https?://media\.mtvnservices\.com/embed/(?P<mgid>.+?)(\?|/|$)'
333
334 _TEST = {
335 # From http://www.thewrap.com/peter-dinklage-sums-up-game-of-thrones-in-45-seconds-video/
336 'url': 'http://media.mtvnservices.com/embed/mgid:uma:video:mtv.com:1043906/cp~vid%3D1043906%26uri%3Dmgid%3Auma%3Avideo%3Amtv.com%3A1043906',
337 'md5': 'cb349b21a7897164cede95bd7bf3fbb9',
338 'info_dict': {
339 'id': '1043906',
340 'ext': 'mp4',
341 'title': 'Peter Dinklage Sums Up \'Game Of Thrones\' In 45 Seconds',
342 'description': '"Sexy sexy sexy, stabby stabby stabby, beautiful language," says Peter Dinklage as he tries summarizing "Game of Thrones" in under a minute.',
343 'timestamp': 1400126400,
344 'upload_date': '20140515',
345 },
346 }
347
348 @staticmethod
349 def _extract_url(webpage):
350 mobj = re.search(
351 r'<iframe[^>]+?src=(["\'])(?P<url>(?:https?:)?//media\.mtvnservices\.com/embed/.+?)\1', webpage)
352 if mobj:
353 return mobj.group('url')
354
355 def _get_feed_url(self, uri, url=None):
356 video_id = self._id_from_uri(uri)
357 config = self._download_json(
358 'http://media.mtvnservices.com/pmt/e1/access/index.html?uri=%s&configtype=edge' % uri, video_id)
359 return self._remove_template_parameter(config['feedWithQueryParams'])
360
361 def _real_extract(self, url):
362 mobj = self._match_valid_url(url)
363 mgid = mobj.group('mgid')
364 return self._get_videos_info(mgid)
365
366
367 class MTVIE(MTVServicesInfoExtractor):
368 IE_NAME = 'mtv'
369 _VALID_URL = r'https?://(?:www\.)?mtv\.com/(?:video-clips|(?:full-)?episodes)/(?P<id>[^/?#.]+)'
370 _FEED_URL = 'http://www.mtv.com/feeds/mrss/'
371
372 _TESTS = [{
373 'url': 'http://www.mtv.com/video-clips/vl8qof/unlocking-the-truth-trailer',
374 'md5': '1edbcdf1e7628e414a8c5dcebca3d32b',
375 'info_dict': {
376 'id': '5e14040d-18a4-47c4-a582-43ff602de88e',
377 'ext': 'mp4',
378 'title': 'Unlocking The Truth|July 18, 2016|1|101|Trailer',
379 'description': '"Unlocking the Truth" premieres August 17th at 11/10c.',
380 'timestamp': 1468846800,
381 'upload_date': '20160718',
382 },
383 }, {
384 'url': 'http://www.mtv.com/full-episodes/94tujl/unlocking-the-truth-gates-of-hell-season-1-ep-101',
385 'only_matching': True,
386 }, {
387 'url': 'http://www.mtv.com/episodes/g8xu7q/teen-mom-2-breaking-the-wall-season-7-ep-713',
388 'only_matching': True,
389 }]
390
391
392 class MTVJapanIE(MTVServicesInfoExtractor):
393 IE_NAME = 'mtvjapan'
394 _VALID_URL = r'https?://(?:www\.)?mtvjapan\.com/videos/(?P<id>[0-9a-z]+)'
395
396 _TEST = {
397 'url': 'http://www.mtvjapan.com/videos/prayht/fresh-info-cadillac-escalade',
398 'info_dict': {
399 'id': 'bc01da03-6fe5-4284-8880-f291f4e368f5',
400 'ext': 'mp4',
401 'title': '【Fresh Info】Cadillac ESCALADE Sport Edition',
402 },
403 'params': {
404 'skip_download': True,
405 },
406 }
407 _GEO_COUNTRIES = ['JP']
408 _FEED_URL = 'http://feeds.mtvnservices.com/od/feed/intl-mrss-player-feed'
409
410 def _get_feed_query(self, uri):
411 return {
412 'arcEp': 'mtvjapan.com',
413 'mgid': uri,
414 }
415
416
417 class MTVVideoIE(MTVServicesInfoExtractor):
418 IE_NAME = 'mtv:video'
419 _VALID_URL = r'''(?x)^https?://
420 (?:(?:www\.)?mtv\.com/videos/.+?/(?P<videoid>[0-9]+)/[^/]+$|
421 m\.mtv\.com/videos/video\.rbml\?.*?id=(?P<mgid>[^&]+))'''
422
423 _FEED_URL = 'http://www.mtv.com/player/embed/AS3/rss/'
424
425 _TESTS = [
426 {
427 'url': 'http://www.mtv.com/videos/misc/853555/ours-vh1-storytellers.jhtml',
428 'md5': '850f3f143316b1e71fa56a4edfd6e0f8',
429 'info_dict': {
430 'id': '853555',
431 'ext': 'mp4',
432 'title': 'Taylor Swift - "Ours (VH1 Storytellers)"',
433 'description': 'Album: Taylor Swift performs "Ours" for VH1 Storytellers at Harvey Mudd College.',
434 'timestamp': 1352610000,
435 'upload_date': '20121111',
436 },
437 },
438 ]
439
440 def _get_thumbnail_url(self, uri, itemdoc):
441 return 'http://mtv.mtvnimages.com/uri/' + uri
442
443 def _real_extract(self, url):
444 mobj = self._match_valid_url(url)
445 video_id = mobj.group('videoid')
446 uri = mobj.groupdict().get('mgid')
447 if uri is None:
448 webpage = self._download_webpage(url, video_id)
449
450 # Some videos come from Vevo.com
451 m_vevo = re.search(
452 r'(?s)isVevoVideo = true;.*?vevoVideoId = "(.*?)";', webpage)
453 if m_vevo:
454 vevo_id = m_vevo.group(1)
455 self.to_screen('Vevo video detected: %s' % vevo_id)
456 return self.url_result('vevo:%s' % vevo_id, ie='Vevo')
457
458 uri = self._html_search_regex(r'/uri/(.*?)\?', webpage, 'uri')
459 return self._get_videos_info(uri)
460
461
462 class MTVDEIE(MTVServicesInfoExtractor):
463 IE_NAME = 'mtv.de'
464 _VALID_URL = r'https?://(?:www\.)?mtv\.de/(?:musik/videoclips|folgen|news)/(?P<id>[0-9a-z]+)'
465 _TESTS = [{
466 'url': 'http://www.mtv.de/musik/videoclips/2gpnv7/Traum',
467 'info_dict': {
468 'id': 'd5d472bc-f5b7-11e5-bffd-a4badb20dab5',
469 'ext': 'mp4',
470 'title': 'Traum',
471 'description': 'Traum',
472 },
473 'params': {
474 # rtmp download
475 'skip_download': True,
476 },
477 'skip': 'Blocked at Travis CI',
478 }, {
479 # mediagen URL without query (e.g. http://videos.mtvnn.com/mediagen/e865da714c166d18d6f80893195fcb97)
480 'url': 'http://www.mtv.de/folgen/6b1ylu/teen-mom-2-enthuellungen-S5-F1',
481 'info_dict': {
482 'id': '1e5a878b-31c5-11e7-a442-0e40cf2fc285',
483 'ext': 'mp4',
484 'title': 'Teen Mom 2',
485 'description': 'md5:dc65e357ef7e1085ed53e9e9d83146a7',
486 },
487 'params': {
488 # rtmp download
489 'skip_download': True,
490 },
491 'skip': 'Blocked at Travis CI',
492 }, {
493 'url': 'http://www.mtv.de/news/glolix/77491-mtv-movies-spotlight--pixels--teil-3',
494 'info_dict': {
495 'id': 'local_playlist-4e760566473c4c8c5344',
496 'ext': 'mp4',
497 'title': 'Article_mtv-movies-spotlight-pixels-teil-3_short-clips_part1',
498 'description': 'MTV Movies Supercut',
499 },
500 'params': {
501 # rtmp download
502 'skip_download': True,
503 },
504 'skip': 'Das Video kann zur Zeit nicht abgespielt werden.',
505 }]
506 _GEO_COUNTRIES = ['DE']
507 _FEED_URL = 'http://feeds.mtvnservices.com/od/feed/intl-mrss-player-feed'
508
509 def _get_feed_query(self, uri):
510 return {
511 'arcEp': 'mtv.de',
512 'mgid': uri,
513 }
514
515
516 class MTVItaliaIE(MTVServicesInfoExtractor):
517 IE_NAME = 'mtv.it'
518 _VALID_URL = r'https?://(?:www\.)?mtv\.it/(?:episodi|video|musica)/(?P<id>[0-9a-z]+)'
519 _TESTS = [{
520 'url': 'http://www.mtv.it/episodi/24bqab/mario-una-serie-di-maccio-capatonda-cavoli-amario-episodio-completo-S1-E1',
521 'info_dict': {
522 'id': '0f0fc78e-45fc-4cce-8f24-971c25477530',
523 'ext': 'mp4',
524 'title': 'Cavoli amario (episodio completo)',
525 'description': 'md5:4962bccea8fed5b7c03b295ae1340660',
526 'series': 'Mario - Una Serie Di Maccio Capatonda',
527 'season_number': 1,
528 'episode_number': 1,
529 },
530 'params': {
531 'skip_download': True,
532 },
533 }]
534 _GEO_COUNTRIES = ['IT']
535 _FEED_URL = 'http://feeds.mtvnservices.com/od/feed/intl-mrss-player-feed'
536
537 def _get_feed_query(self, uri):
538 return {
539 'arcEp': 'mtv.it',
540 'mgid': uri,
541 }
542
543
544 class MTVItaliaProgrammaIE(MTVItaliaIE):
545 IE_NAME = 'mtv.it:programma'
546 _VALID_URL = r'https?://(?:www\.)?mtv\.it/(?:programmi|playlist)/(?P<id>[0-9a-z]+)'
547 _TESTS = [{
548 # program page: general
549 'url': 'http://www.mtv.it/programmi/s2rppv/mario-una-serie-di-maccio-capatonda',
550 'info_dict': {
551 'id': 'a6f155bc-8220-4640-aa43-9b95f64ffa3d',
552 'title': 'Mario - Una Serie Di Maccio Capatonda',
553 'description': 'md5:72fbffe1f77ccf4e90757dd4e3216153',
554 },
555 'playlist_count': 2,
556 'params': {
557 'skip_download': True,
558 },
559 }, {
560 # program page: specific season
561 'url': 'http://www.mtv.it/programmi/d9ncjf/mario-una-serie-di-maccio-capatonda-S2',
562 'info_dict': {
563 'id': '4deeb5d8-f272-490c-bde2-ff8d261c6dd1',
564 'title': 'Mario - Una Serie Di Maccio Capatonda - Stagione 2',
565 },
566 'playlist_count': 34,
567 'params': {
568 'skip_download': True,
569 },
570 }, {
571 # playlist page + redirect
572 'url': 'http://www.mtv.it/playlist/sexy-videos/ilctal',
573 'info_dict': {
574 'id': 'dee8f9ee-756d-493b-bf37-16d1d2783359',
575 'title': 'Sexy Videos',
576 },
577 'playlist_mincount': 145,
578 'params': {
579 'skip_download': True,
580 },
581 }]
582 _GEO_COUNTRIES = ['IT']
583 _FEED_URL = 'http://www.mtv.it/feeds/triforce/manifest/v8'
584
585 def _get_entries(self, title, url):
586 while True:
587 pg = self._search_regex(r'/(\d+)$', url, 'entries', '1')
588 entries = self._download_json(url, title, 'page %s' % pg)
589 url = try_get(
590 entries, lambda x: x['result']['nextPageURL'], compat_str)
591 entries = try_get(
592 entries, (
593 lambda x: x['result']['data']['items'],
594 lambda x: x['result']['data']['seasons']),
595 list)
596 for entry in entries or []:
597 if entry.get('canonicalURL'):
598 yield self.url_result(entry['canonicalURL'])
599 if not url:
600 break
601
602 def _real_extract(self, url):
603 query = {'url': url}
604 info_url = update_url_query(self._FEED_URL, query)
605 video_id = self._match_id(url)
606 info = self._download_json(info_url, video_id).get('manifest')
607
608 redirect = try_get(
609 info, lambda x: x['newLocation']['url'], compat_str)
610 if redirect:
611 return self.url_result(redirect)
612
613 title = info.get('title')
614 video_id = try_get(
615 info, lambda x: x['reporting']['itemId'], compat_str)
616 parent_id = try_get(
617 info, lambda x: x['reporting']['parentId'], compat_str)
618
619 playlist_url = current_url = None
620 for z in (info.get('zones') or {}).values():
621 if z.get('moduleName') in ('INTL_M304', 'INTL_M209'):
622 info_url = z.get('feed')
623 if z.get('moduleName') in ('INTL_M308', 'INTL_M317'):
624 playlist_url = playlist_url or z.get('feed')
625 if z.get('moduleName') in ('INTL_M300',):
626 current_url = current_url or z.get('feed')
627
628 if not info_url:
629 raise ExtractorError('No info found')
630
631 if video_id == parent_id:
632 video_id = self._search_regex(
633 r'([^\/]+)/[^\/]+$', info_url, 'video_id')
634
635 info = self._download_json(info_url, video_id, 'Show infos')
636 info = try_get(info, lambda x: x['result']['data'], dict)
637 title = title or try_get(
638 info, (
639 lambda x: x['title'],
640 lambda x: x['headline']),
641 compat_str)
642 description = try_get(info, lambda x: x['content'], compat_str)
643
644 if current_url:
645 season = try_get(
646 self._download_json(playlist_url, video_id, 'Seasons info'),
647 lambda x: x['result']['data'], dict)
648 current = try_get(
649 season, lambda x: x['currentSeason'], compat_str)
650 seasons = try_get(
651 season, lambda x: x['seasons'], list) or []
652
653 if current in [s.get('eTitle') for s in seasons]:
654 playlist_url = current_url
655
656 title = re.sub(
657 r'[-|]\s*(?:mtv\s*italia|programma|playlist)',
658 '', title, flags=re.IGNORECASE).strip()
659
660 return self.playlist_result(
661 self._get_entries(title, playlist_url),
662 video_id, title, description)