[rai] Fix extraction
[youtube-dl] / youtube_dl / extractor / rai.py
1 from __future__ import unicode_literals
2
3 from .common import InfoExtractor
4 from ..compat import compat_urlparse
5 from ..utils import (
6     ExtractorError,
7     determine_ext,
8     find_xpath_attr,
9     fix_xml_ampersands,
10     int_or_none,
11     parse_duration,
12     unified_strdate,
13     update_url_query,
14     xpath_text,
15 )
16
17
18 class RaiBaseIE(InfoExtractor):
19     def _extract_relinker_formats(self, relinker_url, video_id):
20         formats = []
21
22         for platform in ('mon', 'flash', 'native'):
23             relinker = self._download_xml(
24                 relinker_url, video_id,
25                 note='Downloading XML metadata for platform %s' % platform,
26                 transform_source=fix_xml_ampersands,
27                 query={'output': 45, 'pl': platform},
28                 headers=self.geo_verification_headers())
29
30             media_url = find_xpath_attr(relinker, './url', 'type', 'content').text
31             if media_url == 'http://download.rai.it/video_no_available.mp4':
32                 self.raise_geo_restricted()
33
34             ext = determine_ext(media_url)
35             if (ext == 'm3u8' and platform != 'mon') or (ext == 'f4m' and platform != 'flash'):
36                 continue
37
38             if ext == 'm3u8':
39                 formats.extend(self._extract_m3u8_formats(
40                     media_url, video_id, 'mp4', 'm3u8_native',
41                     m3u8_id='hls', fatal=False))
42             elif ext == 'f4m':
43                 manifest_url = update_url_query(
44                     media_url.replace('manifest#live_hds.f4m', 'manifest.f4m'),
45                     {'hdcore': '3.7.0', 'plugin': 'aasp-3.7.0.39.44'})
46                 formats.extend(self._extract_f4m_formats(
47                     manifest_url, video_id, f4m_id='hds', fatal=False))
48             else:
49                 bitrate = int_or_none(xpath_text(relinker, 'bitrate'))
50                 formats.append({
51                     'url': media_url,
52                     'tbr': bitrate if bitrate > 0 else None,
53                     'format_id': 'http-%d' % bitrate if bitrate > 0 else 'http',
54                 })
55
56         return formats
57
58
59 class RaiPlayIE(RaiBaseIE):
60     _VALID_URL = r'https?://(?:www\.)?raiplay\.it/.+?-(?P<id>[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12})\.html'
61     _TESTS = [{
62         'url': 'http://www.raiplay.it/video/2016/10/La-Casa-Bianca-e06118bb-59a9-4636-b914-498e4cfd2c66.html?source=twitter',
63         'md5': '340aa3b7afb54bfd14a8c11786450d76',
64         'info_dict': {
65             'id': 'e06118bb-59a9-4636-b914-498e4cfd2c66',
66             'ext': 'mp4',
67             'title': 'La Casa Bianca',
68             'thumbnail': r're:^https?://.*\.jpg$',
69             'uploader': r're:^Rai.+',
70             'description': 're:^[A-Za-z]+'
71         }
72     }, {
73         'url': 'http://www.raiplay.it/video/2016/11/gazebotraindesi-efebe701-969c-4593-92f3-285f0d1ce750.html?',
74         'md5': 'ed4da3d70ccf8129a33ab16b34d20ab8',
75         'info_dict': {
76             'id': 'efebe701-969c-4593-92f3-285f0d1ce750',
77             'ext': 'mp4',
78             'title': 'Gazebo - #gazebotraindesi',
79             'thumbnail': r're:^https?://.*\.png$',
80             'uploader': r're:^Rai.+',
81             'description': r're:^[A-Za-z]+'
82         }
83     }, {
84         'url': 'http://www.raiplay.it/video/2014/04/Report-del-07042014-cb27157f-9dd0-4aee-b788-b1f67643a391.html',
85         'md5': '8970abf8caf8aef4696e7b1f2adfc696',
86         'info_dict': {
87             'id': 'cb27157f-9dd0-4aee-b788-b1f67643a391',
88             'ext': 'mp4',
89             'title': 'Report - Report del 07/04/2014',
90             'thumbnail': r're:^https?://.*\.jpg$',
91             'uploader': r're:^Rai.+',
92             'description': r're:^[A-Za-z]+'
93         }
94     }]
95     _RESOLUTION = '600x400'
96
97     def _real_extract(self, url):
98         video_id = self._match_id(url)
99
100         # remove query and fragment part from url
101         canonical_url = compat_urlparse.urljoin(url, compat_urlparse.urlparse(url).path)
102         webpage = self._download_webpage(canonical_url, video_id)
103
104         media = self._download_json('%s?json' % canonical_url,
105                                     video_id, 'Downloading video JSON')
106
107         thumbnails = []
108         if 'images' in media:
109             for _, value in media.get('images').items():
110                 if value:
111                     thumbnails.append({
112                         'url': value.replace('[RESOLUTION]', self._RESOLUTION)
113                     })
114
115         if 'video' not in media:
116             raise ExtractorError('No video found')
117
118         video = media.get('video')
119         duration = parse_duration(video.get('duration')),
120         formats = self._extract_relinker_formats(video.get('contentUrl'), video_id)
121         self._sort_formats(formats)
122
123         return {
124             'id': video_id,
125             'title': self._og_search_title(webpage).replace(' - video - RaiPlay', ''),
126             'description': self._og_search_description(webpage),
127             'uploader': media.get('channel'),
128             'duration': duration,
129             'thumbnails': thumbnails,
130             'formats': formats
131         }
132
133
134 class RaiIE(RaiBaseIE):
135     _VALID_URL = r'https?://.+\.(?:rai|rainews)\.it/dl/.+?-(?P<id>[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12})(?:-.+?)?\.html'
136     _TESTS = [{
137         # subdomain test case
138         'url': 'http://www.raisport.rai.it/dl/raiSport/media/rassegna-stampa-04a9f4bd-b563-40cf-82a6-aad3529cb4a9.html',
139         'info_dict': {
140             'id': '04a9f4bd-b563-40cf-82a6-aad3529cb4a9',
141             'ext': 'mp4',
142             'title': 'TG PRIMO TEMPO',
143             'upload_date': '20140612',
144             'duration': 1758,
145             'thumbnail': r're:^https?://.*\.jpg$'
146         }
147     }, {
148         # rainews test case
149         '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',
150         'info_dict': {
151             'id': '1632c009-c843-4836-bb65-80c33084a64b',
152             'ext': 'mp4',
153             'title': 'Weekend al cinema, da Hollywood arriva il thriller di Tate Taylor \"La ragazza del treno\" ',
154             'upload_date': '20161103',
155             'thumbnail': r're:^https?://.*\.png$',
156             'description': r're:^[A-Za-z]+'
157         }
158     }, {
159         # with media information
160         'url': 'http://www.rai.it/dl/RaiTV/programmi/media/ContentItem-efb17665-691c-45d5-a60c-5301333cbb0c.html',
161         'md5': '11959b4e44fa74de47011b5799490adf',
162         'info_dict': {
163             'id': 'efb17665-691c-45d5-a60c-5301333cbb0c',
164             'ext': 'mp4',
165             'title': 'TG1 ore 20:00 del 03/11/2016',
166             'thumbnail': r're:^https?://.*\.jpg$',
167             'upload_date': '20161103',
168             'description': r're:^[A-Za-z]+'
169         }
170     }, {
171         # drawMediaRaiTV test case
172         'url': 'http://www.report.rai.it/dl/Report/puntata/ContentItem-0c7a664b-d0f4-4b2c-8835-3f82e46f433e.html',
173         'md5': '2dd727e61114e1ee9c47f0da6914e178',
174         'info_dict': {
175             'id': '59d69d28-6bb6-409d-a4b5-ed44096560af',
176             'ext': 'mp4',
177             'title': 'Il pacco',
178             'description': 'md5:4b1afae1364115ce5d78ed83cd2e5b3a',
179             'upload_date': '20141221',
180         },
181     }, {
182         # Direct relinker URL
183         'url': 'http://www.rai.tv/dl/RaiTV/dirette/PublishingBlock-1912dbbf-3f96-44c3-b4cf-523681fbacbc.html?channel=EuroNews',
184         # HDS live stream, MD5 is unstable
185         'info_dict': {
186             'id': '1912dbbf-3f96-44c3-b4cf-523681fbacbc',
187             'ext': 'flv',
188             'title': 'EuroNews',
189         },
190     }, {
191         # Embedded content item ID
192         'url': 'http://www.tg1.rai.it/dl/tg1/2010/edizioni/ContentSet-9b6e0cba-4bef-4aef-8cf0-9f7f665b7dfb-tg1.html?item=undefined',
193         'info_dict': {
194             'id': 'd80d4b70-3812-4501-a888-92edec729f00',
195             'ext': 'mp4',
196             'title': r're:TG1 ore \d{2}:\d{2} del \d{2}/\d{2}/\d{4}',
197             'upload_date': r're:\d{8}',
198             'description': r're:.+',
199         },
200     }, {
201         'url': 'http://www.rainews.it/dl/rainews/live/ContentItem-3156f2f2-dc70-4953-8e2f-70d7489d4ce9.html',
202         # HDS live stream, MD5 is unstable
203         'info_dict': {
204             'id': '3156f2f2-dc70-4953-8e2f-70d7489d4ce9',
205             'ext': 'mp4',
206             'title': 'La diretta di Rainews24',
207         },
208     }]
209
210     def _real_extract(self, url):
211         video_id = self._match_id(url)
212         webpage = self._download_webpage(url, video_id)
213
214         iframe_url = self._search_regex(
215             [r'<iframe[^>]+src="([^"]*/dl/[^"]+\?iframe\b[^"]*)"',
216              r'drawMediaRaiTV\(["\'](.+?)["\']'],
217             webpage, 'iframe', default=None)
218         if iframe_url:
219             if not iframe_url.startswith('http'):
220                 iframe_url = compat_urlparse.urljoin(url, iframe_url)
221             return self.url_result(iframe_url)
222
223         content_item_id = self._search_regex(
224             r'initEdizione\((?P<q1>[\'"])ContentItem-(?P<content_id>[^\'"]+)(?P=q1)',
225             webpage, 'content item ID', group='content_id', default=None)
226         if content_item_id:
227             return self._extract_from_content_id(content_item_id, url)
228
229         try:
230             return self._extract_from_content_id(video_id, url)
231         except ExtractorError:
232             # no media data, only direct relinker
233             pass
234
235         relinker_url = compat_urlparse.urljoin(url, self._search_regex(
236             r'(?:var\s+videoURL|mediaInfo\.mediaUri)\s*=\s*(?P<q1>[\'"])(?P<url>(https?:)?//mediapolis\.rai\.it/relinker/relinkerServlet\.htm\?cont=\d+)(?P=q1)',
237             webpage, 'relinker URL', group='url'))
238         formats = self._extract_relinker_formats(relinker_url, video_id)
239         self._sort_formats(formats)
240
241         title = self._search_regex(
242             r'var\s+videoTitolo\s*=\s*([\'"])(?P<title>[^\'"]+)\1',
243             webpage, 'title', group='title', default=None) or self._og_search_title(webpage)
244
245         return {
246             'id': video_id,
247             'title': title,
248             'formats': formats,
249         }
250
251     def _extract_from_content_id(self, content_id, url):
252         media = self._download_json(
253             'http://www.rai.tv/dl/RaiTV/programmi/media/ContentItem-%s.html?json' % content_id,
254             content_id, 'Downloading video JSON')
255
256         thumbnails = []
257         for image_type in ('image', 'image_medium', 'image_300'):
258             thumbnail_url = media.get(image_type)
259             if thumbnail_url:
260                 thumbnails.append({
261                     'url': compat_urlparse.urljoin(url, thumbnail_url),
262                 })
263
264         formats = []
265         media_type = media['type']
266         if 'Audio' in media_type:
267             formats.append({
268                 'format_id': media.get('formatoAudio'),
269                 'url': media['audioUrl'],
270                 'ext': media.get('formatoAudio'),
271             })
272         elif 'Video' in media_type:
273             formats.extend(self._extract_relinker_formats(media['mediaUri'], content_id))
274             self._sort_formats(formats)
275         else:
276             raise ExtractorError('not a media file')
277
278         subtitles = {}
279         captions = media.get('subtitlesUrl')
280         if captions:
281             STL_EXT = '.stl'
282             SRT_EXT = '.srt'
283             if captions.endswith(STL_EXT):
284                 captions = captions[:-len(STL_EXT)] + SRT_EXT
285             subtitles['it'] = [{
286                 'ext': 'srt',
287                 'url': captions,
288             }]
289
290         return {
291             'id': content_id,
292             'title': media['name'],
293             'description': media.get('desc'),
294             'thumbnails': thumbnails,
295             'uploader': media.get('author'),
296             'upload_date': unified_strdate(media.get('date')),
297             'duration': parse_duration(media.get('length')),
298             'formats': formats,
299             'subtitles': subtitles,
300         }