Merge pull request #8898 from dstftw/fragment-retries
[youtube-dl] / youtube_dl / extractor / francetv.py
1 # encoding: 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 DailymotionCloudIE
18
19
20 class FranceTVBaseInfoExtractor(InfoExtractor):
21     def _extract_video(self, video_id, catalogue):
22         info = self._download_json(
23             'http://webservices.francetelevisions.fr/tools/getInfosOeuvre/v2/?idDiffusion=%s&catalogue=%s'
24             % (video_id, catalogue),
25             video_id, 'Downloading video JSON')
26
27         if info.get('status') == 'NOK':
28             raise ExtractorError(
29                 '%s returned error: %s' % (self.IE_NAME, info['message']), expected=True)
30         allowed_countries = info['videos'][0].get('geoblocage')
31         if allowed_countries:
32             georestricted = True
33             geo_info = self._download_json(
34                 'http://geo.francetv.fr/ws/edgescape.json', video_id,
35                 'Downloading geo restriction info')
36             country = geo_info['reponse']['geo_info']['country_code']
37             if country not in allowed_countries:
38                 raise ExtractorError(
39                     'The video is not available from your location',
40                     expected=True)
41         else:
42             georestricted = False
43
44         formats = []
45         for video in info['videos']:
46             if video['statut'] != 'ONLINE':
47                 continue
48             video_url = video['url']
49             if not video_url:
50                 continue
51             format_id = video['format']
52             ext = determine_ext(video_url)
53             if ext == 'f4m':
54                 if georestricted:
55                     # See https://github.com/rg3/youtube-dl/issues/3963
56                     # m3u8 urls work fine
57                     continue
58                 f4m_url = self._download_webpage(
59                     'http://hdfauth.francetv.fr/esi/TA?url=%s' % video_url,
60                     video_id, 'Downloading f4m manifest token', fatal=False)
61                 if f4m_url:
62                     formats.extend(self._extract_f4m_formats(
63                         f4m_url + '&hdcore=3.7.0&plugin=aasp-3.7.0.39.44',
64                         video_id, f4m_id=format_id, fatal=False))
65             elif ext == 'm3u8':
66                 formats.extend(self._extract_m3u8_formats(
67                     video_url, video_id, 'mp4', entry_protocol='m3u8_native',
68                     m3u8_id=format_id, fatal=False))
69             elif video_url.startswith('rtmp'):
70                 formats.append({
71                     'url': video_url,
72                     'format_id': 'rtmp-%s' % format_id,
73                     'ext': 'flv',
74                 })
75             else:
76                 if self._is_valid_url(video_url, video_id, format_id):
77                     formats.append({
78                         'url': video_url,
79                         'format_id': format_id,
80                     })
81         self._sort_formats(formats)
82
83         title = info['titre']
84         subtitle = info.get('sous_titre')
85         if subtitle:
86             title += ' - %s' % subtitle
87         title = title.strip()
88
89         subtitles = {}
90         subtitles_list = [{
91             'url': subformat['url'],
92             'ext': subformat.get('format'),
93         } for subformat in info.get('subtitles', []) if subformat.get('url')]
94         if subtitles_list:
95             subtitles['fr'] = subtitles_list
96
97         return {
98             'id': video_id,
99             'title': title,
100             'description': clean_html(info['synopsis']),
101             'thumbnail': compat_urlparse.urljoin('http://pluzz.francetv.fr', info['image']),
102             'duration': int_or_none(info.get('real_duration')) or parse_duration(info['duree']),
103             'timestamp': int_or_none(info['diffusion']['timestamp']),
104             'formats': formats,
105             'subtitles': subtitles,
106         }
107
108
109 class PluzzIE(FranceTVBaseInfoExtractor):
110     IE_NAME = 'pluzz.francetv.fr'
111     _VALID_URL = r'https?://(?:m\.)?pluzz\.francetv\.fr/videos/(?P<id>.+?)\.html'
112
113     # Can't use tests, videos expire in 7 days
114
115     def _real_extract(self, url):
116         display_id = self._match_id(url)
117
118         webpage = self._download_webpage(url, display_id)
119
120         video_id = self._html_search_meta(
121             'id_video', webpage, 'video id', default=None)
122         if not video_id:
123             video_id = self._search_regex(
124                 r'data-diffusion=["\'](\d+)', webpage, 'video id')
125
126         return self._extract_video(video_id, 'Pluzz')
127
128
129 class FranceTvInfoIE(FranceTVBaseInfoExtractor):
130     IE_NAME = 'francetvinfo.fr'
131     _VALID_URL = r'https?://(?:www|mobile|france3-regions)\.francetvinfo\.fr/.*/(?P<title>.+)\.html'
132
133     _TESTS = [{
134         'url': 'http://www.francetvinfo.fr/replay-jt/france-3/soir-3/jt-grand-soir-3-lundi-26-aout-2013_393427.html',
135         'info_dict': {
136             'id': '84981923',
137             'ext': 'mp4',
138             'title': 'Soir 3',
139             'upload_date': '20130826',
140             'timestamp': 1377548400,
141             'subtitles': {
142                 'fr': 'mincount:2',
143             },
144         },
145         'params': {
146             # m3u8 downloads
147             'skip_download': True,
148         },
149     }, {
150         'url': 'http://www.francetvinfo.fr/elections/europeennes/direct-europeennes-regardez-le-debat-entre-les-candidats-a-la-presidence-de-la-commission_600639.html',
151         'info_dict': {
152             'id': 'EV_20019',
153             'ext': 'mp4',
154             'title': 'Débat des candidats à la Commission européenne',
155             'description': 'Débat des candidats à la Commission européenne',
156         },
157         'params': {
158             'skip_download': 'HLS (reqires ffmpeg)'
159         },
160         'skip': 'Ce direct est terminé et sera disponible en rattrapage dans quelques minutes.',
161     }, {
162         'url': 'http://www.francetvinfo.fr/economie/entreprises/les-entreprises-familiales-le-secret-de-la-reussite_933271.html',
163         'md5': 'f485bda6e185e7d15dbc69b72bae993e',
164         'info_dict': {
165             'id': 'NI_173343',
166             'ext': 'mp4',
167             'title': 'Les entreprises familiales : le secret de la réussite',
168             'thumbnail': 're:^https?://.*\.jpe?g$',
169             'timestamp': 1433273139,
170             'upload_date': '20150602',
171         },
172         'params': {
173             # m3u8 downloads
174             'skip_download': True,
175         },
176     }, {
177         'url': 'http://france3-regions.francetvinfo.fr/bretagne/cotes-d-armor/thalassa-echappee-breizh-ce-venredi-dans-les-cotes-d-armor-954961.html',
178         'md5': 'f485bda6e185e7d15dbc69b72bae993e',
179         'info_dict': {
180             'id': 'NI_657393',
181             'ext': 'mp4',
182             'title': 'Olivier Monthus, réalisateur de "Bretagne, le choix de l’Armor"',
183             'description': 'md5:a3264114c9d29aeca11ced113c37b16c',
184             'thumbnail': 're:^https?://.*\.jpe?g$',
185             'timestamp': 1458300695,
186             'upload_date': '20160318',
187         },
188         'params': {
189             'skip_download': True,
190         },
191     }]
192
193     def _real_extract(self, url):
194         mobj = re.match(self._VALID_URL, url)
195         page_title = mobj.group('title')
196         webpage = self._download_webpage(url, page_title)
197
198         dmcloud_url = DailymotionCloudIE._extract_dmcloud_url(webpage)
199         if dmcloud_url:
200             return self.url_result(dmcloud_url, 'DailymotionCloud')
201
202         video_id, catalogue = self._search_regex(
203             (r'id-video=([^@]+@[^"]+)',
204              r'<a[^>]+href="(?:https?:)?//videos\.francetv\.fr/video/([^@]+@[^"]+)"'),
205             webpage, 'video id').split('@')
206         return self._extract_video(video_id, catalogue)
207
208
209 class FranceTVIE(FranceTVBaseInfoExtractor):
210     IE_NAME = 'francetv'
211     IE_DESC = 'France 2, 3, 4, 5 and Ô'
212     _VALID_URL = r'''(?x)
213                     https?://
214                         (?:
215                             (?:www\.)?france[2345o]\.fr/
216                                 (?:
217                                     emissions/[^/]+/(?:videos|diffusions)|
218                                     emission/[^/]+|
219                                     videos|
220                                     jt
221                                 )
222                             /|
223                             embed\.francetv\.fr/\?ue=
224                         )
225                         (?P<id>[^/?]+)
226                     '''
227
228     _TESTS = [
229         # france2
230         {
231             'url': 'http://www.france2.fr/emissions/13h15-le-samedi-le-dimanche/videos/75540104',
232             'md5': 'c03fc87cb85429ffd55df32b9fc05523',
233             'info_dict': {
234                 'id': '109169362',
235                 'ext': 'flv',
236                 'title': '13h15, le dimanche...',
237                 'description': 'md5:9a0932bb465f22d377a449be9d1a0ff7',
238                 'upload_date': '20140914',
239                 'timestamp': 1410693600,
240             },
241         },
242         # france3
243         {
244             'url': 'http://www.france3.fr/emissions/pieces-a-conviction/diffusions/13-11-2013_145575',
245             'md5': '679bb8f8921f8623bd658fa2f8364da0',
246             'info_dict': {
247                 'id': '000702326_CAPP_PicesconvictionExtrait313022013_120220131722_Au',
248                 'ext': 'mp4',
249                 'title': 'Le scandale du prix des médicaments',
250                 'description': 'md5:1384089fbee2f04fc6c9de025ee2e9ce',
251                 'upload_date': '20131113',
252                 'timestamp': 1384380000,
253             },
254         },
255         # france4
256         {
257             'url': 'http://www.france4.fr/emissions/hero-corp/videos/rhozet_herocorp_bonus_1_20131106_1923_06112013172108_F4',
258             'md5': 'a182bf8d2c43d88d46ec48fbdd260c1c',
259             'info_dict': {
260                 'id': 'rhozet_herocorp_bonus_1_20131106_1923_06112013172108_F4',
261                 'ext': 'mp4',
262                 'title': 'Hero Corp Making of - Extrait 1',
263                 'description': 'md5:c87d54871b1790679aec1197e73d650a',
264                 'upload_date': '20131106',
265                 'timestamp': 1383766500,
266             },
267         },
268         # france5
269         {
270             'url': 'http://www.france5.fr/emissions/c-a-dire/videos/quels_sont_les_enjeux_de_cette_rentree_politique__31-08-2015_908948?onglet=tous&page=1',
271             'md5': 'f6c577df3806e26471b3d21631241fd0',
272             'info_dict': {
273                 'id': '123327454',
274                 'ext': 'flv',
275                 'title': 'C à dire ?! - Quels sont les enjeux de cette rentrée politique ?',
276                 'description': 'md5:4a0d5cb5dce89d353522a84462bae5a4',
277                 'upload_date': '20150831',
278                 'timestamp': 1441035120,
279             },
280         },
281         # franceo
282         {
283             'url': 'http://www.franceo.fr/jt/info-soir/18-07-2015',
284             'md5': '47d5816d3b24351cdce512ad7ab31da8',
285             'info_dict': {
286                 'id': '125377621',
287                 'ext': 'flv',
288                 'title': 'Infô soir',
289                 'description': 'md5:01b8c6915a3d93d8bbbd692651714309',
290                 'upload_date': '20150718',
291                 'timestamp': 1437241200,
292                 'duration': 414,
293             },
294         },
295         {
296             # francetv embed
297             'url': 'http://embed.francetv.fr/?ue=8d7d3da1e3047c42ade5a5d7dfd3fc87',
298             'info_dict': {
299                 'id': 'EV_30231',
300                 'ext': 'flv',
301                 'title': 'Alcaline, le concert avec Calogero',
302                 'description': 'md5:61f08036dcc8f47e9cfc33aed08ffaff',
303                 'upload_date': '20150226',
304                 'timestamp': 1424989860,
305                 'duration': 5400,
306             },
307         },
308         {
309             'url': 'http://www.france4.fr/emission/highlander/diffusion-du-17-07-2015-04h05',
310             'only_matching': True,
311         },
312         {
313             'url': 'http://www.franceo.fr/videos/125377617',
314             'only_matching': True,
315         }
316     ]
317
318     def _real_extract(self, url):
319         video_id = self._match_id(url)
320         webpage = self._download_webpage(url, video_id)
321         video_id, catalogue = self._html_search_regex(
322             r'(?:href=|player\.setVideo\(\s*)"http://videos?\.francetv\.fr/video/([^@]+@[^"]+)"',
323             webpage, 'video ID').split('@')
324         return self._extract_video(video_id, catalogue)
325
326
327 class GenerationQuoiIE(InfoExtractor):
328     IE_NAME = 'france2.fr:generation-quoi'
329     _VALID_URL = r'https?://generation-quoi\.france2\.fr/portrait/(?P<id>[^/?#]+)'
330
331     _TEST = {
332         'url': 'http://generation-quoi.france2.fr/portrait/garde-a-vous',
333         'info_dict': {
334             'id': 'k7FJX8VBcvvLmX4wA5Q',
335             'ext': 'mp4',
336             'title': 'Génération Quoi - Garde à Vous',
337             'uploader': 'Génération Quoi',
338         },
339         'params': {
340             # It uses Dailymotion
341             'skip_download': True,
342         },
343     }
344
345     def _real_extract(self, url):
346         display_id = self._match_id(url)
347         info_url = compat_urlparse.urljoin(url, '/medias/video/%s.json' % display_id)
348         info_json = self._download_webpage(info_url, display_id)
349         info = json.loads(info_json)
350         return self.url_result('http://www.dailymotion.com/video/%s' % info['id'],
351                                ie='Dailymotion')
352
353
354 class CultureboxIE(FranceTVBaseInfoExtractor):
355     IE_NAME = 'culturebox.francetvinfo.fr'
356     _VALID_URL = r'https?://(?:m\.)?culturebox\.francetvinfo\.fr/(?P<name>.*?)(\?|$)'
357
358     _TEST = {
359         'url': 'http://culturebox.francetvinfo.fr/live/musique/musique-classique/le-livre-vermeil-de-montserrat-a-la-cathedrale-delne-214511',
360         'md5': '9b88dc156781c4dbebd4c3e066e0b1d6',
361         'info_dict': {
362             'id': 'EV_50111',
363             'ext': 'flv',
364             'title': "Le Livre Vermeil de Montserrat à la Cathédrale d'Elne",
365             'description': 'md5:f8a4ad202e8fe533e2c493cc12e739d9',
366             'upload_date': '20150320',
367             'timestamp': 1426892400,
368             'duration': 2760.9,
369         },
370     }
371
372     def _real_extract(self, url):
373         mobj = re.match(self._VALID_URL, url)
374         name = mobj.group('name')
375
376         webpage = self._download_webpage(url, name)
377
378         if ">Ce live n'est plus disponible en replay<" in webpage:
379             raise ExtractorError('Video %s is not available' % name, expected=True)
380
381         video_id, catalogue = self._search_regex(
382             r'"http://videos\.francetv\.fr/video/([^@]+@[^"]+)"', webpage, 'video id').split('@')
383
384         return self._extract_video(video_id, catalogue)