[francetv] Add support for zouzous.fr and ludo.fr (closes #10454, closes #13087,...
[youtube-dl] / youtube_dl / extractor / francetv.py
1 # coding: utf-8
2
3 from __future__ import unicode_literals
4
5 import re
6
7 from .common import InfoExtractor
8 from ..compat import (
9     compat_str,
10     compat_urlparse,
11 )
12 from ..utils import (
13     clean_html,
14     ExtractorError,
15     int_or_none,
16     parse_duration,
17     determine_ext,
18 )
19 from .dailymotion import DailymotionIE
20
21
22 class FranceTVBaseInfoExtractor(InfoExtractor):
23     def _make_url_result(self, video_or_full_id, catalog=None):
24         full_id = 'francetv:%s' % video_or_full_id
25         if '@' not in video_or_full_id and catalog:
26             full_id += '@%s' % catalog
27         return self.url_result(
28             full_id, ie=FranceTVIE.ie_key(),
29             video_id=video_or_full_id.split('@')[0])
30
31
32 class FranceTVIE(InfoExtractor):
33     _VALID_URL = r'''(?x)
34                     (?:
35                         https?://
36                             sivideo\.webservices\.francetelevisions\.fr/tools/getInfosOeuvre/v2/\?
37                             .*?\bidDiffusion=[^&]+|
38                         (?:
39                             https?://videos\.francetv\.fr/video/|
40                             francetv:
41                         )
42                         (?P<id>[^@]+)(?:@(?P<catalog>.+))?
43                     )
44                     '''
45
46     _TESTS = [{
47         # without catalog
48         'url': 'https://sivideo.webservices.francetelevisions.fr/tools/getInfosOeuvre/v2/?idDiffusion=162311093&callback=_jsonp_loader_callback_request_0',
49         'md5': 'c2248a8de38c4e65ea8fae7b5df2d84f',
50         'info_dict': {
51             'id': '162311093',
52             'ext': 'mp4',
53             'title': '13h15, le dimanche... - Les mystères de Jésus',
54             'description': 'md5:75efe8d4c0a8205e5904498ffe1e1a42',
55             'timestamp': 1502623500,
56             'upload_date': '20170813',
57         },
58     }, {
59         # with catalog
60         'url': 'https://sivideo.webservices.francetelevisions.fr/tools/getInfosOeuvre/v2/?idDiffusion=NI_1004933&catalogue=Zouzous&callback=_jsonp_loader_callback_request_4',
61         'only_matching': True,
62     }, {
63         'url': 'http://videos.francetv.fr/video/NI_657393@Regions',
64         'only_matching': True,
65     }, {
66         'url': 'francetv:162311093',
67         'only_matching': True,
68     }, {
69         'url': 'francetv:NI_1004933@Zouzous',
70         'only_matching': True,
71     }, {
72         'url': 'francetv:NI_983319@Info-web',
73         'only_matching': True,
74     }, {
75         'url': 'francetv:NI_983319',
76         'only_matching': True,
77     }, {
78         'url': 'francetv:NI_657393@Regions',
79         'only_matching': True,
80     }]
81
82     def _extract_video(self, video_id, catalogue=None):
83         # Videos are identified by idDiffusion so catalogue part is optional.
84         # However when provided, some extra formats may be returned so we pass
85         # it if available.
86         info = self._download_json(
87             'https://sivideo.webservices.francetelevisions.fr/tools/getInfosOeuvre/v2/',
88             video_id, 'Downloading video JSON', query={
89                 'idDiffusion': video_id,
90                 'catalogue': catalogue or '',
91             })
92
93         if info.get('status') == 'NOK':
94             raise ExtractorError(
95                 '%s returned error: %s' % (self.IE_NAME, info['message']),
96                 expected=True)
97         allowed_countries = info['videos'][0].get('geoblocage')
98         if allowed_countries:
99             georestricted = True
100             geo_info = self._download_json(
101                 'http://geo.francetv.fr/ws/edgescape.json', video_id,
102                 'Downloading geo restriction info')
103             country = geo_info['reponse']['geo_info']['country_code']
104             if country not in allowed_countries:
105                 raise ExtractorError(
106                     'The video is not available from your location',
107                     expected=True)
108         else:
109             georestricted = False
110
111         def sign(manifest_url, manifest_id):
112             for host in ('hdfauthftv-a.akamaihd.net', 'hdfauth.francetv.fr'):
113                 signed_url = self._download_webpage(
114                     'https://%s/esi/TA' % host, video_id,
115                     'Downloading signed %s manifest URL' % manifest_id,
116                     fatal=False, query={
117                         'url': manifest_url,
118                     })
119                 if (signed_url and isinstance(signed_url, compat_str) and
120                         re.search(r'^(?:https?:)?//', signed_url)):
121                     return signed_url
122             return manifest_url
123
124         formats = []
125         for video in info['videos']:
126             if video['statut'] != 'ONLINE':
127                 continue
128             video_url = video['url']
129             if not video_url:
130                 continue
131             format_id = video['format']
132             ext = determine_ext(video_url)
133             if ext == 'f4m':
134                 if georestricted:
135                     # See https://github.com/rg3/youtube-dl/issues/3963
136                     # m3u8 urls work fine
137                     continue
138                 formats.extend(self._extract_f4m_formats(
139                     sign(video_url, format_id) + '&hdcore=3.7.0&plugin=aasp-3.7.0.39.44',
140                     video_id, f4m_id=format_id, fatal=False))
141             elif ext == 'm3u8':
142                 formats.extend(self._extract_m3u8_formats(
143                     sign(video_url, format_id), video_id, 'mp4',
144                     entry_protocol='m3u8_native', m3u8_id=format_id,
145                     fatal=False))
146             elif video_url.startswith('rtmp'):
147                 formats.append({
148                     'url': video_url,
149                     'format_id': 'rtmp-%s' % format_id,
150                     'ext': 'flv',
151                 })
152             else:
153                 if self._is_valid_url(video_url, video_id, format_id):
154                     formats.append({
155                         'url': video_url,
156                         'format_id': format_id,
157                     })
158         self._sort_formats(formats)
159
160         title = info['titre']
161         subtitle = info.get('sous_titre')
162         if subtitle:
163             title += ' - %s' % subtitle
164         title = title.strip()
165
166         subtitles = {}
167         subtitles_list = [{
168             'url': subformat['url'],
169             'ext': subformat.get('format'),
170         } for subformat in info.get('subtitles', []) if subformat.get('url')]
171         if subtitles_list:
172             subtitles['fr'] = subtitles_list
173
174         return {
175             'id': video_id,
176             'title': title,
177             'description': clean_html(info['synopsis']),
178             'thumbnail': compat_urlparse.urljoin('http://pluzz.francetv.fr', info['image']),
179             'duration': int_or_none(info.get('real_duration')) or parse_duration(info['duree']),
180             'timestamp': int_or_none(info['diffusion']['timestamp']),
181             'formats': formats,
182             'subtitles': subtitles,
183         }
184
185     def _real_extract(self, url):
186         mobj = re.match(self._VALID_URL, url)
187         video_id = mobj.group('id')
188         catalog = mobj.group('catalog')
189
190         if not video_id:
191             qs = compat_urlparse.parse_qs(compat_urlparse.urlparse(url).query)
192             video_id = qs.get('idDiffusion', [None])[0]
193             catalog = qs.get('catalogue', [None])[0]
194             if not video_id:
195                 raise ExtractorError('Invalid URL', expected=True)
196
197         return self._extract_video(video_id, catalog)
198
199
200 class FranceTVSiteIE(FranceTVBaseInfoExtractor):
201     _VALID_URL = r'https?://(?:(?:www\.)?france\.tv|mobile\.france\.tv)/(?:[^/]+/)*(?P<id>[^/]+)\.html'
202
203     _TESTS = [{
204         'url': 'https://www.france.tv/france-2/13h15-le-dimanche/140921-les-mysteres-de-jesus.html',
205         'info_dict': {
206             'id': '162311093',
207             'ext': 'mp4',
208             'title': '13h15, le dimanche... - Les mystères de Jésus',
209             'description': 'md5:75efe8d4c0a8205e5904498ffe1e1a42',
210             'timestamp': 1502623500,
211             'upload_date': '20170813',
212         },
213         'params': {
214             'skip_download': True,
215         },
216         'add_ie': [FranceTVIE.ie_key()],
217     }, {
218         # france3
219         'url': 'https://www.france.tv/france-3/des-chiffres-et-des-lettres/139063-emission-du-mardi-9-mai-2017.html',
220         'only_matching': True,
221     }, {
222         # france4
223         'url': 'https://www.france.tv/france-4/hero-corp/saison-1/134151-apres-le-calme.html',
224         'only_matching': True,
225     }, {
226         # france5
227         'url': 'https://www.france.tv/france-5/c-a-dire/saison-10/137013-c-a-dire.html',
228         'only_matching': True,
229     }, {
230         # franceo
231         'url': 'https://www.france.tv/france-o/archipels/132249-mon-ancetre-l-esclave.html',
232         'only_matching': True,
233     }, {
234         # france2 live
235         'url': 'https://www.france.tv/france-2/direct.html',
236         'only_matching': True,
237     }, {
238         'url': 'https://www.france.tv/documentaires/histoire/136517-argentine-les-500-bebes-voles-de-la-dictature.html',
239         'only_matching': True,
240     }, {
241         'url': 'https://www.france.tv/jeux-et-divertissements/divertissements/133965-le-web-contre-attaque.html',
242         'only_matching': True,
243     }, {
244         'url': 'https://mobile.france.tv/france-5/c-dans-l-air/137347-emission-du-vendredi-12-mai-2017.html',
245         'only_matching': True,
246     }, {
247         'url': 'https://www.france.tv/142749-rouge-sang.html',
248         'only_matching': True,
249     }]
250
251     def _real_extract(self, url):
252         display_id = self._match_id(url)
253
254         webpage = self._download_webpage(url, display_id)
255
256         catalogue = None
257         video_id = self._search_regex(
258             r'data-main-video=(["\'])(?P<id>(?:(?!\1).)+)\1',
259             webpage, 'video id', default=None, group='id')
260
261         if not video_id:
262             video_id, catalogue = self._html_search_regex(
263                 r'(?:href=|player\.setVideo\(\s*)"http://videos?\.francetv\.fr/video/([^@]+@[^"]+)"',
264                 webpage, 'video ID').split('@')
265
266         return self._make_url_result(video_id, catalogue)
267
268
269 class FranceTVEmbedIE(FranceTVBaseInfoExtractor):
270     _VALID_URL = r'https?://embed\.francetv\.fr/*\?.*?\bue=(?P<id>[^&]+)'
271
272     _TESTS = [{
273         'url': 'http://embed.francetv.fr/?ue=7fd581a2ccf59d2fc5719c5c13cf6961',
274         'info_dict': {
275             'id': 'NI_983319',
276             'ext': 'mp4',
277             'title': 'Le Pen Reims',
278             'upload_date': '20170505',
279             'timestamp': 1493981780,
280             'duration': 16,
281         },
282         'params': {
283             'skip_download': True,
284         },
285         'add_ie': [FranceTVIE.ie_key()],
286     }]
287
288     def _real_extract(self, url):
289         video_id = self._match_id(url)
290
291         video = self._download_json(
292             'http://api-embed.webservices.francetelevisions.fr/key/%s' % video_id,
293             video_id)
294
295         return self._make_url_result(video['video_id'], video.get('catalog'))
296
297
298 class FranceTVInfoIE(FranceTVBaseInfoExtractor):
299     IE_NAME = 'francetvinfo.fr'
300     _VALID_URL = r'https?://(?:www|mobile|france3-regions)\.francetvinfo\.fr/(?:[^/]+/)*(?P<id>[^/?#&.]+)'
301
302     _TESTS = [{
303         'url': 'http://www.francetvinfo.fr/replay-jt/france-3/soir-3/jt-grand-soir-3-lundi-26-aout-2013_393427.html',
304         'info_dict': {
305             'id': '84981923',
306             'ext': 'mp4',
307             'title': 'Soir 3',
308             'upload_date': '20130826',
309             'timestamp': 1377548400,
310             'subtitles': {
311                 'fr': 'mincount:2',
312             },
313         },
314         'params': {
315             'skip_download': True,
316         },
317         'add_ie': [FranceTVIE.ie_key()],
318     }, {
319         'url': 'http://www.francetvinfo.fr/elections/europeennes/direct-europeennes-regardez-le-debat-entre-les-candidats-a-la-presidence-de-la-commission_600639.html',
320         'only_matching': True,
321     }, {
322         'url': 'http://www.francetvinfo.fr/economie/entreprises/les-entreprises-familiales-le-secret-de-la-reussite_933271.html',
323         'only_matching': True,
324     }, {
325         'url': 'http://france3-regions.francetvinfo.fr/bretagne/cotes-d-armor/thalassa-echappee-breizh-ce-venredi-dans-les-cotes-d-armor-954961.html',
326         'only_matching': True,
327     }, {
328         # Dailymotion embed
329         'url': 'http://www.francetvinfo.fr/politique/notre-dame-des-landes/video-sur-france-inter-cecile-duflot-denonce-le-regard-meprisant-de-patrick-cohen_1520091.html',
330         'md5': 'ee7f1828f25a648addc90cb2687b1f12',
331         'info_dict': {
332             'id': 'x4iiko0',
333             'ext': 'mp4',
334             'title': 'NDDL, référendum, Brexit : Cécile Duflot répond à Patrick Cohen',
335             'description': 'Au lendemain de la victoire du "oui" au référendum sur l\'aéroport de Notre-Dame-des-Landes, l\'ancienne ministre écologiste est l\'invitée de Patrick Cohen. Plus d\'info : https://www.franceinter.fr/emissions/le-7-9/le-7-9-27-juin-2016',
336             'timestamp': 1467011958,
337             'upload_date': '20160627',
338             'uploader': 'France Inter',
339             'uploader_id': 'x2q2ez',
340         },
341         'add_ie': ['Dailymotion'],
342     }, {
343         'url': 'http://france3-regions.francetvinfo.fr/limousin/emissions/jt-1213-limousin',
344         'only_matching': True,
345     }]
346
347     def _real_extract(self, url):
348         display_id = self._match_id(url)
349
350         webpage = self._download_webpage(url, display_id)
351
352         dailymotion_urls = DailymotionIE._extract_urls(webpage)
353         if dailymotion_urls:
354             return self.playlist_result([
355                 self.url_result(dailymotion_url, DailymotionIE.ie_key())
356                 for dailymotion_url in dailymotion_urls])
357
358         video_id, catalogue = self._search_regex(
359             (r'id-video=([^@]+@[^"]+)',
360              r'<a[^>]+href="(?:https?:)?//videos\.francetv\.fr/video/([^@]+@[^"]+)"'),
361             webpage, 'video id').split('@')
362
363         return self._make_url_result(video_id, catalogue)
364
365
366 class GenerationWhatIE(InfoExtractor):
367     IE_NAME = 'france2.fr:generation-what'
368     _VALID_URL = r'https?://generation-what\.francetv\.fr/[^/]+/video/(?P<id>[^/?#&]+)'
369
370     _TESTS = [{
371         'url': 'http://generation-what.francetv.fr/portrait/video/present-arms',
372         'info_dict': {
373             'id': 'wtvKYUG45iw',
374             'ext': 'mp4',
375             'title': 'Generation What - Garde à vous - FRA',
376             'uploader': 'Generation What',
377             'uploader_id': 'UCHH9p1eetWCgt4kXBYCb3_w',
378             'upload_date': '20160411',
379         },
380         'params': {
381             'skip_download': True,
382         },
383         'add_ie': ['Youtube'],
384     }, {
385         'url': 'http://generation-what.francetv.fr/europe/video/present-arms',
386         'only_matching': True,
387     }]
388
389     def _real_extract(self, url):
390         display_id = self._match_id(url)
391
392         webpage = self._download_webpage(url, display_id)
393
394         youtube_id = self._search_regex(
395             r"window\.videoURL\s*=\s*'([0-9A-Za-z_-]{11})';",
396             webpage, 'youtube id')
397
398         return self.url_result(youtube_id, ie='Youtube', video_id=youtube_id)
399
400
401 class CultureboxIE(FranceTVBaseInfoExtractor):
402     _VALID_URL = r'https?://(?:m\.)?culturebox\.francetvinfo\.fr/(?:[^/]+/)*(?P<id>[^/?#&]+)'
403
404     _TESTS = [{
405         'url': 'https://culturebox.francetvinfo.fr/opera-classique/musique-classique/c-est-baroque/concerts/cantates-bwv-4-106-et-131-de-bach-par-raphael-pichon-57-268689',
406         'info_dict': {
407             'id': 'EV_134885',
408             'ext': 'mp4',
409             'title': 'Cantates BWV 4, 106 et 131 de Bach par Raphaël Pichon 5/7',
410             'description': 'md5:19c44af004b88219f4daa50fa9a351d4',
411             'upload_date': '20180206',
412             'timestamp': 1517945220,
413             'duration': 5981,
414         },
415         'params': {
416             'skip_download': True,
417         },
418         'add_ie': [FranceTVIE.ie_key()],
419     }]
420
421     def _real_extract(self, url):
422         display_id = self._match_id(url)
423
424         webpage = self._download_webpage(url, display_id)
425
426         if ">Ce live n'est plus disponible en replay<" in webpage:
427             raise ExtractorError(
428                 'Video %s is not available' % display_id, expected=True)
429
430         video_id, catalogue = self._search_regex(
431             r'["\'>]https?://videos\.francetv\.fr/video/([^@]+@.+?)["\'<]',
432             webpage, 'video id').split('@')
433
434         return self._make_url_result(video_id, catalogue)
435
436
437 class FranceTVJeunesseIE(FranceTVBaseInfoExtractor):
438     _VALID_URL = r'(?P<url>https?://(?:www\.)?(?:zouzous|ludo)\.fr/heros/(?P<id>[^/?#&]+))'
439
440     _TESTS = [{
441         'url': 'https://www.zouzous.fr/heros/simon',
442         'info_dict': {
443             'id': 'simon',
444         },
445         'playlist_count': 9,
446     }, {
447         'url': 'https://www.ludo.fr/heros/ninjago',
448         'info_dict': {
449             'id': 'ninjago',
450         },
451         'playlist_count': 10,
452     }, {
453         'url': 'https://www.zouzous.fr/heros/simon?abc',
454         'only_matching': True,
455     }]
456
457     def _real_extract(self, url):
458         mobj = re.match(self._VALID_URL, url)
459         playlist_id = mobj.group('id')
460
461         playlist = self._download_json(
462             '%s/%s' % (mobj.group('url'), 'playlist'), playlist_id)
463
464         if not playlist.get('count'):
465             raise ExtractorError(
466                 '%s is not available' % playlist_id, expected=True)
467
468         entries = []
469         for item in playlist['items']:
470             identity = item.get('identity')
471             if identity and isinstance(identity, compat_str):
472                 entries.append(self._make_url_result(identity))
473
474         return self.playlist_result(entries, playlist_id)