[raiplay:live] Add extractor
[youtube-dl] / youtube_dl / extractor / rai.py
1 from __future__ import unicode_literals
2
3 import re
4
5 from .common import InfoExtractor
6 from ..compat import (
7     compat_urlparse,
8     compat_str,
9 )
10 from ..utils import (
11     ExtractorError,
12     determine_ext,
13     find_xpath_attr,
14     fix_xml_ampersands,
15     GeoRestrictedError,
16     int_or_none,
17     parse_duration,
18     strip_or_none,
19     try_get,
20     unified_strdate,
21     unified_timestamp,
22     update_url_query,
23     urljoin,
24     xpath_text,
25 )
26
27
28 class RaiBaseIE(InfoExtractor):
29     _UUID_RE = r'[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}'
30     _GEO_COUNTRIES = ['IT']
31     _GEO_BYPASS = False
32
33     def _extract_relinker_info(self, relinker_url, video_id):
34         formats = []
35         geoprotection = None
36         is_live = None
37         duration = None
38
39         for platform in ('mon', 'flash', 'native'):
40             relinker = self._download_xml(
41                 relinker_url, video_id,
42                 note='Downloading XML metadata for platform %s' % platform,
43                 transform_source=fix_xml_ampersands,
44                 query={'output': 45, 'pl': platform},
45                 headers=self.geo_verification_headers())
46
47             if not geoprotection:
48                 geoprotection = xpath_text(
49                     relinker, './geoprotection', default=None) == 'Y'
50
51             if not is_live:
52                 is_live = xpath_text(
53                     relinker, './is_live', default=None) == 'Y'
54             if not duration:
55                 duration = parse_duration(xpath_text(
56                     relinker, './duration', default=None))
57
58             url_elem = find_xpath_attr(relinker, './url', 'type', 'content')
59             if url_elem is None:
60                 continue
61
62             media_url = url_elem.text
63
64             # This does not imply geo restriction (e.g.
65             # http://www.raisport.rai.it/dl/raiSport/media/rassegna-stampa-04a9f4bd-b563-40cf-82a6-aad3529cb4a9.html)
66             if media_url == 'http://download.rai.it/video_no_available.mp4':
67                 continue
68
69             ext = determine_ext(media_url)
70             if (ext == 'm3u8' and platform != 'mon') or (ext == 'f4m' and platform != 'flash'):
71                 continue
72
73             if ext == 'm3u8':
74                 formats.extend(self._extract_m3u8_formats(
75                     media_url, video_id, 'mp4', 'm3u8_native',
76                     m3u8_id='hls', fatal=False))
77             elif ext == 'f4m':
78                 manifest_url = update_url_query(
79                     media_url.replace('manifest#live_hds.f4m', 'manifest.f4m'),
80                     {'hdcore': '3.7.0', 'plugin': 'aasp-3.7.0.39.44'})
81                 formats.extend(self._extract_f4m_formats(
82                     manifest_url, video_id, f4m_id='hds', fatal=False))
83             else:
84                 bitrate = int_or_none(xpath_text(relinker, 'bitrate'))
85                 formats.append({
86                     'url': media_url,
87                     'tbr': bitrate if bitrate > 0 else None,
88                     'format_id': 'http-%d' % bitrate if bitrate > 0 else 'http',
89                 })
90
91         if not formats and geoprotection is True:
92             self.raise_geo_restricted(countries=self._GEO_COUNTRIES)
93
94         return dict((k, v) for k, v in {
95             'is_live': is_live,
96             'duration': duration,
97             'formats': formats,
98         }.items() if v is not None)
99
100     @staticmethod
101     def _extract_subtitles(url, subtitle_url):
102         subtitles = {}
103         if subtitle_url and isinstance(subtitle_url, compat_str):
104             subtitle_url = urljoin(url, subtitle_url)
105             STL_EXT = '.stl'
106             SRT_EXT = '.srt'
107             subtitles['it'] = [{
108                 'ext': 'stl',
109                 'url': subtitle_url,
110             }]
111             if subtitle_url.endswith(STL_EXT):
112                 srt_url = subtitle_url[:-len(STL_EXT)] + SRT_EXT
113                 subtitles['it'].append({
114                     'ext': 'srt',
115                     'url': srt_url,
116                 })
117         return subtitles
118
119
120 class RaiPlayIE(RaiBaseIE):
121     _VALID_URL = r'(?P<url>https?://(?:www\.)?raiplay\.it/.+?-(?P<id>%s)\.html)' % RaiBaseIE._UUID_RE
122     _TESTS = [{
123         'url': 'http://www.raiplay.it/video/2016/10/La-Casa-Bianca-e06118bb-59a9-4636-b914-498e4cfd2c66.html?source=twitter',
124         'md5': '340aa3b7afb54bfd14a8c11786450d76',
125         'info_dict': {
126             'id': 'e06118bb-59a9-4636-b914-498e4cfd2c66',
127             'ext': 'mp4',
128             'title': 'La Casa Bianca',
129             'alt_title': 'S2016 - Puntata del 23/10/2016',
130             'description': 'md5:a09d45890850458077d1f68bb036e0a5',
131             'thumbnail': r're:^https?://.*\.jpg$',
132             'uploader': 'Rai 3',
133             'creator': 'Rai 3',
134             'duration': 3278,
135             'timestamp': 1477764300,
136             'upload_date': '20161029',
137             'series': 'La Casa Bianca',
138             'season': '2016',
139         },
140     }, {
141         'url': 'http://www.raiplay.it/video/2014/04/Report-del-07042014-cb27157f-9dd0-4aee-b788-b1f67643a391.html',
142         'md5': '8970abf8caf8aef4696e7b1f2adfc696',
143         'info_dict': {
144             'id': 'cb27157f-9dd0-4aee-b788-b1f67643a391',
145             'ext': 'mp4',
146             'title': 'Report del 07/04/2014',
147             'alt_title': 'S2013/14 - Puntata del 07/04/2014',
148             'description': 'md5:f27c544694cacb46a078db84ec35d2d9',
149             'thumbnail': r're:^https?://.*\.jpg$',
150             'uploader': 'Rai 5',
151             'creator': 'Rai 5',
152             'duration': 6160,
153             'series': 'Report',
154             'season_number': 5,
155             'season': '2013/14',
156         },
157         'params': {
158             'skip_download': True,
159         },
160     }, {
161         'url': 'http://www.raiplay.it/video/2016/11/gazebotraindesi-efebe701-969c-4593-92f3-285f0d1ce750.html?',
162         'only_matching': True,
163     }]
164
165     def _real_extract(self, url):
166         mobj = re.match(self._VALID_URL, url)
167         url, video_id = mobj.group('url', 'id')
168
169         media = self._download_json(
170             '%s?json' % url, video_id, 'Downloading video JSON')
171
172         title = media['name']
173
174         video = media['video']
175
176         relinker_info = self._extract_relinker_info(video['contentUrl'], video_id)
177         self._sort_formats(relinker_info['formats'])
178
179         thumbnails = []
180         if 'images' in media:
181             for _, value in media.get('images').items():
182                 if value:
183                     thumbnails.append({
184                         'url': value.replace('[RESOLUTION]', '600x400')
185                     })
186
187         timestamp = unified_timestamp(try_get(
188             media, lambda x: x['availabilities'][0]['start'], compat_str))
189
190         subtitles = self._extract_subtitles(url, video.get('subtitles'))
191
192         info = {
193             'id': video_id,
194             'title': title,
195             'alt_title': media.get('subtitle'),
196             'description': media.get('description'),
197             'uploader': media.get('channel'),
198             'creator': media.get('editor'),
199             'duration': parse_duration(video.get('duration')),
200             'timestamp': timestamp,
201             'thumbnails': thumbnails,
202             'series': try_get(
203                 media, lambda x: x['isPartOf']['name'], compat_str),
204             'season_number': int_or_none(try_get(
205                 media, lambda x: x['isPartOf']['numeroStagioni'])),
206             'season': media.get('stagione') or None,
207             'subtitles': subtitles,
208         }
209
210         info.update(relinker_info)
211         return info
212
213
214 class RaiPlayLiveIE(RaiBaseIE):
215     _VALID_URL = r'https?://(?:www\.)?raiplay\.it/dirette/(?P<id>\w*)'
216     _TEST = {
217         'url': 'http://www.raiplay.it/dirette/rai3',
218         'only_matching': True,
219     }
220
221     def _real_extract(self, url):
222         channel = self._match_id(url)
223
224         webpage = self._download_webpage(url, channel)
225         re_id = r'<div([^>]*)data-uniquename=(["\'])[\w-]*(?P<id>%s)(\2)([^>]*?)>' % RaiBaseIE._UUID_RE
226         video_id = self._html_search_regex(re_id, webpage, 'livestream-id', group='id')
227
228         return self.url_result('http://www.raiplay.it/dirette/ContentItem-%s.html' % video_id,
229                                RaiPlayIE.ie_key(), video_id)
230
231
232 class RaiIE(RaiBaseIE):
233     _VALID_URL = r'https?://[^/]+\.(?:rai\.(?:it|tv)|rainews\.it)/dl/.+?-(?P<id>%s)(?:-.+?)?\.html' % RaiBaseIE._UUID_RE
234     _TESTS = [{
235         # var uniquename = "ContentItem-..."
236         # data-id="ContentItem-..."
237         'url': 'http://www.raisport.rai.it/dl/raiSport/media/rassegna-stampa-04a9f4bd-b563-40cf-82a6-aad3529cb4a9.html',
238         'info_dict': {
239             'id': '04a9f4bd-b563-40cf-82a6-aad3529cb4a9',
240             'ext': 'mp4',
241             'title': 'TG PRIMO TEMPO',
242             'thumbnail': r're:^https?://.*\.jpg$',
243             'duration': 1758,
244             'upload_date': '20140612',
245         }
246     }, {
247         # with ContentItem in many metas
248         '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',
249         'info_dict': {
250             'id': '1632c009-c843-4836-bb65-80c33084a64b',
251             'ext': 'mp4',
252             'title': 'Weekend al cinema, da Hollywood arriva il thriller di Tate Taylor "La ragazza del treno"',
253             'description': 'I film in uscita questa settimana.',
254             'thumbnail': r're:^https?://.*\.png$',
255             'duration': 833,
256             'upload_date': '20161103',
257         }
258     }, {
259         # with ContentItem in og:url
260         'url': 'http://www.rai.it/dl/RaiTV/programmi/media/ContentItem-efb17665-691c-45d5-a60c-5301333cbb0c.html',
261         'md5': '11959b4e44fa74de47011b5799490adf',
262         'info_dict': {
263             'id': 'efb17665-691c-45d5-a60c-5301333cbb0c',
264             'ext': 'mp4',
265             'title': 'TG1 ore 20:00 del 03/11/2016',
266             'description': 'TG1 edizione integrale ore 20:00 del giorno 03/11/2016',
267             'thumbnail': r're:^https?://.*\.jpg$',
268             'duration': 2214,
269             'upload_date': '20161103',
270         }
271     }, {
272         # drawMediaRaiTV(...)
273         'url': 'http://www.report.rai.it/dl/Report/puntata/ContentItem-0c7a664b-d0f4-4b2c-8835-3f82e46f433e.html',
274         'md5': '2dd727e61114e1ee9c47f0da6914e178',
275         'info_dict': {
276             'id': '59d69d28-6bb6-409d-a4b5-ed44096560af',
277             'ext': 'mp4',
278             'title': 'Il pacco',
279             'description': 'md5:4b1afae1364115ce5d78ed83cd2e5b3a',
280             'thumbnail': r're:^https?://.*\.jpg$',
281             'upload_date': '20141221',
282         },
283     }, {
284         # initEdizione('ContentItem-...'
285         'url': 'http://www.tg1.rai.it/dl/tg1/2010/edizioni/ContentSet-9b6e0cba-4bef-4aef-8cf0-9f7f665b7dfb-tg1.html?item=undefined',
286         'info_dict': {
287             'id': 'c2187016-8484-4e3a-8ac8-35e475b07303',
288             'ext': 'mp4',
289             'title': r're:TG1 ore \d{2}:\d{2} del \d{2}/\d{2}/\d{4}',
290             'duration': 2274,
291             'upload_date': '20170401',
292         },
293         'skip': 'Changes daily',
294     }, {
295         # HDS live stream with only relinker URL
296         'url': 'http://www.rai.tv/dl/RaiTV/dirette/PublishingBlock-1912dbbf-3f96-44c3-b4cf-523681fbacbc.html?channel=EuroNews',
297         'info_dict': {
298             'id': '1912dbbf-3f96-44c3-b4cf-523681fbacbc',
299             'ext': 'flv',
300             'title': 'EuroNews',
301         },
302         'params': {
303             'skip_download': True,
304         },
305     }, {
306         # HLS live stream with ContentItem in og:url
307         'url': 'http://www.rainews.it/dl/rainews/live/ContentItem-3156f2f2-dc70-4953-8e2f-70d7489d4ce9.html',
308         'info_dict': {
309             'id': '3156f2f2-dc70-4953-8e2f-70d7489d4ce9',
310             'ext': 'mp4',
311             'title': 'La diretta di Rainews24',
312         },
313         'params': {
314             'skip_download': True,
315         },
316     }]
317
318     def _extract_from_content_id(self, content_id, url):
319         media = self._download_json(
320             'http://www.rai.tv/dl/RaiTV/programmi/media/ContentItem-%s.html?json' % content_id,
321             content_id, 'Downloading video JSON')
322
323         title = media['name'].strip()
324
325         media_type = media['type']
326         if 'Audio' in media_type:
327             relinker_info = {
328                 'formats': {
329                     'format_id': media.get('formatoAudio'),
330                     'url': media['audioUrl'],
331                     'ext': media.get('formatoAudio'),
332                 }
333             }
334         elif 'Video' in media_type:
335             relinker_info = self._extract_relinker_info(media['mediaUri'], content_id)
336         else:
337             raise ExtractorError('not a media file')
338
339         self._sort_formats(relinker_info['formats'])
340
341         thumbnails = []
342         for image_type in ('image', 'image_medium', 'image_300'):
343             thumbnail_url = media.get(image_type)
344             if thumbnail_url:
345                 thumbnails.append({
346                     'url': compat_urlparse.urljoin(url, thumbnail_url),
347                 })
348
349         subtitles = self._extract_subtitles(url, media.get('subtitlesUrl'))
350
351         info = {
352             'id': content_id,
353             'title': title,
354             'description': strip_or_none(media.get('desc')),
355             'thumbnails': thumbnails,
356             'uploader': media.get('author'),
357             'upload_date': unified_strdate(media.get('date')),
358             'duration': parse_duration(media.get('length')),
359             'subtitles': subtitles,
360         }
361
362         info.update(relinker_info)
363
364         return info
365
366     def _real_extract(self, url):
367         video_id = self._match_id(url)
368
369         webpage = self._download_webpage(url, video_id)
370
371         content_item_id = None
372
373         content_item_url = self._html_search_meta(
374             ('og:url', 'og:video', 'og:video:secure_url', 'twitter:url',
375              'twitter:player', 'jsonlink'), webpage, default=None)
376         if content_item_url:
377             content_item_id = self._search_regex(
378                 r'ContentItem-(%s)' % self._UUID_RE, content_item_url,
379                 'content item id', default=None)
380
381         if not content_item_id:
382             content_item_id = self._search_regex(
383                 r'''(?x)
384                     (?:
385                         (?:initEdizione|drawMediaRaiTV)\(|
386                         <(?:[^>]+\bdata-id|var\s+uniquename)=
387                     )
388                     (["\'])
389                     (?:(?!\1).)*\bContentItem-(?P<id>%s)
390                 ''' % self._UUID_RE,
391                 webpage, 'content item id', default=None, group='id')
392
393         content_item_ids = set()
394         if content_item_id:
395             content_item_ids.add(content_item_id)
396         if video_id not in content_item_ids:
397             content_item_ids.add(video_id)
398
399         for content_item_id in content_item_ids:
400             try:
401                 return self._extract_from_content_id(content_item_id, url)
402             except GeoRestrictedError:
403                 raise
404             except ExtractorError:
405                 pass
406
407         relinker_url = self._search_regex(
408             r'''(?x)
409                 (?:
410                     var\s+videoURL|
411                     mediaInfo\.mediaUri
412                 )\s*=\s*
413                 ([\'"])
414                 (?P<url>
415                     (?:https?:)?
416                     //mediapolis(?:vod)?\.rai\.it/relinker/relinkerServlet\.htm\?
417                     (?:(?!\1).)*\bcont=(?:(?!\1).)+)\1
418             ''',
419             webpage, 'relinker URL', group='url')
420
421         relinker_info = self._extract_relinker_info(
422             urljoin(url, relinker_url), video_id)
423         self._sort_formats(relinker_info['formats'])
424
425         title = self._search_regex(
426             r'var\s+videoTitolo\s*=\s*([\'"])(?P<title>[^\'"]+)\1',
427             webpage, 'title', group='title',
428             default=None) or self._og_search_title(webpage)
429
430         info = {
431             'id': video_id,
432             'title': title,
433         }
434
435         info.update(relinker_info)
436
437         return info