[france2.fr:generation-what] fix extraction
[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 compat_urlparse
9 from ..utils import (
10     clean_html,
11     ExtractorError,
12     int_or_none,
13     parse_duration,
14     determine_ext,
15 )
16 from .dailymotion import (
17     DailymotionIE,
18     DailymotionCloudIE,
19 )
20
21
22 class FranceTVBaseInfoExtractor(InfoExtractor):
23     def _extract_video(self, video_id, catalogue=None):
24         info = self._download_json(
25             'https://sivideo.webservices.francetelevisions.fr/tools/getInfosOeuvre/v2/',
26             video_id, 'Downloading video JSON', query={
27                 'idDiffusion': video_id,
28                 'catalogue': catalogue or '',
29             })
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                 f4m_url = self._download_webpage(
63                     'http://hdfauth.francetv.fr/esi/TA?url=%s' % video_url,
64                     video_id, 'Downloading f4m manifest token', fatal=False)
65                 if f4m_url:
66                     formats.extend(self._extract_f4m_formats(
67                         f4m_url + '&hdcore=3.7.0&plugin=aasp-3.7.0.39.44',
68                         video_id, f4m_id=format_id, fatal=False))
69             elif ext == 'm3u8':
70                 formats.extend(self._extract_m3u8_formats(
71                     video_url, video_id, 'mp4', entry_protocol='m3u8_native',
72                     m3u8_id=format_id, fatal=False))
73             elif video_url.startswith('rtmp'):
74                 formats.append({
75                     'url': video_url,
76                     'format_id': 'rtmp-%s' % format_id,
77                     'ext': 'flv',
78                 })
79             else:
80                 if self._is_valid_url(video_url, video_id, format_id):
81                     formats.append({
82                         'url': video_url,
83                         'format_id': format_id,
84                     })
85         self._sort_formats(formats)
86
87         title = info['titre']
88         subtitle = info.get('sous_titre')
89         if subtitle:
90             title += ' - %s' % subtitle
91         title = title.strip()
92
93         subtitles = {}
94         subtitles_list = [{
95             'url': subformat['url'],
96             'ext': subformat.get('format'),
97         } for subformat in info.get('subtitles', []) if subformat.get('url')]
98         if subtitles_list:
99             subtitles['fr'] = subtitles_list
100
101         return {
102             'id': video_id,
103             'title': title,
104             'description': clean_html(info['synopsis']),
105             'thumbnail': compat_urlparse.urljoin('http://pluzz.francetv.fr', info['image']),
106             'duration': int_or_none(info.get('real_duration')) or parse_duration(info['duree']),
107             'timestamp': int_or_none(info['diffusion']['timestamp']),
108             'formats': formats,
109             'subtitles': subtitles,
110         }
111
112
113 class FranceTVIE(FranceTVBaseInfoExtractor):
114     _VALID_URL = r'https?://(?:(?:www\.)?france\.tv|mobile\.france\.tv)/(?:[^/]+/)*(?P<id>[^/]+)\.html'
115
116     _TESTS = [{
117         'url': 'https://www.france.tv/france-2/13h15-le-dimanche/140921-les-mysteres-de-jesus.html',
118         'info_dict': {
119             'id': '157550144',
120             'ext': 'mp4',
121             'title': '13h15, le dimanche... - Les mystères de Jésus',
122             'description': 'md5:75efe8d4c0a8205e5904498ffe1e1a42',
123             'timestamp': 1494156300,
124             'upload_date': '20170507',
125         },
126         'params': {
127             # m3u8 downloads
128             'skip_download': True,
129         },
130     }, {
131         # france3
132         'url': 'https://www.france.tv/france-3/des-chiffres-et-des-lettres/139063-emission-du-mardi-9-mai-2017.html',
133         'only_matching': True,
134     }, {
135         # france4
136         'url': 'https://www.france.tv/france-4/hero-corp/saison-1/134151-apres-le-calme.html',
137         'only_matching': True,
138     }, {
139         # france5
140         'url': 'https://www.france.tv/france-5/c-a-dire/saison-10/137013-c-a-dire.html',
141         'only_matching': True,
142     }, {
143         # franceo
144         'url': 'https://www.france.tv/france-o/archipels/132249-mon-ancetre-l-esclave.html',
145         'only_matching': True,
146     }, {
147         # france2 live
148         'url': 'https://www.france.tv/france-2/direct.html',
149         'only_matching': True,
150     }, {
151         'url': 'https://www.france.tv/documentaires/histoire/136517-argentine-les-500-bebes-voles-de-la-dictature.html',
152         'only_matching': True,
153     }, {
154         'url': 'https://www.france.tv/jeux-et-divertissements/divertissements/133965-le-web-contre-attaque.html',
155         'only_matching': True,
156     }, {
157         'url': 'https://mobile.france.tv/france-5/c-dans-l-air/137347-emission-du-vendredi-12-mai-2017.html',
158         'only_matching': True,
159     }, {
160         'url': 'https://www.france.tv/142749-rouge-sang.html',
161         'only_matching': True,
162     }]
163
164     def _real_extract(self, url):
165         display_id = self._match_id(url)
166
167         webpage = self._download_webpage(url, display_id)
168
169         catalogue = None
170         video_id = self._search_regex(
171             r'data-main-video=(["\'])(?P<id>(?:(?!\1).)+)\1',
172             webpage, 'video id', default=None, group='id')
173
174         if not video_id:
175             video_id, catalogue = self._html_search_regex(
176                 r'(?:href=|player\.setVideo\(\s*)"http://videos?\.francetv\.fr/video/([^@]+@[^"]+)"',
177                 webpage, 'video ID').split('@')
178         return self._extract_video(video_id, catalogue)
179
180
181 class FranceTVEmbedIE(FranceTVBaseInfoExtractor):
182     _VALID_URL = r'https?://embed\.francetv\.fr/*\?.*?\bue=(?P<id>[^&]+)'
183
184     _TEST = {
185         'url': 'http://embed.francetv.fr/?ue=7fd581a2ccf59d2fc5719c5c13cf6961',
186         'info_dict': {
187             'id': 'NI_983319',
188             'ext': 'mp4',
189             'title': 'Le Pen Reims',
190             'upload_date': '20170505',
191             'timestamp': 1493981780,
192             'duration': 16,
193         },
194     }
195
196     def _real_extract(self, url):
197         video_id = self._match_id(url)
198
199         video = self._download_json(
200             'http://api-embed.webservices.francetelevisions.fr/key/%s' % video_id,
201             video_id)
202
203         return self._extract_video(video['video_id'], video.get('catalog'))
204
205
206 class FranceTVInfoIE(FranceTVBaseInfoExtractor):
207     IE_NAME = 'francetvinfo.fr'
208     _VALID_URL = r'https?://(?:www|mobile|france3-regions)\.francetvinfo\.fr/(?:[^/]+/)*(?P<title>[^/?#&.]+)'
209
210     _TESTS = [{
211         'url': 'http://www.francetvinfo.fr/replay-jt/france-3/soir-3/jt-grand-soir-3-lundi-26-aout-2013_393427.html',
212         'info_dict': {
213             'id': '84981923',
214             'ext': 'mp4',
215             'title': 'Soir 3',
216             'upload_date': '20130826',
217             'timestamp': 1377548400,
218             'subtitles': {
219                 'fr': 'mincount:2',
220             },
221         },
222         'params': {
223             # m3u8 downloads
224             'skip_download': True,
225         },
226     }, {
227         'url': 'http://www.francetvinfo.fr/elections/europeennes/direct-europeennes-regardez-le-debat-entre-les-candidats-a-la-presidence-de-la-commission_600639.html',
228         'info_dict': {
229             'id': 'EV_20019',
230             'ext': 'mp4',
231             'title': 'Débat des candidats à la Commission européenne',
232             'description': 'Débat des candidats à la Commission européenne',
233         },
234         'params': {
235             'skip_download': 'HLS (reqires ffmpeg)'
236         },
237         'skip': 'Ce direct est terminé et sera disponible en rattrapage dans quelques minutes.',
238     }, {
239         'url': 'http://www.francetvinfo.fr/economie/entreprises/les-entreprises-familiales-le-secret-de-la-reussite_933271.html',
240         'md5': 'f485bda6e185e7d15dbc69b72bae993e',
241         'info_dict': {
242             'id': 'NI_173343',
243             'ext': 'mp4',
244             'title': 'Les entreprises familiales : le secret de la réussite',
245             'thumbnail': r're:^https?://.*\.jpe?g$',
246             'timestamp': 1433273139,
247             'upload_date': '20150602',
248         },
249         'params': {
250             # m3u8 downloads
251             'skip_download': True,
252         },
253     }, {
254         'url': 'http://france3-regions.francetvinfo.fr/bretagne/cotes-d-armor/thalassa-echappee-breizh-ce-venredi-dans-les-cotes-d-armor-954961.html',
255         'md5': 'f485bda6e185e7d15dbc69b72bae993e',
256         'info_dict': {
257             'id': 'NI_657393',
258             'ext': 'mp4',
259             'title': 'Olivier Monthus, réalisateur de "Bretagne, le choix de l’Armor"',
260             'description': 'md5:a3264114c9d29aeca11ced113c37b16c',
261             'thumbnail': r're:^https?://.*\.jpe?g$',
262             'timestamp': 1458300695,
263             'upload_date': '20160318',
264         },
265         'params': {
266             'skip_download': True,
267         },
268     }, {
269         # Dailymotion embed
270         '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',
271         'md5': 'ee7f1828f25a648addc90cb2687b1f12',
272         'info_dict': {
273             'id': 'x4iiko0',
274             'ext': 'mp4',
275             'title': 'NDDL, référendum, Brexit : Cécile Duflot répond à Patrick Cohen',
276             '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',
277             'timestamp': 1467011958,
278             'upload_date': '20160627',
279             'uploader': 'France Inter',
280             'uploader_id': 'x2q2ez',
281         },
282         'add_ie': ['Dailymotion'],
283     }, {
284         'url': 'http://france3-regions.francetvinfo.fr/limousin/emissions/jt-1213-limousin',
285         'only_matching': True,
286     }]
287
288     def _real_extract(self, url):
289         mobj = re.match(self._VALID_URL, url)
290         page_title = mobj.group('title')
291         webpage = self._download_webpage(url, page_title)
292
293         dmcloud_url = DailymotionCloudIE._extract_dmcloud_url(webpage)
294         if dmcloud_url:
295             return self.url_result(dmcloud_url, DailymotionCloudIE.ie_key())
296
297         dailymotion_urls = DailymotionIE._extract_urls(webpage)
298         if dailymotion_urls:
299             return self.playlist_result([
300                 self.url_result(dailymotion_url, DailymotionIE.ie_key())
301                 for dailymotion_url in dailymotion_urls])
302
303         video_id, catalogue = self._search_regex(
304             (r'id-video=([^@]+@[^"]+)',
305              r'<a[^>]+href="(?:https?:)?//videos\.francetv\.fr/video/([^@]+@[^"]+)"'),
306             webpage, 'video id').split('@')
307         return self._extract_video(video_id, catalogue)
308
309
310 class GenerationWhatIE(InfoExtractor):
311     IE_NAME = 'france2.fr:generation-what'
312     _VALID_URL = r'https?://generation-what\.francetv\.fr/[^/]+/video/(?P<id>[^/?#]+)'
313
314     _TESTS = [{
315         'url': 'http://generation-what.francetv.fr/portrait/video/present-arms',
316         'info_dict': {
317             'id': 'wtvKYUG45iw',
318             'ext': 'mp4',
319             'title': 'Generation What - Garde à vous - FRA',
320             'uploader': 'Generation What',
321             'uploader_id': 'UCHH9p1eetWCgt4kXBYCb3_w',
322             'upload_date': '20160411',
323         },
324     }, {
325         'url': 'http://generation-what.francetv.fr/europe/video/present-arms',
326         'only_matching': True,
327     }]
328
329     def _real_extract(self, url):
330         display_id = self._match_id(url)
331         webpage = self._download_webpage(url, display_id)
332         youtube_id = self._search_regex(
333             r"window\.videoURL\s*=\s*'([0-9A-Za-z_-]{11})';",
334             webpage, 'youtube id')
335         return self.url_result(youtube_id, 'Youtube', youtube_id)
336
337
338 class CultureboxIE(FranceTVBaseInfoExtractor):
339     IE_NAME = 'culturebox.francetvinfo.fr'
340     _VALID_URL = r'https?://(?:m\.)?culturebox\.francetvinfo\.fr/(?P<name>.*?)(\?|$)'
341
342     _TEST = {
343         'url': 'http://culturebox.francetvinfo.fr/live/musique/musique-classique/le-livre-vermeil-de-montserrat-a-la-cathedrale-delne-214511',
344         'md5': '9b88dc156781c4dbebd4c3e066e0b1d6',
345         'info_dict': {
346             'id': 'EV_50111',
347             'ext': 'flv',
348             'title': "Le Livre Vermeil de Montserrat à la Cathédrale d'Elne",
349             'description': 'md5:f8a4ad202e8fe533e2c493cc12e739d9',
350             'upload_date': '20150320',
351             'timestamp': 1426892400,
352             'duration': 2760.9,
353         },
354     }
355
356     def _real_extract(self, url):
357         mobj = re.match(self._VALID_URL, url)
358         name = mobj.group('name')
359
360         webpage = self._download_webpage(url, name)
361
362         if ">Ce live n'est plus disponible en replay<" in webpage:
363             raise ExtractorError('Video %s is not available' % name, expected=True)
364
365         video_id, catalogue = self._search_regex(
366             r'"https?://videos\.francetv\.fr/video/([^@]+@[^"]+)"', webpage, 'video id').split('@')
367
368         return self._extract_video(video_id, catalogue)