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