[francetv] Sign m3u8 manifest URLs (closes #15565)
[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 DailymotionIE
17
18
19 class FranceTVBaseInfoExtractor(InfoExtractor):
20     def _extract_video(self, video_id, catalogue=None):
21         info = self._download_json(
22             'https://sivideo.webservices.francetelevisions.fr/tools/getInfosOeuvre/v2/',
23             video_id, 'Downloading video JSON', query={
24                 'idDiffusion': video_id,
25                 'catalogue': catalogue or '',
26             })
27
28         if info.get('status') == 'NOK':
29             raise ExtractorError(
30                 '%s returned error: %s' % (self.IE_NAME, info['message']), expected=True)
31         allowed_countries = info['videos'][0].get('geoblocage')
32         if allowed_countries:
33             georestricted = True
34             geo_info = self._download_json(
35                 'http://geo.francetv.fr/ws/edgescape.json', video_id,
36                 'Downloading geo restriction info')
37             country = geo_info['reponse']['geo_info']['country_code']
38             if country not in allowed_countries:
39                 raise ExtractorError(
40                     'The video is not available from your location',
41                     expected=True)
42         else:
43             georestricted = False
44
45         formats = []
46         for video in info['videos']:
47             if video['statut'] != 'ONLINE':
48                 continue
49             video_url = video['url']
50             if not video_url:
51                 continue
52             format_id = video['format']
53             ext = determine_ext(video_url)
54             if ext == 'f4m':
55                 if georestricted:
56                     # See https://github.com/rg3/youtube-dl/issues/3963
57                     # m3u8 urls work fine
58                     continue
59                 f4m_url = self._download_webpage(
60                     'http://hdfauth.francetv.fr/esi/TA?url=%s' % video_url,
61                     video_id, 'Downloading f4m manifest token', fatal=False)
62                 if f4m_url:
63                     formats.extend(self._extract_f4m_formats(
64                         f4m_url + '&hdcore=3.7.0&plugin=aasp-3.7.0.39.44',
65                         video_id, f4m_id=format_id, fatal=False))
66             elif ext == 'm3u8':
67                 m3u8_url = self._download_webpage(
68                     'http://hdfauth.francetv.fr/esi/TA?url=%s' % video_url,
69                     video_id, 'Downloading m3u8 token', fatal=False)
70                 if m3u8_url:
71                     formats.extend(self._extract_m3u8_formats(
72                         m3u8_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|mobile\.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         'url': 'https://mobile.france.tv/france-5/c-dans-l-air/137347-emission-du-vendredi-12-mai-2017.html',
159         'only_matching': True,
160     }, {
161         'url': 'https://www.france.tv/142749-rouge-sang.html',
162         'only_matching': True,
163     }]
164
165     def _real_extract(self, url):
166         display_id = self._match_id(url)
167
168         webpage = self._download_webpage(url, display_id)
169
170         catalogue = None
171         video_id = self._search_regex(
172             r'data-main-video=(["\'])(?P<id>(?:(?!\1).)+)\1',
173             webpage, 'video id', default=None, group='id')
174
175         if not video_id:
176             video_id, catalogue = self._html_search_regex(
177                 r'(?:href=|player\.setVideo\(\s*)"http://videos?\.francetv\.fr/video/([^@]+@[^"]+)"',
178                 webpage, 'video ID').split('@')
179         return self._extract_video(video_id, catalogue)
180
181
182 class FranceTVEmbedIE(FranceTVBaseInfoExtractor):
183     _VALID_URL = r'https?://embed\.francetv\.fr/*\?.*?\bue=(?P<id>[^&]+)'
184
185     _TEST = {
186         'url': 'http://embed.francetv.fr/?ue=7fd581a2ccf59d2fc5719c5c13cf6961',
187         'info_dict': {
188             'id': 'NI_983319',
189             'ext': 'mp4',
190             'title': 'Le Pen Reims',
191             'upload_date': '20170505',
192             'timestamp': 1493981780,
193             'duration': 16,
194         },
195     }
196
197     def _real_extract(self, url):
198         video_id = self._match_id(url)
199
200         video = self._download_json(
201             'http://api-embed.webservices.francetelevisions.fr/key/%s' % video_id,
202             video_id)
203
204         return self._extract_video(video['video_id'], video.get('catalog'))
205
206
207 class FranceTVInfoIE(FranceTVBaseInfoExtractor):
208     IE_NAME = 'francetvinfo.fr'
209     _VALID_URL = r'https?://(?:www|mobile|france3-regions)\.francetvinfo\.fr/(?:[^/]+/)*(?P<title>[^/?#&.]+)'
210
211     _TESTS = [{
212         'url': 'http://www.francetvinfo.fr/replay-jt/france-3/soir-3/jt-grand-soir-3-lundi-26-aout-2013_393427.html',
213         'info_dict': {
214             'id': '84981923',
215             'ext': 'mp4',
216             'title': 'Soir 3',
217             'upload_date': '20130826',
218             'timestamp': 1377548400,
219             'subtitles': {
220                 'fr': 'mincount:2',
221             },
222         },
223         'params': {
224             # m3u8 downloads
225             'skip_download': True,
226         },
227     }, {
228         'url': 'http://www.francetvinfo.fr/elections/europeennes/direct-europeennes-regardez-le-debat-entre-les-candidats-a-la-presidence-de-la-commission_600639.html',
229         'info_dict': {
230             'id': 'EV_20019',
231             'ext': 'mp4',
232             'title': 'Débat des candidats à la Commission européenne',
233             'description': 'Débat des candidats à la Commission européenne',
234         },
235         'params': {
236             'skip_download': 'HLS (reqires ffmpeg)'
237         },
238         'skip': 'Ce direct est terminé et sera disponible en rattrapage dans quelques minutes.',
239     }, {
240         'url': 'http://www.francetvinfo.fr/economie/entreprises/les-entreprises-familiales-le-secret-de-la-reussite_933271.html',
241         'md5': 'f485bda6e185e7d15dbc69b72bae993e',
242         'info_dict': {
243             'id': 'NI_173343',
244             'ext': 'mp4',
245             'title': 'Les entreprises familiales : le secret de la réussite',
246             'thumbnail': r're:^https?://.*\.jpe?g$',
247             'timestamp': 1433273139,
248             'upload_date': '20150602',
249         },
250         'params': {
251             # m3u8 downloads
252             'skip_download': True,
253         },
254     }, {
255         'url': 'http://france3-regions.francetvinfo.fr/bretagne/cotes-d-armor/thalassa-echappee-breizh-ce-venredi-dans-les-cotes-d-armor-954961.html',
256         'md5': 'f485bda6e185e7d15dbc69b72bae993e',
257         'info_dict': {
258             'id': 'NI_657393',
259             'ext': 'mp4',
260             'title': 'Olivier Monthus, réalisateur de "Bretagne, le choix de l’Armor"',
261             'description': 'md5:a3264114c9d29aeca11ced113c37b16c',
262             'thumbnail': r're:^https?://.*\.jpe?g$',
263             'timestamp': 1458300695,
264             'upload_date': '20160318',
265         },
266         'params': {
267             'skip_download': True,
268         },
269     }, {
270         # Dailymotion embed
271         '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',
272         'md5': 'ee7f1828f25a648addc90cb2687b1f12',
273         'info_dict': {
274             'id': 'x4iiko0',
275             'ext': 'mp4',
276             'title': 'NDDL, référendum, Brexit : Cécile Duflot répond à Patrick Cohen',
277             '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',
278             'timestamp': 1467011958,
279             'upload_date': '20160627',
280             'uploader': 'France Inter',
281             'uploader_id': 'x2q2ez',
282         },
283         'add_ie': ['Dailymotion'],
284     }, {
285         'url': 'http://france3-regions.francetvinfo.fr/limousin/emissions/jt-1213-limousin',
286         'only_matching': True,
287     }]
288
289     def _real_extract(self, url):
290         mobj = re.match(self._VALID_URL, url)
291         page_title = mobj.group('title')
292         webpage = self._download_webpage(url, page_title)
293
294         dailymotion_urls = DailymotionIE._extract_urls(webpage)
295         if dailymotion_urls:
296             return self.playlist_result([
297                 self.url_result(dailymotion_url, DailymotionIE.ie_key())
298                 for dailymotion_url in dailymotion_urls])
299
300         video_id, catalogue = self._search_regex(
301             (r'id-video=([^@]+@[^"]+)',
302              r'<a[^>]+href="(?:https?:)?//videos\.francetv\.fr/video/([^@]+@[^"]+)"'),
303             webpage, 'video id').split('@')
304         return self._extract_video(video_id, catalogue)
305
306
307 class GenerationWhatIE(InfoExtractor):
308     IE_NAME = 'france2.fr:generation-what'
309     _VALID_URL = r'https?://generation-what\.francetv\.fr/[^/]+/video/(?P<id>[^/?#]+)'
310
311     _TESTS = [{
312         'url': 'http://generation-what.francetv.fr/portrait/video/present-arms',
313         'info_dict': {
314             'id': 'wtvKYUG45iw',
315             'ext': 'mp4',
316             'title': 'Generation What - Garde à vous - FRA',
317             'uploader': 'Generation What',
318             'uploader_id': 'UCHH9p1eetWCgt4kXBYCb3_w',
319             'upload_date': '20160411',
320         },
321     }, {
322         'url': 'http://generation-what.francetv.fr/europe/video/present-arms',
323         'only_matching': True,
324     }]
325
326     def _real_extract(self, url):
327         display_id = self._match_id(url)
328         webpage = self._download_webpage(url, display_id)
329         youtube_id = self._search_regex(
330             r"window\.videoURL\s*=\s*'([0-9A-Za-z_-]{11})';",
331             webpage, 'youtube id')
332         return self.url_result(youtube_id, 'Youtube', youtube_id)
333
334
335 class CultureboxIE(FranceTVBaseInfoExtractor):
336     IE_NAME = 'culturebox.francetvinfo.fr'
337     _VALID_URL = r'https?://(?:m\.)?culturebox\.francetvinfo\.fr/(?P<name>.*?)(\?|$)'
338
339     _TEST = {
340         'url': 'http://culturebox.francetvinfo.fr/live/musique/musique-classique/le-livre-vermeil-de-montserrat-a-la-cathedrale-delne-214511',
341         'md5': '9b88dc156781c4dbebd4c3e066e0b1d6',
342         'info_dict': {
343             'id': 'EV_50111',
344             'ext': 'flv',
345             'title': "Le Livre Vermeil de Montserrat à la Cathédrale d'Elne",
346             'description': 'md5:f8a4ad202e8fe533e2c493cc12e739d9',
347             'upload_date': '20150320',
348             'timestamp': 1426892400,
349             'duration': 2760.9,
350         },
351     }
352
353     def _real_extract(self, url):
354         mobj = re.match(self._VALID_URL, url)
355         name = mobj.group('name')
356
357         webpage = self._download_webpage(url, name)
358
359         if ">Ce live n'est plus disponible en replay<" in webpage:
360             raise ExtractorError('Video %s is not available' % name, expected=True)
361
362         video_id, catalogue = self._search_regex(
363             r'["\'>]https?://videos\.francetv\.fr/video/([^@]+@.+?)["\'<]',
364             webpage, 'video id').split('@')
365
366         return self._extract_video(video_id, catalogue)