ArteTVIE: support emission urls that don't contain the video id
[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         if video_id.replace('-','').isdigit():
81             json_url = 'http://org-www.arte.tv/papi/tvguide/videos/stream/player/F/%s_PLUS7-F/ALL/ALL.json' % video_id
82         else:
83             # We don't know the real id of the video, we have to search in the webpage
84             webpage = self._download_webpage(url, video_id)
85             json_url = self._html_search_regex(r'arte_vp_url="(.*?)"', webpage, 'json url')
86
87         json_info = self._download_webpage(json_url, video_id, 'Downloading info json')
88         self.report_extraction(video_id)
89         info = json.loads(json_info)
90         player_info = info['videoJsonPlayer']
91
92         info_dict = {'id': player_info['VID'],
93                      'title': player_info['VTI'],
94                      'description': player_info['VDE'],
95                      'upload_date': unified_strdate(player_info['VDA'].split(' ')[0]),
96                      'thumbnail': player_info['programImage'],
97                      'ext': 'flv',
98                      }
99
100         formats = player_info['VSR'].values()
101         def _match_lang(f):
102             # Return true if that format is in the language of the url
103             if lang == 'fr':
104                 l = 'F'
105             elif lang == 'de':
106                 l = 'A'
107             regexes = [r'VO?%s' % l, r'V%s-ST.' % l]
108             return any(re.match(r, f['versionCode']) for r in regexes)
109         # Some formats may not be in the same language as the url
110         formats = filter(_match_lang, formats)
111         # We order the formats by quality
112         formats = sorted(formats, key=lambda f: int(f['height']))
113         # Pick the best quality
114         format_info = formats[-1]
115         if format_info['mediaType'] == u'rtmp':
116             info_dict['url'] = format_info['streamer']
117             info_dict['play_path'] = 'mp4:' + format_info['url']
118         else:
119             info_dict['url'] = format_info['url']
120
121         return info_dict
122
123     def _extract_video(self, url, video_id, lang):
124         """Extract from videos.arte.tv"""
125         ref_xml_url = url.replace('/videos/', '/do_delegate/videos/')
126         ref_xml_url = ref_xml_url.replace('.html', ',view,asPlayerXml.xml')
127         ref_xml = self._download_webpage(ref_xml_url, video_id, note=u'Downloading metadata')
128         ref_xml_doc = xml.etree.ElementTree.fromstring(ref_xml)
129         config_node = ref_xml_doc.find('.//video[@lang="%s"]' % lang)
130         config_xml_url = config_node.attrib['ref']
131         config_xml = self._download_webpage(config_xml_url, video_id, note=u'Downloading configuration')
132
133         video_urls = list(re.finditer(r'<url quality="(?P<quality>.*?)">(?P<url>.*?)</url>', config_xml))
134         def _key(m):
135             quality = m.group('quality')
136             if quality == 'hd':
137                 return 2
138             else:
139                 return 1
140         # We pick the best quality
141         video_urls = sorted(video_urls, key=_key)
142         video_url = list(video_urls)[-1].group('url')
143         
144         title = self._html_search_regex(r'<name>(.*?)</name>', config_xml, 'title')
145         thumbnail = self._html_search_regex(r'<firstThumbnailUrl>(.*?)</firstThumbnailUrl>',
146                                             config_xml, 'thumbnail')
147         return {'id': video_id,
148                 'title': title,
149                 'thumbnail': thumbnail,
150                 'url': video_url,
151                 'ext': 'flv',
152                 }