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