Use the new '_download_xml' helper in more extractors
[youtube-dl] / youtube_dl / extractor / arte.py
1 # encoding: utf-8
2 import re
3 import json
4
5 from .common import InfoExtractor
6 from ..utils import (
7     ExtractorError,
8     find_xpath_attr,
9     unified_strdate,
10     determine_ext,
11     get_element_by_id,
12     compat_str,
13 )
14
15 # There are different sources of video in arte.tv, the extraction process 
16 # is different for each one. The videos usually expire in 7 days, so we can't
17 # add tests.
18
19 class ArteTvIE(InfoExtractor):
20     _VIDEOS_URL = r'(?:http://)?videos.arte.tv/(?P<lang>fr|de)/.*-(?P<id>.*?).html'
21     _LIVEWEB_URL = r'(?:http://)?liveweb.arte.tv/(?P<lang>fr|de)/(?P<subpage>.+?)/(?P<name>.+)'
22     _LIVE_URL = r'index-[0-9]+\.html$'
23
24     IE_NAME = u'arte.tv'
25
26     @classmethod
27     def suitable(cls, url):
28         return any(re.match(regex, url) for regex in (cls._VIDEOS_URL, cls._LIVEWEB_URL))
29
30     # TODO implement Live Stream
31     # from ..utils import compat_urllib_parse
32     # def extractLiveStream(self, url):
33     #     video_lang = url.split('/')[-4]
34     #     info = self.grep_webpage(
35     #         url,
36     #         r'src="(.*?/videothek_js.*?\.js)',
37     #         0,
38     #         [
39     #             (1, 'url', u'Invalid URL: %s' % url)
40     #         ]
41     #     )
42     #     http_host = url.split('/')[2]
43     #     next_url = 'http://%s%s' % (http_host, compat_urllib_parse.unquote(info.get('url')))
44     #     info = self.grep_webpage(
45     #         next_url,
46     #         r'(s_artestras_scst_geoFRDE_' + video_lang + '.*?)\'.*?' +
47     #             '(http://.*?\.swf).*?' +
48     #             '(rtmp://.*?)\'',
49     #         re.DOTALL,
50     #         [
51     #             (1, 'path',   u'could not extract video path: %s' % url),
52     #             (2, 'player', u'could not extract video player: %s' % url),
53     #             (3, 'url',    u'could not extract video url: %s' % url)
54     #         ]
55     #     )
56     #     video_url = u'%s/%s' % (info.get('url'), info.get('path'))
57
58     def _real_extract(self, url):
59         mobj = re.match(self._VIDEOS_URL, url)
60         if mobj is not None:
61             id = mobj.group('id')
62             lang = mobj.group('lang')
63             return self._extract_video(url, id, lang)
64
65         mobj = re.match(self._LIVEWEB_URL, url)
66         if mobj is not None:
67             name = mobj.group('name')
68             lang = mobj.group('lang')
69             return self._extract_liveweb(url, name, lang)
70
71         if re.search(self._LIVE_URL, url) is not None:
72             raise ExtractorError(u'Arte live streams are not yet supported, sorry')
73             # self.extractLiveStream(url)
74             # return
75
76     def _extract_video(self, url, video_id, lang):
77         """Extract from videos.arte.tv"""
78         ref_xml_url = url.replace('/videos/', '/do_delegate/videos/')
79         ref_xml_url = ref_xml_url.replace('.html', ',view,asPlayerXml.xml')
80         ref_xml_doc = self._download_xml(ref_xml_url, video_id, note=u'Downloading metadata')
81         config_node = find_xpath_attr(ref_xml_doc, './/video', 'lang', lang)
82         config_xml_url = config_node.attrib['ref']
83         config_xml = self._download_webpage(config_xml_url, video_id, note=u'Downloading configuration')
84
85         video_urls = list(re.finditer(r'<url quality="(?P<quality>.*?)">(?P<url>.*?)</url>', config_xml))
86         def _key(m):
87             quality = m.group('quality')
88             if quality == 'hd':
89                 return 2
90             else:
91                 return 1
92         # We pick the best quality
93         video_urls = sorted(video_urls, key=_key)
94         video_url = list(video_urls)[-1].group('url')
95         
96         title = self._html_search_regex(r'<name>(.*?)</name>', config_xml, 'title')
97         thumbnail = self._html_search_regex(r'<firstThumbnailUrl>(.*?)</firstThumbnailUrl>',
98                                             config_xml, 'thumbnail')
99         return {'id': video_id,
100                 'title': title,
101                 'thumbnail': thumbnail,
102                 'url': video_url,
103                 'ext': 'flv',
104                 }
105
106     def _extract_liveweb(self, url, name, lang):
107         """Extract form http://liveweb.arte.tv/"""
108         webpage = self._download_webpage(url, name)
109         video_id = self._search_regex(r'eventId=(\d+?)("|&)', webpage, u'event id')
110         config_doc = self._download_xml('http://download.liveweb.arte.tv/o21/liveweb/events/event-%s.xml' % video_id,
111                                             video_id, u'Downloading information')
112         event_doc = config_doc.find('event')
113         url_node = event_doc.find('video').find('urlHd')
114         if url_node is None:
115             url_node = event_doc.find('urlSd')
116
117         return {'id': video_id,
118                 'title': event_doc.find('name%s' % lang.capitalize()).text,
119                 'url': url_node.text.replace('MP4', 'mp4'),
120                 'ext': 'flv',
121                 'thumbnail': self._og_search_thumbnail(webpage),
122                 }
123
124
125 class ArteTVPlus7IE(InfoExtractor):
126     IE_NAME = u'arte.tv:+7'
127     _VALID_URL = r'https?://www\.arte.tv/guide/(?P<lang>fr|de)/(?:(?:sendungen|emissions)/)?(?P<id>.*?)/(?P<name>.*?)(\?.*)?'
128
129     @classmethod
130     def _extract_url_info(cls, url):
131         mobj = re.match(cls._VALID_URL, url)
132         lang = mobj.group('lang')
133         # This is not a real id, it can be for example AJT for the news
134         # http://www.arte.tv/guide/fr/emissions/AJT/arte-journal
135         video_id = mobj.group('id')
136         return video_id, lang
137
138     def _real_extract(self, url):
139         video_id, lang = self._extract_url_info(url)
140         webpage = self._download_webpage(url, video_id)
141         return self._extract_from_webpage(webpage, video_id, lang)
142
143     def _extract_from_webpage(self, webpage, video_id, lang):
144         json_url = self._html_search_regex(r'arte_vp_url="(.*?)"', webpage, 'json url')
145
146         json_info = self._download_webpage(json_url, video_id, 'Downloading info json')
147         self.report_extraction(video_id)
148         info = json.loads(json_info)
149         player_info = info['videoJsonPlayer']
150
151         info_dict = {
152             'id': player_info['VID'],
153             'title': player_info['VTI'],
154             'description': player_info.get('VDE'),
155             'upload_date': unified_strdate(player_info.get('VDA', '').split(' ')[0]),
156             'thumbnail': player_info.get('programImage') or player_info.get('VTU', {}).get('IUR'),
157         }
158
159         all_formats = player_info['VSR'].values()
160         # Some formats use the m3u8 protocol
161         all_formats = list(filter(lambda f: f.get('videoFormat') != 'M3U8', all_formats))
162         def _match_lang(f):
163             if f.get('versionCode') is None:
164                 return True
165             # Return true if that format is in the language of the url
166             if lang == 'fr':
167                 l = 'F'
168             elif lang == 'de':
169                 l = 'A'
170             regexes = [r'VO?%s' % l, r'VO?.-ST%s' % l]
171             return any(re.match(r, f['versionCode']) for r in regexes)
172         # Some formats may not be in the same language as the url
173         formats = filter(_match_lang, all_formats)
174         formats = list(formats) # in python3 filter returns an iterator
175         if not formats:
176             # Some videos are only available in the 'Originalversion'
177             # they aren't tagged as being in French or German
178             if all(f['versionCode'] == 'VO' for f in all_formats):
179                 formats = all_formats
180             else:
181                 raise ExtractorError(u'The formats list is empty')
182
183         if re.match(r'[A-Z]Q', formats[0]['quality']) is not None:
184             def sort_key(f):
185                 return ['HQ', 'MQ', 'EQ', 'SQ'].index(f['quality'])
186         else:
187             def sort_key(f):
188                 return (
189                     # Sort first by quality
190                     int(f.get('height',-1)),
191                     int(f.get('bitrate',-1)),
192                     # The original version with subtitles has lower relevance
193                     re.match(r'VO-ST(F|A)', f.get('versionCode', '')) is None,
194                     # The version with sourds/mal subtitles has also lower relevance
195                     re.match(r'VO?(F|A)-STM\1', f.get('versionCode', '')) is None,
196                 )
197         formats = sorted(formats, key=sort_key)
198         def _format(format_info):
199             quality = ''
200             height = format_info.get('height')
201             if height is not None:
202                 quality = compat_str(height)
203             bitrate = format_info.get('bitrate')
204             if bitrate is not None:
205                 quality += '-%d' % bitrate
206             if format_info.get('versionCode') is not None:
207                 format_id = u'%s-%s' % (quality, format_info['versionCode'])
208             else:
209                 format_id = quality
210             info = {
211                 'format_id': format_id,
212                 'format_note': format_info.get('versionLibelle'),
213                 'width': format_info.get('width'),
214                 'height': height,
215             }
216             if format_info['mediaType'] == u'rtmp':
217                 info['url'] = format_info['streamer']
218                 info['play_path'] = 'mp4:' + format_info['url']
219                 info['ext'] = 'flv'
220             else:
221                 info['url'] = format_info['url']
222                 info['ext'] = determine_ext(info['url'])
223             return info
224         info_dict['formats'] = [_format(f) for f in formats]
225
226         return info_dict
227
228
229 # It also uses the arte_vp_url url from the webpage to extract the information
230 class ArteTVCreativeIE(ArteTVPlus7IE):
231     IE_NAME = u'arte.tv:creative'
232     _VALID_URL = r'https?://creative\.arte\.tv/(?P<lang>fr|de)/magazine?/(?P<id>.+)'
233
234     _TEST = {
235         u'url': u'http://creative.arte.tv/de/magazin/agentur-amateur-corporate-design',
236         u'file': u'050489-002.mp4',
237         u'info_dict': {
238             u'title': u'Agentur Amateur / Agence Amateur #2 : Corporate Design',
239         },
240     }
241
242
243 class ArteTVFutureIE(ArteTVPlus7IE):
244     IE_NAME = u'arte.tv:future'
245     _VALID_URL = r'https?://future\.arte\.tv/(?P<lang>fr|de)/(thema|sujet)/.*?#article-anchor-(?P<id>\d+)'
246
247     _TEST = {
248         u'url': u'http://future.arte.tv/fr/sujet/info-sciences#article-anchor-7081',
249         u'file': u'050940-003.mp4',
250         u'info_dict': {
251             u'title': u'Les champignons au secours de la planète',
252         },
253     }
254
255     def _real_extract(self, url):
256         anchor_id, lang = self._extract_url_info(url)
257         webpage = self._download_webpage(url, anchor_id)
258         row = get_element_by_id(anchor_id, webpage)
259         return self._extract_from_webpage(row, anchor_id, lang)