[rai] Fix extraction and update _TESTS
[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     determine_ext,
7     ExtractorError,
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 RaiTVIE(InfoExtractor):
19     _VALID_URL = r'https?://(?:.+?\.)?(?:rai\.it|rai\.tv|rainews\.it)/dl/(?:[^/]+/)+media/.+?-(?P<id>[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12})(?:-.+?)?\.html'
20     _TESTS = [
21         {
22             'url': 'http://www.rai.tv/dl/RaiTV/programmi/media/ContentItem-cb27157f-9dd0-4aee-b788-b1f67643a391.html',
23             'md5': '8970abf8caf8aef4696e7b1f2adfc696',
24             'info_dict': {
25                 'id': 'cb27157f-9dd0-4aee-b788-b1f67643a391',
26                 'ext': 'mp4',
27                 'title': 'Report del 07/04/2014',
28                 'description': 'md5:f27c544694cacb46a078db84ec35d2d9',
29                 'upload_date': '20140407',
30                 'duration': 6160,
31                 'thumbnail': 're:^https?://.*\.jpg$',
32             }
33         },
34         {
35             # no m3u8 stream
36             'url': 'http://www.raisport.rai.it/dl/raiSport/media/rassegna-stampa-04a9f4bd-b563-40cf-82a6-aad3529cb4a9.html',
37             # HDS download, MD5 is unstable
38             'info_dict': {
39                 'id': '04a9f4bd-b563-40cf-82a6-aad3529cb4a9',
40                 'ext': 'flv',
41                 'title': 'TG PRIMO TEMPO',
42                 'upload_date': '20140612',
43                 'duration': 1758,
44                 'thumbnail': 're:^https?://.*\.jpg$',
45             },
46             'skip': 'Geo-restricted to Italy',
47         },
48         {
49             'url': 'http://www.rainews.it/dl/rainews/media/state-of-the-net-Antonella-La-Carpia-regole-virali-7aafdea9-0e5d-49d5-88a6-7e65da67ae13.html',
50             'md5': '35cf7c229f22eeef43e48b5cf923bef0',
51             'info_dict': {
52                 'id': '7aafdea9-0e5d-49d5-88a6-7e65da67ae13',
53                 'ext': 'mp4',
54                 'title': 'State of the Net, Antonella La Carpia: regole virali',
55                 'description': 'md5:b0ba04a324126903e3da7763272ae63c',
56                 'upload_date': '20140613',
57             },
58             'skip': 'Error 404',
59         },
60         {
61             'url': 'http://www.rai.tv/dl/RaiTV/programmi/media/ContentItem-b4a49761-e0cc-4b14-8736-2729f6f73132-tg2.html',
62             'info_dict': {
63                 'id': 'b4a49761-e0cc-4b14-8736-2729f6f73132',
64                 'ext': 'mp4',
65                 'title': 'Alluvione in Sardegna e dissesto idrogeologico',
66                 'description': 'Edizione delle ore 20:30 ',
67             },
68             'skip': 'invalid urls',
69         },
70         {
71             'url': 'http://www.ilcandidato.rai.it/dl/ray/media/Il-Candidato---Primo-episodio-Le-Primarie-28e5525a-b495-45e8-a7c3-bc48ba45d2b6.html',
72             'md5': 'e57493e1cb8bc7c564663f363b171847',
73             'info_dict': {
74                 'id': '28e5525a-b495-45e8-a7c3-bc48ba45d2b6',
75                 'ext': 'mp4',
76                 'title': 'Il Candidato - Primo episodio: "Le Primarie"',
77                 'description': 'md5:364b604f7db50594678f483353164fb8',
78                 'upload_date': '20140923',
79                 'duration': 386,
80                 'thumbnail': 're:^https?://.*\.jpg$',
81             }
82         },
83     ]
84
85     def _real_extract(self, url):
86         video_id = self._match_id(url)
87
88         media = self._download_json(
89             'http://www.rai.tv/dl/RaiTV/programmi/media/ContentItem-%s.html?json' % video_id,
90             video_id, 'Downloading video JSON')
91
92         thumbnails = []
93         for image_type in ('image', 'image_medium', 'image_300'):
94             thumbnail_url = media.get(image_type)
95             if thumbnail_url:
96                 thumbnails.append({
97                     'url': compat_urlparse.urljoin(url, thumbnail_url),
98                 })
99
100         formats = []
101         media_type = media['type']
102         if 'Audio' in media_type:
103             formats.append({
104                 'format_id': media.get('formatoAudio'),
105                 'url': media['audioUrl'],
106                 'ext': media.get('formatoAudio'),
107             })
108         elif 'Video' in media_type:
109             for platform in ('mon', 'flash', 'native'):
110                 headers = {}
111                 # TODO: rename --cn-verification-proxy
112                 cn_verification_proxy = self._downloader.params.get('cn_verification_proxy')
113                 if cn_verification_proxy:
114                     headers['Ytdl-request-proxy'] = cn_verification_proxy
115
116                 relinker = self._download_xml(
117                     media['mediaUri'], video_id,
118                     note='Downloading XML metadata for platform %s' % platform,
119                     transform_source=fix_xml_ampersands,
120                     query={'output': 45, 'pl': platform}, headers=headers)
121
122                 media_url = find_xpath_attr(relinker, './url', 'type', 'content').text
123                 if media_url == 'http://download.rai.it/video_no_available.mp4':
124                     self.raise_geo_restricted()
125
126                 ext = determine_ext(media_url)
127                 if (platform == 'mon' and ext != 'm3u8') or (platform == 'flash' and ext != 'f4m'):
128                     continue
129
130                 if ext == 'm3u8':
131                     formats.extend(self._extract_m3u8_formats(
132                         media_url, video_id, 'mp4', 'm3u8_native',
133                         m3u8_id='hls', fatal=False))
134                 elif ext == 'f4m':
135                     manifest_url = update_url_query(
136                         media_url, {'hdcore': '3.7.0', 'plugin': 'aasp-3.7.0.39.44'})
137                     formats.extend(self._extract_f4m_formats(
138                         manifest_url, video_id, f4m_id='hds', fatal=False))
139                 else:
140                     bitrate = int_or_none(xpath_text(relinker, 'bitrate'))
141                     formats.append({
142                         'url': media_url,
143                         'tbr': bitrate if bitrate > 0 else None,
144                         'format_id': 'http-%d' % bitrate if bitrate > 0 else 'http',
145                     })
146
147             self._sort_formats(formats)
148         else:
149             raise ExtractorError('not a media file')
150
151         subtitles = {}
152         captions = media.get('subtitlesUrl')
153         if captions:
154             STL_EXT = '.stl'
155             SRT_EXT = '.srt'
156             if captions.endswith(STL_EXT):
157                 captions = captions[:-len(STL_EXT)] + SRT_EXT
158             subtitles['it'] = [{
159                 'ext': 'srt',
160                 'url': captions,
161             }]
162
163         return {
164             'id': video_id,
165             'title': media['name'],
166             'description': media.get('desc'),
167             'thumbnails': thumbnails,
168             'uploader': media.get('author'),
169             'upload_date': unified_strdate(media.get('date')),
170             'duration': parse_duration(media.get('length')),
171             'formats': formats,
172             'subtitles': subtitles,
173         }
174
175
176 class RaiIE(InfoExtractor):
177     _VALID_URL = r'https?://(?:.+?\.)?(?:rai\.it|rai\.tv|rainews\.it)/dl/.+?-(?P<id>[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12})(?:-.+?)?\.html'
178     _TESTS = [
179         {
180             'url': 'http://www.report.rai.it/dl/Report/puntata/ContentItem-0c7a664b-d0f4-4b2c-8835-3f82e46f433e.html',
181             'md5': '2dd727e61114e1ee9c47f0da6914e178',
182             'info_dict': {
183                 'id': '59d69d28-6bb6-409d-a4b5-ed44096560af',
184                 'ext': 'mp4',
185                 'title': 'Il pacco',
186                 'description': 'md5:4b1afae1364115ce5d78ed83cd2e5b3a',
187                 'upload_date': '20141221',
188             },
189         }
190     ]
191
192     @classmethod
193     def suitable(cls, url):
194         return False if RaiTVIE.suitable(url) else super(RaiIE, cls).suitable(url)
195
196     def _real_extract(self, url):
197         video_id = self._match_id(url)
198         webpage = self._download_webpage(url, video_id)
199
200         iframe_url = self._search_regex(
201             [r'<iframe[^>]+src="([^"]*/dl/[^"]+\?iframe\b[^"]*)"',
202              r'drawMediaRaiTV\(["\'](.+?)["\']'],
203             webpage, 'iframe')
204         if not iframe_url.startswith('http'):
205             iframe_url = compat_urlparse.urljoin(url, iframe_url)
206         return self.url_result(iframe_url)