]> Raphaël G. Git Repositories - youtubedl/blob - youtube_dl/extractor/ard.py
debian/patches: Refresh patches to apply cleanly.
[youtubedl] / youtube_dl / extractor / ard.py
1 # coding: utf-8
2 from __future__ import unicode_literals
3
4 import re
5
6 from .common import InfoExtractor
7 from .generic import GenericIE
8 from ..utils import (
9 determine_ext,
10 ExtractorError,
11 int_or_none,
12 parse_duration,
13 qualities,
14 str_or_none,
15 try_get,
16 unified_strdate,
17 unified_timestamp,
18 update_url_query,
19 url_or_none,
20 xpath_text,
21 )
22 from ..compat import compat_etree_fromstring
23
24
25 class ARDMediathekIE(InfoExtractor):
26 IE_NAME = 'ARD:mediathek'
27 _VALID_URL = r'^https?://(?:(?:(?:www|classic)\.)?ardmediathek\.de|mediathek\.(?:daserste|rbb-online)\.de|one\.ard\.de)/(?:.*/)(?P<video_id>[0-9]+|[^0-9][^/\?]+)[^/\?]*(?:\?.*)?'
28
29 _TESTS = [{
30 # available till 26.07.2022
31 'url': 'http://www.ardmediathek.de/tv/S%C3%9CDLICHT/Was-ist-die-Kunst-der-Zukunft-liebe-Ann/BR-Fernsehen/Video?bcastId=34633636&documentId=44726822',
32 'info_dict': {
33 'id': '44726822',
34 'ext': 'mp4',
35 'title': 'Was ist die Kunst der Zukunft, liebe Anna McCarthy?',
36 'description': 'md5:4ada28b3e3b5df01647310e41f3a62f5',
37 'duration': 1740,
38 },
39 'params': {
40 # m3u8 download
41 'skip_download': True,
42 }
43 }, {
44 'url': 'https://one.ard.de/tv/Mord-mit-Aussicht/Mord-mit-Aussicht-6-39-T%C3%B6dliche-Nach/ONE/Video?bcastId=46384294&documentId=55586872',
45 'only_matching': True,
46 }, {
47 # audio
48 'url': 'http://www.ardmediathek.de/tv/WDR-H%C3%B6rspiel-Speicher/Tod-eines-Fu%C3%9Fballers/WDR-3/Audio-Podcast?documentId=28488308&bcastId=23074086',
49 'only_matching': True,
50 }, {
51 'url': 'http://mediathek.daserste.de/sendungen_a-z/328454_anne-will/22429276_vertrauen-ist-gut-spionieren-ist-besser-geht',
52 'only_matching': True,
53 }, {
54 # audio
55 'url': 'http://mediathek.rbb-online.de/radio/Hörspiel/Vor-dem-Fest/kulturradio/Audio?documentId=30796318&topRessort=radio&bcastId=9839158',
56 'only_matching': True,
57 }, {
58 'url': 'https://classic.ardmediathek.de/tv/Panda-Gorilla-Co/Panda-Gorilla-Co-Folge-274/Das-Erste/Video?bcastId=16355486&documentId=58234698',
59 'only_matching': True,
60 }]
61
62 @classmethod
63 def suitable(cls, url):
64 return False if ARDBetaMediathekIE.suitable(url) else super(ARDMediathekIE, cls).suitable(url)
65
66 def _extract_media_info(self, media_info_url, webpage, video_id):
67 media_info = self._download_json(
68 media_info_url, video_id, 'Downloading media JSON')
69
70 formats = self._extract_formats(media_info, video_id)
71
72 if not formats:
73 if '"fsk"' in webpage:
74 raise ExtractorError(
75 'This video is only available after 20:00', expected=True)
76 elif media_info.get('_geoblocked'):
77 raise ExtractorError('This video is not available due to geo restriction', expected=True)
78
79 self._sort_formats(formats)
80
81 duration = int_or_none(media_info.get('_duration'))
82 thumbnail = media_info.get('_previewImage')
83 is_live = media_info.get('_isLive') is True
84
85 subtitles = {}
86 subtitle_url = media_info.get('_subtitleUrl')
87 if subtitle_url:
88 subtitles['de'] = [{
89 'ext': 'ttml',
90 'url': subtitle_url,
91 }]
92
93 return {
94 'id': video_id,
95 'duration': duration,
96 'thumbnail': thumbnail,
97 'is_live': is_live,
98 'formats': formats,
99 'subtitles': subtitles,
100 }
101
102 def _extract_formats(self, media_info, video_id):
103 type_ = media_info.get('_type')
104 media_array = media_info.get('_mediaArray', [])
105 formats = []
106 for num, media in enumerate(media_array):
107 for stream in media.get('_mediaStreamArray', []):
108 stream_urls = stream.get('_stream')
109 if not stream_urls:
110 continue
111 if not isinstance(stream_urls, list):
112 stream_urls = [stream_urls]
113 quality = stream.get('_quality')
114 server = stream.get('_server')
115 for stream_url in stream_urls:
116 if not url_or_none(stream_url):
117 continue
118 ext = determine_ext(stream_url)
119 if quality != 'auto' and ext in ('f4m', 'm3u8'):
120 continue
121 if ext == 'f4m':
122 formats.extend(self._extract_f4m_formats(
123 update_url_query(stream_url, {
124 'hdcore': '3.1.1',
125 'plugin': 'aasp-3.1.1.69.124'
126 }),
127 video_id, f4m_id='hds', fatal=False))
128 elif ext == 'm3u8':
129 formats.extend(self._extract_m3u8_formats(
130 stream_url, video_id, 'mp4', m3u8_id='hls', fatal=False))
131 else:
132 if server and server.startswith('rtmp'):
133 f = {
134 'url': server,
135 'play_path': stream_url,
136 'format_id': 'a%s-rtmp-%s' % (num, quality),
137 }
138 else:
139 f = {
140 'url': stream_url,
141 'format_id': 'a%s-%s-%s' % (num, ext, quality)
142 }
143 m = re.search(r'_(?P<width>\d+)x(?P<height>\d+)\.mp4$', stream_url)
144 if m:
145 f.update({
146 'width': int(m.group('width')),
147 'height': int(m.group('height')),
148 })
149 if type_ == 'audio':
150 f['vcodec'] = 'none'
151 formats.append(f)
152 return formats
153
154 def _real_extract(self, url):
155 # determine video id from url
156 m = re.match(self._VALID_URL, url)
157
158 document_id = None
159
160 numid = re.search(r'documentId=([0-9]+)', url)
161 if numid:
162 document_id = video_id = numid.group(1)
163 else:
164 video_id = m.group('video_id')
165
166 webpage = self._download_webpage(url, video_id)
167
168 ERRORS = (
169 ('>Leider liegt eine Störung vor.', 'Video %s is unavailable'),
170 ('>Der gewünschte Beitrag ist nicht mehr verfügbar.<',
171 'Video %s is no longer available'),
172 )
173
174 for pattern, message in ERRORS:
175 if pattern in webpage:
176 raise ExtractorError(message % video_id, expected=True)
177
178 if re.search(r'[\?&]rss($|[=&])', url):
179 doc = compat_etree_fromstring(webpage.encode('utf-8'))
180 if doc.tag == 'rss':
181 return GenericIE()._extract_rss(url, video_id, doc)
182
183 title = self._html_search_regex(
184 [r'<h1(?:\s+class="boxTopHeadline")?>(.*?)</h1>',
185 r'<meta name="dcterms\.title" content="(.*?)"/>',
186 r'<h4 class="headline">(.*?)</h4>',
187 r'<title[^>]*>(.*?)</title>'],
188 webpage, 'title')
189 description = self._html_search_meta(
190 'dcterms.abstract', webpage, 'description', default=None)
191 if description is None:
192 description = self._html_search_meta(
193 'description', webpage, 'meta description', default=None)
194 if description is None:
195 description = self._html_search_regex(
196 r'<p\s+class="teasertext">(.+?)</p>',
197 webpage, 'teaser text', default=None)
198
199 # Thumbnail is sometimes not present.
200 # It is in the mobile version, but that seems to use a different URL
201 # structure altogether.
202 thumbnail = self._og_search_thumbnail(webpage, default=None)
203
204 media_streams = re.findall(r'''(?x)
205 mediaCollection\.addMediaStream\([0-9]+,\s*[0-9]+,\s*"[^"]*",\s*
206 "([^"]+)"''', webpage)
207
208 if media_streams:
209 QUALITIES = qualities(['lo', 'hi', 'hq'])
210 formats = []
211 for furl in set(media_streams):
212 if furl.endswith('.f4m'):
213 fid = 'f4m'
214 else:
215 fid_m = re.match(r'.*\.([^.]+)\.[^.]+$', furl)
216 fid = fid_m.group(1) if fid_m else None
217 formats.append({
218 'quality': QUALITIES(fid),
219 'format_id': fid,
220 'url': furl,
221 })
222 self._sort_formats(formats)
223 info = {
224 'formats': formats,
225 }
226 else: # request JSON file
227 if not document_id:
228 video_id = self._search_regex(
229 r'/play/(?:config|media)/(\d+)', webpage, 'media id')
230 info = self._extract_media_info(
231 'http://www.ardmediathek.de/play/media/%s' % video_id,
232 webpage, video_id)
233
234 info.update({
235 'id': video_id,
236 'title': self._live_title(title) if info.get('is_live') else title,
237 'description': description,
238 'thumbnail': thumbnail,
239 })
240
241 return info
242
243
244 class ARDIE(InfoExtractor):
245 _VALID_URL = r'(?P<mainurl>https?://(www\.)?daserste\.de/[^?#]+/videos/(?P<display_id>[^/?#]+)-(?P<id>[0-9]+))\.html'
246 _TESTS = [{
247 # available till 14.02.2019
248 'url': 'http://www.daserste.de/information/talk/maischberger/videos/das-groko-drama-zerlegen-sich-die-volksparteien-video-102.html',
249 'md5': '8e4ec85f31be7c7fc08a26cdbc5a1f49',
250 'info_dict': {
251 'display_id': 'das-groko-drama-zerlegen-sich-die-volksparteien-video',
252 'id': '102',
253 'ext': 'mp4',
254 'duration': 4435.0,
255 'title': 'Das GroKo-Drama: Zerlegen sich die Volksparteien?',
256 'upload_date': '20180214',
257 'thumbnail': r're:^https?://.*\.jpg$',
258 },
259 }, {
260 'url': 'http://www.daserste.de/information/reportage-dokumentation/dokus/videos/die-story-im-ersten-mission-unter-falscher-flagge-100.html',
261 'only_matching': True,
262 }]
263
264 def _real_extract(self, url):
265 mobj = re.match(self._VALID_URL, url)
266 display_id = mobj.group('display_id')
267
268 player_url = mobj.group('mainurl') + '~playerXml.xml'
269 doc = self._download_xml(player_url, display_id)
270 video_node = doc.find('./video')
271 upload_date = unified_strdate(xpath_text(
272 video_node, './broadcastDate'))
273 thumbnail = xpath_text(video_node, './/teaserImage//variant/url')
274
275 formats = []
276 for a in video_node.findall('.//asset'):
277 f = {
278 'format_id': a.attrib['type'],
279 'width': int_or_none(a.find('./frameWidth').text),
280 'height': int_or_none(a.find('./frameHeight').text),
281 'vbr': int_or_none(a.find('./bitrateVideo').text),
282 'abr': int_or_none(a.find('./bitrateAudio').text),
283 'vcodec': a.find('./codecVideo').text,
284 'tbr': int_or_none(a.find('./totalBitrate').text),
285 }
286 if a.find('./serverPrefix').text:
287 f['url'] = a.find('./serverPrefix').text
288 f['playpath'] = a.find('./fileName').text
289 else:
290 f['url'] = a.find('./fileName').text
291 formats.append(f)
292 self._sort_formats(formats)
293
294 return {
295 'id': mobj.group('id'),
296 'formats': formats,
297 'display_id': display_id,
298 'title': video_node.find('./title').text,
299 'duration': parse_duration(video_node.find('./duration').text),
300 'upload_date': upload_date,
301 'thumbnail': thumbnail,
302 }
303
304
305 class ARDBetaMediathekIE(InfoExtractor):
306 _VALID_URL = r'https://(?:beta|www)\.ardmediathek\.de/[^/]+/(?:player|live)/(?P<video_id>[a-zA-Z0-9]+)(?:/(?P<display_id>[^/?#]+))?'
307 _TESTS = [{
308 'url': 'https://beta.ardmediathek.de/ard/player/Y3JpZDovL2Rhc2Vyc3RlLmRlL3RhdG9ydC9mYmM4NGM1NC0xNzU4LTRmZGYtYWFhZS0wYzcyZTIxNGEyMDE/die-robuste-roswita',
309 'md5': '2d02d996156ea3c397cfc5036b5d7f8f',
310 'info_dict': {
311 'display_id': 'die-robuste-roswita',
312 'id': 'Y3JpZDovL2Rhc2Vyc3RlLmRlL3RhdG9ydC9mYmM4NGM1NC0xNzU4LTRmZGYtYWFhZS0wYzcyZTIxNGEyMDE',
313 'title': 'Tatort: Die robuste Roswita',
314 'description': r're:^Der Mord.*trüber ist als die Ilm.',
315 'duration': 5316,
316 'thumbnail': 'https://img.ardmediathek.de/standard/00/55/43/59/34/-1774185891/16x9/960?mandant=ard',
317 'upload_date': '20180826',
318 'ext': 'mp4',
319 },
320 }, {
321 'url': 'https://www.ardmediathek.de/ard/player/Y3JpZDovL3N3ci5kZS9hZXgvbzEwNzE5MTU/',
322 'only_matching': True,
323 }, {
324 'url': 'https://www.ardmediathek.de/swr/live/Y3JpZDovL3N3ci5kZS8xMzQ4MTA0Mg',
325 'only_matching': True,
326 }]
327
328 def _real_extract(self, url):
329 mobj = re.match(self._VALID_URL, url)
330 video_id = mobj.group('video_id')
331 display_id = mobj.group('display_id') or video_id
332
333 webpage = self._download_webpage(url, display_id)
334 data_json = self._search_regex(r'window\.__APOLLO_STATE__\s*=\s*(\{.*);\n', webpage, 'json')
335 data = self._parse_json(data_json, display_id)
336
337 res = {
338 'id': video_id,
339 'display_id': display_id,
340 }
341 formats = []
342 subtitles = {}
343 geoblocked = False
344 for widget in data.values():
345 if widget.get('_geoblocked') is True:
346 geoblocked = True
347 if '_duration' in widget:
348 res['duration'] = int_or_none(widget['_duration'])
349 if 'clipTitle' in widget:
350 res['title'] = widget['clipTitle']
351 if '_previewImage' in widget:
352 res['thumbnail'] = widget['_previewImage']
353 if 'broadcastedOn' in widget:
354 res['timestamp'] = unified_timestamp(widget['broadcastedOn'])
355 if 'synopsis' in widget:
356 res['description'] = widget['synopsis']
357 subtitle_url = url_or_none(widget.get('_subtitleUrl'))
358 if subtitle_url:
359 subtitles.setdefault('de', []).append({
360 'ext': 'ttml',
361 'url': subtitle_url,
362 })
363 if '_quality' in widget:
364 format_url = url_or_none(try_get(
365 widget, lambda x: x['_stream']['json'][0]))
366 if not format_url:
367 continue
368 ext = determine_ext(format_url)
369 if ext == 'f4m':
370 formats.extend(self._extract_f4m_formats(
371 format_url + '?hdcore=3.11.0',
372 video_id, f4m_id='hds', fatal=False))
373 elif ext == 'm3u8':
374 formats.extend(self._extract_m3u8_formats(
375 format_url, video_id, 'mp4', m3u8_id='hls',
376 fatal=False))
377 else:
378 # HTTP formats are not available when geoblocked is True,
379 # other formats are fine though
380 if geoblocked:
381 continue
382 quality = str_or_none(widget.get('_quality'))
383 formats.append({
384 'format_id': ('http-' + quality) if quality else 'http',
385 'url': format_url,
386 'preference': 10, # Plain HTTP, that's nice
387 })
388
389 if not formats and geoblocked:
390 self.raise_geo_restricted(
391 msg='This video is not available due to geoblocking',
392 countries=['DE'])
393
394 self._sort_formats(formats)
395 res.update({
396 'subtitles': subtitles,
397 'formats': formats,
398 })
399
400 return res