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