[arte] Prepare for generic format support (#980)
[youtube-dl] / youtube_dl / extractor / arte.py
1 import re
2 import json
3 import xml.etree.ElementTree
4
5 from .common import InfoExtractor
6 from ..utils import (
7     ExtractorError,
8     find_xpath_attr,
9     unified_strdate,
10 )
11
12 class ArteTvIE(InfoExtractor):
13     """
14     There are two sources of video in arte.tv: videos.arte.tv and
15     www.arte.tv/guide, the extraction process is different for each one.
16     The videos expire in 7 days, so we can't add tests.
17     """
18     _EMISSION_URL = r'(?:http://)?www\.arte.tv/guide/(?P<lang>fr|de)/(?:(?:sendungen|emissions)/)?(?P<id>.*?)/(?P<name>.*?)(\?.*)?'
19     _VIDEOS_URL = r'(?:http://)?videos.arte.tv/(?P<lang>fr|de)/.*-(?P<id>.*?).html'
20     _LIVEWEB_URL = r'(?:http://)?liveweb.arte.tv/(?P<lang>fr|de)/(?P<subpage>.+?)/(?P<name>.+)'
21     _LIVE_URL = r'index-[0-9]+\.html$'
22
23     IE_NAME = u'arte.tv'
24
25     @classmethod
26     def suitable(cls, url):
27         return any(re.match(regex, url) for regex in (cls._EMISSION_URL, cls._VIDEOS_URL, cls._LIVEWEB_URL))
28
29     # TODO implement Live Stream
30     # from ..utils import compat_urllib_parse
31     # def extractLiveStream(self, url):
32     #     video_lang = url.split('/')[-4]
33     #     info = self.grep_webpage(
34     #         url,
35     #         r'src="(.*?/videothek_js.*?\.js)',
36     #         0,
37     #         [
38     #             (1, 'url', u'Invalid URL: %s' % url)
39     #         ]
40     #     )
41     #     http_host = url.split('/')[2]
42     #     next_url = 'http://%s%s' % (http_host, compat_urllib_parse.unquote(info.get('url')))
43     #     info = self.grep_webpage(
44     #         next_url,
45     #         r'(s_artestras_scst_geoFRDE_' + video_lang + '.*?)\'.*?' +
46     #             '(http://.*?\.swf).*?' +
47     #             '(rtmp://.*?)\'',
48     #         re.DOTALL,
49     #         [
50     #             (1, 'path',   u'could not extract video path: %s' % url),
51     #             (2, 'player', u'could not extract video player: %s' % url),
52     #             (3, 'url',    u'could not extract video url: %s' % url)
53     #         ]
54     #     )
55     #     video_url = u'%s/%s' % (info.get('url'), info.get('path'))
56
57     def _real_extract(self, url):
58         mobj = re.match(self._EMISSION_URL, url)
59         if mobj is not None:
60             lang = mobj.group('lang')
61             # This is not a real id, it can be for example AJT for the news
62             # http://www.arte.tv/guide/fr/emissions/AJT/arte-journal
63             video_id = mobj.group('id')
64             return self._extract_emission(url, video_id, lang)
65
66         mobj = re.match(self._VIDEOS_URL, url)
67         if mobj is not None:
68             id = mobj.group('id')
69             lang = mobj.group('lang')
70             return self._extract_video(url, id, lang)
71
72         mobj = re.match(self._LIVEWEB_URL, url)
73         if mobj is not None:
74             name = mobj.group('name')
75             lang = mobj.group('lang')
76             return self._extract_liveweb(url, name, lang)
77
78         if re.search(self._LIVE_URL, video_id) is not None:
79             raise ExtractorError(u'Arte live streams are not yet supported, sorry')
80             # self.extractLiveStream(url)
81             # return
82
83     def _extract_emission(self, url, video_id, lang):
84         """Extract from www.arte.tv/guide"""
85         webpage = self._download_webpage(url, video_id)
86         json_url = self._html_search_regex(r'arte_vp_url="(.*?)"', webpage, 'json url')
87
88         json_info = self._download_webpage(json_url, video_id, 'Downloading info json')
89         self.report_extraction(video_id)
90         info = json.loads(json_info)
91         player_info = info['videoJsonPlayer']
92
93         info_dict = {'id': player_info['VID'],
94                      'title': player_info['VTI'],
95                      'description': player_info.get('VDE'),
96                      'upload_date': unified_strdate(player_info['VDA'].split(' ')[0]),
97                      'thumbnail': player_info['programImage'],
98                      'ext': 'flv',
99                      }
100
101         formats = player_info['VSR'].values()
102         def _match_lang(f):
103             # Return true if that format is in the language of the url
104             if lang == 'fr':
105                 l = 'F'
106             elif lang == 'de':
107                 l = 'A'
108             regexes = [r'VO?%s' % l, r'VO?.-ST%s' % l]
109             return any(re.match(r, f['versionCode']) for r in regexes)
110         # Some formats may not be in the same language as the url
111         formats = filter(_match_lang, formats)
112         # Some formats use the m3u8 protocol
113         formats = filter(lambda f: f['videoFormat'] != 'M3U8', formats)
114         # We order the formats by quality
115         formats = sorted(formats, key=lambda f: int(f['height']))
116         # Prefer videos without subtitles in the same language
117         formats = sorted(formats, key=lambda f: re.match(r'VO(F|A)-STM\1', f['versionCode']) is None)
118         # Pick the best quality
119         def _format(format_info):
120             info = {'ext': 'flv',
121                     'width': format_info.get('width'),
122                     'height': format_info.get('height'),
123                     }
124             if format_info['mediaType'] == u'rtmp':
125                 info['url'] = format_info['streamer']
126                 info['play_path'] = 'mp4:' + format_info['url']
127             else:
128                 info_dict['url'] = format_info['url']
129             return info
130         info_dict['formats'] = [_format(f) for f in formats]
131         # TODO: Remove when #980 has been merged 
132         info_dict.update(info_dict['formats'][-1])
133
134         return info_dict
135
136     def _extract_video(self, url, video_id, lang):
137         """Extract from videos.arte.tv"""
138         ref_xml_url = url.replace('/videos/', '/do_delegate/videos/')
139         ref_xml_url = ref_xml_url.replace('.html', ',view,asPlayerXml.xml')
140         ref_xml = self._download_webpage(ref_xml_url, video_id, note=u'Downloading metadata')
141         ref_xml_doc = xml.etree.ElementTree.fromstring(ref_xml)
142         config_node = find_xpath_attr(ref_xml_doc, './/video', 'lang', lang)
143         config_xml_url = config_node.attrib['ref']
144         config_xml = self._download_webpage(config_xml_url, video_id, note=u'Downloading configuration')
145
146         video_urls = list(re.finditer(r'<url quality="(?P<quality>.*?)">(?P<url>.*?)</url>', config_xml))
147         def _key(m):
148             quality = m.group('quality')
149             if quality == 'hd':
150                 return 2
151             else:
152                 return 1
153         # We pick the best quality
154         video_urls = sorted(video_urls, key=_key)
155         video_url = list(video_urls)[-1].group('url')
156         
157         title = self._html_search_regex(r'<name>(.*?)</name>', config_xml, 'title')
158         thumbnail = self._html_search_regex(r'<firstThumbnailUrl>(.*?)</firstThumbnailUrl>',
159                                             config_xml, 'thumbnail')
160         return {'id': video_id,
161                 'title': title,
162                 'thumbnail': thumbnail,
163                 'url': video_url,
164                 'ext': 'flv',
165                 }
166
167     def _extract_liveweb(self, url, name, lang):
168         """Extract form http://liveweb.arte.tv/"""
169         webpage = self._download_webpage(url, name)
170         video_id = self._search_regex(r'eventId=(\d+?)("|&)', webpage, u'event id')
171         config_xml = self._download_webpage('http://download.liveweb.arte.tv/o21/liveweb/events/event-%s.xml' % video_id,
172                                             video_id, u'Downloading information')
173         config_doc = xml.etree.ElementTree.fromstring(config_xml.encode('utf-8'))
174         event_doc = config_doc.find('event')
175         url_node = event_doc.find('video').find('urlHd')
176         if url_node is None:
177             url_node = video_doc.find('urlSd')
178
179         return {'id': video_id,
180                 'title': event_doc.find('name%s' % lang.capitalize()).text,
181                 'url': url_node.text.replace('MP4', 'mp4'),
182                 'ext': 'flv',
183                 'thumbnail': self._og_search_thumbnail(webpage),
184                 }