]> jfr.im git - yt-dlp.git/blame - yt_dlp/extractor/zdf.py
[youtube] Differentiate descriptive audio by language code
[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 = [{
f5c2c2c9 139 'url': 'https://www.zdf.de/nachrichten/heute-journal/heute-journal-vom-30-12-2021-100.html',
ec5e77c5 140 'info_dict': {
f5c2c2c9 141 'id': '211230_sendung_hjo',
ec5e77c5 142 'ext': 'mp4',
f5c2c2c9 143 'description': 'md5:47dff85977bde9fb8cba9e9c9b929839',
144 'duration': 1890.0,
145 'upload_date': '20211230',
146 'chapters': list,
147 'thumbnail': 'md5:e65f459f741be5455c952cd820eb188e',
148 'title': 'heute journal vom 30.12.2021',
149 'timestamp': 1640897100,
150 }
ec5e77c5 151 }, {
152 'url': 'https://www.zdf.de/dokumentation/terra-x/die-magie-der-farben-von-koenigspurpur-und-jeansblau-100.html',
153 'info_dict': {
154 'id': '151025_magie_farben2_tex',
155 'ext': 'mp4',
156 'title': 'Die Magie der Farben (2/2)',
157 'description': 'md5:a89da10c928c6235401066b60a6d5c1a',
158 'duration': 2615,
159 'timestamp': 1465021200,
160 'upload_date': '20160604',
f5c2c2c9 161 'thumbnail': 'https://www.zdf.de/assets/mauve-im-labor-100~768x432?cb=1464909117806',
ec5e77c5 162 },
5f9aaac8 163 }, {
164 'url': 'https://www.zdf.de/funk/druck-11790/funk-alles-ist-verzaubert-102.html',
165 'md5': '3d6f1049e9682178a11c54b91f3dd065',
166 'info_dict': {
167 'ext': 'mp4',
168 'id': 'video_funk_1770473',
169 'duration': 1278,
170 'description': 'Die Neue an der Schule verdreht Ismail den Kopf.',
171 'title': 'Alles ist verzaubert',
172 'timestamp': 1635520560,
f5c2c2c9 173 'upload_date': '20211029',
174 'thumbnail': 'https://www.zdf.de/assets/teaser-funk-alles-ist-verzaubert-100~1920x1080?cb=1636466431799',
5f9aaac8 175 },
ec5e77c5 176 }, {
177 # Same as https://www.phoenix.de/sendungen/dokumentationen/gesten-der-maechtigen-i-a-89468.html?ref=suche
178 'url': 'https://www.zdf.de/politik/phoenix-sendungen/die-gesten-der-maechtigen-100.html',
179 'only_matching': True,
180 }, {
181 # Same as https://www.3sat.de/film/spielfilm/der-hauptmann-100.html
182 'url': 'https://www.zdf.de/filme/filme-sonstige/der-hauptmann-112.html',
183 'only_matching': True,
184 }, {
185 # Same as https://www.3sat.de/wissen/nano/nano-21-mai-2019-102.html, equal media ids
186 'url': 'https://www.zdf.de/wissen/nano/nano-21-mai-2019-102.html',
187 'only_matching': True,
188 }, {
189 'url': 'https://www.zdf.de/service-und-hilfe/die-neue-zdf-mediathek/zdfmediathek-trailer-100.html',
190 'only_matching': True,
191 }, {
192 'url': 'https://www.zdf.de/filme/taunuskrimi/die-lebenden-und-die-toten-1---ein-taunuskrimi-100.html',
193 'only_matching': True,
194 }, {
195 'url': 'https://www.zdf.de/dokumentation/planet-e/planet-e-uebersichtsseite-weitere-dokumentationen-von-planet-e-100.html',
196 'only_matching': True,
5f9aaac8 197 }, {
198 # Same as https://www.phoenix.de/sendungen/ereignisse/corona-nachgehakt/wohin-fuehrt-der-protest-in-der-pandemie-a-2050630.html
199 'url': 'https://www.zdf.de/politik/phoenix-sendungen/wohin-fuehrt-der-protest-in-der-pandemie-100.html',
200 'only_matching': True
f5c2c2c9 201 }, {
202 # Same as https://www.3sat.de/film/ab-18/10-wochen-sommer-108.html
203 'url': 'https://www.zdf.de/dokumentation/ab-18/10-wochen-sommer-102.html',
204 'only_matching': True
ec5e77c5 205 }]
206
207 def _extract_entry(self, url, player, content, video_id):
208 title = content.get('title') or content['teaserHeadline']
209
210 t = content['mainVideoContent']['http://zdf.de/rels/target']
211
212 ptmd_path = t.get('http://zdf.de/rels/streams/ptmd')
213
214 if not ptmd_path:
5f9aaac8 215 ptmd_path = traverse_obj(
216 t, ('streams', 'default', 'http://zdf.de/rels/streams/ptmd-template'),
217 'http://zdf.de/rels/streams/ptmd-template').replace(
ec5e77c5 218 '{playerId}', 'ngplayer_2_4')
219
220 info = self._extract_ptmd(
221 urljoin(url, ptmd_path), video_id, player['apiToken'], url)
222
fb47cb5b
S
223 thumbnails = []
224 layouts = try_get(
225 content, lambda x: x['teaserImageRef']['layouts'], dict)
226 if layouts:
227 for layout_key, layout_url in layouts.items():
3052a30d
S
228 layout_url = url_or_none(layout_url)
229 if not layout_url:
fb47cb5b
S
230 continue
231 thumbnail = {
232 'url': layout_url,
233 'format_id': layout_key,
234 }
235 mobj = re.search(r'(?P<width>\d+)x(?P<height>\d+)', layout_key)
236 if mobj:
237 thumbnail.update({
238 'width': int(mobj.group('width')),
239 'height': int(mobj.group('height')),
240 })
241 thumbnails.append(thumbnail)
a5c1d955 242
f5c2c2c9 243 chapter_marks = t.get('streamAnchorTag') or []
244 chapter_marks.append({'anchorOffset': int_or_none(t.get('duration'))})
245 chapters = [{
246 'start_time': chap.get('anchorOffset'),
247 'end_time': next_chap.get('anchorOffset'),
248 'title': chap.get('anchorLabel')
249 } for chap, next_chap in zip(chapter_marks, chapter_marks[1:])]
250
ec5e77c5 251 return merge_dicts(info, {
fb47cb5b
S
252 'title': title,
253 'description': content.get('leadParagraph') or content.get('teasertext'),
254 'duration': int_or_none(t.get('duration')),
255 'timestamp': unified_timestamp(content.get('editorialDate')),
256 'thumbnails': thumbnails,
f5c2c2c9 257 'chapters': chapters or None
ec5e77c5 258 })
d5822b96 259
fb47cb5b 260 def _extract_regular(self, url, player, video_id):
50de3dba 261 content = self._call_api(
ec5e77c5 262 player['content'], video_id, 'content', player['apiToken'], url)
50de3dba 263 return self._extract_entry(player['content'], player, content, video_id)
b6de53ea 264
fb47cb5b 265 def _extract_mobile(self, video_id):
ec5e77c5 266 video = self._download_json(
fb47cb5b 267 'https://zdf-cdn.live.cellular.de/mediathekV2/document/%s' % video_id,
ec5e77c5 268 video_id)
269
270 document = video['document']
b6de53ea 271
fb47cb5b 272 title = document['titel']
ec5e77c5 273 content_id = document['basename']
b6de53ea 274
fb47cb5b
S
275 formats = []
276 format_urls = set()
277 for f in document['formitaeten']:
ec5e77c5 278 self._extract_format(content_id, formats, format_urls, f)
fb47cb5b
S
279 self._sort_formats(formats)
280
281 thumbnails = []
282 teaser_bild = document.get('teaserBild')
283 if isinstance(teaser_bild, dict):
284 for thumbnail_key, thumbnail in teaser_bild.items():
285 thumbnail_url = try_get(
286 thumbnail, lambda x: x['url'], compat_str)
287 if thumbnail_url:
288 thumbnails.append({
289 'url': thumbnail_url,
290 'id': thumbnail_key,
291 'width': int_or_none(thumbnail.get('width')),
292 'height': int_or_none(thumbnail.get('height')),
293 })
b6de53ea 294
fb47cb5b 295 return {
ec5e77c5 296 'id': content_id,
fb47cb5b
S
297 'title': title,
298 'description': document.get('beschreibung'),
299 'duration': int_or_none(document.get('length')),
ec5e77c5 300 'timestamp': unified_timestamp(document.get('date')) or unified_timestamp(
301 try_get(video, lambda x: x['meta']['editorialDate'], compat_str)),
fb47cb5b
S
302 'thumbnails': thumbnails,
303 'subtitles': self._extract_subtitles(document),
304 'formats': formats,
305 }
b6de53ea 306
fb47cb5b
S
307 def _real_extract(self, url):
308 video_id = self._match_id(url)
b6de53ea 309
fb47cb5b
S
310 webpage = self._download_webpage(url, video_id, fatal=False)
311 if webpage:
312 player = self._extract_player(webpage, url, fatal=False)
313 if player:
314 return self._extract_regular(url, player, video_id)
b6de53ea 315
fb47cb5b 316 return self._extract_mobile(video_id)
b6de53ea 317
b6de53ea 318
fb47cb5b
S
319class ZDFChannelIE(ZDFBaseIE):
320 _VALID_URL = r'https?://www\.zdf\.de/(?:[^/]+/)*(?P<id>[^/?#&]+)'
c2404463 321 _TESTS = [{
fb47cb5b 322 'url': 'https://www.zdf.de/sport/das-aktuelle-sportstudio',
8560c618 323 'info_dict': {
fb47cb5b
S
324 'id': 'das-aktuelle-sportstudio',
325 'title': 'das aktuelle sportstudio | ZDF',
8560c618 326 },
b4cbdbd4 327 'playlist_mincount': 23,
c2404463 328 }, {
fb47cb5b
S
329 'url': 'https://www.zdf.de/dokumentation/planet-e',
330 'info_dict': {
331 'id': 'planet-e',
332 'title': 'planet e.',
333 },
b4cbdbd4 334 'playlist_mincount': 50,
c2404463 335 }, {
fb47cb5b 336 'url': 'https://www.zdf.de/filme/taunuskrimi/',
c2404463
S
337 'only_matching': True,
338 }]
fb47cb5b
S
339
340 @classmethod
341 def suitable(cls, url):
342 return False if ZDFIE.suitable(url) else super(ZDFChannelIE, cls).suitable(url)
9abd500a
PH
343
344 def _real_extract(self, url):
345 channel_id = self._match_id(url)
8560c618 346
fb47cb5b
S
347 webpage = self._download_webpage(url, channel_id)
348
349 entries = [
350 self.url_result(item_url, ie=ZDFIE.ie_key())
351 for item_url in orderedSet(re.findall(
352 r'data-plusbar-url=["\'](http.+?\.html)', webpage))]
353
354 return self.playlist_result(
355 entries, channel_id, self._og_search_title(webpage, fatal=False))
356
ec85ded8 357 r"""
fb47cb5b
S
358 player = self._extract_player(webpage, channel_id)
359
360 channel_id = self._search_regex(
361 r'docId\s*:\s*(["\'])(?P<id>(?!\1).+?)\1', webpage,
362 'channel id', group='id')
363
364 channel = self._call_api(
365 'https://api.zdf.de/content/documents/%s.json' % channel_id,
366 player, url, channel_id)
367
368 items = []
369 for module in channel['module']:
370 for teaser in try_get(module, lambda x: x['teaser'], list) or []:
371 t = try_get(
372 teaser, lambda x: x['http://zdf.de/rels/target'], dict)
373 if not t:
374 continue
375 items.extend(try_get(
376 t,
377 lambda x: x['resultsWithVideo']['http://zdf.de/rels/search/results'],
378 list) or [])
379 items.extend(try_get(
380 module,
381 lambda x: x['filterRef']['resultsWithVideo']['http://zdf.de/rels/search/results'],
382 list) or [])
383
384 entries = []
385 entry_urls = set()
386 for item in items:
387 t = try_get(item, lambda x: x['http://zdf.de/rels/target'], dict)
388 if not t:
389 continue
390 sharing_url = t.get('http://zdf.de/rels/sharing-url')
391 if not sharing_url or not isinstance(sharing_url, compat_str):
392 continue
393 if sharing_url in entry_urls:
394 continue
395 entry_urls.add(sharing_url)
396 entries.append(self.url_result(
397 sharing_url, ie=ZDFIE.ie_key(), video_id=t.get('id')))
398
399 return self.playlist_result(entries, channel_id, channel.get('title'))
400 """