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