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