[arte] Extend more _VALID_URLs for en and es support
[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'http://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 ArteTVPlus7IE(InfoExtractor):
65     IE_NAME = 'arte.tv:+7'
66     _VALID_URL = r'https?://(?:www\.)?arte\.tv/guide/(?P<lang>fr|de|en|es)/(?:(?:sendungen|emissions)/)?(?P<id>.*?)/(?P<name>.*?)(\?.*)?'
67
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 _real_extract(self, url):
82         video_id, lang = self._extract_url_info(url)
83         webpage = self._download_webpage(url, video_id)
84         return self._extract_from_webpage(webpage, video_id, lang)
85
86     def _extract_from_webpage(self, webpage, video_id, lang):
87         patterns_templates = (r'arte_vp_url=["\'](.*?%s.*?)["\']', r'data-url=["\']([^"]+%s[^"]+)["\']')
88         ids = (video_id, '')
89         # some pages contain multiple videos (like
90         # http://www.arte.tv/guide/de/sendungen/XEN/xenius/?vid=055918-015_PLUS7-D),
91         # so we first try to look for json URLs that contain the video id from
92         # the 'vid' parameter.
93         patterns = [t % re.escape(_id) for _id in ids for t in patterns_templates]
94         json_url = self._html_search_regex(
95             patterns, webpage, 'json vp url', default=None)
96         if not json_url:
97             def find_iframe_url(webpage, default=NO_DEFAULT):
98                 return self._html_search_regex(
99                     r'<iframe[^>]+src=(["\'])(?P<url>.+\bjson_url=.+?)\1',
100                     webpage, 'iframe url', group='url', default=default)
101
102             iframe_url = find_iframe_url(webpage, None)
103             if not iframe_url:
104                 embed_url = self._html_search_regex(
105                     r'arte_vp_url_oembed=\'([^\']+?)\'', webpage, 'embed url', default=None)
106                 if embed_url:
107                     player = self._download_json(
108                         embed_url, video_id, 'Downloading player page')
109                     iframe_url = find_iframe_url(player['html'])
110             # en and es URLs produce react-based pages with different layout (e.g.
111             # http://www.arte.tv/guide/en/053330-002-A/carnival-italy?zone=world)
112             if not iframe_url:
113                 embed_html = self._parse_json(
114                     self._search_regex(
115                         r'program\s*:\s*({.+?["\']embed_html["\'].+?}),?\s*\n',
116                         webpage, 'program'),
117                     video_id)['embed_html']
118                 iframe_url= find_iframe_url(embed_html)
119             json_url = compat_parse_qs(
120                 compat_urllib_parse_urlparse(iframe_url).query)['json_url'][0]
121         return self._extract_from_json_url(json_url, video_id, lang)
122
123     def _extract_from_json_url(self, json_url, video_id, lang):
124         info = self._download_json(json_url, video_id)
125         player_info = info['videoJsonPlayer']
126
127         upload_date_str = player_info.get('shootingDate')
128         if not upload_date_str:
129             upload_date_str = player_info.get('VDA', '').split(' ')[0]
130
131         title = player_info['VTI'].strip()
132         subtitle = player_info.get('VSU', '').strip()
133         if subtitle:
134             title += ' - %s' % subtitle
135
136         info_dict = {
137             'id': player_info['VID'],
138             'title': title,
139             'description': player_info.get('VDE'),
140             'upload_date': unified_strdate(upload_date_str),
141             'thumbnail': player_info.get('programImage') or player_info.get('VTU', {}).get('IUR'),
142         }
143         qfunc = qualities(['HQ', 'MQ', 'EQ', 'SQ'])
144
145         formats = []
146         for format_id, format_dict in player_info['VSR'].items():
147             f = dict(format_dict)
148             versionCode = f.get('versionCode')
149
150             langcode = {
151                 'fr': 'F',
152                 'de': 'A',
153             }.get(lang, lang)
154             lang_rexs = [r'VO?%s' % langcode, r'VO?.-ST%s' % langcode]
155             lang_pref = (
156                 None if versionCode is None else (
157                     10 if any(re.match(r, versionCode) for r in lang_rexs)
158                     else -10))
159             source_pref = 0
160             if versionCode is not None:
161                 # The original version with subtitles has lower relevance
162                 if re.match(r'VO-ST(F|A)', versionCode):
163                     source_pref -= 10
164                 # The version with sourds/mal subtitles has also lower relevance
165                 elif re.match(r'VO?(F|A)-STM\1', versionCode):
166                     source_pref -= 9
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                 'source_preference': source_pref,
177             }
178
179             if f.get('mediaType') == 'rtmp':
180                 format['url'] = f['streamer']
181                 format['play_path'] = 'mp4:' + f['url']
182                 format['ext'] = 'flv'
183             else:
184                 format['url'] = f['url']
185
186             formats.append(format)
187
188         self._check_formats(formats, video_id)
189         self._sort_formats(formats)
190
191         info_dict['formats'] = formats
192         return info_dict
193
194
195 # It also uses the arte_vp_url url from the webpage to extract the information
196 class ArteTVCreativeIE(ArteTVPlus7IE):
197     IE_NAME = 'arte.tv:creative'
198     _VALID_URL = r'https?://creative\.arte\.tv/(?P<lang>fr|de|en|es)/(?:magazine?/)?(?P<id>[^?#]+)'
199
200     _TESTS = [{
201         'url': 'http://creative.arte.tv/de/magazin/agentur-amateur-corporate-design',
202         'info_dict': {
203             'id': '72176',
204             'ext': 'mp4',
205             'title': 'Folge 2 - Corporate Design',
206             'upload_date': '20131004',
207         },
208     }, {
209         'url': 'http://creative.arte.tv/fr/Monty-Python-Reunion',
210         'info_dict': {
211             'id': '160676',
212             'ext': 'mp4',
213             'title': 'Monty Python live (mostly)',
214             'description': 'Événement ! Quarante-cinq ans après leurs premiers succès, les légendaires Monty Python remontent sur scène.\n',
215             'upload_date': '20140805',
216         }
217     }]
218
219
220 class ArteTVFutureIE(ArteTVPlus7IE):
221     IE_NAME = 'arte.tv:future'
222     _VALID_URL = r'https?://future\.arte\.tv/(?P<lang>fr|de|en|es)/(?P<id>.+)'
223
224     _TESTS = [{
225         'url': 'http://future.arte.tv/fr/info-sciences/les-ecrevisses-aussi-sont-anxieuses',
226         'info_dict': {
227             'id': '050940-028-A',
228             'ext': 'mp4',
229             'title': 'Les écrevisses aussi peuvent être anxieuses',
230         },
231     }, {
232         'url': 'http://future.arte.tv/fr/la-science-est-elle-responsable',
233         'only_matching': True,
234     }]
235
236
237 class ArteTVDDCIE(ArteTVPlus7IE):
238     IE_NAME = 'arte.tv:ddc'
239     _VALID_URL = r'https?://ddc\.arte\.tv/(?P<lang>emission|folge)/(?P<id>.+)'
240
241     def _real_extract(self, url):
242         video_id, lang = self._extract_url_info(url)
243         if lang == 'folge':
244             lang = 'de'
245         elif lang == 'emission':
246             lang = 'fr'
247         webpage = self._download_webpage(url, video_id)
248         scriptElement = get_element_by_attribute('class', 'visu_video_block', webpage)
249         script_url = self._html_search_regex(r'src="(.*?)"', scriptElement, 'script url')
250         javascriptPlayerGenerator = self._download_webpage(script_url, video_id, 'Download javascript player generator')
251         json_url = self._search_regex(r"json_url=(.*)&rendering_place.*", javascriptPlayerGenerator, 'json url')
252         return self._extract_from_json_url(json_url, video_id, lang)
253
254
255 class ArteTVConcertIE(ArteTVPlus7IE):
256     IE_NAME = 'arte.tv:concert'
257     _VALID_URL = r'https?://concert\.arte\.tv/(?P<lang>fr|de|en|es)/(?P<id>.+)'
258
259     _TEST = {
260         'url': 'http://concert.arte.tv/de/notwist-im-pariser-konzertclub-divan-du-monde',
261         'md5': '9ea035b7bd69696b67aa2ccaaa218161',
262         'info_dict': {
263             'id': '186',
264             'ext': 'mp4',
265             'title': 'The Notwist im Pariser Konzertclub "Divan du Monde"',
266             'upload_date': '20140128',
267             'description': 'md5:486eb08f991552ade77439fe6d82c305',
268         },
269     }
270
271
272 class ArteTVCinemaIE(ArteTVPlus7IE):
273     IE_NAME = 'arte.tv:cinema'
274     _VALID_URL = r'https?://cinema\.arte\.tv/(?P<lang>fr|de|en|es)/(?P<id>.+)'
275
276     _TEST = {
277         'url': 'http://cinema.arte.tv/de/node/38291',
278         'md5': '6b275511a5107c60bacbeeda368c3aa1',
279         'info_dict': {
280             'id': '055876-000_PWA12025-D',
281             'ext': 'mp4',
282             'title': 'Tod auf dem Nil',
283             'upload_date': '20160122',
284             'description': 'md5:7f749bbb77d800ef2be11d54529b96bc',
285         },
286     }
287
288
289 class ArteTVEmbedIE(ArteTVPlus7IE):
290     IE_NAME = 'arte.tv:embed'
291     _VALID_URL = r'''(?x)
292         http://www\.arte\.tv
293         /playerv2/embed\.php\?json_url=
294         (?P<json_url>
295             http://arte\.tv/papi/tvguide/videos/stream/player/
296             (?P<lang>[^/]+)/(?P<id>[^/]+)[^&]*
297         )
298     '''
299
300     def _real_extract(self, url):
301         mobj = re.match(self._VALID_URL, url)
302         video_id = mobj.group('id')
303         lang = mobj.group('lang')
304         json_url = mobj.group('json_url')
305         return self._extract_from_json_url(json_url, video_id, lang)