]> jfr.im git - yt-dlp.git/blob - yt_dlp/extractor/rai.py
[ie/FlexTV] Add extractor (#9178)
[yt-dlp.git] / yt_dlp / extractor / rai.py
1 import re
2
3 from .common import InfoExtractor
4 from ..networking import HEADRequest
5 from ..utils import (
6 clean_html,
7 determine_ext,
8 ExtractorError,
9 filter_dict,
10 GeoRestrictedError,
11 int_or_none,
12 join_nonempty,
13 parse_duration,
14 remove_start,
15 strip_or_none,
16 traverse_obj,
17 try_get,
18 unified_strdate,
19 unified_timestamp,
20 update_url_query,
21 urljoin,
22 xpath_text,
23 )
24
25
26 class RaiBaseIE(InfoExtractor):
27 _UUID_RE = r'[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}'
28 _GEO_COUNTRIES = ['IT']
29 _GEO_BYPASS = False
30
31 def _extract_relinker_info(self, relinker_url, video_id, audio_only=False):
32 def fix_cdata(s):
33 # remove \r\n\t before and after <![CDATA[ ]]> to avoid
34 # polluted text with xpath_text
35 s = re.sub(r'(\]\]>)[\r\n\t]+(</)', '\\1\\2', s)
36 return re.sub(r'(>)[\r\n\t]+(<!\[CDATA\[)', '\\1\\2', s)
37
38 if not re.match(r'https?://', relinker_url):
39 return {'formats': [{'url': relinker_url}]}
40
41 # set User-Agent to generic 'Rai' to avoid quality filtering from
42 # the media server and get the maximum qualities available
43 relinker = self._download_xml(
44 relinker_url, video_id, note='Downloading XML metadata',
45 transform_source=fix_cdata, query={'output': 64},
46 headers={**self.geo_verification_headers(), 'User-Agent': 'Rai'})
47
48 if xpath_text(relinker, './license_url', default='{}') != '{}':
49 self.report_drm(video_id)
50
51 is_live = xpath_text(relinker, './is_live', default='N') == 'Y'
52 duration = parse_duration(xpath_text(relinker, './duration', default=None))
53 media_url = xpath_text(relinker, './url[@type="content"]', default=None)
54
55 if not media_url:
56 self.raise_no_formats('The relinker returned no media url')
57
58 # geo flag is a bit unreliable and not properly set all the time
59 geoprotection = xpath_text(relinker, './geoprotection', default='N') == 'Y'
60
61 ext = determine_ext(media_url)
62 formats = []
63
64 if ext == 'mp3':
65 formats.append({
66 'url': media_url,
67 'vcodec': 'none',
68 'acodec': 'mp3',
69 'format_id': 'https-mp3',
70 })
71 elif ext == 'm3u8' or 'format=m3u8' in media_url:
72 formats.extend(self._extract_m3u8_formats(
73 media_url, video_id, 'mp4', m3u8_id='hls', fatal=False))
74 elif ext == 'f4m':
75 # very likely no longer needed. Cannot find any url that uses it.
76 manifest_url = update_url_query(
77 media_url.replace('manifest#live_hds.f4m', 'manifest.f4m'),
78 {'hdcore': '3.7.0', 'plugin': 'aasp-3.7.0.39.44'})
79 formats.extend(self._extract_f4m_formats(
80 manifest_url, video_id, f4m_id='hds', fatal=False))
81 elif ext == 'mp4':
82 bitrate = int_or_none(xpath_text(relinker, './bitrate'))
83 formats.append({
84 'url': media_url,
85 'tbr': bitrate if bitrate > 0 else None,
86 'format_id': join_nonempty('https', bitrate, delim='-'),
87 })
88 else:
89 raise ExtractorError('Unrecognized media file found')
90
91 if (not formats and geoprotection is True) or '/video_no_available.mp4' in media_url:
92 self.raise_geo_restricted(countries=self._GEO_COUNTRIES, metadata_available=True)
93
94 if not audio_only and not is_live:
95 formats.extend(self._create_http_urls(media_url, relinker_url, formats, video_id))
96
97 return filter_dict({
98 'is_live': is_live,
99 'duration': duration,
100 'formats': formats,
101 })
102
103 def _create_http_urls(self, manifest_url, relinker_url, fmts, video_id):
104 _MANIFEST_REG = r'/(?P<id>\w+)(?:_(?P<quality>[\d\,]+))?(?:\.mp4)?(?:\.csmil)?/playlist\.m3u8'
105 _MP4_TMPL = '%s&overrideUserAgentRule=mp4-%s'
106 _QUALITY = {
107 # tbr: w, h
108 250: [352, 198],
109 400: [512, 288],
110 600: [512, 288],
111 700: [512, 288],
112 800: [700, 394],
113 1200: [736, 414],
114 1500: [920, 518],
115 1800: [1024, 576],
116 2400: [1280, 720],
117 3200: [1440, 810],
118 3600: [1440, 810],
119 5000: [1920, 1080],
120 10000: [1920, 1080],
121 }
122
123 def percentage(number, target, pc=20, roof=125):
124 '''check if the target is in the range of number +/- percent'''
125 if not number or number < 0:
126 return False
127 return abs(target - number) < min(float(number) * float(pc) / 100.0, roof)
128
129 def get_format_info(tbr):
130 import math
131 br = int_or_none(tbr)
132 if len(fmts) == 1 and not br:
133 br = fmts[0].get('tbr')
134 if br and br > 300:
135 tbr = math.floor(br / 100) * 100
136 else:
137 tbr = 250
138
139 # try extracting info from available m3u8 formats
140 format_copy = [None, None]
141 for f in fmts:
142 if f.get('tbr'):
143 if percentage(tbr, f['tbr']):
144 format_copy[0] = f.copy()
145 if [f.get('width'), f.get('height')] == _QUALITY.get(tbr):
146 format_copy[1] = f.copy()
147 format_copy[1]['tbr'] = tbr
148
149 # prefer format with similar bitrate because there might be
150 # multiple video with the same resolution but different bitrate
151 format_copy = format_copy[0] or format_copy[1] or {}
152 return {
153 'format_id': f'https-{tbr}',
154 'width': format_copy.get('width'),
155 'height': format_copy.get('height'),
156 'tbr': format_copy.get('tbr'),
157 'vcodec': format_copy.get('vcodec'),
158 'acodec': format_copy.get('acodec'),
159 'fps': format_copy.get('fps'),
160 } if format_copy else {
161 'format_id': f'https-{tbr}',
162 'width': _QUALITY[tbr][0],
163 'height': _QUALITY[tbr][1],
164 'tbr': tbr,
165 'vcodec': 'avc1',
166 'acodec': 'mp4a',
167 'fps': 25,
168 }
169
170 # Check if MP4 download is available
171 try:
172 self._request_webpage(
173 HEADRequest(_MP4_TMPL % (relinker_url, '*')), video_id, 'Checking MP4 availability')
174 except ExtractorError as e:
175 self.to_screen(f'{video_id}: MP4 direct download is not available: {e.cause}')
176 return []
177
178 # filter out single-stream formats
179 fmts = [f for f in fmts
180 if not f.get('vcodec') == 'none' and not f.get('acodec') == 'none']
181
182 mobj = re.search(_MANIFEST_REG, manifest_url)
183 if not mobj:
184 return []
185 available_qualities = mobj.group('quality').split(',') if mobj.group('quality') else ['*']
186
187 formats = []
188 for q in filter(None, available_qualities):
189 self.write_debug(f'Creating https format for quality {q}')
190 formats.append({
191 'url': _MP4_TMPL % (relinker_url, q),
192 'protocol': 'https',
193 'ext': 'mp4',
194 **get_format_info(q)
195 })
196 return formats
197
198 @staticmethod
199 def _get_thumbnails_list(thumbs, url):
200 return [{
201 'url': urljoin(url, thumb_url),
202 } for thumb_url in (thumbs or {}).values() if thumb_url]
203
204 @staticmethod
205 def _extract_subtitles(url, video_data):
206 STL_EXT = 'stl'
207 SRT_EXT = 'srt'
208 subtitles = {}
209 subtitles_array = video_data.get('subtitlesArray') or video_data.get('subtitleList') or []
210 for k in ('subtitles', 'subtitlesUrl'):
211 subtitles_array.append({'url': video_data.get(k)})
212 for subtitle in subtitles_array:
213 sub_url = subtitle.get('url')
214 if sub_url and isinstance(sub_url, str):
215 sub_lang = subtitle.get('language') or 'it'
216 sub_url = urljoin(url, sub_url)
217 sub_ext = determine_ext(sub_url, SRT_EXT)
218 subtitles.setdefault(sub_lang, []).append({
219 'ext': sub_ext,
220 'url': sub_url,
221 })
222 if STL_EXT == sub_ext:
223 subtitles[sub_lang].append({
224 'ext': SRT_EXT,
225 'url': sub_url[:-len(STL_EXT)] + SRT_EXT,
226 })
227 return subtitles
228
229
230 class RaiPlayIE(RaiBaseIE):
231 _VALID_URL = rf'(?P<base>https?://(?:www\.)?raiplay\.it/.+?-(?P<id>{RaiBaseIE._UUID_RE}))\.(?:html|json)'
232 _TESTS = [{
233 'url': 'https://www.raiplay.it/video/2014/04/Report-del-07042014-cb27157f-9dd0-4aee-b788-b1f67643a391.html',
234 'md5': '8970abf8caf8aef4696e7b1f2adfc696',
235 'info_dict': {
236 'id': 'cb27157f-9dd0-4aee-b788-b1f67643a391',
237 'ext': 'mp4',
238 'title': 'Report del 07/04/2014',
239 'alt_title': 'St 2013/14 - Report - Espresso nel caffè - 07/04/2014',
240 'description': 'md5:d730c168a58f4bb35600fc2f881ec04e',
241 'thumbnail': r're:^https?://www\.raiplay\.it/.+\.jpg',
242 'uploader': 'Rai 3',
243 'creator': 'Rai 3',
244 'duration': 6160,
245 'series': 'Report',
246 'season': '2013/14',
247 'subtitles': {'it': 'count:4'},
248 'release_year': 2022,
249 'episode': 'Espresso nel caffè - 07/04/2014',
250 'timestamp': 1396919880,
251 'upload_date': '20140408',
252 'formats': 'count:4',
253 },
254 'params': {'skip_download': True},
255 }, {
256 # 1080p direct mp4 url
257 'url': 'https://www.raiplay.it/video/2021/11/Blanca-S1E1-Senza-occhi-b1255a4a-8e72-4a2f-b9f3-fc1308e00736.html',
258 'md5': 'aeda7243115380b2dd5e881fd42d949a',
259 'info_dict': {
260 'id': 'b1255a4a-8e72-4a2f-b9f3-fc1308e00736',
261 'ext': 'mp4',
262 'title': 'Blanca - S1E1 - Senza occhi',
263 'alt_title': 'St 1 Ep 1 - Blanca - Senza occhi',
264 'description': 'md5:75f95d5c030ec8bac263b1212322e28c',
265 'thumbnail': r're:^https://www\.raiplay\.it/dl/img/.+\.jpg',
266 'uploader': 'Rai Premium',
267 'creator': 'Rai Fiction',
268 'duration': 6493,
269 'series': 'Blanca',
270 'season': 'Season 1',
271 'episode_number': 1,
272 'release_year': 2021,
273 'season_number': 1,
274 'episode': 'Senza occhi',
275 'timestamp': 1637318940,
276 'upload_date': '20211119',
277 'formats': 'count:12',
278 },
279 'params': {'skip_download': True},
280 'expected_warnings': ['Video not available. Likely due to geo-restriction.']
281 }, {
282 # 1500 quality
283 'url': 'https://www.raiplay.it/video/2012/09/S1E11---Tutto-cio-che-luccica-0cab3323-732e-45d6-8e86-7704acab6598.html',
284 'md5': 'a634d20e8ab2d43724c273563f6bf87a',
285 'info_dict': {
286 'id': '0cab3323-732e-45d6-8e86-7704acab6598',
287 'ext': 'mp4',
288 'title': 'Mia and Me - S1E11 - Tutto ciò che luccica',
289 'alt_title': 'St 1 Ep 11 - Mia and Me - Tutto ciò che luccica',
290 'description': 'md5:4969e594184b1920c4c1f2b704da9dea',
291 'thumbnail': r're:^https?://.*\.jpg$',
292 'uploader': 'Rai Gulp',
293 'series': 'Mia and Me',
294 'season': 'Season 1',
295 'episode_number': 11,
296 'release_year': 2015,
297 'season_number': 1,
298 'episode': 'Tutto ciò che luccica',
299 'timestamp': 1348495020,
300 'upload_date': '20120924',
301 },
302 }, {
303 'url': 'http://www.raiplay.it/video/2016/11/gazebotraindesi-efebe701-969c-4593-92f3-285f0d1ce750.html?',
304 'only_matching': True,
305 }, {
306 # subtitles at 'subtitlesArray' key (see #27698)
307 'url': 'https://www.raiplay.it/video/2020/12/Report---04-01-2021-2e90f1de-8eee-4de4-ac0e-78d21db5b600.html',
308 'only_matching': True,
309 }, {
310 # DRM protected
311 'url': 'https://www.raiplay.it/video/2021/06/Lo-straordinario-mondo-di-Zoey-S2E1-Lo-straordinario-ritorno-di-Zoey-3ba992de-2332-41ad-9214-73e32ab209f4.html',
312 'only_matching': True,
313 }]
314
315 def _real_extract(self, url):
316 base, video_id = self._match_valid_url(url).groups()
317
318 media = self._download_json(
319 f'{base}.json', video_id, 'Downloading video JSON')
320
321 if not self.get_param('allow_unplayable_formats'):
322 if traverse_obj(media, (('program_info', None), 'rights_management', 'rights', 'drm')):
323 self.report_drm(video_id)
324
325 video = media['video']
326 relinker_info = self._extract_relinker_info(video['content_url'], video_id)
327 date_published = join_nonempty(
328 media.get('date_published'), media.get('time_published'), delim=' ')
329 season = media.get('season')
330 alt_title = join_nonempty(media.get('subtitle'), media.get('toptitle'), delim=' - ')
331
332 return {
333 'id': remove_start(media.get('id'), 'ContentItem-') or video_id,
334 'display_id': video_id,
335 'title': media.get('name'),
336 'alt_title': strip_or_none(alt_title or None),
337 'description': media.get('description'),
338 'uploader': strip_or_none(
339 traverse_obj(media, ('program_info', 'channel'))
340 or media.get('channel') or None),
341 'creator': strip_or_none(
342 traverse_obj(media, ('program_info', 'editor'))
343 or media.get('editor') or None),
344 'duration': parse_duration(video.get('duration')),
345 'timestamp': unified_timestamp(date_published),
346 'thumbnails': self._get_thumbnails_list(media.get('images'), url),
347 'series': traverse_obj(media, ('program_info', 'name')),
348 'season_number': int_or_none(season),
349 'season': season if (season and not season.isdigit()) else None,
350 'episode': media.get('episode_title'),
351 'episode_number': int_or_none(media.get('episode')),
352 'subtitles': self._extract_subtitles(url, video),
353 'release_year': int_or_none(traverse_obj(media, ('track_info', 'edit_year'))),
354 **relinker_info
355 }
356
357
358 class RaiPlayLiveIE(RaiPlayIE): # XXX: Do not subclass from concrete IE
359 _VALID_URL = r'(?P<base>https?://(?:www\.)?raiplay\.it/dirette/(?P<id>[^/?#&]+))'
360 _TESTS = [{
361 'url': 'http://www.raiplay.it/dirette/rainews24',
362 'info_dict': {
363 'id': 'd784ad40-e0ae-4a69-aa76-37519d238a9c',
364 'display_id': 'rainews24',
365 'ext': 'mp4',
366 'title': 're:^Diretta di Rai News 24 [0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}$',
367 'description': 'md5:4d00bcf6dc98b27c6ec480de329d1497',
368 'uploader': 'Rai News 24',
369 'creator': 'Rai News 24',
370 'is_live': True,
371 'live_status': 'is_live',
372 'upload_date': '20090502',
373 'timestamp': 1241276220,
374 'formats': 'count:3',
375 },
376 'params': {'skip_download': True},
377 }]
378
379
380 class RaiPlayPlaylistIE(InfoExtractor):
381 _VALID_URL = r'(?P<base>https?://(?:www\.)?raiplay\.it/programmi/(?P<id>[^/?#&]+))(?:/(?P<extra_id>[^?#&]+))?'
382 _TESTS = [{
383 # entire series episodes + extras...
384 'url': 'https://www.raiplay.it/programmi/nondirloalmiocapo/',
385 'info_dict': {
386 'id': 'nondirloalmiocapo',
387 'title': 'Non dirlo al mio capo',
388 'description': 'md5:98ab6b98f7f44c2843fd7d6f045f153b',
389 },
390 'playlist_mincount': 30,
391 }, {
392 # single season
393 'url': 'https://www.raiplay.it/programmi/nondirloalmiocapo/episodi/stagione-2/',
394 'info_dict': {
395 'id': 'nondirloalmiocapo',
396 'title': 'Non dirlo al mio capo - Stagione 2',
397 'description': 'md5:98ab6b98f7f44c2843fd7d6f045f153b',
398 },
399 'playlist_count': 12,
400 }]
401
402 def _real_extract(self, url):
403 base, playlist_id, extra_id = self._match_valid_url(url).groups()
404
405 program = self._download_json(
406 f'{base}.json', playlist_id, 'Downloading program JSON')
407
408 if extra_id:
409 extra_id = extra_id.upper().rstrip('/')
410
411 playlist_title = program.get('name')
412 entries = []
413 for b in (program.get('blocks') or []):
414 for s in (b.get('sets') or []):
415 if extra_id:
416 if extra_id != join_nonempty(
417 b.get('name'), s.get('name'), delim='/').replace(' ', '-').upper():
418 continue
419 playlist_title = join_nonempty(playlist_title, s.get('name'), delim=' - ')
420
421 s_id = s.get('id')
422 if not s_id:
423 continue
424 medias = self._download_json(
425 f'{base}/{s_id}.json', s_id,
426 'Downloading content set JSON', fatal=False)
427 if not medias:
428 continue
429 for m in (medias.get('items') or []):
430 path_id = m.get('path_id')
431 if not path_id:
432 continue
433 video_url = urljoin(url, path_id)
434 entries.append(self.url_result(
435 video_url, ie=RaiPlayIE.ie_key(),
436 video_id=RaiPlayIE._match_id(video_url)))
437
438 return self.playlist_result(
439 entries, playlist_id, playlist_title,
440 try_get(program, lambda x: x['program_info']['description']))
441
442
443 class RaiPlaySoundIE(RaiBaseIE):
444 _VALID_URL = rf'(?P<base>https?://(?:www\.)?raiplaysound\.it/.+?-(?P<id>{RaiBaseIE._UUID_RE}))\.(?:html|json)'
445 _TESTS = [{
446 'url': 'https://www.raiplaysound.it/audio/2021/12/IL-RUGGITO-DEL-CONIGLIO-1ebae2a7-7cdb-42bb-842e-fe0d193e9707.html',
447 'md5': '8970abf8caf8aef4696e7b1f2adfc696',
448 'info_dict': {
449 'id': '1ebae2a7-7cdb-42bb-842e-fe0d193e9707',
450 'ext': 'mp3',
451 'title': 'Il Ruggito del Coniglio del 10/12/2021',
452 'alt_title': 'md5:0e6476cd57858bb0f3fcc835d305b455',
453 'description': 'md5:2a17d2107e59a4a8faa0e18334139ee2',
454 'thumbnail': r're:^https?://.+\.jpg$',
455 'uploader': 'rai radio 2',
456 'duration': 5685,
457 'series': 'Il Ruggito del Coniglio',
458 'episode': 'Il Ruggito del Coniglio del 10/12/2021',
459 'creator': 'rai radio 2',
460 'timestamp': 1638346620,
461 'upload_date': '20211201',
462 },
463 'params': {'skip_download': True},
464 }]
465
466 def _real_extract(self, url):
467 base, audio_id = self._match_valid_url(url).group('base', 'id')
468 media = self._download_json(f'{base}.json', audio_id, 'Downloading audio JSON')
469 uid = try_get(media, lambda x: remove_start(remove_start(x['uniquename'], 'ContentItem-'), 'Page-'))
470
471 info = {}
472 formats = []
473 relinkers = set(traverse_obj(media, (('downloadable_audio', 'audio', ('live', 'cards', 0, 'audio')), 'url')))
474 for r in relinkers:
475 info = self._extract_relinker_info(r, audio_id, True)
476 formats.extend(info.get('formats'))
477
478 date_published = try_get(media, (lambda x: f'{x["create_date"]} {x.get("create_time") or ""}',
479 lambda x: x['live']['create_date']))
480
481 podcast_info = traverse_obj(media, 'podcast_info', ('live', 'cards', 0)) or {}
482
483 return {
484 **info,
485 'id': uid or audio_id,
486 'display_id': audio_id,
487 'title': traverse_obj(media, 'title', 'episode_title'),
488 'alt_title': traverse_obj(media, ('track_info', 'media_name'), expected_type=strip_or_none),
489 'description': media.get('description'),
490 'uploader': traverse_obj(media, ('track_info', 'channel'), expected_type=strip_or_none),
491 'creator': traverse_obj(media, ('track_info', 'editor'), expected_type=strip_or_none),
492 'timestamp': unified_timestamp(date_published),
493 'thumbnails': self._get_thumbnails_list(podcast_info.get('images'), url),
494 'series': podcast_info.get('title'),
495 'season_number': int_or_none(media.get('season')),
496 'episode': media.get('episode_title'),
497 'episode_number': int_or_none(media.get('episode')),
498 'formats': formats,
499 }
500
501
502 class RaiPlaySoundLiveIE(RaiPlaySoundIE): # XXX: Do not subclass from concrete IE
503 _VALID_URL = r'(?P<base>https?://(?:www\.)?raiplaysound\.it/(?P<id>[^/?#&]+)$)'
504 _TESTS = [{
505 'url': 'https://www.raiplaysound.it/radio2',
506 'info_dict': {
507 'id': 'b00a50e6-f404-4af6-8f8c-ff3b9af73a44',
508 'display_id': 'radio2',
509 'ext': 'mp4',
510 'title': r're:Rai Radio 2 \d+-\d+-\d+ \d+:\d+',
511 'thumbnail': r're:^https://www\.raiplaysound\.it/dl/img/.+\.png',
512 'uploader': 'rai radio 2',
513 'series': 'Rai Radio 2',
514 'creator': 'raiplaysound',
515 'is_live': True,
516 'live_status': 'is_live',
517 },
518 'params': {'skip_download': True},
519 }]
520
521
522 class RaiPlaySoundPlaylistIE(InfoExtractor):
523 _VALID_URL = r'(?P<base>https?://(?:www\.)?raiplaysound\.it/(?:programmi|playlist|audiolibri)/(?P<id>[^/?#&]+))(?:/(?P<extra_id>[^?#&]+))?'
524 _TESTS = [{
525 # entire show
526 'url': 'https://www.raiplaysound.it/programmi/ilruggitodelconiglio',
527 'info_dict': {
528 'id': 'ilruggitodelconiglio',
529 'title': 'Il Ruggito del Coniglio',
530 'description': 'md5:48cff6972435964284614d70474132e6',
531 },
532 'playlist_mincount': 65,
533 }, {
534 # single season
535 'url': 'https://www.raiplaysound.it/programmi/ilruggitodelconiglio/puntate/prima-stagione-1995',
536 'info_dict': {
537 'id': 'ilruggitodelconiglio_puntate_prima-stagione-1995',
538 'title': 'Prima Stagione 1995',
539 },
540 'playlist_count': 1,
541 }]
542
543 def _real_extract(self, url):
544 base, playlist_id, extra_id = self._match_valid_url(url).group('base', 'id', 'extra_id')
545 url = f'{base}.json'
546 program = self._download_json(url, playlist_id, 'Downloading program JSON')
547
548 if extra_id:
549 extra_id = extra_id.rstrip('/')
550 playlist_id += '_' + extra_id.replace('/', '_')
551 path = next(c['path_id'] for c in program.get('filters') or [] if extra_id in c.get('weblink'))
552 program = self._download_json(
553 urljoin('https://www.raiplaysound.it', path), playlist_id, 'Downloading program secondary JSON')
554
555 entries = [
556 self.url_result(urljoin(base, c['path_id']), ie=RaiPlaySoundIE.ie_key())
557 for c in traverse_obj(program, 'cards', ('block', 'cards')) or []
558 if c.get('path_id')]
559
560 return self.playlist_result(entries, playlist_id, program.get('title'),
561 traverse_obj(program, ('podcast_info', 'description')))
562
563
564 class RaiIE(RaiBaseIE):
565 _VALID_URL = rf'https?://[^/]+\.(?:rai\.(?:it|tv))/.+?-(?P<id>{RaiBaseIE._UUID_RE})(?:-.+?)?\.html'
566 _TESTS = [{
567 'url': 'https://www.raisport.rai.it/dl/raiSport/media/rassegna-stampa-04a9f4bd-b563-40cf-82a6-aad3529cb4a9.html',
568 'info_dict': {
569 'id': '04a9f4bd-b563-40cf-82a6-aad3529cb4a9',
570 'ext': 'mp4',
571 'title': 'TG PRIMO TEMPO',
572 'thumbnail': r're:^https?://.*\.jpg',
573 'duration': 1758,
574 'upload_date': '20140612',
575 },
576 'params': {'skip_download': True},
577 'expected_warnings': ['Video not available. Likely due to geo-restriction.']
578 }, {
579 'url': 'https://www.rai.it/dl/RaiTV/programmi/media/ContentItem-efb17665-691c-45d5-a60c-5301333cbb0c.html',
580 'info_dict': {
581 'id': 'efb17665-691c-45d5-a60c-5301333cbb0c',
582 'ext': 'mp4',
583 'title': 'TG1 ore 20:00 del 03/11/2016',
584 'description': 'TG1 edizione integrale ore 20:00 del giorno 03/11/2016',
585 'thumbnail': r're:^https?://.*\.jpg$',
586 'duration': 2214,
587 'upload_date': '20161103'
588 },
589 'params': {'skip_download': True},
590 }, {
591 # Direct MMS: Media URL no longer works.
592 'url': 'http://www.rai.it/dl/RaiTV/programmi/media/ContentItem-b63a4089-ac28-48cf-bca5-9f5b5bc46df5.html',
593 'only_matching': True,
594 }]
595
596 def _real_extract(self, url):
597 content_id = self._match_id(url)
598 media = self._download_json(
599 f'https://www.rai.tv/dl/RaiTV/programmi/media/ContentItem-{content_id}.html?json',
600 content_id, 'Downloading video JSON', fatal=False, expected_status=404)
601
602 if media is None:
603 return None
604
605 if 'Audio' in media['type']:
606 relinker_info = {
607 'formats': [{
608 'format_id': join_nonempty('https', media.get('formatoAudio'), delim='-'),
609 'url': media['audioUrl'],
610 'ext': media.get('formatoAudio'),
611 'vcodec': 'none',
612 'acodec': media.get('formatoAudio'),
613 }]
614 }
615 elif 'Video' in media['type']:
616 relinker_info = self._extract_relinker_info(media['mediaUri'], content_id)
617 else:
618 raise ExtractorError('not a media file')
619
620 thumbnails = self._get_thumbnails_list(
621 {image_type: media.get(image_type) for image_type in (
622 'image', 'image_medium', 'image_300')}, url)
623
624 return {
625 'id': content_id,
626 'title': strip_or_none(media.get('name') or media.get('title')),
627 'description': strip_or_none(media.get('desc')) or None,
628 'thumbnails': thumbnails,
629 'uploader': strip_or_none(media.get('author')) or None,
630 'upload_date': unified_strdate(media.get('date')),
631 'duration': parse_duration(media.get('length')),
632 'subtitles': self._extract_subtitles(url, media),
633 **relinker_info
634 }
635
636
637 class RaiNewsIE(RaiIE): # XXX: Do not subclass from concrete IE
638 _VALID_URL = rf'https?://(www\.)?rainews\.it/(?!articoli)[^?#]+-(?P<id>{RaiBaseIE._UUID_RE})(?:-[^/?#]+)?\.html'
639 _EMBED_REGEX = [rf'<iframe[^>]+data-src="(?P<url>/iframe/[^?#]+?{RaiBaseIE._UUID_RE}\.html)']
640 _TESTS = [{
641 # new rainews player (#3911)
642 'url': 'https://www.rainews.it/rubriche/24mm/video/2022/05/24mm-del-29052022-12cf645d-1ffd-4220-b27c-07c226dbdecf.html',
643 'info_dict': {
644 'id': '12cf645d-1ffd-4220-b27c-07c226dbdecf',
645 'ext': 'mp4',
646 'title': 'Puntata del 29/05/2022',
647 'duration': 1589,
648 'upload_date': '20220529',
649 'uploader': 'rainews',
650 },
651 'params': {'skip_download': True},
652 }, {
653 # old content with fallback method to extract media urls
654 'url': 'https://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',
655 'info_dict': {
656 'id': '1632c009-c843-4836-bb65-80c33084a64b',
657 'ext': 'mp4',
658 'title': 'Weekend al cinema, da Hollywood arriva il thriller di Tate Taylor "La ragazza del treno"',
659 'description': 'I film in uscita questa settimana.',
660 'thumbnail': r're:^https?://.*\.png$',
661 'duration': 833,
662 'upload_date': '20161103'
663 },
664 'params': {'skip_download': True},
665 'expected_warnings': ['unable to extract player_data'],
666 }, {
667 # iframe + drm
668 'url': 'https://www.rainews.it/iframe/video/2022/07/euro2022-europei-calcio-femminile-italia-belgio-gol-0-1-video-4de06a69-de75-4e32-a657-02f0885f8118.html',
669 'only_matching': True,
670 }]
671 _PLAYER_TAG = 'news'
672
673 def _real_extract(self, url):
674 video_id = self._match_id(url)
675
676 webpage = self._download_webpage(url, video_id)
677
678 player_data = self._search_json(
679 rf'<rai{self._PLAYER_TAG}-player\s*data=\'', webpage, 'player_data', video_id,
680 transform_source=clean_html, default={})
681 track_info = player_data.get('track_info')
682 relinker_url = traverse_obj(player_data, 'mediapolis', 'content_url')
683
684 if not relinker_url:
685 # fallback on old implementation for some old content
686 try:
687 return self._extract_from_content_id(video_id, url)
688 except GeoRestrictedError:
689 raise
690 except ExtractorError as e:
691 raise ExtractorError('Relinker URL not found', cause=e)
692
693 relinker_info = self._extract_relinker_info(urljoin(url, relinker_url), video_id)
694
695 return {
696 'id': video_id,
697 'title': player_data.get('title') or track_info.get('title') or self._og_search_title(webpage),
698 'upload_date': unified_strdate(track_info.get('date')),
699 'uploader': strip_or_none(track_info.get('editor') or None),
700 **relinker_info
701 }
702
703
704 class RaiCulturaIE(RaiNewsIE): # XXX: Do not subclass from concrete IE
705 _VALID_URL = rf'https?://(www\.)?raicultura\.it/(?!articoli)[^?#]+-(?P<id>{RaiBaseIE._UUID_RE})(?:-[^/?#]+)?\.html'
706 _EMBED_REGEX = [rf'<iframe[^>]+data-src="(?P<url>/iframe/[^?#]+?{RaiBaseIE._UUID_RE}\.html)']
707 _TESTS = [{
708 'url': 'https://www.raicultura.it/letteratura/articoli/2018/12/Alberto-Asor-Rosa-Letteratura-e-potere-05ba8775-82b5-45c5-a89d-dd955fbde1fb.html',
709 'info_dict': {
710 'id': '05ba8775-82b5-45c5-a89d-dd955fbde1fb',
711 'ext': 'mp4',
712 'title': 'Alberto Asor Rosa: Letteratura e potere',
713 'duration': 1756,
714 'upload_date': '20181206',
715 'uploader': 'raicultura',
716 'formats': 'count:2',
717 },
718 'params': {'skip_download': True},
719 }]
720 _PLAYER_TAG = 'cultura'
721
722
723 class RaiSudtirolIE(RaiBaseIE):
724 _VALID_URL = r'https?://raisudtirol\.rai\.it/.+media=(?P<id>\w+)'
725 _TESTS = [{
726 # mp4 file
727 'url': 'https://raisudtirol.rai.it/la/index.php?media=Ptv1619729460',
728 'info_dict': {
729 'id': 'Ptv1619729460',
730 'ext': 'mp4',
731 'title': 'Euro: trasmisciun d\'economia - 29-04-2021 20:51',
732 'series': 'Euro: trasmisciun d\'economia',
733 'upload_date': '20210429',
734 'thumbnail': r're:https://raisudtirol\.rai\.it/img/.+\.jpg',
735 'uploader': 'raisudtirol',
736 'formats': 'count:1',
737 },
738 'params': {'skip_download': True},
739 }, {
740 # m3u manifest
741 'url': 'https://raisudtirol.rai.it/it/kidsplayer.php?lang=it&media=GUGGUG_P1.smil',
742 'info_dict': {
743 'id': 'GUGGUG_P1',
744 'ext': 'mp4',
745 'title': 'GUGGUG! La Prospettiva - Die Perspektive',
746 'uploader': 'raisudtirol',
747 'formats': 'count:6',
748 },
749 'params': {'skip_download': True},
750 }]
751
752 def _real_extract(self, url):
753 video_id = self._match_id(url)
754 webpage = self._download_webpage(url, video_id)
755
756 video_date = self._html_search_regex(
757 r'<span class="med_data">(.+?)</span>', webpage, 'video_date', default=None)
758 video_title = self._html_search_regex([
759 r'<span class="med_title">(.+?)</span>', r'title: \'(.+?)\','],
760 webpage, 'video_title', default=None)
761 video_url = self._html_search_regex([
762 r'sources:\s*\[\{file:\s*"(.+?)"\}\]',
763 r'<source\s+src="(.+?)"\s+type="application/x-mpegURL"'],
764 webpage, 'video_url', default=None)
765
766 ext = determine_ext(video_url)
767 if ext == 'm3u8':
768 formats = self._extract_m3u8_formats(video_url, video_id)
769 elif ext == 'mp4':
770 formats = [{
771 'format_id': 'https-mp4',
772 'url': self._proto_relative_url(video_url),
773 'width': 1024,
774 'height': 576,
775 'fps': 25,
776 'vcodec': 'avc1',
777 'acodec': 'mp4a',
778 }]
779 else:
780 formats = []
781 self.raise_no_formats(f'Unrecognized media file: {video_url}')
782
783 return {
784 'id': video_id,
785 'title': join_nonempty(video_title, video_date, delim=' - '),
786 'series': video_title if video_date else None,
787 'upload_date': unified_strdate(video_date),
788 'thumbnail': urljoin('https://raisudtirol.rai.it/', self._html_search_regex(
789 r'image: \'(.+?)\'', webpage, 'video_thumb', default=None)),
790 'uploader': 'raisudtirol',
791 'formats': formats,
792 }