]> jfr.im git - yt-dlp.git/blob - youtube_dlc/extractor/rai.py
Merge 'ytdl-org/youtube-dl/master' release 2020.11.19
[yt-dlp.git] / youtube_dlc / extractor / rai.py
1 # coding: utf-8
2 from __future__ import unicode_literals
3
4 import re
5
6 from .common import InfoExtractor
7 from ..compat import (
8 compat_urlparse,
9 compat_str,
10 )
11 from ..utils import (
12 ExtractorError,
13 determine_ext,
14 find_xpath_attr,
15 fix_xml_ampersands,
16 GeoRestrictedError,
17 int_or_none,
18 parse_duration,
19 strip_or_none,
20 unescapeHTML,
21 unified_strdate,
22 unified_timestamp,
23 update_url_query,
24 urljoin,
25 xpath_text,
26 )
27
28
29 class RaiBaseIE(InfoExtractor):
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):
35 if not re.match(r'https?://', relinker_url):
36 return {'formats': [{'url': relinker_url}]}
37
38 formats = []
39 geoprotection = None
40 is_live = None
41 duration = None
42
43 for platform in ('mon', 'flash', 'native'):
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,
48 query={'output': 45, 'pl': platform},
49 headers=self.geo_verification_headers())
50
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)
70 if media_url == 'http://download.rai.it/video_no_available.mp4':
71 continue
72
73 ext = determine_ext(media_url)
74 if (ext == 'm3u8' and platform != 'mon') or (ext == 'f4m' and platform != 'flash'):
75 continue
76
77 if ext == 'm3u8' or 'format=m3u8' in media_url or platform == 'mon':
78 formats.extend(self._extract_m3u8_formats(
79 media_url, video_id, 'mp4', 'm3u8_native',
80 m3u8_id='hls', fatal=False))
81 elif ext == 'f4m' or platform == 'flash':
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
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)
103
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
123
124 class RaiPlayIE(RaiBaseIE):
125 _VALID_URL = r'(?P<url>https?://(?:www\.)?raiplay\.it/.+?-(?P<id>%s)\.(?:html|json))' % RaiBaseIE._UUID_RE
126 _TESTS = [{
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 }, {
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',
151 'title': 'Report del 07/04/2014',
152 'alt_title': 'St 2013/14 - Espresso nel caffè - 07/04/2014',
153 'description': 'md5:d730c168a58f4bb35600fc2f881ec04e',
154 'thumbnail': r're:^https?://.*\.jpg$',
155 'uploader': 'Rai Gulp',
156 'duration': 6160,
157 'series': 'Report',
158 'season': '2013/14',
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,
166 }]
167
168 def _real_extract(self, url):
169 url, video_id = re.match(self._VALID_URL, url).groups()
170
171 media = self._download_json(
172 url.replace('.html', '.json'), video_id, 'Downloading video JSON')
173
174 title = media['name']
175 video = media['video']
176
177 relinker_info = self._extract_relinker_info(video['content_url'], video_id)
178 self._sort_formats(relinker_info['formats'])
179
180 thumbnails = []
181 for _, value in media.get('images', {}).items():
182 if value:
183 thumbnails.append({
184 'url': urljoin(url, value),
185 })
186
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
191
192 subtitles = self._extract_subtitles(url, video.get('subtitles'))
193
194 program_info = media.get('program_info') or {}
195 season = media.get('season')
196
197 info = {
198 'id': video_id,
199 'title': self._live_title(title) if relinker_info.get(
200 'is_live') else title,
201 'alt_title': strip_or_none(media.get('subtitle')),
202 'description': media.get('description'),
203 'uploader': strip_or_none(media.get('channel')),
204 'creator': strip_or_none(media.get('editor') or None),
205 'duration': parse_duration(video.get('duration')),
206 'timestamp': unified_timestamp(date_published),
207 'thumbnails': thumbnails,
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')),
213 'subtitles': subtitles,
214 }
215
216 info.update(relinker_info)
217 return info
218
219
220 class RaiPlayLiveIE(RaiBaseIE):
221 _VALID_URL = r'https?://(?:www\.)?raiplay\.it/dirette/(?P<id>[^/?#&]+)'
222 _TEST = {
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}$',
229 'description': 'md5:6eca31500550f9376819f174e5644754',
230 'uploader': 'Rai News 24',
231 'creator': 'Rai News 24',
232 'is_live': True,
233 },
234 'params': {
235 'skip_download': True,
236 },
237 }
238
239 def _real_extract(self, url):
240 display_id = self._match_id(url)
241
242 webpage = self._download_webpage(url, display_id)
243
244 video_id = self._search_regex(
245 r'data-uniquename=["\']ContentItem-(%s)' % RaiBaseIE._UUID_RE,
246 webpage, 'content id')
247
248 return {
249 '_type': 'url_transparent',
250 'ie_key': RaiPlayIE.ie_key(),
251 'url': 'http://www.raiplay.it/dirette/ContentItem-%s.html' % video_id,
252 'id': video_id,
253 'display_id': display_id,
254 }
255
256
257 class 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',
264 'description': 'md5:9f3d603b2947c1c7abb098f3b14fac86',
265 },
266 'playlist_mincount': 12,
267 }]
268
269 def _real_extract(self, url):
270 playlist_id = self._match_id(url)
271
272 webpage = self._download_webpage(url, playlist_id)
273
274 title = self._html_search_meta(
275 ('programma', 'nomeProgramma'), webpage, 'title')
276 description = unescapeHTML(self._html_search_meta(
277 ('description', 'og:description'), webpage, 'description'))
278
279 entries = []
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)))
287
288 return self.playlist_result(entries, playlist_id, title, description)
289
290
291 class RaiIE(RaiBaseIE):
292 _VALID_URL = r'https?://[^/]+\.(?:rai\.(?:it|tv)|rainews\.it)/.+?-(?P<id>%s)(?:-.+?)?\.html' % RaiBaseIE._UUID_RE
293 _TESTS = [{
294 # var uniquename = "ContentItem-..."
295 # data-id="ContentItem-..."
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',
301 'thumbnail': r're:^https?://.*\.jpg$',
302 'duration': 1758,
303 'upload_date': '20140612',
304 },
305 'skip': 'This content is available only in Italy',
306 }, {
307 # with ContentItem in many metas
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',
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.',
314 'thumbnail': r're:^https?://.*\.png$',
315 'duration': 833,
316 'upload_date': '20161103',
317 }
318 }, {
319 # with ContentItem in og:url
320 'url': 'http://www.rai.it/dl/RaiTV/programmi/media/ContentItem-efb17665-691c-45d5-a60c-5301333cbb0c.html',
321 'md5': '6865dd00cf0bbf5772fdd89d59bd768a',
322 'info_dict': {
323 'id': 'efb17665-691c-45d5-a60c-5301333cbb0c',
324 'ext': 'mp4',
325 'title': 'TG1 ore 20:00 del 03/11/2016',
326 'description': 'TG1 edizione integrale ore 20:00 del giorno 03/11/2016',
327 'thumbnail': r're:^https?://.*\.jpg$',
328 'duration': 2214,
329 'upload_date': '20161103',
330 }
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',
344 }, {
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',
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',
367 }, {
368 # HLS live stream with ContentItem in og:url
369 'url': 'http://www.rainews.it/dl/rainews/live/ContentItem-3156f2f2-dc70-4953-8e2f-70d7489d4ce9.html',
370 'info_dict': {
371 'id': '3156f2f2-dc70-4953-8e2f-70d7489d4ce9',
372 'ext': 'mp4',
373 'title': 'La diretta di Rainews24',
374 },
375 'params': {
376 'skip_download': True,
377 },
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,
382 }, {
383 'url': 'https://www.rainews.it/tgr/marche/notiziari/video/2019/02/ContentItem-6ba945a2-889c-4a80-bdeb-8489c70a8db9.html',
384 'only_matching': True,
385 }]
386
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
392 title = media['name'].strip()
393
394 media_type = media['type']
395 if 'Audio' in media_type:
396 relinker_info = {
397 'formats': [{
398 'format_id': media.get('formatoAudio'),
399 'url': media['audioUrl'],
400 'ext': media.get('formatoAudio'),
401 }]
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
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
418 subtitles = self._extract_subtitles(url, media.get('subtitlesUrl'))
419
420 info = {
421 'id': content_id,
422 'title': title,
423 'description': strip_or_none(media.get('desc')),
424 'thumbnails': thumbnails,
425 'uploader': media.get('author'),
426 'upload_date': unified_strdate(media.get('date')),
427 'duration': parse_duration(media.get('length')),
428 'subtitles': subtitles,
429 }
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()
463 if content_item_id:
464 content_item_ids.add(content_item_id)
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