]> jfr.im git - yt-dlp.git/blame - yt_dlp/extractor/rai.py
Add option `--ignore-no-formats-error`
[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
S
7from ..compat import (
8 compat_urlparse,
9 compat_str,
10)
b0adbe98 11from ..utils import (
f1388739 12 ExtractorError,
51342717 13 determine_ext,
f1388739
YCH
14 find_xpath_attr,
15 fix_xml_ampersands,
b8d8cced 16 GeoRestrictedError,
f1388739 17 int_or_none,
b0adbe98 18 parse_duration,
a0566bbf 19 remove_start,
b8d8cced 20 strip_or_none,
a0566bbf 21 try_get,
b0adbe98 22 unified_strdate,
b8d8cced 23 unified_timestamp,
f1388739 24 update_url_query,
b8d8cced 25 urljoin,
06d5556d 26 xpath_text,
b0adbe98
S
27)
28
29
034a8849 30class RaiBaseIE(InfoExtractor):
b8d8cced
S
31 _UUID_RE = r'[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}'
32 _GEO_COUNTRIES = ['IT']
33 _GEO_BYPASS = False
34
35 def _extract_relinker_info(self, relinker_url, video_id):
0c7b4f49
RA
36 if not re.match(r'https?://', relinker_url):
37 return {'formats': [{'url': relinker_url}]}
38
034a8849 39 formats = []
b8d8cced
S
40 geoprotection = None
41 is_live = None
42 duration = None
034a8849
YCH
43
44 for platform in ('mon', 'flash', 'native'):
034a8849
YCH
45 relinker = self._download_xml(
46 relinker_url, video_id,
47 note='Downloading XML metadata for platform %s' % platform,
48 transform_source=fix_xml_ampersands,
38cce791
YCH
49 query={'output': 45, 'pl': platform},
50 headers=self.geo_verification_headers())
034a8849 51
b8d8cced
S
52 if not geoprotection:
53 geoprotection = xpath_text(
54 relinker, './geoprotection', default=None) == 'Y'
55
56 if not is_live:
57 is_live = xpath_text(
58 relinker, './is_live', default=None) == 'Y'
59 if not duration:
60 duration = parse_duration(xpath_text(
61 relinker, './duration', default=None))
62
63 url_elem = find_xpath_attr(relinker, './url', 'type', 'content')
64 if url_elem is None:
65 continue
66
67 media_url = url_elem.text
68
69 # This does not imply geo restriction (e.g.
70 # http://www.raisport.rai.it/dl/raiSport/media/rassegna-stampa-04a9f4bd-b563-40cf-82a6-aad3529cb4a9.html)
a0566bbf 71 if '/video_no_available.mp4' in media_url:
b8d8cced 72 continue
034a8849
YCH
73
74 ext = determine_ext(media_url)
75 if (ext == 'm3u8' and platform != 'mon') or (ext == 'f4m' and platform != 'flash'):
76 continue
77
c17eb5b4 78 if ext == 'm3u8' or 'format=m3u8' in media_url or platform == 'mon':
034a8849
YCH
79 formats.extend(self._extract_m3u8_formats(
80 media_url, video_id, 'mp4', 'm3u8_native',
81 m3u8_id='hls', fatal=False))
c17eb5b4 82 elif ext == 'f4m' or platform == 'flash':
034a8849
YCH
83 manifest_url = update_url_query(
84 media_url.replace('manifest#live_hds.f4m', 'manifest.f4m'),
85 {'hdcore': '3.7.0', 'plugin': 'aasp-3.7.0.39.44'})
86 formats.extend(self._extract_f4m_formats(
87 manifest_url, video_id, f4m_id='hds', fatal=False))
88 else:
89 bitrate = int_or_none(xpath_text(relinker, 'bitrate'))
90 formats.append({
91 'url': media_url,
92 'tbr': bitrate if bitrate > 0 else None,
93 'format_id': 'http-%d' % bitrate if bitrate > 0 else 'http',
94 })
95
b8d8cced 96 if not formats and geoprotection is True:
b7da73eb 97 self.raise_geo_restricted(countries=self._GEO_COUNTRIES, metadata_available=True)
b8d8cced
S
98
99 return dict((k, v) for k, v in {
100 'is_live': is_live,
101 'duration': duration,
102 'formats': formats,
103 }.items() if v is not None)
034a8849 104
1b3feca0 105 @staticmethod
00dd0cd5 106 def _extract_subtitles(url, video_data):
107 STL_EXT = 'stl'
108 SRT_EXT = 'srt'
1b3feca0 109 subtitles = {}
00dd0cd5 110 subtitles_array = video_data.get('subtitlesArray') or []
111 for k in ('subtitles', 'subtitlesUrl'):
112 subtitles_array.append({'url': video_data.get(k)})
113 for subtitle in subtitles_array:
114 sub_url = subtitle.get('url')
115 if sub_url and isinstance(sub_url, compat_str):
116 sub_lang = subtitle.get('language') or 'it'
117 sub_url = urljoin(url, sub_url)
118 sub_ext = determine_ext(sub_url, SRT_EXT)
119 subtitles.setdefault(sub_lang, []).append({
120 'ext': sub_ext,
121 'url': sub_url,
1b3feca0 122 })
00dd0cd5 123 if STL_EXT == sub_ext:
124 subtitles[sub_lang].append({
125 'ext': SRT_EXT,
126 'url': sub_url[:-len(STL_EXT)] + SRT_EXT,
127 })
1b3feca0
S
128 return subtitles
129
2b28b892 130
51342717 131class RaiPlayIE(RaiBaseIE):
a0566bbf 132 _VALID_URL = r'(?P<base>https?://(?:www\.)?raiplay\.it/.+?-(?P<id>%s))\.(?:html|json)' % RaiBaseIE._UUID_RE
51342717 133 _TESTS = [{
51342717
T
134 'url': 'http://www.raiplay.it/video/2014/04/Report-del-07042014-cb27157f-9dd0-4aee-b788-b1f67643a391.html',
135 'md5': '8970abf8caf8aef4696e7b1f2adfc696',
136 'info_dict': {
137 'id': 'cb27157f-9dd0-4aee-b788-b1f67643a391',
138 'ext': 'mp4',
b8d8cced 139 'title': 'Report del 07/04/2014',
8bdd16b4 140 'alt_title': 'St 2013/14 - Espresso nel caffè - 07/04/2014',
abea9145 141 'description': 'md5:d730c168a58f4bb35600fc2f881ec04e',
51342717 142 'thumbnail': r're:^https?://.*\.jpg$',
abea9145 143 'uploader': 'Rai Gulp',
b8d8cced 144 'duration': 6160,
8bdd16b4 145 'series': 'Report',
146 'season': '2013/14',
00dd0cd5 147 'subtitles': {
148 'it': 'count:2',
149 },
b8d8cced
S
150 },
151 'params': {
152 'skip_download': True,
153 },
154 }, {
155 'url': 'http://www.raiplay.it/video/2016/11/gazebotraindesi-efebe701-969c-4593-92f3-285f0d1ce750.html?',
156 'only_matching': True,
00dd0cd5 157 }, {
158 # subtitles at 'subtitlesArray' key (see #27698)
159 'url': 'https://www.raiplay.it/video/2020/12/Report---04-01-2021-2e90f1de-8eee-4de4-ac0e-78d21db5b600.html',
160 'only_matching': True,
0852947f 161 }, {
162 # DRM protected
163 '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',
164 'only_matching': True,
51342717 165 }]
2b28b892 166
51342717 167 def _real_extract(self, url):
a0566bbf 168 base, video_id = re.match(self._VALID_URL, url).groups()
2b28b892 169
b8d8cced 170 media = self._download_json(
a0566bbf 171 base + '.json', video_id, 'Downloading video JSON')
2b28b892 172
8eec0120 173 if not self._downloader.params.get('allow_unplayable_formats'):
0852947f 174 if try_get(
175 media,
176 (lambda x: x['rights_management']['rights']['drm'],
177 lambda x: x['program_info']['rights_management']['rights']['drm']),
178 dict):
179 raise ExtractorError('This video is DRM protected.', expected=True)
180
b8d8cced 181 title = media['name']
b8d8cced
S
182 video = media['video']
183
abea9145 184 relinker_info = self._extract_relinker_info(video['content_url'], video_id)
b8d8cced 185 self._sort_formats(relinker_info['formats'])
2b28b892 186
51342717 187 thumbnails = []
8bdd16b4 188 for _, value in media.get('images', {}).items():
189 if value:
190 thumbnails.append({
191 'url': urljoin(url, value),
192 })
034a8849 193
8bdd16b4 194 date_published = media.get('date_published')
195 time_published = media.get('time_published')
196 if date_published and time_published:
197 date_published += ' ' + time_published
b0adbe98 198
00dd0cd5 199 subtitles = self._extract_subtitles(url, video)
1b3feca0 200
8bdd16b4 201 program_info = media.get('program_info') or {}
202 season = media.get('season')
203
b8d8cced 204 info = {
a0566bbf 205 'id': remove_start(media.get('id'), 'ContentItem-') or video_id,
206 'display_id': video_id,
9c48b5a1
S
207 'title': self._live_title(title) if relinker_info.get(
208 'is_live') else title,
8bdd16b4 209 'alt_title': strip_or_none(media.get('subtitle')),
b8d8cced 210 'description': media.get('description'),
9c48b5a1 211 'uploader': strip_or_none(media.get('channel')),
8bdd16b4 212 'creator': strip_or_none(media.get('editor') or None),
b8d8cced 213 'duration': parse_duration(video.get('duration')),
8bdd16b4 214 'timestamp': unified_timestamp(date_published),
51342717 215 'thumbnails': thumbnails,
8bdd16b4 216 'series': program_info.get('name'),
217 'season_number': int_or_none(season),
218 'season': season if (season and not season.isdigit()) else None,
219 'episode': media.get('episode_title'),
220 'episode_number': int_or_none(media.get('episode')),
1b3feca0 221 'subtitles': subtitles,
51342717 222 }
b0adbe98 223
b8d8cced 224 info.update(relinker_info)
b8d8cced
S
225 return info
226
06d5556d 227
a0566bbf 228class RaiPlayLiveIE(RaiPlayIE):
229 _VALID_URL = r'(?P<base>https?://(?:www\.)?raiplay\.it/dirette/(?P<id>[^/?#&]+))'
230 _TESTS = [{
9c48b5a1
S
231 'url': 'http://www.raiplay.it/dirette/rainews24',
232 'info_dict': {
233 'id': 'd784ad40-e0ae-4a69-aa76-37519d238a9c',
234 'display_id': 'rainews24',
235 'ext': 'mp4',
236 'title': 're:^Diretta di Rai News 24 [0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}$',
a0566bbf 237 'description': 'md5:4d00bcf6dc98b27c6ec480de329d1497',
9c48b5a1
S
238 'uploader': 'Rai News 24',
239 'creator': 'Rai News 24',
240 'is_live': True,
241 },
242 'params': {
243 'skip_download': True,
244 },
a0566bbf 245 }]
449c6657 246
247
1115271a 248class RaiPlayPlaylistIE(InfoExtractor):
a0566bbf 249 _VALID_URL = r'(?P<base>https?://(?:www\.)?raiplay\.it/programmi/(?P<id>[^/?#&]+))'
1115271a
S
250 _TESTS = [{
251 'url': 'http://www.raiplay.it/programmi/nondirloalmiocapo/',
252 'info_dict': {
253 'id': 'nondirloalmiocapo',
254 'title': 'Non dirlo al mio capo',
a0566bbf 255 'description': 'md5:98ab6b98f7f44c2843fd7d6f045f153b',
1115271a
S
256 },
257 'playlist_mincount': 12,
258 }]
259
260 def _real_extract(self, url):
a0566bbf 261 base, playlist_id = re.match(self._VALID_URL, url).groups()
1115271a 262
a0566bbf 263 program = self._download_json(
264 base + '.json', playlist_id, 'Downloading program JSON')
1115271a
S
265
266 entries = []
a0566bbf 267 for b in (program.get('blocks') or []):
268 for s in (b.get('sets') or []):
269 s_id = s.get('id')
270 if not s_id:
271 continue
272 medias = self._download_json(
273 '%s/%s.json' % (base, s_id), s_id,
274 'Downloading content set JSON', fatal=False)
275 if not medias:
276 continue
277 for m in (medias.get('items') or []):
278 path_id = m.get('path_id')
279 if not path_id:
280 continue
281 video_url = urljoin(url, path_id)
282 entries.append(self.url_result(
283 video_url, ie=RaiPlayIE.ie_key(),
284 video_id=RaiPlayIE._match_id(video_url)))
285
286 return self.playlist_result(
287 entries, playlist_id, program.get('name'),
288 try_get(program, lambda x: x['program_info']['description']))
1115271a
S
289
290
034a8849 291class RaiIE(RaiBaseIE):
2b2da3ba 292 _VALID_URL = r'https?://[^/]+\.(?:rai\.(?:it|tv)|rainews\.it)/.+?-(?P<id>%s)(?:-.+?)?\.html' % RaiBaseIE._UUID_RE
51342717 293 _TESTS = [{
b8d8cced
S
294 # var uniquename = "ContentItem-..."
295 # data-id="ContentItem-..."
51342717
T
296 'url': 'http://www.raisport.rai.it/dl/raiSport/media/rassegna-stampa-04a9f4bd-b563-40cf-82a6-aad3529cb4a9.html',
297 'info_dict': {
298 'id': '04a9f4bd-b563-40cf-82a6-aad3529cb4a9',
299 'ext': 'mp4',
300 'title': 'TG PRIMO TEMPO',
b8d8cced 301 'thumbnail': r're:^https?://.*\.jpg$',
51342717 302 'duration': 1758,
b8d8cced 303 'upload_date': '20140612',
8bdd16b4 304 },
305 'skip': 'This content is available only in Italy',
51342717 306 }, {
b8d8cced 307 # with ContentItem in many metas
51342717
T
308 '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',
309 'info_dict': {
310 'id': '1632c009-c843-4836-bb65-80c33084a64b',
311 'ext': 'mp4',
b8d8cced
S
312 'title': 'Weekend al cinema, da Hollywood arriva il thriller di Tate Taylor "La ragazza del treno"',
313 'description': 'I film in uscita questa settimana.',
51342717 314 'thumbnail': r're:^https?://.*\.png$',
b8d8cced
S
315 'duration': 833,
316 'upload_date': '20161103',
51342717
T
317 }
318 }, {
b8d8cced 319 # with ContentItem in og:url
51342717 320 'url': 'http://www.rai.it/dl/RaiTV/programmi/media/ContentItem-efb17665-691c-45d5-a60c-5301333cbb0c.html',
abea9145 321 'md5': '6865dd00cf0bbf5772fdd89d59bd768a',
51342717
T
322 'info_dict': {
323 'id': 'efb17665-691c-45d5-a60c-5301333cbb0c',
324 'ext': 'mp4',
325 'title': 'TG1 ore 20:00 del 03/11/2016',
b8d8cced 326 'description': 'TG1 edizione integrale ore 20:00 del giorno 03/11/2016',
51342717 327 'thumbnail': r're:^https?://.*\.jpg$',
b8d8cced 328 'duration': 2214,
51342717 329 'upload_date': '20161103',
51342717 330 }
51342717 331 }, {
b8d8cced
S
332 # initEdizione('ContentItem-...'
333 'url': 'http://www.tg1.rai.it/dl/tg1/2010/edizioni/ContentSet-9b6e0cba-4bef-4aef-8cf0-9f7f665b7dfb-tg1.html?item=undefined',
334 'info_dict': {
335 'id': 'c2187016-8484-4e3a-8ac8-35e475b07303',
336 'ext': 'mp4',
337 'title': r're:TG1 ore \d{2}:\d{2} del \d{2}/\d{2}/\d{4}',
338 'duration': 2274,
339 'upload_date': '20170401',
340 },
341 'skip': 'Changes daily',
51342717 342 }, {
b8d8cced 343 # HLS live stream with ContentItem in og:url
51342717 344 'url': 'http://www.rainews.it/dl/rainews/live/ContentItem-3156f2f2-dc70-4953-8e2f-70d7489d4ce9.html',
51342717
T
345 'info_dict': {
346 'id': '3156f2f2-dc70-4953-8e2f-70d7489d4ce9',
347 'ext': 'mp4',
348 'title': 'La diretta di Rainews24',
15e4b6b7 349 },
b8d8cced
S
350 'params': {
351 'skip_download': True,
352 },
00dd0cd5 353 }, {
354 # ContentItem in iframe (see #12652) and subtitle at 'subtitlesUrl' key
355 'url': 'http://www.presadiretta.rai.it/dl/portali/site/puntata/ContentItem-3ed19d13-26c2-46ff-a551-b10828262f1b.html',
356 'info_dict': {
357 'id': '1ad6dc64-444a-42a4-9bea-e5419ad2f5fd',
358 'ext': 'mp4',
359 'title': 'Partiti acchiappavoti - Presa diretta del 13/09/2015',
360 'description': 'md5:d291b03407ec505f95f27970c0b025f4',
361 'upload_date': '20150913',
362 'subtitles': {
363 'it': 'count:2',
364 },
365 },
366 'params': {
367 'skip_download': True,
368 },
0c7b4f49
RA
369 }, {
370 # Direct MMS URL
371 'url': 'http://www.rai.it/dl/RaiTV/programmi/media/ContentItem-b63a4089-ac28-48cf-bca5-9f5b5bc46df5.html',
372 'only_matching': True,
2b2da3ba
S
373 }, {
374 'url': 'https://www.rainews.it/tgr/marche/notiziari/video/2019/02/ContentItem-6ba945a2-889c-4a80-bdeb-8489c70a8db9.html',
375 'only_matching': True,
51342717 376 }]
06d5556d 377
51342717
T
378 def _extract_from_content_id(self, content_id, url):
379 media = self._download_json(
380 'http://www.rai.tv/dl/RaiTV/programmi/media/ContentItem-%s.html?json' % content_id,
381 content_id, 'Downloading video JSON')
382
b8d8cced
S
383 title = media['name'].strip()
384
385 media_type = media['type']
386 if 'Audio' in media_type:
387 relinker_info = {
085d9dd9 388 'formats': [{
b8d8cced
S
389 'format_id': media.get('formatoAudio'),
390 'url': media['audioUrl'],
391 'ext': media.get('formatoAudio'),
085d9dd9 392 }]
b8d8cced
S
393 }
394 elif 'Video' in media_type:
395 relinker_info = self._extract_relinker_info(media['mediaUri'], content_id)
396 else:
397 raise ExtractorError('not a media file')
398
399 self._sort_formats(relinker_info['formats'])
400
51342717
T
401 thumbnails = []
402 for image_type in ('image', 'image_medium', 'image_300'):
403 thumbnail_url = media.get(image_type)
404 if thumbnail_url:
405 thumbnails.append({
406 'url': compat_urlparse.urljoin(url, thumbnail_url),
407 })
408
00dd0cd5 409 subtitles = self._extract_subtitles(url, media)
51342717 410
b8d8cced 411 info = {
51342717 412 'id': content_id,
b8d8cced
S
413 'title': title,
414 'description': strip_or_none(media.get('desc')),
51342717
T
415 'thumbnails': thumbnails,
416 'uploader': media.get('author'),
417 'upload_date': unified_strdate(media.get('date')),
418 'duration': parse_duration(media.get('length')),
51342717
T
419 'subtitles': subtitles,
420 }
b8d8cced
S
421
422 info.update(relinker_info)
423
424 return info
425
426 def _real_extract(self, url):
427 video_id = self._match_id(url)
428
429 webpage = self._download_webpage(url, video_id)
430
431 content_item_id = None
432
433 content_item_url = self._html_search_meta(
434 ('og:url', 'og:video', 'og:video:secure_url', 'twitter:url',
435 'twitter:player', 'jsonlink'), webpage, default=None)
436 if content_item_url:
437 content_item_id = self._search_regex(
438 r'ContentItem-(%s)' % self._UUID_RE, content_item_url,
439 'content item id', default=None)
440
441 if not content_item_id:
442 content_item_id = self._search_regex(
443 r'''(?x)
444 (?:
445 (?:initEdizione|drawMediaRaiTV)\(|
00dd0cd5 446 <(?:[^>]+\bdata-id|var\s+uniquename)=|
447 <iframe[^>]+\bsrc=
b8d8cced
S
448 )
449 (["\'])
450 (?:(?!\1).)*\bContentItem-(?P<id>%s)
451 ''' % self._UUID_RE,
452 webpage, 'content item id', default=None, group='id')
453
454 content_item_ids = set()
361f293a
S
455 if content_item_id:
456 content_item_ids.add(content_item_id)
b8d8cced
S
457 if video_id not in content_item_ids:
458 content_item_ids.add(video_id)
459
460 for content_item_id in content_item_ids:
461 try:
462 return self._extract_from_content_id(content_item_id, url)
463 except GeoRestrictedError:
464 raise
465 except ExtractorError:
466 pass
467
a0566bbf 468 relinker_url = self._proto_relative_url(self._search_regex(
b8d8cced
S
469 r'''(?x)
470 (?:
471 var\s+videoURL|
472 mediaInfo\.mediaUri
473 )\s*=\s*
474 ([\'"])
475 (?P<url>
476 (?:https?:)?
477 //mediapolis(?:vod)?\.rai\.it/relinker/relinkerServlet\.htm\?
478 (?:(?!\1).)*\bcont=(?:(?!\1).)+)\1
479 ''',
a0566bbf 480 webpage, 'relinker URL', group='url'))
b8d8cced
S
481
482 relinker_info = self._extract_relinker_info(
483 urljoin(url, relinker_url), video_id)
484 self._sort_formats(relinker_info['formats'])
485
486 title = self._search_regex(
487 r'var\s+videoTitolo\s*=\s*([\'"])(?P<title>[^\'"]+)\1',
488 webpage, 'title', group='title',
489 default=None) or self._og_search_title(webpage)
490
491 info = {
492 'id': video_id,
493 'title': title,
494 }
495
496 info.update(relinker_info)
497
498 return info