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