Merge branch 'qqmusic-format-fix' of https://github.com/ping/youtube-dl into ping...
[youtube-dl] / youtube_dl / extractor / francetv.py
1 # encoding: utf-8
2
3 from __future__ import unicode_literals
4
5 import re
6 import json
7
8 from .common import InfoExtractor
9 from ..compat import (
10     compat_urllib_parse_urlparse,
11     compat_urlparse,
12 )
13 from ..utils import (
14     clean_html,
15     ExtractorError,
16     int_or_none,
17     float_or_none,
18     parse_duration,
19     determine_ext,
20 )
21 from .dailymotion import DailymotionCloudIE
22
23
24 class FranceTVBaseInfoExtractor(InfoExtractor):
25     def _extract_video(self, video_id, catalogue):
26         info = self._download_json(
27             'http://webservices.francetelevisions.fr/tools/getInfosOeuvre/v2/?idDiffusion=%s&catalogue=%s'
28             % (video_id, catalogue),
29             video_id, 'Downloading video JSON')
30
31         if info.get('status') == 'NOK':
32             raise ExtractorError(
33                 '%s returned error: %s' % (self.IE_NAME, info['message']), expected=True)
34         allowed_countries = info['videos'][0].get('geoblocage')
35         if allowed_countries:
36             georestricted = True
37             geo_info = self._download_json(
38                 'http://geo.francetv.fr/ws/edgescape.json', video_id,
39                 'Downloading geo restriction info')
40             country = geo_info['reponse']['geo_info']['country_code']
41             if country not in allowed_countries:
42                 raise ExtractorError(
43                     'The video is not available from your location',
44                     expected=True)
45         else:
46             georestricted = False
47
48         formats = []
49         for video in info['videos']:
50             if video['statut'] != 'ONLINE':
51                 continue
52             video_url = video['url']
53             if not video_url:
54                 continue
55             format_id = video['format']
56             ext = determine_ext(video_url)
57             if ext == 'f4m':
58                 if georestricted:
59                     # See https://github.com/rg3/youtube-dl/issues/3963
60                     # m3u8 urls work fine
61                     continue
62                 video_url_parsed = compat_urllib_parse_urlparse(video_url)
63                 f4m_url = self._download_webpage(
64                     'http://hdfauth.francetv.fr/esi/TA?url=%s' % video_url_parsed.path,
65                     video_id, 'Downloading f4m manifest token', fatal=False)
66                 if f4m_url:
67                     formats.extend(self._extract_f4m_formats(f4m_url, video_id, 1, format_id))
68             elif ext == 'm3u8':
69                 formats.extend(self._extract_m3u8_formats(video_url, video_id, 'mp4', m3u8_id=format_id))
70             elif video_url.startswith('rtmp'):
71                 formats.append({
72                     'url': video_url,
73                     'format_id': 'rtmp-%s' % format_id,
74                     'ext': 'flv',
75                     'preference': 1,
76                 })
77             else:
78                 formats.append({
79                     'url': video_url,
80                     'format_id': format_id,
81                     'preference': -1,
82                 })
83         self._sort_formats(formats)
84
85         return {
86             'id': video_id,
87             'title': info['titre'],
88             'description': clean_html(info['synopsis']),
89             'thumbnail': compat_urlparse.urljoin('http://pluzz.francetv.fr', info['image']),
90             'duration': float_or_none(info.get('real_duration'), 1000) or parse_duration(info['duree']),
91             'timestamp': int_or_none(info['diffusion']['timestamp']),
92             'formats': formats,
93         }
94
95
96 class PluzzIE(FranceTVBaseInfoExtractor):
97     IE_NAME = 'pluzz.francetv.fr'
98     _VALID_URL = r'https?://pluzz\.francetv\.fr/videos/(.*?)\.html'
99
100     # Can't use tests, videos expire in 7 days
101
102     def _real_extract(self, url):
103         title = re.match(self._VALID_URL, url).group(1)
104         webpage = self._download_webpage(url, title)
105         video_id = self._search_regex(
106             r'data-diffusion="(\d+)"', webpage, 'ID')
107         return self._extract_video(video_id, 'Pluzz')
108
109
110 class FranceTvInfoIE(FranceTVBaseInfoExtractor):
111     IE_NAME = 'francetvinfo.fr'
112     _VALID_URL = r'https?://(?:www|mobile)\.francetvinfo\.fr/.*/(?P<title>.+)\.html'
113
114     _TESTS = [{
115         'url': 'http://www.francetvinfo.fr/replay-jt/france-3/soir-3/jt-grand-soir-3-lundi-26-aout-2013_393427.html',
116         'info_dict': {
117             'id': '84981923',
118             'ext': 'flv',
119             'title': 'Soir 3',
120             'upload_date': '20130826',
121             'timestamp': 1377548400,
122         },
123     }, {
124         'url': 'http://www.francetvinfo.fr/elections/europeennes/direct-europeennes-regardez-le-debat-entre-les-candidats-a-la-presidence-de-la-commission_600639.html',
125         'info_dict': {
126             'id': 'EV_20019',
127             'ext': 'mp4',
128             'title': 'Débat des candidats à la Commission européenne',
129             'description': 'Débat des candidats à la Commission européenne',
130         },
131         'params': {
132             'skip_download': 'HLS (reqires ffmpeg)'
133         },
134         'skip': 'Ce direct est terminé et sera disponible en rattrapage dans quelques minutes.',
135     }, {
136         'url': 'http://www.francetvinfo.fr/economie/entreprises/les-entreprises-familiales-le-secret-de-la-reussite_933271.html',
137         'md5': 'f485bda6e185e7d15dbc69b72bae993e',
138         'info_dict': {
139             'id': '556e03339473995ee145930c',
140             'ext': 'mp4',
141             'title': 'Les entreprises familiales : le secret de la réussite',
142             'thumbnail': 're:^https?://.*\.jpe?g$',
143         }
144     }]
145
146     def _real_extract(self, url):
147         mobj = re.match(self._VALID_URL, url)
148         page_title = mobj.group('title')
149         webpage = self._download_webpage(url, page_title)
150
151         dmcloud_url = DailymotionCloudIE._extract_dmcloud_url(webpage)
152         if dmcloud_url:
153             return self.url_result(dmcloud_url, 'DailymotionCloud')
154
155         video_id, catalogue = self._search_regex(
156             r'id-video=([^@]+@[^"]+)', webpage, 'video id').split('@')
157         return self._extract_video(video_id, catalogue)
158
159
160 class FranceTVIE(FranceTVBaseInfoExtractor):
161     IE_NAME = 'francetv'
162     IE_DESC = 'France 2, 3, 4, 5 and Ô'
163     _VALID_URL = r'''(?x)https?://www\.france[2345o]\.fr/
164         (?:
165             emissions/.*?/(videos|emissions)/(?P<id>[^/?]+)
166         |   (emissions?|jt)/(?P<key>[^/?]+)
167         )'''
168
169     _TESTS = [
170         # france2
171         {
172             'url': 'http://www.france2.fr/emissions/13h15-le-samedi-le-dimanche/videos/75540104',
173             'md5': 'c03fc87cb85429ffd55df32b9fc05523',
174             'info_dict': {
175                 'id': '109169362',
176                 'ext': 'flv',
177                 'title': '13h15, le dimanche...',
178                 'description': 'md5:9a0932bb465f22d377a449be9d1a0ff7',
179                 'upload_date': '20140914',
180                 'timestamp': 1410693600,
181             },
182         },
183         # france3
184         {
185             'url': 'http://www.france3.fr/emissions/pieces-a-conviction/diffusions/13-11-2013_145575',
186             'md5': '679bb8f8921f8623bd658fa2f8364da0',
187             'info_dict': {
188                 'id': '000702326_CAPP_PicesconvictionExtrait313022013_120220131722_Au',
189                 'ext': 'mp4',
190                 'title': 'Le scandale du prix des médicaments',
191                 'description': 'md5:1384089fbee2f04fc6c9de025ee2e9ce',
192                 'upload_date': '20131113',
193                 'timestamp': 1384380000,
194             },
195         },
196         # france4
197         {
198             'url': 'http://www.france4.fr/emissions/hero-corp/videos/rhozet_herocorp_bonus_1_20131106_1923_06112013172108_F4',
199             'md5': 'a182bf8d2c43d88d46ec48fbdd260c1c',
200             'info_dict': {
201                 'id': 'rhozet_herocorp_bonus_1_20131106_1923_06112013172108_F4',
202                 'ext': 'mp4',
203                 'title': 'Hero Corp Making of - Extrait 1',
204                 'description': 'md5:c87d54871b1790679aec1197e73d650a',
205                 'upload_date': '20131106',
206                 'timestamp': 1383766500,
207             },
208         },
209         # france5
210         {
211             'url': 'http://www.france5.fr/emissions/c-a-dire/videos/92837968',
212             'md5': '78f0f4064f9074438e660785bbf2c5d9',
213             'info_dict': {
214                 'id': '108961659',
215                 'ext': 'flv',
216                 'title': 'C à dire ?!',
217                 'description': 'md5:1a4aeab476eb657bf57c4ff122129f81',
218                 'upload_date': '20140915',
219                 'timestamp': 1410795000,
220             },
221         },
222         # franceo
223         {
224             'url': 'http://www.franceo.fr/jt/info-afrique/04-12-2013',
225             'md5': '52f0bfe202848b15915a2f39aaa8981b',
226             'info_dict': {
227                 'id': '108634970',
228                 'ext': 'flv',
229                 'title': 'Infô Afrique',
230                 'description': 'md5:ebf346da789428841bee0fd2a935ea55',
231                 'upload_date': '20140915',
232                 'timestamp': 1410822000,
233             },
234         },
235     ]
236
237     def _real_extract(self, url):
238         mobj = re.match(self._VALID_URL, url)
239         webpage = self._download_webpage(url, mobj.group('key') or mobj.group('id'))
240         video_id, catalogue = self._html_search_regex(
241             r'href="http://videos\.francetv\.fr/video/([^@]+@[^"]+)"',
242             webpage, 'video ID').split('@')
243         return self._extract_video(video_id, catalogue)
244
245
246 class GenerationQuoiIE(InfoExtractor):
247     IE_NAME = 'france2.fr:generation-quoi'
248     _VALID_URL = r'https?://generation-quoi\.france2\.fr/portrait/(?P<id>[^/?#]+)'
249
250     _TEST = {
251         'url': 'http://generation-quoi.france2.fr/portrait/garde-a-vous',
252         'info_dict': {
253             'id': 'k7FJX8VBcvvLmX4wA5Q',
254             'ext': 'mp4',
255             'title': 'Génération Quoi - Garde à Vous',
256             'uploader': 'Génération Quoi',
257         },
258         'params': {
259             # It uses Dailymotion
260             'skip_download': True,
261         },
262     }
263
264     def _real_extract(self, url):
265         display_id = self._match_id(url)
266         info_url = compat_urlparse.urljoin(url, '/medias/video/%s.json' % display_id)
267         info_json = self._download_webpage(info_url, display_id)
268         info = json.loads(info_json)
269         return self.url_result('http://www.dailymotion.com/video/%s' % info['id'],
270                                ie='Dailymotion')
271
272
273 class CultureboxIE(FranceTVBaseInfoExtractor):
274     IE_NAME = 'culturebox.francetvinfo.fr'
275     _VALID_URL = r'https?://(?:m\.)?culturebox\.francetvinfo\.fr/(?P<name>.*?)(\?|$)'
276
277     _TEST = {
278         'url': 'http://culturebox.francetvinfo.fr/live/musique/musique-classique/le-livre-vermeil-de-montserrat-a-la-cathedrale-delne-214511',
279         'md5': '9b88dc156781c4dbebd4c3e066e0b1d6',
280         'info_dict': {
281             'id': 'EV_50111',
282             'ext': 'flv',
283             'title': "Le Livre Vermeil de Montserrat à la Cathédrale d'Elne",
284             'description': 'md5:f8a4ad202e8fe533e2c493cc12e739d9',
285             'upload_date': '20150320',
286             'timestamp': 1426892400,
287             'duration': 2760.9,
288         },
289     }
290
291     def _real_extract(self, url):
292         mobj = re.match(self._VALID_URL, url)
293         name = mobj.group('name')
294
295         webpage = self._download_webpage(url, name)
296
297         if ">Ce live n'est plus disponible en replay<" in webpage:
298             raise ExtractorError('Video %s is not available' % name, expected=True)
299
300         video_id, catalogue = self._search_regex(
301             r'"http://videos\.francetv\.fr/video/([^@]+@[^"]+)"', webpage, 'video id').split('@')
302
303         return self._extract_video(video_id, catalogue)