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