]> asedeno.scripts.mit.edu Git - youtube-dl.git/blob - youtube_dl/extractor/rai.py
[rai] fix protocol relative relinker URLs(closes #22766)
[youtube-dl.git] / youtube_dl / 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     remove_start,
20     strip_or_none,
21     try_get,
22     unified_strdate,
23     unified_timestamp,
24     update_url_query,
25     urljoin,
26     xpath_text,
27 )
28
29
30 class RaiBaseIE(InfoExtractor):
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):
36         if not re.match(r'https?://', relinker_url):
37             return {'formats': [{'url': relinker_url}]}
38
39         formats = []
40         geoprotection = None
41         is_live = None
42         duration = None
43
44         for platform in ('mon', 'flash', 'native'):
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,
49                 query={'output': 45, 'pl': platform},
50                 headers=self.geo_verification_headers())
51
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)
71             if '/video_no_available.mp4' in media_url:
72                 continue
73
74             ext = determine_ext(media_url)
75             if (ext == 'm3u8' and platform != 'mon') or (ext == 'f4m' and platform != 'flash'):
76                 continue
77
78             if ext == 'm3u8' or 'format=m3u8' in media_url or platform == 'mon':
79                 formats.extend(self._extract_m3u8_formats(
80                     media_url, video_id, 'mp4', 'm3u8_native',
81                     m3u8_id='hls', fatal=False))
82             elif ext == 'f4m' or platform == 'flash':
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
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)
104
105     @staticmethod
106     def _extract_subtitles(url, subtitle_url):
107         subtitles = {}
108         if subtitle_url and isinstance(subtitle_url, compat_str):
109             subtitle_url = urljoin(url, subtitle_url)
110             STL_EXT = '.stl'
111             SRT_EXT = '.srt'
112             subtitles['it'] = [{
113                 'ext': 'stl',
114                 'url': subtitle_url,
115             }]
116             if subtitle_url.endswith(STL_EXT):
117                 srt_url = subtitle_url[:-len(STL_EXT)] + SRT_EXT
118                 subtitles['it'].append({
119                     'ext': 'srt',
120                     'url': srt_url,
121                 })
122         return subtitles
123
124
125 class RaiPlayIE(RaiBaseIE):
126     _VALID_URL = r'(?P<base>https?://(?:www\.)?raiplay\.it/.+?-(?P<id>%s))\.(?:html|json)' % RaiBaseIE._UUID_RE
127     _TESTS = [{
128         'url': 'http://www.raiplay.it/video/2014/04/Report-del-07042014-cb27157f-9dd0-4aee-b788-b1f67643a391.html',
129         'md5': '8970abf8caf8aef4696e7b1f2adfc696',
130         'info_dict': {
131             'id': 'cb27157f-9dd0-4aee-b788-b1f67643a391',
132             'ext': 'mp4',
133             'title': 'Report del 07/04/2014',
134             'alt_title': 'St 2013/14 - Espresso nel caffè - 07/04/2014',
135             'description': 'md5:d730c168a58f4bb35600fc2f881ec04e',
136             'thumbnail': r're:^https?://.*\.jpg$',
137             'uploader': 'Rai Gulp',
138             'duration': 6160,
139             'series': 'Report',
140             'season': '2013/14',
141         },
142         'params': {
143             'skip_download': True,
144         },
145     }, {
146         'url': 'http://www.raiplay.it/video/2016/11/gazebotraindesi-efebe701-969c-4593-92f3-285f0d1ce750.html?',
147         'only_matching': True,
148     }]
149
150     def _real_extract(self, url):
151         base, video_id = re.match(self._VALID_URL, url).groups()
152
153         media = self._download_json(
154             base + '.json', video_id, 'Downloading video JSON')
155
156         title = media['name']
157
158         video = media['video']
159
160         relinker_info = self._extract_relinker_info(video['content_url'], video_id)
161         self._sort_formats(relinker_info['formats'])
162
163         thumbnails = []
164         for _, value in media.get('images', {}).items():
165             if value:
166                 thumbnails.append({
167                     'url': urljoin(url, value),
168                 })
169
170         date_published = media.get('date_published')
171         time_published = media.get('time_published')
172         if date_published and time_published:
173             date_published += ' ' + time_published
174
175         subtitles = self._extract_subtitles(url, video.get('subtitles'))
176
177         program_info = media.get('program_info') or {}
178         season = media.get('season')
179
180         info = {
181             'id': remove_start(media.get('id'), 'ContentItem-') or video_id,
182             'display_id': video_id,
183             'title': self._live_title(title) if relinker_info.get(
184                 'is_live') else title,
185             'alt_title': strip_or_none(media.get('subtitle')),
186             'description': media.get('description'),
187             'uploader': strip_or_none(media.get('channel')),
188             'creator': strip_or_none(media.get('editor') or None),
189             'duration': parse_duration(video.get('duration')),
190             'timestamp': unified_timestamp(date_published),
191             'thumbnails': thumbnails,
192             'series': program_info.get('name'),
193             'season_number': int_or_none(season),
194             'season': season if (season and not season.isdigit()) else None,
195             'episode': media.get('episode_title'),
196             'episode_number': int_or_none(media.get('episode')),
197             'subtitles': subtitles,
198         }
199
200         info.update(relinker_info)
201         return info
202
203
204 class RaiPlayLiveIE(RaiPlayIE):
205     _VALID_URL = r'(?P<base>https?://(?:www\.)?raiplay\.it/dirette/(?P<id>[^/?#&]+))'
206     _TESTS = [{
207         'url': 'http://www.raiplay.it/dirette/rainews24',
208         'info_dict': {
209             'id': 'd784ad40-e0ae-4a69-aa76-37519d238a9c',
210             'display_id': 'rainews24',
211             'ext': 'mp4',
212             'title': 're:^Diretta di Rai News 24 [0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}$',
213             'description': 'md5:4d00bcf6dc98b27c6ec480de329d1497',
214             'uploader': 'Rai News 24',
215             'creator': 'Rai News 24',
216             'is_live': True,
217         },
218         'params': {
219             'skip_download': True,
220         },
221     }]
222
223
224 class RaiPlayPlaylistIE(InfoExtractor):
225     _VALID_URL = r'(?P<base>https?://(?:www\.)?raiplay\.it/programmi/(?P<id>[^/?#&]+))'
226     _TESTS = [{
227         'url': 'http://www.raiplay.it/programmi/nondirloalmiocapo/',
228         'info_dict': {
229             'id': 'nondirloalmiocapo',
230             'title': 'Non dirlo al mio capo',
231             'description': 'md5:98ab6b98f7f44c2843fd7d6f045f153b',
232         },
233         'playlist_mincount': 12,
234     }]
235
236     def _real_extract(self, url):
237         base, playlist_id = re.match(self._VALID_URL, url).groups()
238
239         program = self._download_json(
240             base + '.json', playlist_id, 'Downloading program JSON')
241
242         entries = []
243         for b in (program.get('blocks') or []):
244             for s in (b.get('sets') or []):
245                 s_id = s.get('id')
246                 if not s_id:
247                     continue
248                 medias = self._download_json(
249                     '%s/%s.json' % (base, s_id), s_id,
250                     'Downloading content set JSON', fatal=False)
251                 if not medias:
252                     continue
253                 for m in (medias.get('items') or []):
254                     path_id = m.get('path_id')
255                     if not path_id:
256                         continue
257                     video_url = urljoin(url, path_id)
258                     entries.append(self.url_result(
259                         video_url, ie=RaiPlayIE.ie_key(),
260                         video_id=RaiPlayIE._match_id(video_url)))
261
262         return self.playlist_result(
263             entries, playlist_id, program.get('name'),
264             try_get(program, lambda x: x['program_info']['description']))
265
266
267 class RaiIE(RaiBaseIE):
268     _VALID_URL = r'https?://[^/]+\.(?:rai\.(?:it|tv)|rainews\.it)/.+?-(?P<id>%s)(?:-.+?)?\.html' % RaiBaseIE._UUID_RE
269     _TESTS = [{
270         # var uniquename = "ContentItem-..."
271         # data-id="ContentItem-..."
272         'url': 'http://www.raisport.rai.it/dl/raiSport/media/rassegna-stampa-04a9f4bd-b563-40cf-82a6-aad3529cb4a9.html',
273         'info_dict': {
274             'id': '04a9f4bd-b563-40cf-82a6-aad3529cb4a9',
275             'ext': 'mp4',
276             'title': 'TG PRIMO TEMPO',
277             'thumbnail': r're:^https?://.*\.jpg$',
278             'duration': 1758,
279             'upload_date': '20140612',
280         },
281         'skip': 'This content is available only in Italy',
282     }, {
283         # with ContentItem in many metas
284         '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',
285         'info_dict': {
286             'id': '1632c009-c843-4836-bb65-80c33084a64b',
287             'ext': 'mp4',
288             'title': 'Weekend al cinema, da Hollywood arriva il thriller di Tate Taylor "La ragazza del treno"',
289             'description': 'I film in uscita questa settimana.',
290             'thumbnail': r're:^https?://.*\.png$',
291             'duration': 833,
292             'upload_date': '20161103',
293         }
294     }, {
295         # with ContentItem in og:url
296         'url': 'http://www.rai.it/dl/RaiTV/programmi/media/ContentItem-efb17665-691c-45d5-a60c-5301333cbb0c.html',
297         'md5': '6865dd00cf0bbf5772fdd89d59bd768a',
298         'info_dict': {
299             'id': 'efb17665-691c-45d5-a60c-5301333cbb0c',
300             'ext': 'mp4',
301             'title': 'TG1 ore 20:00 del 03/11/2016',
302             'description': 'TG1 edizione integrale ore 20:00 del giorno 03/11/2016',
303             'thumbnail': r're:^https?://.*\.jpg$',
304             'duration': 2214,
305             'upload_date': '20161103',
306         }
307     }, {
308         # initEdizione('ContentItem-...'
309         'url': 'http://www.tg1.rai.it/dl/tg1/2010/edizioni/ContentSet-9b6e0cba-4bef-4aef-8cf0-9f7f665b7dfb-tg1.html?item=undefined',
310         'info_dict': {
311             'id': 'c2187016-8484-4e3a-8ac8-35e475b07303',
312             'ext': 'mp4',
313             'title': r're:TG1 ore \d{2}:\d{2} del \d{2}/\d{2}/\d{4}',
314             'duration': 2274,
315             'upload_date': '20170401',
316         },
317         'skip': 'Changes daily',
318     }, {
319         # HLS live stream with ContentItem in og:url
320         'url': 'http://www.rainews.it/dl/rainews/live/ContentItem-3156f2f2-dc70-4953-8e2f-70d7489d4ce9.html',
321         'info_dict': {
322             'id': '3156f2f2-dc70-4953-8e2f-70d7489d4ce9',
323             'ext': 'mp4',
324             'title': 'La diretta di Rainews24',
325         },
326         'params': {
327             'skip_download': True,
328         },
329     }, {
330         # Direct MMS URL
331         'url': 'http://www.rai.it/dl/RaiTV/programmi/media/ContentItem-b63a4089-ac28-48cf-bca5-9f5b5bc46df5.html',
332         'only_matching': True,
333     }, {
334         'url': 'https://www.rainews.it/tgr/marche/notiziari/video/2019/02/ContentItem-6ba945a2-889c-4a80-bdeb-8489c70a8db9.html',
335         'only_matching': True,
336     }]
337
338     def _extract_from_content_id(self, content_id, url):
339         media = self._download_json(
340             'http://www.rai.tv/dl/RaiTV/programmi/media/ContentItem-%s.html?json' % content_id,
341             content_id, 'Downloading video JSON')
342
343         title = media['name'].strip()
344
345         media_type = media['type']
346         if 'Audio' in media_type:
347             relinker_info = {
348                 'formats': [{
349                     'format_id': media.get('formatoAudio'),
350                     'url': media['audioUrl'],
351                     'ext': media.get('formatoAudio'),
352                 }]
353             }
354         elif 'Video' in media_type:
355             relinker_info = self._extract_relinker_info(media['mediaUri'], content_id)
356         else:
357             raise ExtractorError('not a media file')
358
359         self._sort_formats(relinker_info['formats'])
360
361         thumbnails = []
362         for image_type in ('image', 'image_medium', 'image_300'):
363             thumbnail_url = media.get(image_type)
364             if thumbnail_url:
365                 thumbnails.append({
366                     'url': compat_urlparse.urljoin(url, thumbnail_url),
367                 })
368
369         subtitles = self._extract_subtitles(url, media.get('subtitlesUrl'))
370
371         info = {
372             'id': content_id,
373             'title': title,
374             'description': strip_or_none(media.get('desc')),
375             'thumbnails': thumbnails,
376             'uploader': media.get('author'),
377             'upload_date': unified_strdate(media.get('date')),
378             'duration': parse_duration(media.get('length')),
379             'subtitles': subtitles,
380         }
381
382         info.update(relinker_info)
383
384         return info
385
386     def _real_extract(self, url):
387         video_id = self._match_id(url)
388
389         webpage = self._download_webpage(url, video_id)
390
391         content_item_id = None
392
393         content_item_url = self._html_search_meta(
394             ('og:url', 'og:video', 'og:video:secure_url', 'twitter:url',
395              'twitter:player', 'jsonlink'), webpage, default=None)
396         if content_item_url:
397             content_item_id = self._search_regex(
398                 r'ContentItem-(%s)' % self._UUID_RE, content_item_url,
399                 'content item id', default=None)
400
401         if not content_item_id:
402             content_item_id = self._search_regex(
403                 r'''(?x)
404                     (?:
405                         (?:initEdizione|drawMediaRaiTV)\(|
406                         <(?:[^>]+\bdata-id|var\s+uniquename)=
407                     )
408                     (["\'])
409                     (?:(?!\1).)*\bContentItem-(?P<id>%s)
410                 ''' % self._UUID_RE,
411                 webpage, 'content item id', default=None, group='id')
412
413         content_item_ids = set()
414         if content_item_id:
415             content_item_ids.add(content_item_id)
416         if video_id not in content_item_ids:
417             content_item_ids.add(video_id)
418
419         for content_item_id in content_item_ids:
420             try:
421                 return self._extract_from_content_id(content_item_id, url)
422             except GeoRestrictedError:
423                 raise
424             except ExtractorError:
425                 pass
426
427         relinker_url = self._proto_relative_url(self._search_regex(
428             r'''(?x)
429                 (?:
430                     var\s+videoURL|
431                     mediaInfo\.mediaUri
432                 )\s*=\s*
433                 ([\'"])
434                 (?P<url>
435                     (?:https?:)?
436                     //mediapolis(?:vod)?\.rai\.it/relinker/relinkerServlet\.htm\?
437                     (?:(?!\1).)*\bcont=(?:(?!\1).)+)\1
438             ''',
439             webpage, 'relinker URL', group='url'))
440
441         relinker_info = self._extract_relinker_info(
442             urljoin(url, relinker_url), video_id)
443         self._sort_formats(relinker_info['formats'])
444
445         title = self._search_regex(
446             r'var\s+videoTitolo\s*=\s*([\'"])(?P<title>[^\'"]+)\1',
447             webpage, 'title', group='title',
448             default=None) or self._og_search_title(webpage)
449
450         info = {
451             'id': video_id,
452             'title': title,
453         }
454
455         info.update(relinker_info)
456
457         return info