]> jfr.im git - yt-dlp.git/blame - yt_dlp/extractor/zdf.py
[extractor] Fix bug in 617f658b7ec1193749848c1b7343acab125dbc46
[yt-dlp.git] / yt_dlp / extractor / zdf.py
CommitLineData
d5822b96
PH
1import re
2
3from .common import InfoExtractor
fb47cb5b 4from ..compat import compat_str
d5822b96 5from ..utils import (
a5c1d955 6 determine_ext,
ec5e77c5 7 float_or_none,
fb47cb5b 8 int_or_none,
34921b43 9 join_nonempty,
ec5e77c5 10 merge_dicts,
fb47cb5b
S
11 NO_DEFAULT,
12 orderedSet,
13 parse_codecs,
14 qualities,
5f9aaac8 15 traverse_obj,
fb47cb5b
S
16 try_get,
17 unified_timestamp,
18 update_url_query,
3052a30d 19 url_or_none,
fb47cb5b 20 urljoin,
d5822b96 21)
0b7c2485 22
fb47cb5b
S
23
24class ZDFBaseIE(InfoExtractor):
9cf26b6e 25 _GEO_COUNTRIES = ['DE']
ec5e77c5 26 _QUALITIES = ('auto', 'low', 'med', 'high', 'veryhigh', 'hd')
a2e6db36 27
ec5e77c5 28 def _call_api(self, url, video_id, item, api_token=None, referrer=None):
29 headers = {}
30 if api_token:
31 headers['Api-Auth'] = 'Bearer %s' % api_token
32 if referrer:
33 headers['Referer'] = referrer
34 return self._download_json(
35 url, video_id, 'Downloading JSON %s' % item, headers=headers)
a5c1d955 36
fb47cb5b
S
37 @staticmethod
38 def _extract_subtitles(src):
39 subtitles = {}
40 for caption in try_get(src, lambda x: x['captions'], list) or []:
3052a30d
S
41 subtitle_url = url_or_none(caption.get('uri'))
42 if subtitle_url:
fb47cb5b
S
43 lang = caption.get('language', 'deu')
44 subtitles.setdefault(lang, []).append({
45 'url': subtitle_url,
46 })
47 return subtitles
48
49 def _extract_format(self, video_id, formats, format_urls, meta):
3052a30d 50 format_url = url_or_none(meta.get('url'))
600e9003 51 if not format_url or format_url in format_urls:
fb47cb5b
S
52 return
53 format_urls.add(format_url)
600e9003 54
55 mime_type, ext = meta.get('mimeType'), determine_ext(format_url)
fb47cb5b 56 if mime_type == 'application/x-mpegURL' or ext == 'm3u8':
600e9003 57 new_formats = self._extract_m3u8_formats(
fb47cb5b 58 format_url, video_id, 'mp4', m3u8_id='hls',
600e9003 59 entry_protocol='m3u8_native', fatal=False)
fb47cb5b 60 elif mime_type == 'application/f4m+xml' or ext == 'f4m':
600e9003 61 new_formats = self._extract_f4m_formats(
62 update_url_query(format_url, {'hdcore': '3.7.0'}), video_id, f4m_id='hds', fatal=False)
fb47cb5b
S
63 else:
64 f = parse_codecs(meta.get('mimeCodec'))
600e9003 65 if not f and meta.get('type'):
66 data = meta['type'].split('_')
67 if try_get(data, lambda x: x[2]) == ext:
68 f = {'vcodec': data[0], 'acodec': data[1]}
fb47cb5b
S
69 f.update({
70 'url': format_url,
34921b43 71 'format_id': join_nonempty('http', meta.get('type'), meta.get('quality')),
fb47cb5b 72 })
600e9003 73 new_formats = [f]
74 formats.extend(merge_dicts(f, {
34921b43 75 'format_note': join_nonempty('quality', 'class', from_dict=meta, delim=', '),
600e9003 76 'language': meta.get('language'),
77 'language_preference': 10 if meta.get('class') == 'main' else -10 if meta.get('class') == 'ad' else -1,
78 'quality': qualities(self._QUALITIES)(meta.get('quality')),
79 }) for f in new_formats)
fb47cb5b 80
ec5e77c5 81 def _extract_ptmd(self, ptmd_url, video_id, api_token, referrer):
50de3dba 82 ptmd = self._call_api(
ec5e77c5 83 ptmd_url, video_id, 'metadata', api_token, referrer)
84
85 content_id = ptmd.get('basename') or ptmd_url.split('/')[-1]
fb47cb5b 86
a5c1d955 87 formats = []
fb47cb5b
S
88 track_uris = set()
89 for p in ptmd['priorityList']:
90 formitaeten = p.get('formitaeten')
91 if not isinstance(formitaeten, list):
a5c1d955 92 continue
fb47cb5b
S
93 for f in formitaeten:
94 f_qualities = f.get('qualities')
95 if not isinstance(f_qualities, list):
96 continue
97 for quality in f_qualities:
98 tracks = try_get(quality, lambda x: x['audio']['tracks'], list)
99 if not tracks:
100 continue
101 for track in tracks:
102 self._extract_format(
ec5e77c5 103 content_id, formats, track_uris, {
fb47cb5b
S
104 'url': track.get('uri'),
105 'type': f.get('type'),
106 'mimeType': f.get('mimeType'),
107 'quality': quality.get('quality'),
600e9003 108 'class': track.get('class'),
fb47cb5b
S
109 'language': track.get('language'),
110 })
600e9003 111 self._sort_formats(formats, ('hasaud', 'res', 'quality', 'language_preference'))
fb47cb5b 112
ec5e77c5 113 duration = float_or_none(try_get(
114 ptmd, lambda x: x['attributes']['duration']['value']), scale=1000)
115
116 return {
117 'extractor_key': ZDFIE.ie_key(),
118 'id': content_id,
119 'duration': duration,
120 'formats': formats,
121 'subtitles': self._extract_subtitles(ptmd),
122 }
123
124 def _extract_player(self, webpage, video_id, fatal=True):
125 return self._parse_json(
126 self._search_regex(
127 r'(?s)data-zdfplayer-jsb=(["\'])(?P<json>{.+?})\1', webpage,
128 'player JSON', default='{}' if not fatal else NO_DEFAULT,
129 group='json'),
130 video_id)
131
132
133class ZDFIE(ZDFBaseIE):
134 _VALID_URL = r'https?://www\.zdf\.de/(?:[^/]+/)*(?P<id>[^/?#&]+)\.html'
135 _TESTS = [{
50e93e03 136 # Same as https://www.phoenix.de/sendungen/ereignisse/corona-nachgehakt/wohin-fuehrt-der-protest-in-der-pandemie-a-2050630.html
137 'url': 'https://www.zdf.de/politik/phoenix-sendungen/wohin-fuehrt-der-protest-in-der-pandemie-100.html',
138 'md5': '34ec321e7eb34231fd88616c65c92db0',
139 'info_dict': {
140 'id': '210222_phx_nachgehakt_corona_protest',
141 'ext': 'mp4',
142 'title': 'Wohin führt der Protest in der Pandemie?',
143 'description': 'md5:7d643fe7f565e53a24aac036b2122fbd',
144 'duration': 1691,
145 'timestamp': 1613948400,
146 'upload_date': '20210221',
147 },
148 'skip': 'No longer available: "Diese Seite wurde leider nicht gefunden"',
149 }, {
150 # Same as https://www.3sat.de/film/ab-18/10-wochen-sommer-108.html
151 'url': 'https://www.zdf.de/dokumentation/ab-18/10-wochen-sommer-102.html',
152 'md5': '0aff3e7bc72c8813f5e0fae333316a1d',
153 'info_dict': {
154 'id': '141007_ab18_10wochensommer_film',
155 'ext': 'mp4',
156 'title': 'Ab 18! - 10 Wochen Sommer',
157 'description': 'md5:8253f41dc99ce2c3ff892dac2d65fe26',
158 'duration': 2660,
159 'timestamp': 1608604200,
160 'upload_date': '20201222',
161 },
162 'skip': 'No longer available: "Diese Seite wurde leider nicht gefunden"',
163 }, {
f5c2c2c9 164 'url': 'https://www.zdf.de/nachrichten/heute-journal/heute-journal-vom-30-12-2021-100.html',
ec5e77c5 165 'info_dict': {
f5c2c2c9 166 'id': '211230_sendung_hjo',
ec5e77c5 167 'ext': 'mp4',
f5c2c2c9 168 'description': 'md5:47dff85977bde9fb8cba9e9c9b929839',
169 'duration': 1890.0,
170 'upload_date': '20211230',
171 'chapters': list,
172 'thumbnail': 'md5:e65f459f741be5455c952cd820eb188e',
173 'title': 'heute journal vom 30.12.2021',
174 'timestamp': 1640897100,
175 }
ec5e77c5 176 }, {
177 'url': 'https://www.zdf.de/dokumentation/terra-x/die-magie-der-farben-von-koenigspurpur-und-jeansblau-100.html',
178 'info_dict': {
179 'id': '151025_magie_farben2_tex',
180 'ext': 'mp4',
181 'title': 'Die Magie der Farben (2/2)',
182 'description': 'md5:a89da10c928c6235401066b60a6d5c1a',
183 'duration': 2615,
184 'timestamp': 1465021200,
185 'upload_date': '20160604',
f5c2c2c9 186 'thumbnail': 'https://www.zdf.de/assets/mauve-im-labor-100~768x432?cb=1464909117806',
ec5e77c5 187 },
5f9aaac8 188 }, {
189 'url': 'https://www.zdf.de/funk/druck-11790/funk-alles-ist-verzaubert-102.html',
190 'md5': '3d6f1049e9682178a11c54b91f3dd065',
191 'info_dict': {
192 'ext': 'mp4',
193 'id': 'video_funk_1770473',
194 'duration': 1278,
195 'description': 'Die Neue an der Schule verdreht Ismail den Kopf.',
196 'title': 'Alles ist verzaubert',
197 'timestamp': 1635520560,
f5c2c2c9 198 'upload_date': '20211029',
199 'thumbnail': 'https://www.zdf.de/assets/teaser-funk-alles-ist-verzaubert-100~1920x1080?cb=1636466431799',
5f9aaac8 200 },
ec5e77c5 201 }, {
202 # Same as https://www.phoenix.de/sendungen/dokumentationen/gesten-der-maechtigen-i-a-89468.html?ref=suche
203 'url': 'https://www.zdf.de/politik/phoenix-sendungen/die-gesten-der-maechtigen-100.html',
204 'only_matching': True,
205 }, {
206 # Same as https://www.3sat.de/film/spielfilm/der-hauptmann-100.html
207 'url': 'https://www.zdf.de/filme/filme-sonstige/der-hauptmann-112.html',
208 'only_matching': True,
209 }, {
210 # Same as https://www.3sat.de/wissen/nano/nano-21-mai-2019-102.html, equal media ids
211 'url': 'https://www.zdf.de/wissen/nano/nano-21-mai-2019-102.html',
212 'only_matching': True,
213 }, {
214 'url': 'https://www.zdf.de/service-und-hilfe/die-neue-zdf-mediathek/zdfmediathek-trailer-100.html',
215 'only_matching': True,
216 }, {
217 'url': 'https://www.zdf.de/filme/taunuskrimi/die-lebenden-und-die-toten-1---ein-taunuskrimi-100.html',
218 'only_matching': True,
219 }, {
220 'url': 'https://www.zdf.de/dokumentation/planet-e/planet-e-uebersichtsseite-weitere-dokumentationen-von-planet-e-100.html',
221 'only_matching': True,
5f9aaac8 222 }, {
50e93e03 223 'url': 'https://www.zdf.de/arte/todliche-flucht/page-video-artede-toedliche-flucht-16-100.html',
224 'info_dict': {
225 'id': 'video_artede_083871-001-A',
226 'ext': 'mp4',
227 'title': 'Tödliche Flucht (1/6)',
228 'description': 'md5:e34f96a9a5f8abd839ccfcebad3d5315',
229 'duration': 3193.0,
230 'timestamp': 1641355200,
231 'upload_date': '20220105',
232 },
ec5e77c5 233 }]
234
235 def _extract_entry(self, url, player, content, video_id):
236 title = content.get('title') or content['teaserHeadline']
237
238 t = content['mainVideoContent']['http://zdf.de/rels/target']
239
240 ptmd_path = t.get('http://zdf.de/rels/streams/ptmd')
241
242 if not ptmd_path:
5f9aaac8 243 ptmd_path = traverse_obj(
244 t, ('streams', 'default', 'http://zdf.de/rels/streams/ptmd-template'),
245 'http://zdf.de/rels/streams/ptmd-template').replace(
ec5e77c5 246 '{playerId}', 'ngplayer_2_4')
247
248 info = self._extract_ptmd(
249 urljoin(url, ptmd_path), video_id, player['apiToken'], url)
250
fb47cb5b
S
251 thumbnails = []
252 layouts = try_get(
253 content, lambda x: x['teaserImageRef']['layouts'], dict)
254 if layouts:
255 for layout_key, layout_url in layouts.items():
3052a30d
S
256 layout_url = url_or_none(layout_url)
257 if not layout_url:
fb47cb5b
S
258 continue
259 thumbnail = {
260 'url': layout_url,
261 'format_id': layout_key,
262 }
263 mobj = re.search(r'(?P<width>\d+)x(?P<height>\d+)', layout_key)
264 if mobj:
265 thumbnail.update({
266 'width': int(mobj.group('width')),
267 'height': int(mobj.group('height')),
268 })
269 thumbnails.append(thumbnail)
a5c1d955 270
f5c2c2c9 271 chapter_marks = t.get('streamAnchorTag') or []
272 chapter_marks.append({'anchorOffset': int_or_none(t.get('duration'))})
273 chapters = [{
274 'start_time': chap.get('anchorOffset'),
275 'end_time': next_chap.get('anchorOffset'),
276 'title': chap.get('anchorLabel')
277 } for chap, next_chap in zip(chapter_marks, chapter_marks[1:])]
278
ec5e77c5 279 return merge_dicts(info, {
fb47cb5b
S
280 'title': title,
281 'description': content.get('leadParagraph') or content.get('teasertext'),
282 'duration': int_or_none(t.get('duration')),
283 'timestamp': unified_timestamp(content.get('editorialDate')),
284 'thumbnails': thumbnails,
f5c2c2c9 285 'chapters': chapters or None
ec5e77c5 286 })
d5822b96 287
fb47cb5b 288 def _extract_regular(self, url, player, video_id):
50de3dba 289 content = self._call_api(
ec5e77c5 290 player['content'], video_id, 'content', player['apiToken'], url)
50de3dba 291 return self._extract_entry(player['content'], player, content, video_id)
b6de53ea 292
fb47cb5b 293 def _extract_mobile(self, video_id):
ec5e77c5 294 video = self._download_json(
fb47cb5b 295 'https://zdf-cdn.live.cellular.de/mediathekV2/document/%s' % video_id,
ec5e77c5 296 video_id)
297
298 document = video['document']
b6de53ea 299
fb47cb5b 300 title = document['titel']
ec5e77c5 301 content_id = document['basename']
b6de53ea 302
fb47cb5b
S
303 formats = []
304 format_urls = set()
305 for f in document['formitaeten']:
ec5e77c5 306 self._extract_format(content_id, formats, format_urls, f)
fb47cb5b
S
307 self._sort_formats(formats)
308
309 thumbnails = []
310 teaser_bild = document.get('teaserBild')
311 if isinstance(teaser_bild, dict):
312 for thumbnail_key, thumbnail in teaser_bild.items():
313 thumbnail_url = try_get(
314 thumbnail, lambda x: x['url'], compat_str)
315 if thumbnail_url:
316 thumbnails.append({
317 'url': thumbnail_url,
318 'id': thumbnail_key,
319 'width': int_or_none(thumbnail.get('width')),
320 'height': int_or_none(thumbnail.get('height')),
321 })
b6de53ea 322
fb47cb5b 323 return {
ec5e77c5 324 'id': content_id,
fb47cb5b
S
325 'title': title,
326 'description': document.get('beschreibung'),
327 'duration': int_or_none(document.get('length')),
ec5e77c5 328 'timestamp': unified_timestamp(document.get('date')) or unified_timestamp(
329 try_get(video, lambda x: x['meta']['editorialDate'], compat_str)),
fb47cb5b
S
330 'thumbnails': thumbnails,
331 'subtitles': self._extract_subtitles(document),
332 'formats': formats,
333 }
b6de53ea 334
fb47cb5b
S
335 def _real_extract(self, url):
336 video_id = self._match_id(url)
b6de53ea 337
fb47cb5b
S
338 webpage = self._download_webpage(url, video_id, fatal=False)
339 if webpage:
340 player = self._extract_player(webpage, url, fatal=False)
341 if player:
342 return self._extract_regular(url, player, video_id)
b6de53ea 343
fb47cb5b 344 return self._extract_mobile(video_id)
b6de53ea 345
b6de53ea 346
fb47cb5b
S
347class ZDFChannelIE(ZDFBaseIE):
348 _VALID_URL = r'https?://www\.zdf\.de/(?:[^/]+/)*(?P<id>[^/?#&]+)'
c2404463 349 _TESTS = [{
fb47cb5b 350 'url': 'https://www.zdf.de/sport/das-aktuelle-sportstudio',
8560c618 351 'info_dict': {
fb47cb5b
S
352 'id': 'das-aktuelle-sportstudio',
353 'title': 'das aktuelle sportstudio | ZDF',
8560c618 354 },
b4cbdbd4 355 'playlist_mincount': 23,
c2404463 356 }, {
fb47cb5b
S
357 'url': 'https://www.zdf.de/dokumentation/planet-e',
358 'info_dict': {
359 'id': 'planet-e',
360 'title': 'planet e.',
361 },
b4cbdbd4 362 'playlist_mincount': 50,
c2404463 363 }, {
fb47cb5b 364 'url': 'https://www.zdf.de/filme/taunuskrimi/',
c2404463
S
365 'only_matching': True,
366 }]
fb47cb5b
S
367
368 @classmethod
369 def suitable(cls, url):
370 return False if ZDFIE.suitable(url) else super(ZDFChannelIE, cls).suitable(url)
9abd500a
PH
371
372 def _real_extract(self, url):
373 channel_id = self._match_id(url)
8560c618 374
fb47cb5b
S
375 webpage = self._download_webpage(url, channel_id)
376
377 entries = [
378 self.url_result(item_url, ie=ZDFIE.ie_key())
379 for item_url in orderedSet(re.findall(
380 r'data-plusbar-url=["\'](http.+?\.html)', webpage))]
381
382 return self.playlist_result(
383 entries, channel_id, self._og_search_title(webpage, fatal=False))
384
ec85ded8 385 r"""
fb47cb5b
S
386 player = self._extract_player(webpage, channel_id)
387
388 channel_id = self._search_regex(
389 r'docId\s*:\s*(["\'])(?P<id>(?!\1).+?)\1', webpage,
390 'channel id', group='id')
391
392 channel = self._call_api(
393 'https://api.zdf.de/content/documents/%s.json' % channel_id,
394 player, url, channel_id)
395
396 items = []
397 for module in channel['module']:
398 for teaser in try_get(module, lambda x: x['teaser'], list) or []:
399 t = try_get(
400 teaser, lambda x: x['http://zdf.de/rels/target'], dict)
401 if not t:
402 continue
403 items.extend(try_get(
404 t,
405 lambda x: x['resultsWithVideo']['http://zdf.de/rels/search/results'],
406 list) or [])
407 items.extend(try_get(
408 module,
409 lambda x: x['filterRef']['resultsWithVideo']['http://zdf.de/rels/search/results'],
410 list) or [])
411
412 entries = []
413 entry_urls = set()
414 for item in items:
415 t = try_get(item, lambda x: x['http://zdf.de/rels/target'], dict)
416 if not t:
417 continue
418 sharing_url = t.get('http://zdf.de/rels/sharing-url')
419 if not sharing_url or not isinstance(sharing_url, compat_str):
420 continue
421 if sharing_url in entry_urls:
422 continue
423 entry_urls.add(sharing_url)
424 entries.append(self.url_result(
425 sharing_url, ie=ZDFIE.ie_key(), video_id=t.get('id')))
426
427 return self.playlist_result(entries, channel_id, channel.get('title'))
428 """