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