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