]> jfr.im git - yt-dlp.git/blame - yt_dlp/extractor/rai.py
[Nebula] Fix bug in 52efa4b31200119adaa8acf33e50b84fcb6948f0
[yt-dlp.git] / yt_dlp / extractor / rai.py
CommitLineData
abea9145 1# coding: utf-8
b0adbe98
S
2from __future__ import unicode_literals
3
b8d8cced
S
4import re
5
afbdd3ac 6from .common import InfoExtractor
b8d8cced 7from ..compat import (
b8d8cced 8 compat_str,
b9d68c19 9 compat_urlparse,
b8d8cced 10)
b0adbe98 11from ..utils import (
51342717 12 determine_ext,
b9d68c19 13 ExtractorError,
90137ca4 14 filter_dict,
f1388739
YCH
15 find_xpath_attr,
16 fix_xml_ampersands,
b8d8cced 17 GeoRestrictedError,
b9d68c19 18 HEADRequest,
f1388739 19 int_or_none,
99148c6a 20 join_nonempty,
b0adbe98 21 parse_duration,
a0566bbf 22 remove_start,
b8d8cced 23 strip_or_none,
0df11daf 24 traverse_obj,
a0566bbf 25 try_get,
b0adbe98 26 unified_strdate,
b8d8cced 27 unified_timestamp,
f1388739 28 update_url_query,
b8d8cced 29 urljoin,
06d5556d 30 xpath_text,
b0adbe98
S
31)
32
33
034a8849 34class RaiBaseIE(InfoExtractor):
b8d8cced
S
35 _UUID_RE = r'[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}'
36 _GEO_COUNTRIES = ['IT']
37 _GEO_BYPASS = False
38
0df11daf 39 def _extract_relinker_info(self, relinker_url, video_id, audio_only=False):
0c7b4f49
RA
40 if not re.match(r'https?://', relinker_url):
41 return {'formats': [{'url': relinker_url}]}
42
034a8849 43 formats = []
b8d8cced
S
44 geoprotection = None
45 is_live = None
46 duration = None
034a8849
YCH
47
48 for platform in ('mon', 'flash', 'native'):
034a8849
YCH
49 relinker = self._download_xml(
50 relinker_url, video_id,
51 note='Downloading XML metadata for platform %s' % platform,
52 transform_source=fix_xml_ampersands,
38cce791
YCH
53 query={'output': 45, 'pl': platform},
54 headers=self.geo_verification_headers())
034a8849 55
b8d8cced
S
56 if not geoprotection:
57 geoprotection = xpath_text(
58 relinker, './geoprotection', default=None) == 'Y'
59
60 if not is_live:
61 is_live = xpath_text(
62 relinker, './is_live', default=None) == 'Y'
63 if not duration:
64 duration = parse_duration(xpath_text(
65 relinker, './duration', default=None))
66
67 url_elem = find_xpath_attr(relinker, './url', 'type', 'content')
68 if url_elem is None:
69 continue
70
71 media_url = url_elem.text
72
73 # This does not imply geo restriction (e.g.
74 # http://www.raisport.rai.it/dl/raiSport/media/rassegna-stampa-04a9f4bd-b563-40cf-82a6-aad3529cb4a9.html)
a0566bbf 75 if '/video_no_available.mp4' in media_url:
b8d8cced 76 continue
034a8849
YCH
77
78 ext = determine_ext(media_url)
79 if (ext == 'm3u8' and platform != 'mon') or (ext == 'f4m' and platform != 'flash'):
80 continue
81
0df11daf 82 if ext == 'mp3':
83 formats.append({
84 'url': media_url,
85 'vcodec': 'none',
86 'acodec': 'mp3',
87 'format_id': 'http-mp3',
88 })
89 break
90 elif ext == 'm3u8' or 'format=m3u8' in media_url or platform == 'mon':
034a8849
YCH
91 formats.extend(self._extract_m3u8_formats(
92 media_url, video_id, 'mp4', 'm3u8_native',
93 m3u8_id='hls', fatal=False))
c17eb5b4 94 elif ext == 'f4m' or platform == 'flash':
034a8849
YCH
95 manifest_url = update_url_query(
96 media_url.replace('manifest#live_hds.f4m', 'manifest.f4m'),
97 {'hdcore': '3.7.0', 'plugin': 'aasp-3.7.0.39.44'})
98 formats.extend(self._extract_f4m_formats(
99 manifest_url, video_id, f4m_id='hds', fatal=False))
100 else:
101 bitrate = int_or_none(xpath_text(relinker, 'bitrate'))
102 formats.append({
103 'url': media_url,
104 'tbr': bitrate if bitrate > 0 else None,
105 'format_id': 'http-%d' % bitrate if bitrate > 0 else 'http',
106 })
107
b8d8cced 108 if not formats and geoprotection is True:
b7da73eb 109 self.raise_geo_restricted(countries=self._GEO_COUNTRIES, metadata_available=True)
b8d8cced 110
0df11daf 111 if not audio_only:
112 formats.extend(self._create_http_urls(relinker_url, formats))
b9d68c19 113
90137ca4 114 return filter_dict({
b8d8cced
S
115 'is_live': is_live,
116 'duration': duration,
117 'formats': formats,
90137ca4 118 })
034a8849 119
b9d68c19 120 def _create_http_urls(self, relinker_url, fmts):
121 _RELINKER_REG = r'https?://(?P<host>[^/]+?)/(?:i/)?(?P<extra>[^/]+?)/(?P<path>.+?)/(?P<id>\d+)(?:_(?P<quality>[\d\,]+))?(?:\.mp4|/playlist\.m3u8).+?'
122 _MP4_TMPL = '%s&overrideUserAgentRule=mp4-%s'
123 _QUALITY = {
124 # tbr: w, h
125 '250': [352, 198],
126 '400': [512, 288],
127 '700': [512, 288],
128 '800': [700, 394],
129 '1200': [736, 414],
130 '1800': [1024, 576],
131 '2400': [1280, 720],
132 '3200': [1440, 810],
133 '3600': [1440, 810],
134 '5000': [1920, 1080],
135 '10000': [1920, 1080],
136 }
137
138 def test_url(url):
139 resp = self._request_webpage(
140 HEADRequest(url), None, headers={'User-Agent': 'Rai'},
141 fatal=False, errnote=False, note=False)
142
143 if resp is False:
144 return False
145
146 if resp.code == 200:
147 return False if resp.url == url else resp.url
148 return None
149
99148c6a 150 # filter out audio-only formats
151 fmts = [f for f in fmts if not f.get('vcodec') == 'none']
152
b9d68c19 153 def get_format_info(tbr):
154 import math
155 br = int_or_none(tbr)
156 if len(fmts) == 1 and not br:
157 br = fmts[0].get('tbr')
158 if br > 300:
159 tbr = compat_str(math.floor(br / 100) * 100)
160 else:
161 tbr = '250'
162
163 # try extracting info from available m3u8 formats
164 format_copy = None
165 for f in fmts:
166 if f.get('tbr'):
167 br_limit = math.floor(br / 100)
168 if br_limit - 1 <= math.floor(f['tbr'] / 100) <= br_limit + 1:
169 format_copy = f.copy()
170 return {
171 'width': format_copy.get('width'),
172 'height': format_copy.get('height'),
173 'tbr': format_copy.get('tbr'),
174 'vcodec': format_copy.get('vcodec'),
175 'acodec': format_copy.get('acodec'),
176 'fps': format_copy.get('fps'),
177 'format_id': 'https-%s' % tbr,
178 } if format_copy else {
179 'width': _QUALITY[tbr][0],
180 'height': _QUALITY[tbr][1],
181 'format_id': 'https-%s' % tbr,
182 'tbr': int(tbr),
183 }
184
185 loc = test_url(_MP4_TMPL % (relinker_url, '*'))
186 if not isinstance(loc, compat_str):
187 return []
188
189 mobj = re.match(
190 _RELINKER_REG,
191 test_url(relinker_url) or '')
192 if not mobj:
193 return []
194
195 available_qualities = mobj.group('quality').split(',') if mobj.group('quality') else ['*']
196 available_qualities = [i for i in available_qualities if i]
197
198 formats = []
199 for q in available_qualities:
200 fmt = {
201 'url': _MP4_TMPL % (relinker_url, q),
202 'protocol': 'https',
203 'ext': 'mp4',
204 }
205 fmt.update(get_format_info(q))
206 formats.append(fmt)
207 return formats
208
1b3feca0 209 @staticmethod
00dd0cd5 210 def _extract_subtitles(url, video_data):
211 STL_EXT = 'stl'
212 SRT_EXT = 'srt'
1b3feca0 213 subtitles = {}
00dd0cd5 214 subtitles_array = video_data.get('subtitlesArray') or []
215 for k in ('subtitles', 'subtitlesUrl'):
216 subtitles_array.append({'url': video_data.get(k)})
217 for subtitle in subtitles_array:
218 sub_url = subtitle.get('url')
219 if sub_url and isinstance(sub_url, compat_str):
220 sub_lang = subtitle.get('language') or 'it'
221 sub_url = urljoin(url, sub_url)
222 sub_ext = determine_ext(sub_url, SRT_EXT)
223 subtitles.setdefault(sub_lang, []).append({
224 'ext': sub_ext,
225 'url': sub_url,
1b3feca0 226 })
00dd0cd5 227 if STL_EXT == sub_ext:
228 subtitles[sub_lang].append({
229 'ext': SRT_EXT,
230 'url': sub_url[:-len(STL_EXT)] + SRT_EXT,
231 })
1b3feca0
S
232 return subtitles
233
2b28b892 234
51342717 235class RaiPlayIE(RaiBaseIE):
a0566bbf 236 _VALID_URL = r'(?P<base>https?://(?:www\.)?raiplay\.it/.+?-(?P<id>%s))\.(?:html|json)' % RaiBaseIE._UUID_RE
51342717 237 _TESTS = [{
51342717
T
238 'url': 'http://www.raiplay.it/video/2014/04/Report-del-07042014-cb27157f-9dd0-4aee-b788-b1f67643a391.html',
239 'md5': '8970abf8caf8aef4696e7b1f2adfc696',
240 'info_dict': {
241 'id': 'cb27157f-9dd0-4aee-b788-b1f67643a391',
242 'ext': 'mp4',
b8d8cced 243 'title': 'Report del 07/04/2014',
99148c6a 244 'alt_title': 'St 2013/14 - Report - Espresso nel caffè - 07/04/2014',
abea9145 245 'description': 'md5:d730c168a58f4bb35600fc2f881ec04e',
51342717 246 'thumbnail': r're:^https?://.*\.jpg$',
abea9145 247 'uploader': 'Rai Gulp',
b8d8cced 248 'duration': 6160,
8bdd16b4 249 'series': 'Report',
250 'season': '2013/14',
00dd0cd5 251 'subtitles': {
99148c6a 252 'it': 'count:4',
00dd0cd5 253 },
b8d8cced
S
254 },
255 'params': {
256 'skip_download': True,
257 },
b9d68c19 258 }, {
259 # 1080p direct mp4 url
99148c6a 260 'url': 'https://www.raiplay.it/video/2021/11/Blanca-S1E1-Senza-occhi-b1255a4a-8e72-4a2f-b9f3-fc1308e00736.html',
261 'md5': 'aeda7243115380b2dd5e881fd42d949a',
b9d68c19 262 'info_dict': {
99148c6a 263 'id': 'b1255a4a-8e72-4a2f-b9f3-fc1308e00736',
b9d68c19 264 'ext': 'mp4',
99148c6a 265 'title': 'Blanca - S1E1 - Senza occhi',
266 'alt_title': 'St 1 Ep 1 - Blanca - Senza occhi',
267 'description': 'md5:75f95d5c030ec8bac263b1212322e28c',
b9d68c19 268 'thumbnail': r're:^https?://.*\.jpg$',
269 'uploader': 'Rai 1',
99148c6a 270 'duration': 6493,
271 'series': 'Blanca',
b9d68c19 272 'season': 'Season 1',
273 },
b8d8cced
S
274 }, {
275 'url': 'http://www.raiplay.it/video/2016/11/gazebotraindesi-efebe701-969c-4593-92f3-285f0d1ce750.html?',
276 'only_matching': True,
00dd0cd5 277 }, {
278 # subtitles at 'subtitlesArray' key (see #27698)
279 'url': 'https://www.raiplay.it/video/2020/12/Report---04-01-2021-2e90f1de-8eee-4de4-ac0e-78d21db5b600.html',
280 'only_matching': True,
0852947f 281 }, {
282 # DRM protected
283 'url': 'https://www.raiplay.it/video/2020/09/Lo-straordinario-mondo-di-Zoey-S1E1-Lo-straordinario-potere-di-Zoey-ed493918-1d32-44b7-8454-862e473d00ff.html',
284 'only_matching': True,
51342717 285 }]
2b28b892 286
51342717 287 def _real_extract(self, url):
5ad28e7f 288 base, video_id = self._match_valid_url(url).groups()
2b28b892 289
b8d8cced 290 media = self._download_json(
a0566bbf 291 base + '.json', video_id, 'Downloading video JSON')
2b28b892 292
a06916d9 293 if not self.get_param('allow_unplayable_formats'):
0852947f 294 if try_get(
295 media,
296 (lambda x: x['rights_management']['rights']['drm'],
297 lambda x: x['program_info']['rights_management']['rights']['drm']),
298 dict):
88acdbc2 299 self.report_drm(video_id)
0852947f 300
b8d8cced 301 title = media['name']
b8d8cced
S
302 video = media['video']
303
abea9145 304 relinker_info = self._extract_relinker_info(video['content_url'], video_id)
b8d8cced 305 self._sort_formats(relinker_info['formats'])
2b28b892 306
51342717 307 thumbnails = []
8bdd16b4 308 for _, value in media.get('images', {}).items():
309 if value:
310 thumbnails.append({
311 'url': urljoin(url, value),
312 })
034a8849 313
8bdd16b4 314 date_published = media.get('date_published')
315 time_published = media.get('time_published')
316 if date_published and time_published:
317 date_published += ' ' + time_published
b0adbe98 318
00dd0cd5 319 subtitles = self._extract_subtitles(url, video)
1b3feca0 320
8bdd16b4 321 program_info = media.get('program_info') or {}
322 season = media.get('season')
323
99148c6a 324 alt_title = join_nonempty(media.get('subtitle'), media.get('toptitle'), delim=' - ')
325
b8d8cced 326 info = {
a0566bbf 327 'id': remove_start(media.get('id'), 'ContentItem-') or video_id,
328 'display_id': video_id,
39ca3b5c 329 'title': title,
99148c6a 330 'alt_title': strip_or_none(alt_title),
b8d8cced 331 'description': media.get('description'),
9c48b5a1 332 'uploader': strip_or_none(media.get('channel')),
8bdd16b4 333 'creator': strip_or_none(media.get('editor') or None),
b8d8cced 334 'duration': parse_duration(video.get('duration')),
8bdd16b4 335 'timestamp': unified_timestamp(date_published),
51342717 336 'thumbnails': thumbnails,
8bdd16b4 337 'series': program_info.get('name'),
338 'season_number': int_or_none(season),
339 'season': season if (season and not season.isdigit()) else None,
340 'episode': media.get('episode_title'),
341 'episode_number': int_or_none(media.get('episode')),
1b3feca0 342 'subtitles': subtitles,
51342717 343 }
b0adbe98 344
b8d8cced 345 info.update(relinker_info)
b8d8cced
S
346 return info
347
06d5556d 348
a0566bbf 349class RaiPlayLiveIE(RaiPlayIE):
350 _VALID_URL = r'(?P<base>https?://(?:www\.)?raiplay\.it/dirette/(?P<id>[^/?#&]+))'
351 _TESTS = [{
9c48b5a1
S
352 'url': 'http://www.raiplay.it/dirette/rainews24',
353 'info_dict': {
354 'id': 'd784ad40-e0ae-4a69-aa76-37519d238a9c',
355 'display_id': 'rainews24',
356 'ext': 'mp4',
357 'title': 're:^Diretta di Rai News 24 [0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}$',
a0566bbf 358 'description': 'md5:4d00bcf6dc98b27c6ec480de329d1497',
9c48b5a1
S
359 'uploader': 'Rai News 24',
360 'creator': 'Rai News 24',
361 'is_live': True,
362 },
363 'params': {
364 'skip_download': True,
365 },
a0566bbf 366 }]
449c6657 367
368
1115271a 369class RaiPlayPlaylistIE(InfoExtractor):
0df11daf 370 _VALID_URL = r'(?P<base>https?://(?:www\.)?raiplay\.it/programmi/(?P<id>[^/?#&]+))(?:/(?P<extra_id>[^?#&]+))?'
1115271a 371 _TESTS = [{
0df11daf 372 'url': 'https://www.raiplay.it/programmi/nondirloalmiocapo/',
1115271a
S
373 'info_dict': {
374 'id': 'nondirloalmiocapo',
375 'title': 'Non dirlo al mio capo',
a0566bbf 376 'description': 'md5:98ab6b98f7f44c2843fd7d6f045f153b',
1115271a
S
377 },
378 'playlist_mincount': 12,
0df11daf 379 }, {
380 'url': 'https://www.raiplay.it/programmi/nondirloalmiocapo/episodi/stagione-2/',
381 'info_dict': {
382 'id': 'nondirloalmiocapo',
383 'title': 'Non dirlo al mio capo - Stagione 2',
384 'description': 'md5:98ab6b98f7f44c2843fd7d6f045f153b',
385 },
386 'playlist_mincount': 12,
1115271a
S
387 }]
388
389 def _real_extract(self, url):
0df11daf 390 base, playlist_id, extra_id = self._match_valid_url(url).groups()
1115271a 391
a0566bbf 392 program = self._download_json(
393 base + '.json', playlist_id, 'Downloading program JSON')
1115271a 394
0df11daf 395 if extra_id:
396 extra_id = extra_id.upper().rstrip('/')
397
398 playlist_title = program.get('name')
1115271a 399 entries = []
a0566bbf 400 for b in (program.get('blocks') or []):
401 for s in (b.get('sets') or []):
0df11daf 402 if extra_id:
403 if extra_id != join_nonempty(
404 b.get('name'), s.get('name'), delim='/').replace(' ', '-').upper():
405 continue
406 playlist_title = join_nonempty(playlist_title, s.get('name'), delim=' - ')
407
a0566bbf 408 s_id = s.get('id')
409 if not s_id:
410 continue
411 medias = self._download_json(
412 '%s/%s.json' % (base, s_id), s_id,
413 'Downloading content set JSON', fatal=False)
414 if not medias:
415 continue
416 for m in (medias.get('items') or []):
417 path_id = m.get('path_id')
418 if not path_id:
419 continue
420 video_url = urljoin(url, path_id)
421 entries.append(self.url_result(
422 video_url, ie=RaiPlayIE.ie_key(),
423 video_id=RaiPlayIE._match_id(video_url)))
424
425 return self.playlist_result(
0df11daf 426 entries, playlist_id, playlist_title,
a0566bbf 427 try_get(program, lambda x: x['program_info']['description']))
1115271a
S
428
429
0df11daf 430class RaiPlaySoundIE(RaiBaseIE):
431 _VALID_URL = r'(?P<base>https?://(?:www\.)?raiplaysound\.it/.+?-(?P<id>%s))\.(?:html|json)' % RaiBaseIE._UUID_RE
432 _TESTS = [{
433 'url': 'https://www.raiplaysound.it/audio/2021/12/IL-RUGGITO-DEL-CONIGLIO-1ebae2a7-7cdb-42bb-842e-fe0d193e9707.html',
434 'md5': '8970abf8caf8aef4696e7b1f2adfc696',
435 'info_dict': {
436 'id': '1ebae2a7-7cdb-42bb-842e-fe0d193e9707',
437 'ext': 'mp3',
438 'title': 'Il Ruggito del Coniglio del 10/12/2021',
439 'description': 'md5:2a17d2107e59a4a8faa0e18334139ee2',
440 'thumbnail': r're:^https?://.*\.jpg$',
441 'uploader': 'rai radio 2',
442 'duration': 5685,
443 'series': 'Il Ruggito del Coniglio',
444 },
445 'params': {
446 'skip_download': True,
447 },
448 }]
449
450 def _real_extract(self, url):
451 base, audio_id = self._match_valid_url(url).group('base', 'id')
452 media = self._download_json(f'{base}.json', audio_id, 'Downloading audio JSON')
453 uid = try_get(media, lambda x: remove_start(remove_start(x['uniquename'], 'ContentItem-'), 'Page-'))
454
455 info = {}
456 formats = []
457 relinkers = set(traverse_obj(media, (('downloadable_audio', 'audio', ('live', 'cards', 0, 'audio')), 'url')))
458 for r in relinkers:
459 info = self._extract_relinker_info(r, audio_id, True)
460 formats.extend(info.get('formats'))
461
462 date_published = try_get(media, (lambda x: f'{x["create_date"]} {x.get("create_time") or ""}',
463 lambda x: x['live']['create_date']))
464
465 podcast_info = traverse_obj(media, 'podcast_info', ('live', 'cards', 0)) or {}
466 thumbnails = [{
467 'url': urljoin(url, thumb_url),
468 } for thumb_url in (podcast_info.get('images') or {}).values() if thumb_url]
469
470 return {
471 **info,
472 'id': uid or audio_id,
473 'display_id': audio_id,
474 'title': traverse_obj(media, 'title', 'episode_title'),
475 'alt_title': traverse_obj(media, ('track_info', 'media_name')),
476 'description': media.get('description'),
477 'uploader': traverse_obj(media, ('track_info', 'channel'), expected_type=strip_or_none),
478 'creator': traverse_obj(media, ('track_info', 'editor'), expected_type=strip_or_none),
479 'timestamp': unified_timestamp(date_published),
480 'thumbnails': thumbnails,
481 'series': podcast_info.get('title'),
482 'season_number': int_or_none(media.get('season')),
483 'episode': media.get('episode_title'),
484 'episode_number': int_or_none(media.get('episode')),
485 'formats': formats,
486 }
487
488
489class RaiPlaySoundLiveIE(RaiPlaySoundIE):
490 _VALID_URL = r'(?P<base>https?://(?:www\.)?raiplaysound\.it/(?P<id>[^/?#&]+)$)'
491 _TESTS = [{
492 'url': 'https://www.raiplaysound.it/radio2',
493 'info_dict': {
494 'id': 'b00a50e6-f404-4af6-8f8c-ff3b9af73a44',
495 'display_id': 'radio2',
496 'ext': 'mp4',
497 'title': 'Rai Radio 2',
498 'uploader': 'rai radio 2',
499 'creator': 'raiplaysound',
500 'is_live': True,
501 },
502 'params': {
503 'skip_download': 'live',
504 },
505 }]
506
507
508class RaiPlaySoundPlaylistIE(InfoExtractor):
509 _VALID_URL = r'(?P<base>https?://(?:www\.)?raiplaysound\.it/(?:programmi|playlist|audiolibri)/(?P<id>[^/?#&]+))(?:/(?P<extra_id>[^?#&]+))?'
510 _TESTS = [{
511 'url': 'https://www.raiplaysound.it/programmi/ilruggitodelconiglio',
512 'info_dict': {
513 'id': 'ilruggitodelconiglio',
514 'title': 'Il Ruggito del Coniglio',
515 'description': 'md5:1bbaf631245a7ab1ec4d9fbb3c7aa8f3',
516 },
517 'playlist_mincount': 65,
518 }, {
519 'url': 'https://www.raiplaysound.it/programmi/ilruggitodelconiglio/puntate/prima-stagione-1995',
520 'info_dict': {
521 'id': 'ilruggitodelconiglio_puntate_prima-stagione-1995',
522 'title': 'Prima Stagione 1995',
523 },
524 'playlist_count': 1,
525 }]
526
527 def _real_extract(self, url):
528 base, playlist_id, extra_id = self._match_valid_url(url).group('base', 'id', 'extra_id')
529 url = f'{base}.json'
530 program = self._download_json(url, playlist_id, 'Downloading program JSON')
531
532 if extra_id:
533 extra_id = extra_id.rstrip('/')
534 playlist_id += '_' + extra_id.replace('/', '_')
535 path = next(c['path_id'] for c in program.get('filters') or [] if extra_id in c.get('weblink'))
536 program = self._download_json(
537 urljoin('https://www.raiplaysound.it', path), playlist_id, 'Downloading program secondary JSON')
538
539 entries = [
540 self.url_result(urljoin(base, c['path_id']), ie=RaiPlaySoundIE.ie_key())
541 for c in traverse_obj(program, 'cards', ('block', 'cards')) or []
542 if c.get('path_id')]
543
544 return self.playlist_result(entries, playlist_id, program.get('title'),
545 traverse_obj(program, ('podcast_info', 'description')))
546
547
034a8849 548class RaiIE(RaiBaseIE):
2b2da3ba 549 _VALID_URL = r'https?://[^/]+\.(?:rai\.(?:it|tv)|rainews\.it)/.+?-(?P<id>%s)(?:-.+?)?\.html' % RaiBaseIE._UUID_RE
51342717 550 _TESTS = [{
b8d8cced
S
551 # var uniquename = "ContentItem-..."
552 # data-id="ContentItem-..."
51342717
T
553 'url': 'http://www.raisport.rai.it/dl/raiSport/media/rassegna-stampa-04a9f4bd-b563-40cf-82a6-aad3529cb4a9.html',
554 'info_dict': {
555 'id': '04a9f4bd-b563-40cf-82a6-aad3529cb4a9',
556 'ext': 'mp4',
557 'title': 'TG PRIMO TEMPO',
b8d8cced 558 'thumbnail': r're:^https?://.*\.jpg$',
51342717 559 'duration': 1758,
b8d8cced 560 'upload_date': '20140612',
8bdd16b4 561 },
562 'skip': 'This content is available only in Italy',
51342717 563 }, {
b8d8cced 564 # with ContentItem in many metas
51342717
T
565 'url': 'http://www.rainews.it/dl/rainews/media/Weekend-al-cinema-da-Hollywood-arriva-il-thriller-di-Tate-Taylor-La-ragazza-del-treno-1632c009-c843-4836-bb65-80c33084a64b.html',
566 'info_dict': {
567 'id': '1632c009-c843-4836-bb65-80c33084a64b',
568 'ext': 'mp4',
b8d8cced
S
569 'title': 'Weekend al cinema, da Hollywood arriva il thriller di Tate Taylor "La ragazza del treno"',
570 'description': 'I film in uscita questa settimana.',
51342717 571 'thumbnail': r're:^https?://.*\.png$',
b8d8cced
S
572 'duration': 833,
573 'upload_date': '20161103',
51342717
T
574 }
575 }, {
b8d8cced 576 # with ContentItem in og:url
51342717 577 'url': 'http://www.rai.it/dl/RaiTV/programmi/media/ContentItem-efb17665-691c-45d5-a60c-5301333cbb0c.html',
b9d68c19 578 'md5': '06345bd97c932f19ffb129973d07a020',
51342717
T
579 'info_dict': {
580 'id': 'efb17665-691c-45d5-a60c-5301333cbb0c',
581 'ext': 'mp4',
582 'title': 'TG1 ore 20:00 del 03/11/2016',
b8d8cced 583 'description': 'TG1 edizione integrale ore 20:00 del giorno 03/11/2016',
51342717 584 'thumbnail': r're:^https?://.*\.jpg$',
b8d8cced 585 'duration': 2214,
51342717 586 'upload_date': '20161103',
51342717 587 }
51342717 588 }, {
b8d8cced
S
589 # initEdizione('ContentItem-...'
590 'url': 'http://www.tg1.rai.it/dl/tg1/2010/edizioni/ContentSet-9b6e0cba-4bef-4aef-8cf0-9f7f665b7dfb-tg1.html?item=undefined',
591 'info_dict': {
592 'id': 'c2187016-8484-4e3a-8ac8-35e475b07303',
593 'ext': 'mp4',
594 'title': r're:TG1 ore \d{2}:\d{2} del \d{2}/\d{2}/\d{4}',
595 'duration': 2274,
596 'upload_date': '20170401',
597 },
598 'skip': 'Changes daily',
51342717 599 }, {
b8d8cced 600 # HLS live stream with ContentItem in og:url
51342717 601 'url': 'http://www.rainews.it/dl/rainews/live/ContentItem-3156f2f2-dc70-4953-8e2f-70d7489d4ce9.html',
51342717
T
602 'info_dict': {
603 'id': '3156f2f2-dc70-4953-8e2f-70d7489d4ce9',
604 'ext': 'mp4',
605 'title': 'La diretta di Rainews24',
15e4b6b7 606 },
b8d8cced
S
607 'params': {
608 'skip_download': True,
609 },
0c7b4f49
RA
610 }, {
611 # Direct MMS URL
612 'url': 'http://www.rai.it/dl/RaiTV/programmi/media/ContentItem-b63a4089-ac28-48cf-bca5-9f5b5bc46df5.html',
613 'only_matching': True,
2b2da3ba
S
614 }, {
615 'url': 'https://www.rainews.it/tgr/marche/notiziari/video/2019/02/ContentItem-6ba945a2-889c-4a80-bdeb-8489c70a8db9.html',
616 'only_matching': True,
51342717 617 }]
06d5556d 618
51342717
T
619 def _extract_from_content_id(self, content_id, url):
620 media = self._download_json(
621 'http://www.rai.tv/dl/RaiTV/programmi/media/ContentItem-%s.html?json' % content_id,
622 content_id, 'Downloading video JSON')
623
b8d8cced
S
624 title = media['name'].strip()
625
626 media_type = media['type']
627 if 'Audio' in media_type:
628 relinker_info = {
085d9dd9 629 'formats': [{
b8d8cced
S
630 'format_id': media.get('formatoAudio'),
631 'url': media['audioUrl'],
632 'ext': media.get('formatoAudio'),
085d9dd9 633 }]
b8d8cced
S
634 }
635 elif 'Video' in media_type:
636 relinker_info = self._extract_relinker_info(media['mediaUri'], content_id)
637 else:
638 raise ExtractorError('not a media file')
639
640 self._sort_formats(relinker_info['formats'])
641
51342717
T
642 thumbnails = []
643 for image_type in ('image', 'image_medium', 'image_300'):
644 thumbnail_url = media.get(image_type)
645 if thumbnail_url:
646 thumbnails.append({
647 'url': compat_urlparse.urljoin(url, thumbnail_url),
648 })
649
00dd0cd5 650 subtitles = self._extract_subtitles(url, media)
51342717 651
b8d8cced 652 info = {
51342717 653 'id': content_id,
b8d8cced
S
654 'title': title,
655 'description': strip_or_none(media.get('desc')),
51342717
T
656 'thumbnails': thumbnails,
657 'uploader': media.get('author'),
658 'upload_date': unified_strdate(media.get('date')),
659 'duration': parse_duration(media.get('length')),
51342717
T
660 'subtitles': subtitles,
661 }
b8d8cced
S
662
663 info.update(relinker_info)
664
665 return info
666
667 def _real_extract(self, url):
668 video_id = self._match_id(url)
669
670 webpage = self._download_webpage(url, video_id)
671
672 content_item_id = None
673
674 content_item_url = self._html_search_meta(
675 ('og:url', 'og:video', 'og:video:secure_url', 'twitter:url',
676 'twitter:player', 'jsonlink'), webpage, default=None)
677 if content_item_url:
678 content_item_id = self._search_regex(
679 r'ContentItem-(%s)' % self._UUID_RE, content_item_url,
680 'content item id', default=None)
681
682 if not content_item_id:
683 content_item_id = self._search_regex(
684 r'''(?x)
685 (?:
686 (?:initEdizione|drawMediaRaiTV)\(|
00dd0cd5 687 <(?:[^>]+\bdata-id|var\s+uniquename)=|
688 <iframe[^>]+\bsrc=
b8d8cced
S
689 )
690 (["\'])
691 (?:(?!\1).)*\bContentItem-(?P<id>%s)
692 ''' % self._UUID_RE,
693 webpage, 'content item id', default=None, group='id')
694
695 content_item_ids = set()
361f293a
S
696 if content_item_id:
697 content_item_ids.add(content_item_id)
b8d8cced
S
698 if video_id not in content_item_ids:
699 content_item_ids.add(video_id)
700
701 for content_item_id in content_item_ids:
702 try:
703 return self._extract_from_content_id(content_item_id, url)
704 except GeoRestrictedError:
705 raise
706 except ExtractorError:
707 pass
708
a0566bbf 709 relinker_url = self._proto_relative_url(self._search_regex(
b8d8cced
S
710 r'''(?x)
711 (?:
712 var\s+videoURL|
713 mediaInfo\.mediaUri
714 )\s*=\s*
715 ([\'"])
716 (?P<url>
717 (?:https?:)?
718 //mediapolis(?:vod)?\.rai\.it/relinker/relinkerServlet\.htm\?
719 (?:(?!\1).)*\bcont=(?:(?!\1).)+)\1
720 ''',
a0566bbf 721 webpage, 'relinker URL', group='url'))
b8d8cced
S
722
723 relinker_info = self._extract_relinker_info(
724 urljoin(url, relinker_url), video_id)
725 self._sort_formats(relinker_info['formats'])
726
727 title = self._search_regex(
728 r'var\s+videoTitolo\s*=\s*([\'"])(?P<title>[^\'"]+)\1',
729 webpage, 'title', group='title',
730 default=None) or self._og_search_title(webpage)
731
732 info = {
733 'id': video_id,
734 'title': title,
735 }
736
737 info.update(relinker_info)
738
739 return info