]> jfr.im git - yt-dlp.git/blame - yt_dlp/extractor/rai.py
Completely change project name to yt-dlp (#85)
[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
S
96 if not formats and geoprotection is True:
97 self.raise_geo_restricted(countries=self._GEO_COUNTRIES)
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,
51342717 161 }]
2b28b892 162
51342717 163 def _real_extract(self, url):
a0566bbf 164 base, video_id = re.match(self._VALID_URL, url).groups()
2b28b892 165
b8d8cced 166 media = self._download_json(
a0566bbf 167 base + '.json', video_id, 'Downloading video JSON')
2b28b892 168
b8d8cced 169 title = media['name']
b8d8cced
S
170 video = media['video']
171
abea9145 172 relinker_info = self._extract_relinker_info(video['content_url'], video_id)
b8d8cced 173 self._sort_formats(relinker_info['formats'])
2b28b892 174
51342717 175 thumbnails = []
8bdd16b4 176 for _, value in media.get('images', {}).items():
177 if value:
178 thumbnails.append({
179 'url': urljoin(url, value),
180 })
034a8849 181
8bdd16b4 182 date_published = media.get('date_published')
183 time_published = media.get('time_published')
184 if date_published and time_published:
185 date_published += ' ' + time_published
b0adbe98 186
00dd0cd5 187 subtitles = self._extract_subtitles(url, video)
1b3feca0 188
8bdd16b4 189 program_info = media.get('program_info') or {}
190 season = media.get('season')
191
b8d8cced 192 info = {
a0566bbf 193 'id': remove_start(media.get('id'), 'ContentItem-') or video_id,
194 'display_id': video_id,
9c48b5a1
S
195 'title': self._live_title(title) if relinker_info.get(
196 'is_live') else title,
8bdd16b4 197 'alt_title': strip_or_none(media.get('subtitle')),
b8d8cced 198 'description': media.get('description'),
9c48b5a1 199 'uploader': strip_or_none(media.get('channel')),
8bdd16b4 200 'creator': strip_or_none(media.get('editor') or None),
b8d8cced 201 'duration': parse_duration(video.get('duration')),
8bdd16b4 202 'timestamp': unified_timestamp(date_published),
51342717 203 'thumbnails': thumbnails,
8bdd16b4 204 'series': program_info.get('name'),
205 'season_number': int_or_none(season),
206 'season': season if (season and not season.isdigit()) else None,
207 'episode': media.get('episode_title'),
208 'episode_number': int_or_none(media.get('episode')),
1b3feca0 209 'subtitles': subtitles,
51342717 210 }
b0adbe98 211
b8d8cced 212 info.update(relinker_info)
b8d8cced
S
213 return info
214
06d5556d 215
a0566bbf 216class RaiPlayLiveIE(RaiPlayIE):
217 _VALID_URL = r'(?P<base>https?://(?:www\.)?raiplay\.it/dirette/(?P<id>[^/?#&]+))'
218 _TESTS = [{
9c48b5a1
S
219 'url': 'http://www.raiplay.it/dirette/rainews24',
220 'info_dict': {
221 'id': 'd784ad40-e0ae-4a69-aa76-37519d238a9c',
222 'display_id': 'rainews24',
223 'ext': 'mp4',
224 'title': 're:^Diretta di Rai News 24 [0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}$',
a0566bbf 225 'description': 'md5:4d00bcf6dc98b27c6ec480de329d1497',
9c48b5a1
S
226 'uploader': 'Rai News 24',
227 'creator': 'Rai News 24',
228 'is_live': True,
229 },
230 'params': {
231 'skip_download': True,
232 },
a0566bbf 233 }]
449c6657 234
235
1115271a 236class RaiPlayPlaylistIE(InfoExtractor):
a0566bbf 237 _VALID_URL = r'(?P<base>https?://(?:www\.)?raiplay\.it/programmi/(?P<id>[^/?#&]+))'
1115271a
S
238 _TESTS = [{
239 'url': 'http://www.raiplay.it/programmi/nondirloalmiocapo/',
240 'info_dict': {
241 'id': 'nondirloalmiocapo',
242 'title': 'Non dirlo al mio capo',
a0566bbf 243 'description': 'md5:98ab6b98f7f44c2843fd7d6f045f153b',
1115271a
S
244 },
245 'playlist_mincount': 12,
246 }]
247
248 def _real_extract(self, url):
a0566bbf 249 base, playlist_id = re.match(self._VALID_URL, url).groups()
1115271a 250
a0566bbf 251 program = self._download_json(
252 base + '.json', playlist_id, 'Downloading program JSON')
1115271a
S
253
254 entries = []
a0566bbf 255 for b in (program.get('blocks') or []):
256 for s in (b.get('sets') or []):
257 s_id = s.get('id')
258 if not s_id:
259 continue
260 medias = self._download_json(
261 '%s/%s.json' % (base, s_id), s_id,
262 'Downloading content set JSON', fatal=False)
263 if not medias:
264 continue
265 for m in (medias.get('items') or []):
266 path_id = m.get('path_id')
267 if not path_id:
268 continue
269 video_url = urljoin(url, path_id)
270 entries.append(self.url_result(
271 video_url, ie=RaiPlayIE.ie_key(),
272 video_id=RaiPlayIE._match_id(video_url)))
273
274 return self.playlist_result(
275 entries, playlist_id, program.get('name'),
276 try_get(program, lambda x: x['program_info']['description']))
1115271a
S
277
278
034a8849 279class RaiIE(RaiBaseIE):
2b2da3ba 280 _VALID_URL = r'https?://[^/]+\.(?:rai\.(?:it|tv)|rainews\.it)/.+?-(?P<id>%s)(?:-.+?)?\.html' % RaiBaseIE._UUID_RE
51342717 281 _TESTS = [{
b8d8cced
S
282 # var uniquename = "ContentItem-..."
283 # data-id="ContentItem-..."
51342717
T
284 'url': 'http://www.raisport.rai.it/dl/raiSport/media/rassegna-stampa-04a9f4bd-b563-40cf-82a6-aad3529cb4a9.html',
285 'info_dict': {
286 'id': '04a9f4bd-b563-40cf-82a6-aad3529cb4a9',
287 'ext': 'mp4',
288 'title': 'TG PRIMO TEMPO',
b8d8cced 289 'thumbnail': r're:^https?://.*\.jpg$',
51342717 290 'duration': 1758,
b8d8cced 291 'upload_date': '20140612',
8bdd16b4 292 },
293 'skip': 'This content is available only in Italy',
51342717 294 }, {
b8d8cced 295 # with ContentItem in many metas
51342717
T
296 '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',
297 'info_dict': {
298 'id': '1632c009-c843-4836-bb65-80c33084a64b',
299 'ext': 'mp4',
b8d8cced
S
300 'title': 'Weekend al cinema, da Hollywood arriva il thriller di Tate Taylor "La ragazza del treno"',
301 'description': 'I film in uscita questa settimana.',
51342717 302 'thumbnail': r're:^https?://.*\.png$',
b8d8cced
S
303 'duration': 833,
304 'upload_date': '20161103',
51342717
T
305 }
306 }, {
b8d8cced 307 # with ContentItem in og:url
51342717 308 'url': 'http://www.rai.it/dl/RaiTV/programmi/media/ContentItem-efb17665-691c-45d5-a60c-5301333cbb0c.html',
abea9145 309 'md5': '6865dd00cf0bbf5772fdd89d59bd768a',
51342717
T
310 'info_dict': {
311 'id': 'efb17665-691c-45d5-a60c-5301333cbb0c',
312 'ext': 'mp4',
313 'title': 'TG1 ore 20:00 del 03/11/2016',
b8d8cced 314 'description': 'TG1 edizione integrale ore 20:00 del giorno 03/11/2016',
51342717 315 'thumbnail': r're:^https?://.*\.jpg$',
b8d8cced 316 'duration': 2214,
51342717 317 'upload_date': '20161103',
51342717 318 }
51342717 319 }, {
b8d8cced
S
320 # initEdizione('ContentItem-...'
321 'url': 'http://www.tg1.rai.it/dl/tg1/2010/edizioni/ContentSet-9b6e0cba-4bef-4aef-8cf0-9f7f665b7dfb-tg1.html?item=undefined',
322 'info_dict': {
323 'id': 'c2187016-8484-4e3a-8ac8-35e475b07303',
324 'ext': 'mp4',
325 'title': r're:TG1 ore \d{2}:\d{2} del \d{2}/\d{2}/\d{4}',
326 'duration': 2274,
327 'upload_date': '20170401',
328 },
329 'skip': 'Changes daily',
51342717 330 }, {
b8d8cced 331 # HLS live stream with ContentItem in og:url
51342717 332 'url': 'http://www.rainews.it/dl/rainews/live/ContentItem-3156f2f2-dc70-4953-8e2f-70d7489d4ce9.html',
51342717
T
333 'info_dict': {
334 'id': '3156f2f2-dc70-4953-8e2f-70d7489d4ce9',
335 'ext': 'mp4',
336 'title': 'La diretta di Rainews24',
15e4b6b7 337 },
b8d8cced
S
338 'params': {
339 'skip_download': True,
340 },
00dd0cd5 341 }, {
342 # ContentItem in iframe (see #12652) and subtitle at 'subtitlesUrl' key
343 'url': 'http://www.presadiretta.rai.it/dl/portali/site/puntata/ContentItem-3ed19d13-26c2-46ff-a551-b10828262f1b.html',
344 'info_dict': {
345 'id': '1ad6dc64-444a-42a4-9bea-e5419ad2f5fd',
346 'ext': 'mp4',
347 'title': 'Partiti acchiappavoti - Presa diretta del 13/09/2015',
348 'description': 'md5:d291b03407ec505f95f27970c0b025f4',
349 'upload_date': '20150913',
350 'subtitles': {
351 'it': 'count:2',
352 },
353 },
354 'params': {
355 'skip_download': True,
356 },
0c7b4f49
RA
357 }, {
358 # Direct MMS URL
359 'url': 'http://www.rai.it/dl/RaiTV/programmi/media/ContentItem-b63a4089-ac28-48cf-bca5-9f5b5bc46df5.html',
360 'only_matching': True,
2b2da3ba
S
361 }, {
362 'url': 'https://www.rainews.it/tgr/marche/notiziari/video/2019/02/ContentItem-6ba945a2-889c-4a80-bdeb-8489c70a8db9.html',
363 'only_matching': True,
51342717 364 }]
06d5556d 365
51342717
T
366 def _extract_from_content_id(self, content_id, url):
367 media = self._download_json(
368 'http://www.rai.tv/dl/RaiTV/programmi/media/ContentItem-%s.html?json' % content_id,
369 content_id, 'Downloading video JSON')
370
b8d8cced
S
371 title = media['name'].strip()
372
373 media_type = media['type']
374 if 'Audio' in media_type:
375 relinker_info = {
085d9dd9 376 'formats': [{
b8d8cced
S
377 'format_id': media.get('formatoAudio'),
378 'url': media['audioUrl'],
379 'ext': media.get('formatoAudio'),
085d9dd9 380 }]
b8d8cced
S
381 }
382 elif 'Video' in media_type:
383 relinker_info = self._extract_relinker_info(media['mediaUri'], content_id)
384 else:
385 raise ExtractorError('not a media file')
386
387 self._sort_formats(relinker_info['formats'])
388
51342717
T
389 thumbnails = []
390 for image_type in ('image', 'image_medium', 'image_300'):
391 thumbnail_url = media.get(image_type)
392 if thumbnail_url:
393 thumbnails.append({
394 'url': compat_urlparse.urljoin(url, thumbnail_url),
395 })
396
00dd0cd5 397 subtitles = self._extract_subtitles(url, media)
51342717 398
b8d8cced 399 info = {
51342717 400 'id': content_id,
b8d8cced
S
401 'title': title,
402 'description': strip_or_none(media.get('desc')),
51342717
T
403 'thumbnails': thumbnails,
404 'uploader': media.get('author'),
405 'upload_date': unified_strdate(media.get('date')),
406 'duration': parse_duration(media.get('length')),
51342717
T
407 'subtitles': subtitles,
408 }
b8d8cced
S
409
410 info.update(relinker_info)
411
412 return info
413
414 def _real_extract(self, url):
415 video_id = self._match_id(url)
416
417 webpage = self._download_webpage(url, video_id)
418
419 content_item_id = None
420
421 content_item_url = self._html_search_meta(
422 ('og:url', 'og:video', 'og:video:secure_url', 'twitter:url',
423 'twitter:player', 'jsonlink'), webpage, default=None)
424 if content_item_url:
425 content_item_id = self._search_regex(
426 r'ContentItem-(%s)' % self._UUID_RE, content_item_url,
427 'content item id', default=None)
428
429 if not content_item_id:
430 content_item_id = self._search_regex(
431 r'''(?x)
432 (?:
433 (?:initEdizione|drawMediaRaiTV)\(|
00dd0cd5 434 <(?:[^>]+\bdata-id|var\s+uniquename)=|
435 <iframe[^>]+\bsrc=
b8d8cced
S
436 )
437 (["\'])
438 (?:(?!\1).)*\bContentItem-(?P<id>%s)
439 ''' % self._UUID_RE,
440 webpage, 'content item id', default=None, group='id')
441
442 content_item_ids = set()
361f293a
S
443 if content_item_id:
444 content_item_ids.add(content_item_id)
b8d8cced
S
445 if video_id not in content_item_ids:
446 content_item_ids.add(video_id)
447
448 for content_item_id in content_item_ids:
449 try:
450 return self._extract_from_content_id(content_item_id, url)
451 except GeoRestrictedError:
452 raise
453 except ExtractorError:
454 pass
455
a0566bbf 456 relinker_url = self._proto_relative_url(self._search_regex(
b8d8cced
S
457 r'''(?x)
458 (?:
459 var\s+videoURL|
460 mediaInfo\.mediaUri
461 )\s*=\s*
462 ([\'"])
463 (?P<url>
464 (?:https?:)?
465 //mediapolis(?:vod)?\.rai\.it/relinker/relinkerServlet\.htm\?
466 (?:(?!\1).)*\bcont=(?:(?!\1).)+)\1
467 ''',
a0566bbf 468 webpage, 'relinker URL', group='url'))
b8d8cced
S
469
470 relinker_info = self._extract_relinker_info(
471 urljoin(url, relinker_url), video_id)
472 self._sort_formats(relinker_info['formats'])
473
474 title = self._search_regex(
475 r'var\s+videoTitolo\s*=\s*([\'"])(?P<title>[^\'"]+)\1',
476 webpage, 'title', group='title',
477 default=None) or self._og_search_title(webpage)
478
479 info = {
480 'id': video_id,
481 'title': title,
482 }
483
484 info.update(relinker_info)
485
486 return info