]> jfr.im git - yt-dlp.git/blame - youtube_dlc/extractor/rai.py
Merge 'ytdl-org/youtube-dl/master' release 2020.11.19
[yt-dlp.git] / youtube_dlc / 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,
b8d8cced 19 strip_or_none,
8bdd16b4 20 unescapeHTML,
b0adbe98 21 unified_strdate,
b8d8cced 22 unified_timestamp,
f1388739 23 update_url_query,
b8d8cced 24 urljoin,
06d5556d 25 xpath_text,
b0adbe98
S
26)
27
28
034a8849 29class RaiBaseIE(InfoExtractor):
b8d8cced
S
30 _UUID_RE = r'[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}'
31 _GEO_COUNTRIES = ['IT']
32 _GEO_BYPASS = False
33
34 def _extract_relinker_info(self, relinker_url, video_id):
0c7b4f49
RA
35 if not re.match(r'https?://', relinker_url):
36 return {'formats': [{'url': relinker_url}]}
37
034a8849 38 formats = []
b8d8cced
S
39 geoprotection = None
40 is_live = None
41 duration = None
034a8849
YCH
42
43 for platform in ('mon', 'flash', 'native'):
034a8849
YCH
44 relinker = self._download_xml(
45 relinker_url, video_id,
46 note='Downloading XML metadata for platform %s' % platform,
47 transform_source=fix_xml_ampersands,
38cce791
YCH
48 query={'output': 45, 'pl': platform},
49 headers=self.geo_verification_headers())
034a8849 50
b8d8cced
S
51 if not geoprotection:
52 geoprotection = xpath_text(
53 relinker, './geoprotection', default=None) == 'Y'
54
55 if not is_live:
56 is_live = xpath_text(
57 relinker, './is_live', default=None) == 'Y'
58 if not duration:
59 duration = parse_duration(xpath_text(
60 relinker, './duration', default=None))
61
62 url_elem = find_xpath_attr(relinker, './url', 'type', 'content')
63 if url_elem is None:
64 continue
65
66 media_url = url_elem.text
67
68 # This does not imply geo restriction (e.g.
69 # http://www.raisport.rai.it/dl/raiSport/media/rassegna-stampa-04a9f4bd-b563-40cf-82a6-aad3529cb4a9.html)
034a8849 70 if media_url == 'http://download.rai.it/video_no_available.mp4':
b8d8cced 71 continue
034a8849
YCH
72
73 ext = determine_ext(media_url)
74 if (ext == 'm3u8' and platform != 'mon') or (ext == 'f4m' and platform != 'flash'):
75 continue
76
c17eb5b4 77 if ext == 'm3u8' or 'format=m3u8' in media_url or platform == 'mon':
034a8849
YCH
78 formats.extend(self._extract_m3u8_formats(
79 media_url, video_id, 'mp4', 'm3u8_native',
80 m3u8_id='hls', fatal=False))
c17eb5b4 81 elif ext == 'f4m' or platform == 'flash':
034a8849
YCH
82 manifest_url = update_url_query(
83 media_url.replace('manifest#live_hds.f4m', 'manifest.f4m'),
84 {'hdcore': '3.7.0', 'plugin': 'aasp-3.7.0.39.44'})
85 formats.extend(self._extract_f4m_formats(
86 manifest_url, video_id, f4m_id='hds', fatal=False))
87 else:
88 bitrate = int_or_none(xpath_text(relinker, 'bitrate'))
89 formats.append({
90 'url': media_url,
91 'tbr': bitrate if bitrate > 0 else None,
92 'format_id': 'http-%d' % bitrate if bitrate > 0 else 'http',
93 })
94
b8d8cced
S
95 if not formats and geoprotection is True:
96 self.raise_geo_restricted(countries=self._GEO_COUNTRIES)
97
98 return dict((k, v) for k, v in {
99 'is_live': is_live,
100 'duration': duration,
101 'formats': formats,
102 }.items() if v is not None)
034a8849 103
1b3feca0
S
104 @staticmethod
105 def _extract_subtitles(url, subtitle_url):
106 subtitles = {}
107 if subtitle_url and isinstance(subtitle_url, compat_str):
108 subtitle_url = urljoin(url, subtitle_url)
109 STL_EXT = '.stl'
110 SRT_EXT = '.srt'
111 subtitles['it'] = [{
112 'ext': 'stl',
113 'url': subtitle_url,
114 }]
115 if subtitle_url.endswith(STL_EXT):
116 srt_url = subtitle_url[:-len(STL_EXT)] + SRT_EXT
117 subtitles['it'].append({
118 'ext': 'srt',
119 'url': srt_url,
120 })
121 return subtitles
122
2b28b892 123
51342717 124class RaiPlayIE(RaiBaseIE):
8bdd16b4 125 _VALID_URL = r'(?P<url>https?://(?:www\.)?raiplay\.it/.+?-(?P<id>%s)\.(?:html|json))' % RaiBaseIE._UUID_RE
51342717 126 _TESTS = [{
8bdd16b4 127 'url': 'http://www.raiplay.it/video/2016/10/La-Casa-Bianca-e06118bb-59a9-4636-b914-498e4cfd2c66.html?source=twitter',
128 'md5': '340aa3b7afb54bfd14a8c11786450d76',
129 'info_dict': {
130 'id': 'e06118bb-59a9-4636-b914-498e4cfd2c66',
131 'ext': 'mp4',
132 'title': 'La Casa Bianca',
133 'alt_title': 'S2016 - Puntata del 23/10/2016',
134 'description': 'md5:a09d45890850458077d1f68bb036e0a5',
135 'thumbnail': r're:^https?://.*\.jpg$',
136 'uploader': 'Rai 3',
137 'creator': 'Rai 3',
138 'duration': 3278,
139 'timestamp': 1477764300,
140 'upload_date': '20161029',
141 'series': 'La Casa Bianca',
142 'season': '2016',
143 },
144 'skip': 'This content is not available',
145 }, {
51342717
T
146 'url': 'http://www.raiplay.it/video/2014/04/Report-del-07042014-cb27157f-9dd0-4aee-b788-b1f67643a391.html',
147 'md5': '8970abf8caf8aef4696e7b1f2adfc696',
148 'info_dict': {
149 'id': 'cb27157f-9dd0-4aee-b788-b1f67643a391',
150 'ext': 'mp4',
b8d8cced 151 'title': 'Report del 07/04/2014',
8bdd16b4 152 'alt_title': 'St 2013/14 - Espresso nel caffè - 07/04/2014',
abea9145 153 'description': 'md5:d730c168a58f4bb35600fc2f881ec04e',
51342717 154 'thumbnail': r're:^https?://.*\.jpg$',
abea9145 155 'uploader': 'Rai Gulp',
b8d8cced 156 'duration': 6160,
8bdd16b4 157 'series': 'Report',
158 'season': '2013/14',
b8d8cced
S
159 },
160 'params': {
161 'skip_download': True,
162 },
163 }, {
164 'url': 'http://www.raiplay.it/video/2016/11/gazebotraindesi-efebe701-969c-4593-92f3-285f0d1ce750.html?',
165 'only_matching': True,
51342717 166 }]
2b28b892 167
51342717 168 def _real_extract(self, url):
8bdd16b4 169 url, video_id = re.match(self._VALID_URL, url).groups()
2b28b892 170
b8d8cced 171 media = self._download_json(
8bdd16b4 172 url.replace('.html', '.json'), video_id, 'Downloading video JSON')
2b28b892 173
b8d8cced 174 title = media['name']
b8d8cced
S
175 video = media['video']
176
abea9145 177 relinker_info = self._extract_relinker_info(video['content_url'], video_id)
b8d8cced 178 self._sort_formats(relinker_info['formats'])
2b28b892 179
51342717 180 thumbnails = []
8bdd16b4 181 for _, value in media.get('images', {}).items():
182 if value:
183 thumbnails.append({
184 'url': urljoin(url, value),
185 })
034a8849 186
8bdd16b4 187 date_published = media.get('date_published')
188 time_published = media.get('time_published')
189 if date_published and time_published:
190 date_published += ' ' + time_published
b0adbe98 191
1b3feca0
S
192 subtitles = self._extract_subtitles(url, video.get('subtitles'))
193
8bdd16b4 194 program_info = media.get('program_info') or {}
195 season = media.get('season')
196
b8d8cced 197 info = {
51342717 198 'id': video_id,
9c48b5a1
S
199 'title': self._live_title(title) if relinker_info.get(
200 'is_live') else title,
8bdd16b4 201 'alt_title': strip_or_none(media.get('subtitle')),
b8d8cced 202 'description': media.get('description'),
9c48b5a1 203 'uploader': strip_or_none(media.get('channel')),
8bdd16b4 204 'creator': strip_or_none(media.get('editor') or None),
b8d8cced 205 'duration': parse_duration(video.get('duration')),
8bdd16b4 206 'timestamp': unified_timestamp(date_published),
51342717 207 'thumbnails': thumbnails,
8bdd16b4 208 'series': program_info.get('name'),
209 'season_number': int_or_none(season),
210 'season': season if (season and not season.isdigit()) else None,
211 'episode': media.get('episode_title'),
212 'episode_number': int_or_none(media.get('episode')),
1b3feca0 213 'subtitles': subtitles,
51342717 214 }
b0adbe98 215
b8d8cced 216 info.update(relinker_info)
b8d8cced
S
217 return info
218
06d5556d 219
449c6657 220class RaiPlayLiveIE(RaiBaseIE):
9c48b5a1 221 _VALID_URL = r'https?://(?:www\.)?raiplay\.it/dirette/(?P<id>[^/?#&]+)'
449c6657 222 _TEST = {
9c48b5a1
S
223 'url': 'http://www.raiplay.it/dirette/rainews24',
224 'info_dict': {
225 'id': 'd784ad40-e0ae-4a69-aa76-37519d238a9c',
226 'display_id': 'rainews24',
227 'ext': 'mp4',
228 'title': 're:^Diretta di Rai News 24 [0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}$',
8bdd16b4 229 'description': 'md5:6eca31500550f9376819f174e5644754',
9c48b5a1
S
230 'uploader': 'Rai News 24',
231 'creator': 'Rai News 24',
232 'is_live': True,
233 },
234 'params': {
235 'skip_download': True,
236 },
449c6657 237 }
238
239 def _real_extract(self, url):
9c48b5a1
S
240 display_id = self._match_id(url)
241
8bdd16b4 242 webpage = self._download_webpage(url, display_id)
abea9145 243
8bdd16b4 244 video_id = self._search_regex(
245 r'data-uniquename=["\']ContentItem-(%s)' % RaiBaseIE._UUID_RE,
246 webpage, 'content id')
449c6657 247
8bdd16b4 248 return {
249 '_type': 'url_transparent',
250 'ie_key': RaiPlayIE.ie_key(),
251 'url': 'http://www.raiplay.it/dirette/ContentItem-%s.html' % video_id,
9c48b5a1
S
252 'id': video_id,
253 'display_id': display_id,
254 }
449c6657 255
256
1115271a
S
257class RaiPlayPlaylistIE(InfoExtractor):
258 _VALID_URL = r'https?://(?:www\.)?raiplay\.it/programmi/(?P<id>[^/?#&]+)'
259 _TESTS = [{
260 'url': 'http://www.raiplay.it/programmi/nondirloalmiocapo/',
261 'info_dict': {
262 'id': 'nondirloalmiocapo',
263 'title': 'Non dirlo al mio capo',
8bdd16b4 264 'description': 'md5:9f3d603b2947c1c7abb098f3b14fac86',
1115271a
S
265 },
266 'playlist_mincount': 12,
267 }]
268
269 def _real_extract(self, url):
270 playlist_id = self._match_id(url)
271
8bdd16b4 272 webpage = self._download_webpage(url, playlist_id)
abea9145 273
8bdd16b4 274 title = self._html_search_meta(
275 ('programma', 'nomeProgramma'), webpage, 'title')
276 description = unescapeHTML(self._html_search_meta(
277 ('description', 'og:description'), webpage, 'description'))
1115271a
S
278
279 entries = []
8bdd16b4 280 for mobj in re.finditer(
281 r'<a\b[^>]+\bhref=(["\'])(?P<path>/raiplay/video/.+?)\1',
282 webpage):
283 video_url = urljoin(url, mobj.group('path'))
284 entries.append(self.url_result(
285 video_url, ie=RaiPlayIE.ie_key(),
286 video_id=RaiPlayIE._match_id(video_url)))
1115271a
S
287
288 return self.playlist_result(entries, playlist_id, title, description)
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 }
8bdd16b4 331 }, {
332 # drawMediaRaiTV(...)
333 'url': 'http://www.report.rai.it/dl/Report/puntata/ContentItem-0c7a664b-d0f4-4b2c-8835-3f82e46f433e.html',
334 'md5': '2dd727e61114e1ee9c47f0da6914e178',
335 'info_dict': {
336 'id': '59d69d28-6bb6-409d-a4b5-ed44096560af',
337 'ext': 'mp4',
338 'title': 'Il pacco',
339 'description': 'md5:4b1afae1364115ce5d78ed83cd2e5b3a',
340 'thumbnail': r're:^https?://.*\.jpg$',
341 'upload_date': '20141221',
342 },
343 'skip': 'This content is not available',
51342717 344 }, {
b8d8cced
S
345 # initEdizione('ContentItem-...'
346 'url': 'http://www.tg1.rai.it/dl/tg1/2010/edizioni/ContentSet-9b6e0cba-4bef-4aef-8cf0-9f7f665b7dfb-tg1.html?item=undefined',
347 'info_dict': {
348 'id': 'c2187016-8484-4e3a-8ac8-35e475b07303',
349 'ext': 'mp4',
350 'title': r're:TG1 ore \d{2}:\d{2} del \d{2}/\d{2}/\d{4}',
351 'duration': 2274,
352 'upload_date': '20170401',
353 },
354 'skip': 'Changes daily',
8bdd16b4 355 }, {
356 # HDS live stream with only relinker URL
357 'url': 'http://www.rai.tv/dl/RaiTV/dirette/PublishingBlock-1912dbbf-3f96-44c3-b4cf-523681fbacbc.html?channel=EuroNews',
358 'info_dict': {
359 'id': '1912dbbf-3f96-44c3-b4cf-523681fbacbc',
360 'ext': 'flv',
361 'title': 'EuroNews',
362 },
363 'params': {
364 'skip_download': True,
365 },
366 'skip': 'This content is available only in Italy',
51342717 367 }, {
b8d8cced 368 # HLS live stream with ContentItem in og:url
51342717 369 'url': 'http://www.rainews.it/dl/rainews/live/ContentItem-3156f2f2-dc70-4953-8e2f-70d7489d4ce9.html',
51342717
T
370 'info_dict': {
371 'id': '3156f2f2-dc70-4953-8e2f-70d7489d4ce9',
372 'ext': 'mp4',
373 'title': 'La diretta di Rainews24',
15e4b6b7 374 },
b8d8cced
S
375 'params': {
376 'skip_download': True,
377 },
0c7b4f49
RA
378 }, {
379 # Direct MMS URL
380 'url': 'http://www.rai.it/dl/RaiTV/programmi/media/ContentItem-b63a4089-ac28-48cf-bca5-9f5b5bc46df5.html',
381 'only_matching': True,
2b2da3ba
S
382 }, {
383 'url': 'https://www.rainews.it/tgr/marche/notiziari/video/2019/02/ContentItem-6ba945a2-889c-4a80-bdeb-8489c70a8db9.html',
384 'only_matching': True,
51342717 385 }]
06d5556d 386
51342717
T
387 def _extract_from_content_id(self, content_id, url):
388 media = self._download_json(
389 'http://www.rai.tv/dl/RaiTV/programmi/media/ContentItem-%s.html?json' % content_id,
390 content_id, 'Downloading video JSON')
391
b8d8cced
S
392 title = media['name'].strip()
393
394 media_type = media['type']
395 if 'Audio' in media_type:
396 relinker_info = {
085d9dd9 397 'formats': [{
b8d8cced
S
398 'format_id': media.get('formatoAudio'),
399 'url': media['audioUrl'],
400 'ext': media.get('formatoAudio'),
085d9dd9 401 }]
b8d8cced
S
402 }
403 elif 'Video' in media_type:
404 relinker_info = self._extract_relinker_info(media['mediaUri'], content_id)
405 else:
406 raise ExtractorError('not a media file')
407
408 self._sort_formats(relinker_info['formats'])
409
51342717
T
410 thumbnails = []
411 for image_type in ('image', 'image_medium', 'image_300'):
412 thumbnail_url = media.get(image_type)
413 if thumbnail_url:
414 thumbnails.append({
415 'url': compat_urlparse.urljoin(url, thumbnail_url),
416 })
417
1b3feca0 418 subtitles = self._extract_subtitles(url, media.get('subtitlesUrl'))
51342717 419
b8d8cced 420 info = {
51342717 421 'id': content_id,
b8d8cced
S
422 'title': title,
423 'description': strip_or_none(media.get('desc')),
51342717
T
424 'thumbnails': thumbnails,
425 'uploader': media.get('author'),
426 'upload_date': unified_strdate(media.get('date')),
427 'duration': parse_duration(media.get('length')),
51342717
T
428 'subtitles': subtitles,
429 }
b8d8cced
S
430
431 info.update(relinker_info)
432
433 return info
434
435 def _real_extract(self, url):
436 video_id = self._match_id(url)
437
438 webpage = self._download_webpage(url, video_id)
439
440 content_item_id = None
441
442 content_item_url = self._html_search_meta(
443 ('og:url', 'og:video', 'og:video:secure_url', 'twitter:url',
444 'twitter:player', 'jsonlink'), webpage, default=None)
445 if content_item_url:
446 content_item_id = self._search_regex(
447 r'ContentItem-(%s)' % self._UUID_RE, content_item_url,
448 'content item id', default=None)
449
450 if not content_item_id:
451 content_item_id = self._search_regex(
452 r'''(?x)
453 (?:
454 (?:initEdizione|drawMediaRaiTV)\(|
455 <(?:[^>]+\bdata-id|var\s+uniquename)=
456 )
457 (["\'])
458 (?:(?!\1).)*\bContentItem-(?P<id>%s)
459 ''' % self._UUID_RE,
460 webpage, 'content item id', default=None, group='id')
461
462 content_item_ids = set()
361f293a
S
463 if content_item_id:
464 content_item_ids.add(content_item_id)
b8d8cced
S
465 if video_id not in content_item_ids:
466 content_item_ids.add(video_id)
467
468 for content_item_id in content_item_ids:
469 try:
470 return self._extract_from_content_id(content_item_id, url)
471 except GeoRestrictedError:
472 raise
473 except ExtractorError:
474 pass
475
476 relinker_url = self._search_regex(
477 r'''(?x)
478 (?:
479 var\s+videoURL|
480 mediaInfo\.mediaUri
481 )\s*=\s*
482 ([\'"])
483 (?P<url>
484 (?:https?:)?
485 //mediapolis(?:vod)?\.rai\.it/relinker/relinkerServlet\.htm\?
486 (?:(?!\1).)*\bcont=(?:(?!\1).)+)\1
487 ''',
488 webpage, 'relinker URL', group='url')
489
490 relinker_info = self._extract_relinker_info(
491 urljoin(url, relinker_url), video_id)
492 self._sort_formats(relinker_info['formats'])
493
494 title = self._search_regex(
495 r'var\s+videoTitolo\s*=\s*([\'"])(?P<title>[^\'"]+)\1',
496 webpage, 'title', group='title',
497 default=None) or self._og_search_title(webpage)
498
499 info = {
500 'id': video_id,
501 'title': title,
502 }
503
504 info.update(relinker_info)
505
506 return info