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