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