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