[arte] Fix language selection (Fixes #988)
[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     # This is used by the not implemented extractLiveStream method
8     compat_urllib_parse,
9
10     ExtractorError,
11     unified_strdate,
12 )
13
14 class ArteTvIE(InfoExtractor):
15     """
16     There are two sources of video in arte.tv: videos.arte.tv and
17     www.arte.tv/guide, the extraction process is different for each one.
18     The videos expire in 7 days, so we can't add tests.
19     """
20     _EMISSION_URL = r'(?:http://)?www\.arte.tv/guide/(?P<lang>fr|de)/(?:(?:sendungen|emissions)/)?(?P<id>.*?)/(?P<name>.*?)(\?.*)?'
21     _VIDEOS_URL = r'(?:http://)?videos.arte.tv/(?P<lang>fr|de)/.*-(?P<id>.*?).html'
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._EMISSION_URL, cls._VIDEOS_URL))
29
30     # TODO implement Live Stream
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             name = mobj.group('name')
61             lang = mobj.group('lang')
62             # This is not a real id, it can be for example AJT for the news
63             # http://www.arte.tv/guide/fr/emissions/AJT/arte-journal
64             video_id = mobj.group('id')
65             return self._extract_emission(url, video_id, lang)
66
67         mobj = re.match(self._VIDEOS_URL, url)
68         if mobj is not None:
69             id = mobj.group('id')
70             lang = mobj.group('lang')
71             return self._extract_video(url, id, lang)
72
73         if re.search(self._LIVE_URL, video_id) is not None:
74             raise ExtractorError(u'Arte live streams are not yet supported, sorry')
75             # self.extractLiveStream(url)
76             # return
77
78     def _extract_emission(self, url, video_id, lang):
79         """Extract from www.arte.tv/guide"""
80         json_url = 'http://org-www.arte.tv/papi/tvguide/videos/stream/player/F/%s_PLUS7-F/ALL/ALL.json' % video_id
81
82         json_info = self._download_webpage(json_url, video_id, 'Downloading info json')
83         self.report_extraction(video_id)
84         info = json.loads(json_info)
85         player_info = info['videoJsonPlayer']
86
87         info_dict = {'id': player_info['VID'],
88                      'title': player_info['VTI'],
89                      'description': player_info['VDE'],
90                      'upload_date': unified_strdate(player_info['VDA'].split(' ')[0]),
91                      'thumbnail': player_info['programImage'],
92                      'ext': 'flv',
93                      }
94
95         formats = player_info['VSR'].values()
96         def _match_lang(f):
97             # Return true if that format is in the language of the url
98             if lang == 'fr':
99                 l = 'F'
100             elif lang == 'de':
101                 l = 'A'
102             regexes = [r'VO?%s' % l, r'V%s-ST.' % l]
103             return any(re.match(r, f['versionCode']) for r in regexes)
104         # Some formats may not be in the same language as the url
105         formats = filter(_match_lang, formats)
106         # We order the formats by quality
107         formats = sorted(formats, key=lambda f: int(f['height']))
108         # Pick the best quality
109         format_info = formats[-1]
110         if format_info['mediaType'] == u'rtmp':
111             info_dict['url'] = format_info['streamer']
112             info_dict['play_path'] = 'mp4:' + format_info['url']
113         else:
114             info_dict['url'] = format_info['url']
115
116         return info_dict
117
118     def _extract_video(self, url, video_id, lang):
119         """Extract from videos.arte.tv"""
120         ref_xml_url = url.replace('/videos/', '/do_delegate/videos/')
121         ref_xml_url = ref_xml_url.replace('.html', ',view,asPlayerXml.xml')
122         ref_xml = self._download_webpage(ref_xml_url, video_id, note=u'Downloading metadata')
123         ref_xml_doc = xml.etree.ElementTree.fromstring(ref_xml)
124         config_node = ref_xml_doc.find('.//video[@lang="%s"]' % lang)
125         config_xml_url = config_node.attrib['ref']
126         config_xml = self._download_webpage(config_xml_url, video_id, note=u'Downloading configuration')
127
128         video_urls = list(re.finditer(r'<url quality="(?P<quality>.*?)">(?P<url>.*?)</url>', config_xml))
129         def _key(m):
130             quality = m.group('quality')
131             if quality == 'hd':
132                 return 2
133             else:
134                 return 1
135         # We pick the best quality
136         video_urls = sorted(video_urls, key=_key)
137         video_url = list(video_urls)[-1].group('url')
138         
139         title = self._html_search_regex(r'<name>(.*?)</name>', config_xml, 'title')
140         thumbnail = self._html_search_regex(r'<firstThumbnailUrl>(.*?)</firstThumbnailUrl>',
141                                             config_xml, 'thumbnail')
142         return {'id': video_id,
143                 'title': title,
144                 'thumbnail': thumbnail,
145                 'url': video_url,
146                 'ext': 'flv',
147                 }