[arte.tv:+7] Improve title extraction (Closes #3995)
[youtube-dl] / youtube_dl / extractor / arte.py
1 # encoding: utf-8
2 from __future__ import unicode_literals
3
4 import re
5
6 from .common import InfoExtractor
7 from ..utils import (
8     ExtractorError,
9     find_xpath_attr,
10     unified_strdate,
11     determine_ext,
12     get_element_by_id,
13     compat_str,
14     get_element_by_attribute,
15     int_or_none,
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
23 class ArteTvIE(InfoExtractor):
24     _VALID_URL = r'http://videos\.arte\.tv/(?P<lang>fr|de)/.*-(?P<id>.*?)\.html'
25     IE_NAME = 'arte.tv'
26
27     def _real_extract(self, url):
28         mobj = re.match(self._VALID_URL, url)
29         lang = mobj.group('lang')
30         video_id = mobj.group('id')
31
32         ref_xml_url = url.replace('/videos/', '/do_delegate/videos/')
33         ref_xml_url = ref_xml_url.replace('.html', ',view,asPlayerXml.xml')
34         ref_xml_doc = self._download_xml(
35             ref_xml_url, video_id, note='Downloading metadata')
36         config_node = find_xpath_attr(ref_xml_doc, './/video', 'lang', lang)
37         config_xml_url = config_node.attrib['ref']
38         config = self._download_xml(
39             config_xml_url, video_id, note='Downloading configuration')
40
41         formats = [{
42             'forma_id': q.attrib['quality'],
43             # The playpath starts at 'mp4:', if we don't manually
44             # split the url, rtmpdump will incorrectly parse them
45             'url': q.text.split('mp4:', 1)[0],
46             'play_path': 'mp4:' + q.text.split('mp4:', 1)[1],
47             'ext': 'flv',
48             'quality': 2 if q.attrib['quality'] == 'hd' else 1,
49         } for q in config.findall('./urls/url')]
50         self._sort_formats(formats)
51
52         title = config.find('.//name').text
53         thumbnail = config.find('.//firstThumbnailUrl').text
54         return {
55             'id': video_id,
56             'title': title,
57             'thumbnail': thumbnail,
58             'formats': formats,
59         }
60
61
62 class ArteTVPlus7IE(InfoExtractor):
63     IE_NAME = 'arte.tv:+7'
64     _VALID_URL = r'https?://(?:www\.)?arte\.tv/guide/(?P<lang>fr|de)/(?:(?:sendungen|emissions)/)?(?P<id>.*?)/(?P<name>.*?)(\?.*)?'
65
66     @classmethod
67     def _extract_url_info(cls, url):
68         mobj = re.match(cls._VALID_URL, url)
69         lang = mobj.group('lang')
70         # This is not a real id, it can be for example AJT for the news
71         # http://www.arte.tv/guide/fr/emissions/AJT/arte-journal
72         video_id = mobj.group('id')
73         return video_id, lang
74
75     def _real_extract(self, url):
76         video_id, lang = self._extract_url_info(url)
77         webpage = self._download_webpage(url, video_id)
78         return self._extract_from_webpage(webpage, video_id, lang)
79
80     def _extract_from_webpage(self, webpage, video_id, lang):
81         json_url = self._html_search_regex(
82             [r'arte_vp_url=["\'](.*?)["\']', r'data-url=["\']([^"]+)["\']'],
83             webpage, 'json vp url')
84         return self._extract_from_json_url(json_url, video_id, lang)
85
86     def _extract_from_json_url(self, json_url, video_id, lang):
87         info = self._download_json(json_url, video_id)
88         player_info = info['videoJsonPlayer']
89
90         upload_date_str = player_info.get('shootingDate')
91         if not upload_date_str:
92             upload_date_str = player_info.get('VDA', '').split(' ')[0]
93
94         title = player_info['VTI'].strip()
95         subtitle = player_info.get('VSU', '').strip()
96         if subtitle:
97             title += ' - %s' % subtitle
98
99         info_dict = {
100             'id': player_info['VID'],
101             'title': title,
102             'description': player_info.get('VDE'),
103             'upload_date': unified_strdate(upload_date_str),
104             'thumbnail': player_info.get('programImage') or player_info.get('VTU', {}).get('IUR'),
105         }
106
107         all_formats = []
108         for format_id, format_dict in player_info['VSR'].items():
109             fmt = dict(format_dict)
110             fmt['format_id'] = format_id
111             all_formats.append(fmt)
112         # Some formats use the m3u8 protocol
113         all_formats = list(filter(lambda f: f.get('videoFormat') != 'M3U8', all_formats))
114         def _match_lang(f):
115             if f.get('versionCode') is None:
116                 return True
117             # Return true if that format is in the language of the url
118             if lang == 'fr':
119                 l = 'F'
120             elif lang == 'de':
121                 l = 'A'
122             else:
123                 l = lang
124             regexes = [r'VO?%s' % l, r'VO?.-ST%s' % l]
125             return any(re.match(r, f['versionCode']) for r in regexes)
126         # Some formats may not be in the same language as the url
127         # TODO: Might want not to drop videos that does not match requested language
128         # but to process those formats with lower precedence
129         formats = filter(_match_lang, all_formats)
130         formats = list(formats)  # in python3 filter returns an iterator
131         if not formats:
132             # Some videos are only available in the 'Originalversion'
133             # they aren't tagged as being in French or German
134             # Sometimes there are neither videos of requested lang code
135             # nor original version videos available
136             # For such cases we just take all_formats as is
137             formats = all_formats
138             if not formats:
139                 raise ExtractorError('The formats list is empty')
140
141         if re.match(r'[A-Z]Q', formats[0]['quality']) is not None:
142             def sort_key(f):
143                 return ['HQ', 'MQ', 'EQ', 'SQ'].index(f['quality'])
144         else:
145             def sort_key(f):
146                 versionCode = f.get('versionCode')
147                 if versionCode is None:
148                     versionCode = ''
149                 return (
150                     # Sort first by quality
151                     int(f.get('height', -1)),
152                     int(f.get('bitrate', -1)),
153                     # The original version with subtitles has lower relevance
154                     re.match(r'VO-ST(F|A)', versionCode) is None,
155                     # The version with sourds/mal subtitles has also lower relevance
156                     re.match(r'VO?(F|A)-STM\1', versionCode) is None,
157                     # Prefer http downloads over m3u8
158                     0 if f['url'].endswith('m3u8') else 1,
159                 )
160         formats = sorted(formats, key=sort_key)
161         def _format(format_info):
162             info = {
163                 'format_id': format_info['format_id'],
164                 'format_note': '%s, %s' % (format_info.get('versionCode'), format_info.get('versionLibelle')),
165                 'width': int_or_none(format_info.get('width')),
166                 'height': int_or_none(format_info.get('height')),
167                 'tbr': int_or_none(format_info.get('bitrate')),
168             }
169             if format_info['mediaType'] == 'rtmp':
170                 info['url'] = format_info['streamer']
171                 info['play_path'] = 'mp4:' + format_info['url']
172                 info['ext'] = 'flv'
173             else:
174                 info['url'] = format_info['url']
175                 info['ext'] = determine_ext(info['url'])
176             return info
177         info_dict['formats'] = [_format(f) for f in formats]
178
179         return info_dict
180
181
182 # It also uses the arte_vp_url url from the webpage to extract the information
183 class ArteTVCreativeIE(ArteTVPlus7IE):
184     IE_NAME = 'arte.tv:creative'
185     _VALID_URL = r'https?://creative\.arte\.tv/(?P<lang>fr|de)/(?:magazine?/)?(?P<id>[^?#]+)'
186
187     _TESTS = [{
188         'url': 'http://creative.arte.tv/de/magazin/agentur-amateur-corporate-design',
189         'info_dict': {
190             'id': '72176',
191             'ext': 'mp4',
192             'title': 'Folge 2 - Corporate Design',
193             'upload_date': '20131004',
194         },
195     }, {
196         'url': 'http://creative.arte.tv/fr/Monty-Python-Reunion',
197         'info_dict': {
198             'id': '160676',
199             'ext': 'mp4',
200             'title': 'Monty Python live (mostly)',
201             'description': 'Événement ! Quarante-cinq ans après leurs premiers succès, les légendaires Monty Python remontent sur scène.\n',
202             'upload_date': '20140805',
203         }
204     }]
205
206
207 class ArteTVFutureIE(ArteTVPlus7IE):
208     IE_NAME = 'arte.tv:future'
209     _VALID_URL = r'https?://future\.arte\.tv/(?P<lang>fr|de)/(thema|sujet)/.*?#article-anchor-(?P<id>\d+)'
210
211     _TEST = {
212         'url': 'http://future.arte.tv/fr/sujet/info-sciences#article-anchor-7081',
213         'info_dict': {
214             'id': '5201',
215             'ext': 'mp4',
216             'title': 'Les champignons au secours de la planète',
217             'upload_date': '20131101',
218         },
219     }
220
221     def _real_extract(self, url):
222         anchor_id, lang = self._extract_url_info(url)
223         webpage = self._download_webpage(url, anchor_id)
224         row = get_element_by_id(anchor_id, webpage)
225         return self._extract_from_webpage(row, anchor_id, lang)
226
227
228 class ArteTVDDCIE(ArteTVPlus7IE):
229     IE_NAME = 'arte.tv:ddc'
230     _VALID_URL = r'https?://ddc\.arte\.tv/(?P<lang>emission|folge)/(?P<id>.+)'
231
232     def _real_extract(self, url):
233         video_id, lang = self._extract_url_info(url)
234         if lang == 'folge':
235             lang = 'de'
236         elif lang == 'emission':
237             lang = 'fr'
238         webpage = self._download_webpage(url, video_id)
239         scriptElement = get_element_by_attribute('class', 'visu_video_block', webpage)
240         script_url = self._html_search_regex(r'src="(.*?)"', scriptElement, 'script url')
241         javascriptPlayerGenerator = self._download_webpage(script_url, video_id, 'Download javascript player generator')
242         json_url = self._search_regex(r"json_url=(.*)&rendering_place.*", javascriptPlayerGenerator, 'json url')
243         return self._extract_from_json_url(json_url, video_id, lang)
244
245
246 class ArteTVConcertIE(ArteTVPlus7IE):
247     IE_NAME = 'arte.tv:concert'
248     _VALID_URL = r'https?://concert\.arte\.tv/(?P<lang>de|fr)/(?P<id>.+)'
249
250     _TEST = {
251         'url': 'http://concert.arte.tv/de/notwist-im-pariser-konzertclub-divan-du-monde',
252         'md5': '9ea035b7bd69696b67aa2ccaaa218161',
253         'info_dict': {
254             'id': '186',
255             'ext': 'mp4',
256             'title': 'The Notwist im Pariser Konzertclub "Divan du Monde"',
257             'upload_date': '20140128',
258             'description': 'md5:486eb08f991552ade77439fe6d82c305',
259         },
260     }
261
262
263 class ArteTVEmbedIE(ArteTVPlus7IE):
264     IE_NAME = 'arte.tv:embed'
265     _VALID_URL = r'''(?x)
266         http://www\.arte\.tv
267         /playerv2/embed\.php\?json_url=
268         (?P<json_url>
269             http://arte\.tv/papi/tvguide/videos/stream/player/
270             (?P<lang>[^/]+)/(?P<id>[^/]+)[^&]*
271         )
272     '''
273
274     def _real_extract(self, url):
275         mobj = re.match(self._VALID_URL, url)
276         video_id = mobj.group('id')
277         lang = mobj.group('lang')
278         json_url = mobj.group('json_url')
279         return self._extract_from_json_url(json_url, video_id, lang)