]> Raphaël G. Git Repositories - youtubedl/blob - youtube_dl/extractor/arte.py
Prepare to upload.
[youtubedl] / youtube_dl / extractor / arte.py
1 # coding: utf-8
2 from __future__ import unicode_literals
3
4 import re
5
6 from .common import InfoExtractor
7 from ..compat import (
8 compat_parse_qs,
9 compat_str,
10 compat_urllib_parse_urlparse,
11 )
12 from ..utils import (
13 ExtractorError,
14 find_xpath_attr,
15 get_element_by_attribute,
16 int_or_none,
17 NO_DEFAULT,
18 qualities,
19 try_get,
20 unified_strdate,
21 )
22
23 # There are different sources of video in arte.tv, the extraction process
24 # is different for each one. The videos usually expire in 7 days, so we can't
25 # add tests.
26
27
28 class ArteTvIE(InfoExtractor):
29 _VALID_URL = r'https?://videos\.arte\.tv/(?P<lang>fr|de|en|es)/.*-(?P<id>.*?)\.html'
30 IE_NAME = 'arte.tv'
31
32 def _real_extract(self, url):
33 mobj = re.match(self._VALID_URL, url)
34 lang = mobj.group('lang')
35 video_id = mobj.group('id')
36
37 ref_xml_url = url.replace('/videos/', '/do_delegate/videos/')
38 ref_xml_url = ref_xml_url.replace('.html', ',view,asPlayerXml.xml')
39 ref_xml_doc = self._download_xml(
40 ref_xml_url, video_id, note='Downloading metadata')
41 config_node = find_xpath_attr(ref_xml_doc, './/video', 'lang', lang)
42 config_xml_url = config_node.attrib['ref']
43 config = self._download_xml(
44 config_xml_url, video_id, note='Downloading configuration')
45
46 formats = [{
47 'format_id': q.attrib['quality'],
48 # The playpath starts at 'mp4:', if we don't manually
49 # split the url, rtmpdump will incorrectly parse them
50 'url': q.text.split('mp4:', 1)[0],
51 'play_path': 'mp4:' + q.text.split('mp4:', 1)[1],
52 'ext': 'flv',
53 'quality': 2 if q.attrib['quality'] == 'hd' else 1,
54 } for q in config.findall('./urls/url')]
55 self._sort_formats(formats)
56
57 title = config.find('.//name').text
58 thumbnail = config.find('.//firstThumbnailUrl').text
59 return {
60 'id': video_id,
61 'title': title,
62 'thumbnail': thumbnail,
63 'formats': formats,
64 }
65
66
67 class ArteTVBaseIE(InfoExtractor):
68 @classmethod
69 def _extract_url_info(cls, url):
70 mobj = re.match(cls._VALID_URL, url)
71 lang = mobj.group('lang')
72 query = compat_parse_qs(compat_urllib_parse_urlparse(url).query)
73 if 'vid' in query:
74 video_id = query['vid'][0]
75 else:
76 # This is not a real id, it can be for example AJT for the news
77 # http://www.arte.tv/guide/fr/emissions/AJT/arte-journal
78 video_id = mobj.group('id')
79 return video_id, lang
80
81 def _extract_from_json_url(self, json_url, video_id, lang, title=None):
82 info = self._download_json(json_url, video_id)
83 player_info = info['videoJsonPlayer']
84
85 vsr = try_get(player_info, lambda x: x['VSR'], dict)
86 if not vsr:
87 error = None
88 if try_get(player_info, lambda x: x['custom_msg']['type']) == 'error':
89 error = try_get(
90 player_info, lambda x: x['custom_msg']['msg'], compat_str)
91 if not error:
92 error = 'Video %s is not available' % player_info.get('VID') or video_id
93 raise ExtractorError(error, expected=True)
94
95 upload_date_str = player_info.get('shootingDate')
96 if not upload_date_str:
97 upload_date_str = (player_info.get('VRA') or player_info.get('VDA') or '').split(' ')[0]
98
99 title = (player_info.get('VTI') or title or player_info['VID']).strip()
100 subtitle = player_info.get('VSU', '').strip()
101 if subtitle:
102 title += ' - %s' % subtitle
103
104 info_dict = {
105 'id': player_info['VID'],
106 'title': title,
107 'description': player_info.get('VDE'),
108 'upload_date': unified_strdate(upload_date_str),
109 'thumbnail': player_info.get('programImage') or player_info.get('VTU', {}).get('IUR'),
110 }
111 qfunc = qualities(['HQ', 'MQ', 'EQ', 'SQ'])
112
113 LANGS = {
114 'fr': 'F',
115 'de': 'A',
116 'en': 'E[ANG]',
117 'es': 'E[ESP]',
118 }
119
120 langcode = LANGS.get(lang, lang)
121
122 formats = []
123 for format_id, format_dict in vsr.items():
124 f = dict(format_dict)
125 versionCode = f.get('versionCode')
126 l = re.escape(langcode)
127
128 # Language preference from most to least priority
129 # Reference: section 5.6.3 of
130 # http://www.arte.tv/sites/en/corporate/files/complete-technical-guidelines-arte-geie-v1-05.pdf
131 PREFERENCES = (
132 # original version in requested language, without subtitles
133 r'VO{0}$'.format(l),
134 # original version in requested language, with partial subtitles in requested language
135 r'VO{0}-ST{0}$'.format(l),
136 # original version in requested language, with subtitles for the deaf and hard-of-hearing in requested language
137 r'VO{0}-STM{0}$'.format(l),
138 # non-original (dubbed) version in requested language, without subtitles
139 r'V{0}$'.format(l),
140 # non-original (dubbed) version in requested language, with subtitles partial subtitles in requested language
141 r'V{0}-ST{0}$'.format(l),
142 # non-original (dubbed) version in requested language, with subtitles for the deaf and hard-of-hearing in requested language
143 r'V{0}-STM{0}$'.format(l),
144 # original version in requested language, with partial subtitles in different language
145 r'VO{0}-ST(?!{0}).+?$'.format(l),
146 # original version in requested language, with subtitles for the deaf and hard-of-hearing in different language
147 r'VO{0}-STM(?!{0}).+?$'.format(l),
148 # original version in different language, with partial subtitles in requested language
149 r'VO(?:(?!{0}).+?)?-ST{0}$'.format(l),
150 # original version in different language, with subtitles for the deaf and hard-of-hearing in requested language
151 r'VO(?:(?!{0}).+?)?-STM{0}$'.format(l),
152 # original version in different language, without subtitles
153 r'VO(?:(?!{0}))?$'.format(l),
154 # original version in different language, with partial subtitles in different language
155 r'VO(?:(?!{0}).+?)?-ST(?!{0}).+?$'.format(l),
156 # original version in different language, with subtitles for the deaf and hard-of-hearing in different language
157 r'VO(?:(?!{0}).+?)?-STM(?!{0}).+?$'.format(l),
158 )
159
160 for pref, p in enumerate(PREFERENCES):
161 if re.match(p, versionCode):
162 lang_pref = len(PREFERENCES) - pref
163 break
164 else:
165 lang_pref = -1
166
167 format = {
168 'format_id': format_id,
169 'preference': -10 if f.get('videoFormat') == 'M3U8' else None,
170 'language_preference': lang_pref,
171 'format_note': '%s, %s' % (f.get('versionCode'), f.get('versionLibelle')),
172 'width': int_or_none(f.get('width')),
173 'height': int_or_none(f.get('height')),
174 'tbr': int_or_none(f.get('bitrate')),
175 'quality': qfunc(f.get('quality')),
176 }
177
178 if f.get('mediaType') == 'rtmp':
179 format['url'] = f['streamer']
180 format['play_path'] = 'mp4:' + f['url']
181 format['ext'] = 'flv'
182 else:
183 format['url'] = f['url']
184
185 formats.append(format)
186
187 self._check_formats(formats, video_id)
188 self._sort_formats(formats)
189
190 info_dict['formats'] = formats
191 return info_dict
192
193
194 class ArteTVPlus7IE(ArteTVBaseIE):
195 IE_NAME = 'arte.tv:+7'
196 _VALID_URL = r'https?://(?:(?:www|sites)\.)?arte\.tv/(?:[^/]+/)?(?P<lang>fr|de|en|es)/(?:videos/)?(?:[^/]+/)*(?P<id>[^/?#&]+)'
197
198 _TESTS = [{
199 'url': 'http://www.arte.tv/guide/de/sendungen/XEN/xenius/?vid=055918-015_PLUS7-D',
200 'only_matching': True,
201 }, {
202 'url': 'http://sites.arte.tv/karambolage/de/video/karambolage-22',
203 'only_matching': True,
204 }, {
205 'url': 'http://www.arte.tv/de/videos/048696-000-A/der-kluge-bauch-unser-zweites-gehirn',
206 'only_matching': True,
207 }]
208
209 @classmethod
210 def suitable(cls, url):
211 return False if ArteTVPlaylistIE.suitable(url) else super(ArteTVPlus7IE, cls).suitable(url)
212
213 def _real_extract(self, url):
214 video_id, lang = self._extract_url_info(url)
215 webpage = self._download_webpage(url, video_id)
216 return self._extract_from_webpage(webpage, video_id, lang)
217
218 def _extract_from_webpage(self, webpage, video_id, lang):
219 patterns_templates = (r'arte_vp_url=["\'](.*?%s.*?)["\']', r'data-url=["\']([^"]+%s[^"]+)["\']')
220 ids = (video_id, '')
221 # some pages contain multiple videos (like
222 # http://www.arte.tv/guide/de/sendungen/XEN/xenius/?vid=055918-015_PLUS7-D),
223 # so we first try to look for json URLs that contain the video id from
224 # the 'vid' parameter.
225 patterns = [t % re.escape(_id) for _id in ids for t in patterns_templates]
226 json_url = self._html_search_regex(
227 patterns, webpage, 'json vp url', default=None)
228 if not json_url:
229 def find_iframe_url(webpage, default=NO_DEFAULT):
230 return self._html_search_regex(
231 r'<iframe[^>]+src=(["\'])(?P<url>.+\bjson_url=.+?)\1',
232 webpage, 'iframe url', group='url', default=default)
233
234 iframe_url = find_iframe_url(webpage, None)
235 if not iframe_url:
236 embed_url = self._html_search_regex(
237 r'arte_vp_url_oembed=\'([^\']+?)\'', webpage, 'embed url', default=None)
238 if embed_url:
239 player = self._download_json(
240 embed_url, video_id, 'Downloading player page')
241 iframe_url = find_iframe_url(player['html'])
242 # en and es URLs produce react-based pages with different layout (e.g.
243 # http://www.arte.tv/guide/en/053330-002-A/carnival-italy?zone=world)
244 if not iframe_url:
245 program = self._search_regex(
246 r'program\s*:\s*({.+?["\']embed_html["\'].+?}),?\s*\n',
247 webpage, 'program', default=None)
248 if program:
249 embed_html = self._parse_json(program, video_id)
250 if embed_html:
251 iframe_url = find_iframe_url(embed_html['embed_html'])
252 if iframe_url:
253 json_url = compat_parse_qs(
254 compat_urllib_parse_urlparse(iframe_url).query)['json_url'][0]
255 if json_url:
256 title = self._search_regex(
257 r'<h3[^>]+title=(["\'])(?P<title>.+?)\1',
258 webpage, 'title', default=None, group='title')
259 return self._extract_from_json_url(json_url, video_id, lang, title=title)
260 # Different kind of embed URL (e.g.
261 # http://www.arte.tv/magazine/trepalium/fr/episode-0406-replay-trepalium)
262 entries = [
263 self.url_result(url)
264 for _, url in re.findall(r'<iframe[^>]+src=(["\'])(?P<url>.+?)\1', webpage)]
265 return self.playlist_result(entries)
266
267
268 # It also uses the arte_vp_url url from the webpage to extract the information
269 class ArteTVCreativeIE(ArteTVPlus7IE):
270 IE_NAME = 'arte.tv:creative'
271 _VALID_URL = r'https?://creative\.arte\.tv/(?P<lang>fr|de|en|es)/(?:[^/]+/)*(?P<id>[^/?#&]+)'
272
273 _TESTS = [{
274 'url': 'http://creative.arte.tv/fr/episode/osmosis-episode-1',
275 'info_dict': {
276 'id': '057405-001-A',
277 'ext': 'mp4',
278 'title': 'OSMOSIS - N\'AYEZ PLUS PEUR D\'AIMER (1)',
279 'upload_date': '20150716',
280 },
281 }, {
282 'url': 'http://creative.arte.tv/fr/Monty-Python-Reunion',
283 'playlist_count': 11,
284 'add_ie': ['Youtube'],
285 }, {
286 'url': 'http://creative.arte.tv/de/episode/agentur-amateur-4-der-erste-kunde',
287 'only_matching': True,
288 }]
289
290
291 class ArteTVInfoIE(ArteTVPlus7IE):
292 IE_NAME = 'arte.tv:info'
293 _VALID_URL = r'https?://info\.arte\.tv/(?P<lang>fr|de|en|es)/(?:[^/]+/)*(?P<id>[^/?#&]+)'
294
295 _TESTS = [{
296 'url': 'http://info.arte.tv/fr/service-civique-un-cache-misere',
297 'info_dict': {
298 'id': '067528-000-A',
299 'ext': 'mp4',
300 'title': 'Service civique, un cache misère ?',
301 'upload_date': '20160403',
302 },
303 }]
304
305
306 class ArteTVFutureIE(ArteTVPlus7IE):
307 IE_NAME = 'arte.tv:future'
308 _VALID_URL = r'https?://future\.arte\.tv/(?P<lang>fr|de|en|es)/(?P<id>[^/?#&]+)'
309
310 _TESTS = [{
311 'url': 'http://future.arte.tv/fr/info-sciences/les-ecrevisses-aussi-sont-anxieuses',
312 'info_dict': {
313 'id': '050940-028-A',
314 'ext': 'mp4',
315 'title': 'Les écrevisses aussi peuvent être anxieuses',
316 'upload_date': '20140902',
317 },
318 }, {
319 'url': 'http://future.arte.tv/fr/la-science-est-elle-responsable',
320 'only_matching': True,
321 }]
322
323
324 class ArteTVDDCIE(ArteTVPlus7IE):
325 IE_NAME = 'arte.tv:ddc'
326 _VALID_URL = r'https?://ddc\.arte\.tv/(?P<lang>emission|folge)/(?P<id>[^/?#&]+)'
327
328 _TESTS = []
329
330 def _real_extract(self, url):
331 video_id, lang = self._extract_url_info(url)
332 if lang == 'folge':
333 lang = 'de'
334 elif lang == 'emission':
335 lang = 'fr'
336 webpage = self._download_webpage(url, video_id)
337 scriptElement = get_element_by_attribute('class', 'visu_video_block', webpage)
338 script_url = self._html_search_regex(r'src="(.*?)"', scriptElement, 'script url')
339 javascriptPlayerGenerator = self._download_webpage(script_url, video_id, 'Download javascript player generator')
340 json_url = self._search_regex(r"json_url=(.*)&rendering_place.*", javascriptPlayerGenerator, 'json url')
341 return self._extract_from_json_url(json_url, video_id, lang)
342
343
344 class ArteTVConcertIE(ArteTVPlus7IE):
345 IE_NAME = 'arte.tv:concert'
346 _VALID_URL = r'https?://concert\.arte\.tv/(?P<lang>fr|de|en|es)/(?P<id>[^/?#&]+)'
347
348 _TESTS = [{
349 'url': 'http://concert.arte.tv/de/notwist-im-pariser-konzertclub-divan-du-monde',
350 'md5': '9ea035b7bd69696b67aa2ccaaa218161',
351 'info_dict': {
352 'id': '186',
353 'ext': 'mp4',
354 'title': 'The Notwist im Pariser Konzertclub "Divan du Monde"',
355 'upload_date': '20140128',
356 'description': 'md5:486eb08f991552ade77439fe6d82c305',
357 },
358 }]
359
360
361 class ArteTVCinemaIE(ArteTVPlus7IE):
362 IE_NAME = 'arte.tv:cinema'
363 _VALID_URL = r'https?://cinema\.arte\.tv/(?P<lang>fr|de|en|es)/(?P<id>.+)'
364
365 _TESTS = [{
366 'url': 'http://cinema.arte.tv/fr/article/les-ailes-du-desir-de-julia-reck',
367 'md5': 'a5b9dd5575a11d93daf0e3f404f45438',
368 'info_dict': {
369 'id': '062494-000-A',
370 'ext': 'mp4',
371 'title': 'Film lauréat du concours web - "Les ailes du désir" de Julia Reck',
372 'upload_date': '20150807',
373 },
374 }]
375
376
377 class ArteTVMagazineIE(ArteTVPlus7IE):
378 IE_NAME = 'arte.tv:magazine'
379 _VALID_URL = r'https?://(?:www\.)?arte\.tv/magazine/[^/]+/(?P<lang>fr|de|en|es)/(?P<id>[^/?#&]+)'
380
381 _TESTS = [{
382 # Embedded via <iframe src="http://www.arte.tv/arte_vp/index.php?json_url=..."
383 'url': 'http://www.arte.tv/magazine/trepalium/fr/entretien-avec-le-realisateur-vincent-lannoo-trepalium',
384 'md5': '2a9369bcccf847d1c741e51416299f25',
385 'info_dict': {
386 'id': '065965-000-A',
387 'ext': 'mp4',
388 'title': 'Trepalium - Extrait Ep.01',
389 'upload_date': '20160121',
390 },
391 }, {
392 # Embedded via <iframe src="http://www.arte.tv/guide/fr/embed/054813-004-A/medium"
393 'url': 'http://www.arte.tv/magazine/trepalium/fr/episode-0406-replay-trepalium',
394 'md5': 'fedc64fc7a946110fe311634e79782ca',
395 'info_dict': {
396 'id': '054813-004_PLUS7-F',
397 'ext': 'mp4',
398 'title': 'Trepalium (4/6)',
399 'description': 'md5:10057003c34d54e95350be4f9b05cb40',
400 'upload_date': '20160218',
401 },
402 }, {
403 'url': 'http://www.arte.tv/magazine/metropolis/de/frank-woeste-german-paris-metropolis',
404 'only_matching': True,
405 }]
406
407
408 class ArteTVEmbedIE(ArteTVPlus7IE):
409 IE_NAME = 'arte.tv:embed'
410 _VALID_URL = r'''(?x)
411 http://www\.arte\.tv
412 /(?:playerv2/embed|arte_vp/index)\.php\?json_url=
413 (?P<json_url>
414 http://arte\.tv/papi/tvguide/videos/stream/player/
415 (?P<lang>[^/]+)/(?P<id>[^/]+)[^&]*
416 )
417 '''
418
419 _TESTS = []
420
421 def _real_extract(self, url):
422 mobj = re.match(self._VALID_URL, url)
423 video_id = mobj.group('id')
424 lang = mobj.group('lang')
425 json_url = mobj.group('json_url')
426 return self._extract_from_json_url(json_url, video_id, lang)
427
428
429 class TheOperaPlatformIE(ArteTVPlus7IE):
430 IE_NAME = 'theoperaplatform'
431 _VALID_URL = r'https?://(?:www\.)?theoperaplatform\.eu/(?P<lang>fr|de|en|es)/(?P<id>[^/?#&]+)'
432
433 _TESTS = [{
434 'url': 'http://www.theoperaplatform.eu/de/opera/verdi-otello',
435 'md5': '970655901fa2e82e04c00b955e9afe7b',
436 'info_dict': {
437 'id': '060338-009-A',
438 'ext': 'mp4',
439 'title': 'Verdi - OTELLO',
440 'upload_date': '20160927',
441 },
442 }]
443
444
445 class ArteTVPlaylistIE(ArteTVBaseIE):
446 IE_NAME = 'arte.tv:playlist'
447 _VALID_URL = r'https?://(?:www\.)?arte\.tv/guide/(?P<lang>fr|de|en|es)/[^#]*#collection/(?P<id>PL-\d+)'
448
449 _TESTS = [{
450 'url': 'http://www.arte.tv/guide/de/plus7/?country=DE#collection/PL-013263/ARTETV',
451 'info_dict': {
452 'id': 'PL-013263',
453 'title': 'Areva & Uramin',
454 'description': 'md5:a1dc0312ce357c262259139cfd48c9bf',
455 },
456 'playlist_mincount': 6,
457 }, {
458 'url': 'http://www.arte.tv/guide/de/playlists?country=DE#collection/PL-013190/ARTETV',
459 'only_matching': True,
460 }]
461
462 def _real_extract(self, url):
463 playlist_id, lang = self._extract_url_info(url)
464 collection = self._download_json(
465 'https://api.arte.tv/api/player/v1/collectionData/%s/%s?source=videos'
466 % (lang, playlist_id), playlist_id)
467 title = collection.get('title')
468 description = collection.get('shortDescription') or collection.get('teaserText')
469 entries = [
470 self._extract_from_json_url(
471 video['jsonUrl'], video.get('programId') or playlist_id, lang)
472 for video in collection['videos'] if video.get('jsonUrl')]
473 return self.playlist_result(entries, playlist_id, title, description)