Merge pull request #6790 from remitamine/tele13
[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 ..compat import (
8     compat_parse_qs,
9     compat_urllib_parse_urlparse,
10 )
11 from ..utils import (
12     find_xpath_attr,
13     unified_strdate,
14     get_element_by_attribute,
15     int_or_none,
16     qualities,
17 )
18
19 # There are different sources of video in arte.tv, the extraction process
20 # is different for each one. The videos usually expire in 7 days, so we can't
21 # add tests.
22
23
24 class ArteTvIE(InfoExtractor):
25     _VALID_URL = r'http://videos\.arte\.tv/(?P<lang>fr|de)/.*-(?P<id>.*?)\.html'
26     IE_NAME = 'arte.tv'
27
28     def _real_extract(self, url):
29         mobj = re.match(self._VALID_URL, url)
30         lang = mobj.group('lang')
31         video_id = mobj.group('id')
32
33         ref_xml_url = url.replace('/videos/', '/do_delegate/videos/')
34         ref_xml_url = ref_xml_url.replace('.html', ',view,asPlayerXml.xml')
35         ref_xml_doc = self._download_xml(
36             ref_xml_url, video_id, note='Downloading metadata')
37         config_node = find_xpath_attr(ref_xml_doc, './/video', 'lang', lang)
38         config_xml_url = config_node.attrib['ref']
39         config = self._download_xml(
40             config_xml_url, video_id, note='Downloading configuration')
41
42         formats = [{
43             'format_id': q.attrib['quality'],
44             # The playpath starts at 'mp4:', if we don't manually
45             # split the url, rtmpdump will incorrectly parse them
46             'url': q.text.split('mp4:', 1)[0],
47             'play_path': 'mp4:' + q.text.split('mp4:', 1)[1],
48             'ext': 'flv',
49             'quality': 2 if q.attrib['quality'] == 'hd' else 1,
50         } for q in config.findall('./urls/url')]
51         self._sort_formats(formats)
52
53         title = config.find('.//name').text
54         thumbnail = config.find('.//firstThumbnailUrl').text
55         return {
56             'id': video_id,
57             'title': title,
58             'thumbnail': thumbnail,
59             'formats': formats,
60         }
61
62
63 class ArteTVPlus7IE(InfoExtractor):
64     IE_NAME = 'arte.tv:+7'
65     _VALID_URL = r'https?://(?:www\.)?arte\.tv/guide/(?P<lang>fr|de)/(?:(?:sendungen|emissions)/)?(?P<id>.*?)/(?P<name>.*?)(\?.*)?'
66
67     @classmethod
68     def _extract_url_info(cls, url):
69         mobj = re.match(cls._VALID_URL, url)
70         lang = mobj.group('lang')
71         # This is not a real id, it can be for example AJT for the news
72         # http://www.arte.tv/guide/fr/emissions/AJT/arte-journal
73         video_id = mobj.group('id')
74         return video_id, lang
75
76     def _real_extract(self, url):
77         video_id, lang = self._extract_url_info(url)
78         webpage = self._download_webpage(url, video_id)
79         return self._extract_from_webpage(webpage, video_id, lang)
80
81     def _extract_from_webpage(self, webpage, video_id, lang):
82         json_url = self._html_search_regex(
83             [r'arte_vp_url=["\'](.*?)["\']', r'data-url=["\']([^"]+)["\']'],
84             webpage, 'json vp url', default=None)
85         if not json_url:
86             iframe_url = self._html_search_regex(
87                 r'<iframe[^>]+src=(["\'])(?P<url>.+\bjson_url=.+?)\1',
88                 webpage, 'iframe url', group='url')
89             json_url = compat_parse_qs(
90                 compat_urllib_parse_urlparse(iframe_url).query)['json_url'][0]
91         return self._extract_from_json_url(json_url, video_id, lang)
92
93     def _extract_from_json_url(self, json_url, video_id, lang):
94         info = self._download_json(json_url, video_id)
95         player_info = info['videoJsonPlayer']
96
97         upload_date_str = player_info.get('shootingDate')
98         if not upload_date_str:
99             upload_date_str = player_info.get('VDA', '').split(' ')[0]
100
101         title = player_info['VTI'].strip()
102         subtitle = player_info.get('VSU', '').strip()
103         if subtitle:
104             title += ' - %s' % subtitle
105
106         info_dict = {
107             'id': player_info['VID'],
108             'title': title,
109             'description': player_info.get('VDE'),
110             'upload_date': unified_strdate(upload_date_str),
111             'thumbnail': player_info.get('programImage') or player_info.get('VTU', {}).get('IUR'),
112         }
113         qfunc = qualities(['HQ', 'MQ', 'EQ', 'SQ'])
114
115         formats = []
116         for format_id, format_dict in player_info['VSR'].items():
117             f = dict(format_dict)
118             versionCode = f.get('versionCode')
119
120             langcode = {
121                 'fr': 'F',
122                 'de': 'A',
123             }.get(lang, lang)
124             lang_rexs = [r'VO?%s' % langcode, r'VO?.-ST%s' % langcode]
125             lang_pref = (
126                 None if versionCode is None else (
127                     10 if any(re.match(r, versionCode) for r in lang_rexs)
128                     else -10))
129             source_pref = 0
130             if versionCode is not None:
131                 # The original version with subtitles has lower relevance
132                 if re.match(r'VO-ST(F|A)', versionCode):
133                     source_pref -= 10
134                 # The version with sourds/mal subtitles has also lower relevance
135                 elif re.match(r'VO?(F|A)-STM\1', versionCode):
136                     source_pref -= 9
137             format = {
138                 'format_id': format_id,
139                 'preference': -10 if f.get('videoFormat') == 'M3U8' else None,
140                 'language_preference': lang_pref,
141                 'format_note': '%s, %s' % (f.get('versionCode'), f.get('versionLibelle')),
142                 'width': int_or_none(f.get('width')),
143                 'height': int_or_none(f.get('height')),
144                 'tbr': int_or_none(f.get('bitrate')),
145                 'quality': qfunc(f.get('quality')),
146                 'source_preference': source_pref,
147             }
148
149             if f.get('mediaType') == 'rtmp':
150                 format['url'] = f['streamer']
151                 format['play_path'] = 'mp4:' + f['url']
152                 format['ext'] = 'flv'
153             else:
154                 format['url'] = f['url']
155
156             formats.append(format)
157
158         self._check_formats(formats, video_id)
159         self._sort_formats(formats)
160
161         info_dict['formats'] = formats
162         return info_dict
163
164
165 # It also uses the arte_vp_url url from the webpage to extract the information
166 class ArteTVCreativeIE(ArteTVPlus7IE):
167     IE_NAME = 'arte.tv:creative'
168     _VALID_URL = r'https?://creative\.arte\.tv/(?P<lang>fr|de)/(?:magazine?/)?(?P<id>[^?#]+)'
169
170     _TESTS = [{
171         'url': 'http://creative.arte.tv/de/magazin/agentur-amateur-corporate-design',
172         'info_dict': {
173             'id': '72176',
174             'ext': 'mp4',
175             'title': 'Folge 2 - Corporate Design',
176             'upload_date': '20131004',
177         },
178     }, {
179         'url': 'http://creative.arte.tv/fr/Monty-Python-Reunion',
180         'info_dict': {
181             'id': '160676',
182             'ext': 'mp4',
183             'title': 'Monty Python live (mostly)',
184             'description': 'Événement ! Quarante-cinq ans après leurs premiers succès, les légendaires Monty Python remontent sur scène.\n',
185             'upload_date': '20140805',
186         }
187     }]
188
189
190 class ArteTVFutureIE(ArteTVPlus7IE):
191     IE_NAME = 'arte.tv:future'
192     _VALID_URL = r'https?://future\.arte\.tv/(?P<lang>fr|de)/(thema|sujet)/.*?#article-anchor-(?P<id>\d+)'
193
194     _TEST = {
195         'url': 'http://future.arte.tv/fr/sujet/info-sciences#article-anchor-7081',
196         'info_dict': {
197             'id': '5201',
198             'ext': 'mp4',
199             'title': 'Les champignons au secours de la planète',
200             'upload_date': '20131101',
201         },
202     }
203
204     def _real_extract(self, url):
205         anchor_id, lang = self._extract_url_info(url)
206         webpage = self._download_webpage(url, anchor_id)
207         row = self._search_regex(
208             r'(?s)id="%s"[^>]*>.+?(<div[^>]*arte_vp_url[^>]*>)' % anchor_id,
209             webpage, 'row')
210         return self._extract_from_webpage(row, anchor_id, lang)
211
212
213 class ArteTVDDCIE(ArteTVPlus7IE):
214     IE_NAME = 'arte.tv:ddc'
215     _VALID_URL = r'https?://ddc\.arte\.tv/(?P<lang>emission|folge)/(?P<id>.+)'
216
217     def _real_extract(self, url):
218         video_id, lang = self._extract_url_info(url)
219         if lang == 'folge':
220             lang = 'de'
221         elif lang == 'emission':
222             lang = 'fr'
223         webpage = self._download_webpage(url, video_id)
224         scriptElement = get_element_by_attribute('class', 'visu_video_block', webpage)
225         script_url = self._html_search_regex(r'src="(.*?)"', scriptElement, 'script url')
226         javascriptPlayerGenerator = self._download_webpage(script_url, video_id, 'Download javascript player generator')
227         json_url = self._search_regex(r"json_url=(.*)&rendering_place.*", javascriptPlayerGenerator, 'json url')
228         return self._extract_from_json_url(json_url, video_id, lang)
229
230
231 class ArteTVConcertIE(ArteTVPlus7IE):
232     IE_NAME = 'arte.tv:concert'
233     _VALID_URL = r'https?://concert\.arte\.tv/(?P<lang>de|fr)/(?P<id>.+)'
234
235     _TEST = {
236         'url': 'http://concert.arte.tv/de/notwist-im-pariser-konzertclub-divan-du-monde',
237         'md5': '9ea035b7bd69696b67aa2ccaaa218161',
238         'info_dict': {
239             'id': '186',
240             'ext': 'mp4',
241             'title': 'The Notwist im Pariser Konzertclub "Divan du Monde"',
242             'upload_date': '20140128',
243             'description': 'md5:486eb08f991552ade77439fe6d82c305',
244         },
245     }
246
247
248 class ArteTVEmbedIE(ArteTVPlus7IE):
249     IE_NAME = 'arte.tv:embed'
250     _VALID_URL = r'''(?x)
251         http://www\.arte\.tv
252         /playerv2/embed\.php\?json_url=
253         (?P<json_url>
254             http://arte\.tv/papi/tvguide/videos/stream/player/
255             (?P<lang>[^/]+)/(?P<id>[^/]+)[^&]*
256         )
257     '''
258
259     def _real_extract(self, url):
260         mobj = re.match(self._VALID_URL, url)
261         video_id = mobj.group('id')
262         lang = mobj.group('lang')
263         json_url = mobj.group('json_url')
264         return self._extract_from_json_url(json_url, video_id, lang)