]> jfr.im git - yt-dlp.git/blob - yt_dlp/extractor/ard.py
[extractor] Deprecate `_sort_formats`
[yt-dlp.git] / yt_dlp / extractor / ard.py
1 import json
2 import re
3
4 from .common import InfoExtractor
5 from .generic import GenericIE
6 from ..utils import (
7 determine_ext,
8 ExtractorError,
9 int_or_none,
10 parse_duration,
11 qualities,
12 str_or_none,
13 try_get,
14 unified_strdate,
15 unified_timestamp,
16 update_url_query,
17 url_or_none,
18 xpath_text,
19 )
20 from ..compat import compat_etree_fromstring
21
22
23 class ARDMediathekBaseIE(InfoExtractor):
24 _GEO_COUNTRIES = ['DE']
25
26 def _extract_media_info(self, media_info_url, webpage, video_id):
27 media_info = self._download_json(
28 media_info_url, video_id, 'Downloading media JSON')
29 return self._parse_media_info(media_info, video_id, '"fsk"' in webpage)
30
31 def _parse_media_info(self, media_info, video_id, fsk):
32 formats = self._extract_formats(media_info, video_id)
33
34 if not formats:
35 if fsk:
36 self.raise_no_formats(
37 'This video is only available after 20:00', expected=True)
38 elif media_info.get('_geoblocked'):
39 self.raise_geo_restricted(
40 'This video is not available due to geoblocking',
41 countries=self._GEO_COUNTRIES, metadata_available=True)
42
43 subtitles = {}
44 subtitle_url = media_info.get('_subtitleUrl')
45 if subtitle_url:
46 subtitles['de'] = [{
47 'ext': 'ttml',
48 'url': subtitle_url,
49 }]
50
51 return {
52 'id': video_id,
53 'duration': int_or_none(media_info.get('_duration')),
54 'thumbnail': media_info.get('_previewImage'),
55 'is_live': media_info.get('_isLive') is True,
56 'formats': formats,
57 'subtitles': subtitles,
58 }
59
60 def _ARD_extract_episode_info(self, title):
61 """Try to extract season/episode data from the title."""
62 res = {}
63 if not title:
64 return res
65
66 for pattern in [
67 # Pattern for title like "Homo sapiens (S06/E07) - Originalversion"
68 # from: https://www.ardmediathek.de/one/sendung/doctor-who/Y3JpZDovL3dkci5kZS9vbmUvZG9jdG9yIHdobw
69 r'.*(?P<ep_info> \(S(?P<season_number>\d+)/E(?P<episode_number>\d+)\)).*',
70 # E.g.: title="Fritjof aus Norwegen (2) (AD)"
71 # from: https://www.ardmediathek.de/ard/sammlung/der-krieg-und-ich/68cMkqJdllm639Skj4c7sS/
72 r'.*(?P<ep_info> \((?:Folge |Teil )?(?P<episode_number>\d+)(?:/\d+)?\)).*',
73 r'.*(?P<ep_info>Folge (?P<episode_number>\d+)(?:\:| -|) )\"(?P<episode>.+)\".*',
74 # E.g.: title="Folge 25/42: Symmetrie"
75 # from: https://www.ardmediathek.de/ard/video/grips-mathe/folge-25-42-symmetrie/ard-alpha/Y3JpZDovL2JyLmRlL3ZpZGVvLzMyYzI0ZjczLWQ1N2MtNDAxNC05ZmZhLTFjYzRkZDA5NDU5OQ/
76 # E.g.: title="Folge 1063 - Vertrauen"
77 # from: https://www.ardmediathek.de/ard/sendung/die-fallers/Y3JpZDovL3N3ci5kZS8yMzAyMDQ4/
78 r'.*(?P<ep_info>Folge (?P<episode_number>\d+)(?:/\d+)?(?:\:| -|) ).*',
79 ]:
80 m = re.match(pattern, title)
81 if m:
82 groupdict = m.groupdict()
83 res['season_number'] = int_or_none(groupdict.get('season_number'))
84 res['episode_number'] = int_or_none(groupdict.get('episode_number'))
85 res['episode'] = str_or_none(groupdict.get('episode'))
86 # Build the episode title by removing numeric episode information:
87 if groupdict.get('ep_info') and not res['episode']:
88 res['episode'] = str_or_none(
89 title.replace(groupdict.get('ep_info'), ''))
90 if res['episode']:
91 res['episode'] = res['episode'].strip()
92 break
93
94 # As a fallback use the whole title as the episode name:
95 if not res.get('episode'):
96 res['episode'] = title.strip()
97 return res
98
99 def _extract_formats(self, media_info, video_id):
100 type_ = media_info.get('_type')
101 media_array = media_info.get('_mediaArray', [])
102 formats = []
103 for num, media in enumerate(media_array):
104 for stream in media.get('_mediaStreamArray', []):
105 stream_urls = stream.get('_stream')
106 if not stream_urls:
107 continue
108 if not isinstance(stream_urls, list):
109 stream_urls = [stream_urls]
110 quality = stream.get('_quality')
111 server = stream.get('_server')
112 for stream_url in stream_urls:
113 if not url_or_none(stream_url):
114 continue
115 ext = determine_ext(stream_url)
116 if quality != 'auto' and ext in ('f4m', 'm3u8'):
117 continue
118 if ext == 'f4m':
119 formats.extend(self._extract_f4m_formats(
120 update_url_query(stream_url, {
121 'hdcore': '3.1.1',
122 'plugin': 'aasp-3.1.1.69.124'
123 }), video_id, f4m_id='hds', fatal=False))
124 elif ext == 'm3u8':
125 formats.extend(self._extract_m3u8_formats(
126 stream_url, video_id, 'mp4', 'm3u8_native',
127 m3u8_id='hls', fatal=False))
128 else:
129 if server and server.startswith('rtmp'):
130 f = {
131 'url': server,
132 'play_path': stream_url,
133 'format_id': 'a%s-rtmp-%s' % (num, quality),
134 }
135 else:
136 f = {
137 'url': stream_url,
138 'format_id': 'a%s-%s-%s' % (num, ext, quality)
139 }
140 m = re.search(
141 r'_(?P<width>\d+)x(?P<height>\d+)\.mp4$',
142 stream_url)
143 if m:
144 f.update({
145 'width': int(m.group('width')),
146 'height': int(m.group('height')),
147 })
148 if type_ == 'audio':
149 f['vcodec'] = 'none'
150 formats.append(f)
151 return formats
152
153
154 class ARDMediathekIE(ARDMediathekBaseIE):
155 IE_NAME = 'ARD:mediathek'
156 _VALID_URL = r'^https?://(?:(?:(?:www|classic)\.)?ardmediathek\.de|mediathek\.(?:daserste|rbb-online)\.de|one\.ard\.de)/(?:.*/)(?P<video_id>[0-9]+|[^0-9][^/\?]+)[^/\?]*(?:\?.*)?'
157
158 _TESTS = [{
159 # available till 26.07.2022
160 'url': 'http://www.ardmediathek.de/tv/S%C3%9CDLICHT/Was-ist-die-Kunst-der-Zukunft-liebe-Ann/BR-Fernsehen/Video?bcastId=34633636&documentId=44726822',
161 'info_dict': {
162 'id': '44726822',
163 'ext': 'mp4',
164 'title': 'Was ist die Kunst der Zukunft, liebe Anna McCarthy?',
165 'description': 'md5:4ada28b3e3b5df01647310e41f3a62f5',
166 'duration': 1740,
167 },
168 'params': {
169 # m3u8 download
170 'skip_download': True,
171 }
172 }, {
173 'url': 'https://one.ard.de/tv/Mord-mit-Aussicht/Mord-mit-Aussicht-6-39-T%C3%B6dliche-Nach/ONE/Video?bcastId=46384294&documentId=55586872',
174 'only_matching': True,
175 }, {
176 # audio
177 'url': 'http://www.ardmediathek.de/tv/WDR-H%C3%B6rspiel-Speicher/Tod-eines-Fu%C3%9Fballers/WDR-3/Audio-Podcast?documentId=28488308&bcastId=23074086',
178 'only_matching': True,
179 }, {
180 'url': 'http://mediathek.daserste.de/sendungen_a-z/328454_anne-will/22429276_vertrauen-ist-gut-spionieren-ist-besser-geht',
181 'only_matching': True,
182 }, {
183 # audio
184 'url': 'http://mediathek.rbb-online.de/radio/Hörspiel/Vor-dem-Fest/kulturradio/Audio?documentId=30796318&topRessort=radio&bcastId=9839158',
185 'only_matching': True,
186 }, {
187 'url': 'https://classic.ardmediathek.de/tv/Panda-Gorilla-Co/Panda-Gorilla-Co-Folge-274/Das-Erste/Video?bcastId=16355486&documentId=58234698',
188 'only_matching': True,
189 }]
190
191 @classmethod
192 def suitable(cls, url):
193 return False if ARDBetaMediathekIE.suitable(url) else super(ARDMediathekIE, cls).suitable(url)
194
195 def _real_extract(self, url):
196 # determine video id from url
197 m = self._match_valid_url(url)
198
199 document_id = None
200
201 numid = re.search(r'documentId=([0-9]+)', url)
202 if numid:
203 document_id = video_id = numid.group(1)
204 else:
205 video_id = m.group('video_id')
206
207 webpage = self._download_webpage(url, video_id)
208
209 ERRORS = (
210 ('>Leider liegt eine Störung vor.', 'Video %s is unavailable'),
211 ('>Der gewünschte Beitrag ist nicht mehr verfügbar.<',
212 'Video %s is no longer available'),
213 )
214
215 for pattern, message in ERRORS:
216 if pattern in webpage:
217 raise ExtractorError(message % video_id, expected=True)
218
219 if re.search(r'[\?&]rss($|[=&])', url):
220 doc = compat_etree_fromstring(webpage.encode('utf-8'))
221 if doc.tag == 'rss':
222 return GenericIE()._extract_rss(url, video_id, doc)
223
224 title = self._og_search_title(webpage, default=None) or self._html_search_regex(
225 [r'<h1(?:\s+class="boxTopHeadline")?>(.*?)</h1>',
226 r'<meta name="dcterms\.title" content="(.*?)"/>',
227 r'<h4 class="headline">(.*?)</h4>',
228 r'<title[^>]*>(.*?)</title>'],
229 webpage, 'title')
230 description = self._og_search_description(webpage, default=None) or self._html_search_meta(
231 'dcterms.abstract', webpage, 'description', default=None)
232 if description is None:
233 description = self._html_search_meta(
234 'description', webpage, 'meta description', default=None)
235 if description is None:
236 description = self._html_search_regex(
237 r'<p\s+class="teasertext">(.+?)</p>',
238 webpage, 'teaser text', default=None)
239
240 # Thumbnail is sometimes not present.
241 # It is in the mobile version, but that seems to use a different URL
242 # structure altogether.
243 thumbnail = self._og_search_thumbnail(webpage, default=None)
244
245 media_streams = re.findall(r'''(?x)
246 mediaCollection\.addMediaStream\([0-9]+,\s*[0-9]+,\s*"[^"]*",\s*
247 "([^"]+)"''', webpage)
248
249 if media_streams:
250 QUALITIES = qualities(['lo', 'hi', 'hq'])
251 formats = []
252 for furl in set(media_streams):
253 if furl.endswith('.f4m'):
254 fid = 'f4m'
255 else:
256 fid_m = re.match(r'.*\.([^.]+)\.[^.]+$', furl)
257 fid = fid_m.group(1) if fid_m else None
258 formats.append({
259 'quality': QUALITIES(fid),
260 'format_id': fid,
261 'url': furl,
262 })
263 info = {
264 'formats': formats,
265 }
266 else: # request JSON file
267 if not document_id:
268 video_id = self._search_regex(
269 (r'/play/(?:config|media|sola)/(\d+)', r'contentId["\']\s*:\s*(\d+)'),
270 webpage, 'media id', default=None)
271 info = self._extract_media_info(
272 'http://www.ardmediathek.de/play/media/%s' % video_id,
273 webpage, video_id)
274
275 info.update({
276 'id': video_id,
277 'title': title,
278 'description': description,
279 'thumbnail': thumbnail,
280 })
281 info.update(self._ARD_extract_episode_info(info['title']))
282
283 return info
284
285
286 class ARDIE(InfoExtractor):
287 _VALID_URL = r'(?P<mainurl>https?://(?:www\.)?daserste\.de/(?:[^/?#&]+/)+(?P<id>[^/?#&]+))\.html'
288 _TESTS = [{
289 # available till 7.01.2022
290 'url': 'https://www.daserste.de/information/talk/maischberger/videos/maischberger-die-woche-video100.html',
291 'md5': '867d8aa39eeaf6d76407c5ad1bb0d4c1',
292 'info_dict': {
293 'id': 'maischberger-die-woche-video100',
294 'display_id': 'maischberger-die-woche-video100',
295 'ext': 'mp4',
296 'duration': 3687.0,
297 'title': 'maischberger. die woche vom 7. Januar 2021',
298 'upload_date': '20210107',
299 'thumbnail': r're:^https?://.*\.jpg$',
300 },
301 }, {
302 'url': 'https://www.daserste.de/information/politik-weltgeschehen/morgenmagazin/videosextern/dominik-kahun-aus-der-nhl-direkt-zur-weltmeisterschaft-100.html',
303 'only_matching': True,
304 }, {
305 'url': 'https://www.daserste.de/information/nachrichten-wetter/tagesthemen/videosextern/tagesthemen-17736.html',
306 'only_matching': True,
307 }, {
308 'url': 'https://www.daserste.de/unterhaltung/serie/in-aller-freundschaft-die-jungen-aerzte/videos/diversity-tag-sanam-afrashteh100.html',
309 'only_matching': True,
310 }, {
311 'url': 'http://www.daserste.de/information/reportage-dokumentation/dokus/videos/die-story-im-ersten-mission-unter-falscher-flagge-100.html',
312 'only_matching': True,
313 }, {
314 'url': 'https://www.daserste.de/unterhaltung/serie/in-aller-freundschaft-die-jungen-aerzte/Drehpause-100.html',
315 'only_matching': True,
316 }, {
317 'url': 'https://www.daserste.de/unterhaltung/film/filmmittwoch-im-ersten/videos/making-ofwendezeit-video-100.html',
318 'only_matching': True,
319 }]
320
321 def _real_extract(self, url):
322 mobj = self._match_valid_url(url)
323 display_id = mobj.group('id')
324
325 player_url = mobj.group('mainurl') + '~playerXml.xml'
326 doc = self._download_xml(player_url, display_id)
327 video_node = doc.find('./video')
328 upload_date = unified_strdate(xpath_text(
329 video_node, './broadcastDate'))
330 thumbnail = xpath_text(video_node, './/teaserImage//variant/url')
331
332 formats = []
333 for a in video_node.findall('.//asset'):
334 file_name = xpath_text(a, './fileName', default=None)
335 if not file_name:
336 continue
337 format_type = a.attrib.get('type')
338 format_url = url_or_none(file_name)
339 if format_url:
340 ext = determine_ext(file_name)
341 if ext == 'm3u8':
342 formats.extend(self._extract_m3u8_formats(
343 format_url, display_id, 'mp4', entry_protocol='m3u8_native',
344 m3u8_id=format_type or 'hls', fatal=False))
345 continue
346 elif ext == 'f4m':
347 formats.extend(self._extract_f4m_formats(
348 update_url_query(format_url, {'hdcore': '3.7.0'}),
349 display_id, f4m_id=format_type or 'hds', fatal=False))
350 continue
351 f = {
352 'format_id': format_type,
353 'width': int_or_none(xpath_text(a, './frameWidth')),
354 'height': int_or_none(xpath_text(a, './frameHeight')),
355 'vbr': int_or_none(xpath_text(a, './bitrateVideo')),
356 'abr': int_or_none(xpath_text(a, './bitrateAudio')),
357 'vcodec': xpath_text(a, './codecVideo'),
358 'tbr': int_or_none(xpath_text(a, './totalBitrate')),
359 }
360 server_prefix = xpath_text(a, './serverPrefix', default=None)
361 if server_prefix:
362 f.update({
363 'url': server_prefix,
364 'playpath': file_name,
365 })
366 else:
367 if not format_url:
368 continue
369 f['url'] = format_url
370 formats.append(f)
371
372 _SUB_FORMATS = (
373 ('./dataTimedText', 'ttml'),
374 ('./dataTimedTextNoOffset', 'ttml'),
375 ('./dataTimedTextVtt', 'vtt'),
376 )
377
378 subtitles = {}
379 for subsel, subext in _SUB_FORMATS:
380 for node in video_node.findall(subsel):
381 subtitles.setdefault('de', []).append({
382 'url': node.attrib['url'],
383 'ext': subext,
384 })
385
386 return {
387 'id': xpath_text(video_node, './videoId', default=display_id),
388 'formats': formats,
389 'subtitles': subtitles,
390 'display_id': display_id,
391 'title': video_node.find('./title').text,
392 'duration': parse_duration(video_node.find('./duration').text),
393 'upload_date': upload_date,
394 'thumbnail': thumbnail,
395 }
396
397
398 class ARDBetaMediathekIE(ARDMediathekBaseIE):
399 _VALID_URL = r'''(?x)https://
400 (?:(?:beta|www)\.)?ardmediathek\.de/
401 (?:(?P<client>[^/]+)/)?
402 (?:player|live|video|(?P<playlist>sendung|sammlung))/
403 (?:(?P<display_id>(?(playlist)[^?#]+?|[^?#]+))/)?
404 (?P<id>(?(playlist)|Y3JpZDovL)[a-zA-Z0-9]+)
405 (?(playlist)/(?P<season>\d+)?/?(?:[?#]|$))'''
406
407 _TESTS = [{
408 'url': 'https://www.ardmediathek.de/mdr/video/die-robuste-roswita/Y3JpZDovL21kci5kZS9iZWl0cmFnL2Ntcy84MWMxN2MzZC0wMjkxLTRmMzUtODk4ZS0wYzhlOWQxODE2NGI/',
409 'md5': 'a1dc75a39c61601b980648f7c9f9f71d',
410 'info_dict': {
411 'display_id': 'die-robuste-roswita',
412 'id': '78566716',
413 'title': 'Die robuste Roswita',
414 'description': r're:^Der Mord.*totgeglaubte Ehefrau Roswita',
415 'duration': 5316,
416 'thumbnail': 'https://img.ardmediathek.de/standard/00/78/56/67/84/575672121/16x9/960?mandant=ard',
417 'timestamp': 1596658200,
418 'upload_date': '20200805',
419 'ext': 'mp4',
420 },
421 'skip': 'Error',
422 }, {
423 'url': 'https://www.ardmediathek.de/video/tagesschau-oder-tagesschau-20-00-uhr/das-erste/Y3JpZDovL2Rhc2Vyc3RlLmRlL3RhZ2Vzc2NoYXUvZmM4ZDUxMjgtOTE0ZC00Y2MzLTgzNzAtNDZkNGNiZWJkOTll',
424 'md5': 'f1837e563323b8a642a8ddeff0131f51',
425 'info_dict': {
426 'id': '10049223',
427 'ext': 'mp4',
428 'title': 'tagesschau, 20:00 Uhr',
429 'timestamp': 1636398000,
430 'description': 'md5:39578c7b96c9fe50afdf5674ad985e6b',
431 'upload_date': '20211108',
432 },
433 }, {
434 'url': 'https://www.ardmediathek.de/sendung/beforeigners/beforeigners/staffel-1/Y3JpZDovL2Rhc2Vyc3RlLmRlL2JlZm9yZWlnbmVycw/1',
435 'playlist_count': 6,
436 'info_dict': {
437 'id': 'Y3JpZDovL2Rhc2Vyc3RlLmRlL2JlZm9yZWlnbmVycw',
438 'title': 'beforeigners/beforeigners/staffel-1',
439 },
440 }, {
441 'url': 'https://beta.ardmediathek.de/ard/video/Y3JpZDovL2Rhc2Vyc3RlLmRlL3RhdG9ydC9mYmM4NGM1NC0xNzU4LTRmZGYtYWFhZS0wYzcyZTIxNGEyMDE',
442 'only_matching': True,
443 }, {
444 'url': 'https://ardmediathek.de/ard/video/saartalk/saartalk-gesellschaftsgift-haltung-gegen-hass/sr-fernsehen/Y3JpZDovL3NyLW9ubGluZS5kZS9TVF84MTY4MA/',
445 'only_matching': True,
446 }, {
447 'url': 'https://www.ardmediathek.de/ard/video/trailer/private-eyes-s01-e01/one/Y3JpZDovL3dkci5kZS9CZWl0cmFnLTE1MTgwYzczLWNiMTEtNGNkMS1iMjUyLTg5MGYzOWQxZmQ1YQ/',
448 'only_matching': True,
449 }, {
450 'url': 'https://www.ardmediathek.de/ard/player/Y3JpZDovL3N3ci5kZS9hZXgvbzEwNzE5MTU/',
451 'only_matching': True,
452 }, {
453 'url': 'https://www.ardmediathek.de/swr/live/Y3JpZDovL3N3ci5kZS8xMzQ4MTA0Mg',
454 'only_matching': True,
455 }, {
456 # playlist of type 'sendung'
457 'url': 'https://www.ardmediathek.de/ard/sendung/doctor-who/Y3JpZDovL3dkci5kZS9vbmUvZG9jdG9yIHdobw/',
458 'only_matching': True,
459 }, {
460 # playlist of type 'sammlung'
461 'url': 'https://www.ardmediathek.de/ard/sammlung/team-muenster/5JpTzLSbWUAK8184IOvEir/',
462 'only_matching': True,
463 }, {
464 'url': 'https://www.ardmediathek.de/video/coronavirus-update-ndr-info/astrazeneca-kurz-lockdown-und-pims-syndrom-81/ndr/Y3JpZDovL25kci5kZS84NzE0M2FjNi0wMWEwLTQ5ODEtOTE5NS1mOGZhNzdhOTFmOTI/',
465 'only_matching': True,
466 }, {
467 'url': 'https://www.ardmediathek.de/ard/player/Y3JpZDovL3dkci5kZS9CZWl0cmFnLWQ2NDJjYWEzLTMwZWYtNGI4NS1iMTI2LTU1N2UxYTcxOGIzOQ/tatort-duo-koeln-leipzig-ihr-kinderlein-kommet',
468 'only_matching': True,
469 }]
470
471 def _ARD_load_playlist_snipped(self, playlist_id, display_id, client, mode, pageNumber):
472 """ Query the ARD server for playlist information
473 and returns the data in "raw" format """
474 if mode == 'sendung':
475 graphQL = json.dumps({
476 'query': '''{
477 showPage(
478 client: "%s"
479 showId: "%s"
480 pageNumber: %d
481 ) {
482 pagination {
483 pageSize
484 totalElements
485 }
486 teasers { # Array
487 mediumTitle
488 links { target { id href title } }
489 type
490 }
491 }}''' % (client, playlist_id, pageNumber),
492 }).encode()
493 else: # mode == 'sammlung'
494 graphQL = json.dumps({
495 'query': '''{
496 morePage(
497 client: "%s"
498 compilationId: "%s"
499 pageNumber: %d
500 ) {
501 widget {
502 pagination {
503 pageSize
504 totalElements
505 }
506 teasers { # Array
507 mediumTitle
508 links { target { id href title } }
509 type
510 }
511 }
512 }}''' % (client, playlist_id, pageNumber),
513 }).encode()
514 # Ressources for ARD graphQL debugging:
515 # https://api-test.ardmediathek.de/public-gateway
516 show_page = self._download_json(
517 'https://api.ardmediathek.de/public-gateway',
518 '[Playlist] %s' % display_id,
519 data=graphQL,
520 headers={'Content-Type': 'application/json'})['data']
521 # align the structure of the returned data:
522 if mode == 'sendung':
523 show_page = show_page['showPage']
524 else: # mode == 'sammlung'
525 show_page = show_page['morePage']['widget']
526 return show_page
527
528 def _ARD_extract_playlist(self, url, playlist_id, display_id, client, mode):
529 """ Collects all playlist entries and returns them as info dict.
530 Supports playlists of mode 'sendung' and 'sammlung', and also nested
531 playlists. """
532 entries = []
533 pageNumber = 0
534 while True: # iterate by pageNumber
535 show_page = self._ARD_load_playlist_snipped(
536 playlist_id, display_id, client, mode, pageNumber)
537 for teaser in show_page['teasers']: # process playlist items
538 if '/compilation/' in teaser['links']['target']['href']:
539 # alternativ cond.: teaser['type'] == "compilation"
540 # => This is an nested compilation, e.g. like:
541 # https://www.ardmediathek.de/ard/sammlung/die-kirche-bleibt-im-dorf/5eOHzt8XB2sqeFXbIoJlg2/
542 link_mode = 'sammlung'
543 else:
544 link_mode = 'video'
545
546 item_url = 'https://www.ardmediathek.de/%s/%s/%s/%s/%s' % (
547 client, link_mode, display_id,
548 # perform HTLM quoting of episode title similar to ARD:
549 re.sub('^-|-$', '', # remove '-' from begin/end
550 re.sub('[^a-zA-Z0-9]+', '-', # replace special chars by -
551 teaser['links']['target']['title'].lower()
552 .replace('ä', 'ae').replace('ö', 'oe')
553 .replace('ü', 'ue').replace('ß', 'ss'))),
554 teaser['links']['target']['id'])
555 entries.append(self.url_result(
556 item_url,
557 ie=ARDBetaMediathekIE.ie_key()))
558
559 if (show_page['pagination']['pageSize'] * (pageNumber + 1)
560 >= show_page['pagination']['totalElements']):
561 # we've processed enough pages to get all playlist entries
562 break
563 pageNumber = pageNumber + 1
564
565 return self.playlist_result(entries, playlist_id, playlist_title=display_id)
566
567 def _real_extract(self, url):
568 video_id, display_id, playlist_type, client, season_number = self._match_valid_url(url).group(
569 'id', 'display_id', 'playlist', 'client', 'season')
570 display_id, client = display_id or video_id, client or 'ard'
571
572 if playlist_type:
573 # TODO: Extract only specified season
574 return self._ARD_extract_playlist(url, video_id, display_id, client, playlist_type)
575
576 player_page = self._download_json(
577 'https://api.ardmediathek.de/public-gateway',
578 display_id, data=json.dumps({
579 'query': '''{
580 playerPage(client:"%s", clipId: "%s") {
581 blockedByFsk
582 broadcastedOn
583 maturityContentRating
584 mediaCollection {
585 _duration
586 _geoblocked
587 _isLive
588 _mediaArray {
589 _mediaStreamArray {
590 _quality
591 _server
592 _stream
593 }
594 }
595 _previewImage
596 _subtitleUrl
597 _type
598 }
599 show {
600 title
601 }
602 synopsis
603 title
604 tracking {
605 atiCustomVars {
606 contentId
607 }
608 }
609 }
610 }''' % (client, video_id),
611 }).encode(), headers={
612 'Content-Type': 'application/json'
613 })['data']['playerPage']
614 title = player_page['title']
615 content_id = str_or_none(try_get(
616 player_page, lambda x: x['tracking']['atiCustomVars']['contentId']))
617 media_collection = player_page.get('mediaCollection') or {}
618 if not media_collection and content_id:
619 media_collection = self._download_json(
620 'https://www.ardmediathek.de/play/media/' + content_id,
621 content_id, fatal=False) or {}
622 info = self._parse_media_info(
623 media_collection, content_id or video_id,
624 player_page.get('blockedByFsk'))
625 age_limit = None
626 description = player_page.get('synopsis')
627 maturity_content_rating = player_page.get('maturityContentRating')
628 if maturity_content_rating:
629 age_limit = int_or_none(maturity_content_rating.lstrip('FSK'))
630 if not age_limit and description:
631 age_limit = int_or_none(self._search_regex(
632 r'\(FSK\s*(\d+)\)\s*$', description, 'age limit', default=None))
633 info.update({
634 'age_limit': age_limit,
635 'display_id': display_id,
636 'title': title,
637 'description': description,
638 'timestamp': unified_timestamp(player_page.get('broadcastedOn')),
639 'series': try_get(player_page, lambda x: x['show']['title']),
640 })
641 info.update(self._ARD_extract_episode_info(info['title']))
642 return info