zdf.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441
  1. import re
  2. from .common import InfoExtractor
  3. from ..utils import (
  4. NO_DEFAULT,
  5. ExtractorError,
  6. determine_ext,
  7. extract_attributes,
  8. float_or_none,
  9. int_or_none,
  10. join_nonempty,
  11. merge_dicts,
  12. parse_codecs,
  13. qualities,
  14. traverse_obj,
  15. try_get,
  16. unified_timestamp,
  17. update_url_query,
  18. url_or_none,
  19. urljoin,
  20. )
  21. class ZDFBaseIE(InfoExtractor):
  22. _GEO_COUNTRIES = ['DE']
  23. _QUALITIES = ('auto', 'low', 'med', 'high', 'veryhigh', 'hd', 'fhd', 'uhd')
  24. def _call_api(self, url, video_id, item, api_token=None, referrer=None):
  25. headers = {}
  26. if api_token:
  27. headers['Api-Auth'] = f'Bearer {api_token}'
  28. if referrer:
  29. headers['Referer'] = referrer
  30. return self._download_json(
  31. url, video_id, f'Downloading JSON {item}', headers=headers)
  32. @staticmethod
  33. def _extract_subtitles(src):
  34. subtitles = {}
  35. for caption in try_get(src, lambda x: x['captions'], list) or []:
  36. subtitle_url = url_or_none(caption.get('uri'))
  37. if subtitle_url:
  38. lang = caption.get('language', 'deu')
  39. subtitles.setdefault(lang, []).append({
  40. 'url': subtitle_url,
  41. })
  42. return subtitles
  43. def _extract_format(self, video_id, formats, format_urls, meta):
  44. format_url = url_or_none(meta.get('url'))
  45. if not format_url or format_url in format_urls:
  46. return
  47. format_urls.add(format_url)
  48. mime_type, ext = meta.get('mimeType'), determine_ext(format_url)
  49. if mime_type == 'application/x-mpegURL' or ext == 'm3u8':
  50. new_formats = self._extract_m3u8_formats(
  51. format_url, video_id, 'mp4', m3u8_id='hls',
  52. entry_protocol='m3u8_native', fatal=False)
  53. elif mime_type == 'application/f4m+xml' or ext == 'f4m':
  54. new_formats = self._extract_f4m_formats(
  55. update_url_query(format_url, {'hdcore': '3.7.0'}), video_id, f4m_id='hds', fatal=False)
  56. elif ext == 'mpd':
  57. new_formats = self._extract_mpd_formats(
  58. format_url, video_id, mpd_id='dash', fatal=False)
  59. else:
  60. f = parse_codecs(meta.get('mimeCodec'))
  61. if not f and meta.get('type'):
  62. data = meta['type'].split('_')
  63. if try_get(data, lambda x: x[2]) == ext:
  64. f = {'vcodec': data[0], 'acodec': data[1]}
  65. f.update({
  66. 'url': format_url,
  67. 'format_id': join_nonempty('http', meta.get('type'), meta.get('quality')),
  68. 'tbr': int_or_none(self._search_regex(r'_(\d+)k_', format_url, 'tbr', default=None)),
  69. })
  70. new_formats = [f]
  71. formats.extend(merge_dicts(f, {
  72. 'format_note': join_nonempty('quality', 'class', from_dict=meta, delim=', '),
  73. 'language': meta.get('language'),
  74. 'language_preference': 10 if meta.get('class') == 'main' else -10 if meta.get('class') == 'ad' else -1,
  75. 'quality': qualities(self._QUALITIES)(meta.get('quality')),
  76. }) for f in new_formats)
  77. def _extract_ptmd(self, ptmd_url, video_id, api_token, referrer):
  78. ptmd = self._call_api(
  79. ptmd_url, video_id, 'metadata', api_token, referrer)
  80. content_id = ptmd.get('basename') or ptmd_url.split('/')[-1]
  81. formats = []
  82. track_uris = set()
  83. for p in ptmd['priorityList']:
  84. formitaeten = p.get('formitaeten')
  85. if not isinstance(formitaeten, list):
  86. continue
  87. for f in formitaeten:
  88. f_qualities = f.get('qualities')
  89. if not isinstance(f_qualities, list):
  90. continue
  91. for quality in f_qualities:
  92. tracks = try_get(quality, lambda x: x['audio']['tracks'], list)
  93. if not tracks:
  94. continue
  95. for track in tracks:
  96. self._extract_format(
  97. content_id, formats, track_uris, {
  98. 'url': track.get('uri'),
  99. 'type': f.get('type'),
  100. 'mimeType': f.get('mimeType'),
  101. 'quality': quality.get('quality'),
  102. 'class': track.get('class'),
  103. 'language': track.get('language'),
  104. })
  105. duration = float_or_none(try_get(
  106. ptmd, lambda x: x['attributes']['duration']['value']), scale=1000)
  107. return {
  108. 'extractor_key': ZDFIE.ie_key(),
  109. 'id': content_id,
  110. 'duration': duration,
  111. 'formats': formats,
  112. 'subtitles': self._extract_subtitles(ptmd),
  113. '_format_sort_fields': ('tbr', 'res', 'quality', 'language_preference'),
  114. }
  115. def _extract_player(self, webpage, video_id, fatal=True):
  116. return self._parse_json(
  117. self._search_regex(
  118. r'(?s)data-zdfplayer-jsb=(["\'])(?P<json>{.+?})\1', webpage,
  119. 'player JSON', default='{}' if not fatal else NO_DEFAULT,
  120. group='json'),
  121. video_id)
  122. class ZDFIE(ZDFBaseIE):
  123. _VALID_URL = r'https?://www\.zdf\.de/(?:[^/]+/)*(?P<id>[^/?#&]+)\.html'
  124. _TESTS = [{
  125. # Same as https://www.phoenix.de/sendungen/ereignisse/corona-nachgehakt/wohin-fuehrt-der-protest-in-der-pandemie-a-2050630.html
  126. 'url': 'https://www.zdf.de/politik/phoenix-sendungen/wohin-fuehrt-der-protest-in-der-pandemie-100.html',
  127. 'md5': '34ec321e7eb34231fd88616c65c92db0',
  128. 'info_dict': {
  129. 'id': '210222_phx_nachgehakt_corona_protest',
  130. 'ext': 'mp4',
  131. 'title': 'Wohin führt der Protest in der Pandemie?',
  132. 'description': 'md5:7d643fe7f565e53a24aac036b2122fbd',
  133. 'duration': 1691,
  134. 'timestamp': 1613948400,
  135. 'upload_date': '20210221',
  136. },
  137. 'skip': 'No longer available: "Diese Seite wurde leider nicht gefunden"',
  138. }, {
  139. # Same as https://www.3sat.de/film/ab-18/10-wochen-sommer-108.html
  140. 'url': 'https://www.zdf.de/dokumentation/ab-18/10-wochen-sommer-102.html',
  141. 'md5': '0aff3e7bc72c8813f5e0fae333316a1d',
  142. 'info_dict': {
  143. 'id': '141007_ab18_10wochensommer_film',
  144. 'ext': 'mp4',
  145. 'title': 'Ab 18! - 10 Wochen Sommer',
  146. 'description': 'md5:8253f41dc99ce2c3ff892dac2d65fe26',
  147. 'duration': 2660,
  148. 'timestamp': 1608604200,
  149. 'upload_date': '20201222',
  150. },
  151. 'skip': 'No longer available: "Diese Seite wurde leider nicht gefunden"',
  152. }, {
  153. 'url': 'https://www.zdf.de/nachrichten/heute-journal/heute-journal-vom-30-12-2021-100.html',
  154. 'info_dict': {
  155. 'id': '211230_sendung_hjo',
  156. 'ext': 'mp4',
  157. 'description': 'md5:47dff85977bde9fb8cba9e9c9b929839',
  158. 'duration': 1890.0,
  159. 'upload_date': '20211230',
  160. 'chapters': list,
  161. 'thumbnail': 'md5:e65f459f741be5455c952cd820eb188e',
  162. 'title': 'heute journal vom 30.12.2021',
  163. 'timestamp': 1640897100,
  164. },
  165. 'skip': 'No longer available: "Diese Seite wurde leider nicht gefunden"',
  166. }, {
  167. 'url': 'https://www.zdf.de/dokumentation/terra-x/die-magie-der-farben-von-koenigspurpur-und-jeansblau-100.html',
  168. 'info_dict': {
  169. 'id': '151025_magie_farben2_tex',
  170. 'ext': 'mp4',
  171. 'title': 'Die Magie der Farben (2/2)',
  172. 'description': 'md5:a89da10c928c6235401066b60a6d5c1a',
  173. 'duration': 2615,
  174. 'timestamp': 1465021200,
  175. 'upload_date': '20160604',
  176. 'thumbnail': 'https://www.zdf.de/assets/mauve-im-labor-100~768x432?cb=1464909117806',
  177. },
  178. }, {
  179. 'url': 'https://www.zdf.de/funk/druck-11790/funk-alles-ist-verzaubert-102.html',
  180. 'md5': '57af4423db0455a3975d2dc4578536bc',
  181. 'info_dict': {
  182. 'ext': 'mp4',
  183. 'id': 'video_funk_1770473',
  184. 'duration': 1278,
  185. 'description': 'Die Neue an der Schule verdreht Ismail den Kopf.',
  186. 'title': 'Alles ist verzaubert',
  187. 'timestamp': 1635520560,
  188. 'upload_date': '20211029',
  189. 'thumbnail': 'https://www.zdf.de/assets/teaser-funk-alles-ist-verzaubert-102~1920x1080?cb=1663848412907',
  190. },
  191. }, {
  192. # Same as https://www.phoenix.de/sendungen/dokumentationen/gesten-der-maechtigen-i-a-89468.html?ref=suche
  193. 'url': 'https://www.zdf.de/politik/phoenix-sendungen/die-gesten-der-maechtigen-100.html',
  194. 'only_matching': True,
  195. }, {
  196. # Same as https://www.3sat.de/film/spielfilm/der-hauptmann-100.html
  197. 'url': 'https://www.zdf.de/filme/filme-sonstige/der-hauptmann-112.html',
  198. 'only_matching': True,
  199. }, {
  200. # Same as https://www.3sat.de/wissen/nano/nano-21-mai-2019-102.html, equal media ids
  201. 'url': 'https://www.zdf.de/wissen/nano/nano-21-mai-2019-102.html',
  202. 'only_matching': True,
  203. }, {
  204. 'url': 'https://www.zdf.de/service-und-hilfe/die-neue-zdf-mediathek/zdfmediathek-trailer-100.html',
  205. 'only_matching': True,
  206. }, {
  207. 'url': 'https://www.zdf.de/filme/taunuskrimi/die-lebenden-und-die-toten-1---ein-taunuskrimi-100.html',
  208. 'only_matching': True,
  209. }, {
  210. 'url': 'https://www.zdf.de/dokumentation/planet-e/planet-e-uebersichtsseite-weitere-dokumentationen-von-planet-e-100.html',
  211. 'only_matching': True,
  212. }, {
  213. 'url': 'https://www.zdf.de/arte/todliche-flucht/page-video-artede-toedliche-flucht-16-100.html',
  214. 'info_dict': {
  215. 'id': 'video_artede_083871-001-A',
  216. 'ext': 'mp4',
  217. 'title': 'Tödliche Flucht (1/6)',
  218. 'description': 'md5:e34f96a9a5f8abd839ccfcebad3d5315',
  219. 'duration': 3193.0,
  220. 'timestamp': 1641355200,
  221. 'upload_date': '20220105',
  222. },
  223. 'skip': 'No longer available "Diese Seite wurde leider nicht gefunden"',
  224. }, {
  225. 'url': 'https://www.zdf.de/serien/soko-stuttgart/das-geld-anderer-leute-100.html',
  226. 'info_dict': {
  227. 'id': '191205_1800_sendung_sok8',
  228. 'ext': 'mp4',
  229. 'title': 'Das Geld anderer Leute',
  230. 'description': 'md5:cb6f660850dc5eb7d1ab776ea094959d',
  231. 'duration': 2581.0,
  232. 'timestamp': 1675160100,
  233. 'upload_date': '20230131',
  234. 'thumbnail': 'https://epg-image.zdf.de/fotobase-webdelivery/images/e2d7e55a-09f0-424e-ac73-6cac4dd65f35?layout=2400x1350',
  235. },
  236. }, {
  237. 'url': 'https://www.zdf.de/dokumentation/terra-x/unser-gruener-planet-wuesten-doku-100.html',
  238. 'info_dict': {
  239. 'id': '220605_dk_gruener_planet_wuesten_tex',
  240. 'ext': 'mp4',
  241. 'title': 'Unser grüner Planet - Wüsten',
  242. 'description': 'md5:4fc647b6f9c3796eea66f4a0baea2862',
  243. 'duration': 2613.0,
  244. 'timestamp': 1654450200,
  245. 'upload_date': '20220605',
  246. 'format_note': 'uhd, main',
  247. 'thumbnail': 'https://www.zdf.de/assets/saguaro-kakteen-102~3840x2160?cb=1655910690796',
  248. },
  249. }]
  250. def _extract_entry(self, url, player, content, video_id):
  251. title = content.get('title') or content['teaserHeadline']
  252. t = content['mainVideoContent']['http://zdf.de/rels/target']
  253. ptmd_path = traverse_obj(t, (
  254. (('streams', 'default'), None),
  255. ('http://zdf.de/rels/streams/ptmd', 'http://zdf.de/rels/streams/ptmd-template'),
  256. ), get_all=False)
  257. if not ptmd_path:
  258. raise ExtractorError('Could not extract ptmd_path')
  259. info = self._extract_ptmd(
  260. urljoin(url, ptmd_path.replace('{playerId}', 'android_native_5')), video_id, player['apiToken'], url)
  261. thumbnails = []
  262. layouts = try_get(
  263. content, lambda x: x['teaserImageRef']['layouts'], dict)
  264. if layouts:
  265. for layout_key, layout_url in layouts.items():
  266. layout_url = url_or_none(layout_url)
  267. if not layout_url:
  268. continue
  269. thumbnail = {
  270. 'url': layout_url,
  271. 'format_id': layout_key,
  272. }
  273. mobj = re.search(r'(?P<width>\d+)x(?P<height>\d+)', layout_key)
  274. if mobj:
  275. thumbnail.update({
  276. 'width': int(mobj.group('width')),
  277. 'height': int(mobj.group('height')),
  278. })
  279. thumbnails.append(thumbnail)
  280. chapter_marks = t.get('streamAnchorTag') or []
  281. chapter_marks.append({'anchorOffset': int_or_none(t.get('duration'))})
  282. chapters = [{
  283. 'start_time': chap.get('anchorOffset'),
  284. 'end_time': next_chap.get('anchorOffset'),
  285. 'title': chap.get('anchorLabel'),
  286. } for chap, next_chap in zip(chapter_marks, chapter_marks[1:])]
  287. return merge_dicts(info, {
  288. 'title': title,
  289. 'description': content.get('leadParagraph') or content.get('teasertext'),
  290. 'duration': int_or_none(t.get('duration')),
  291. 'timestamp': unified_timestamp(content.get('editorialDate')),
  292. 'thumbnails': thumbnails,
  293. 'chapters': chapters or None,
  294. })
  295. def _extract_regular(self, url, player, video_id):
  296. content = self._call_api(
  297. player['content'], video_id, 'content', player['apiToken'], url)
  298. return self._extract_entry(player['content'], player, content, video_id)
  299. def _extract_mobile(self, video_id):
  300. video = self._download_json(
  301. f'https://zdf-cdn.live.cellular.de/mediathekV2/document/{video_id}',
  302. video_id)
  303. formats = []
  304. formitaeten = try_get(video, lambda x: x['document']['formitaeten'], list)
  305. document = formitaeten and video['document']
  306. if formitaeten:
  307. title = document['titel']
  308. content_id = document['basename']
  309. format_urls = set()
  310. for f in formitaeten or []:
  311. self._extract_format(content_id, formats, format_urls, f)
  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'], 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. })
  325. return {
  326. 'id': content_id,
  327. 'title': title,
  328. 'description': document.get('beschreibung'),
  329. 'duration': int_or_none(document.get('length')),
  330. 'timestamp': unified_timestamp(document.get('date')) or unified_timestamp(
  331. try_get(video, lambda x: x['meta']['editorialDate'], str)),
  332. 'thumbnails': thumbnails,
  333. 'subtitles': self._extract_subtitles(document),
  334. 'formats': formats,
  335. }
  336. def _real_extract(self, url):
  337. video_id = self._match_id(url)
  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)
  343. return self._extract_mobile(video_id)
  344. class ZDFChannelIE(ZDFBaseIE):
  345. _VALID_URL = r'https?://www\.zdf\.de/(?:[^/]+/)*(?P<id>[^/?#&]+)'
  346. _TESTS = [{
  347. 'url': 'https://www.zdf.de/sport/das-aktuelle-sportstudio',
  348. 'info_dict': {
  349. 'id': 'das-aktuelle-sportstudio',
  350. 'title': 'das aktuelle sportstudio',
  351. },
  352. 'playlist_mincount': 18,
  353. }, {
  354. 'url': 'https://www.zdf.de/dokumentation/planet-e',
  355. 'info_dict': {
  356. 'id': 'planet-e',
  357. 'title': 'planet e.',
  358. },
  359. 'playlist_mincount': 50,
  360. }, {
  361. 'url': 'https://www.zdf.de/gesellschaft/aktenzeichen-xy-ungeloest',
  362. 'info_dict': {
  363. 'id': 'aktenzeichen-xy-ungeloest',
  364. 'title': 'Aktenzeichen XY... ungelöst',
  365. 'entries': "lambda x: not any('xy580-fall1-kindermoerder-gesucht-100' in e['url'] for e in x)",
  366. },
  367. 'playlist_mincount': 2,
  368. }, {
  369. 'url': 'https://www.zdf.de/filme/taunuskrimi/',
  370. 'only_matching': True,
  371. }]
  372. @classmethod
  373. def suitable(cls, url):
  374. return False if ZDFIE.suitable(url) else super().suitable(url)
  375. def _og_search_title(self, webpage, fatal=False):
  376. title = super()._og_search_title(webpage, fatal=fatal)
  377. return re.split(r'\s+[-|]\s+ZDF(?:mediathek)?$', title or '')[0] or None
  378. def _real_extract(self, url):
  379. channel_id = self._match_id(url)
  380. webpage = self._download_webpage(url, channel_id)
  381. matches = re.finditer(
  382. rf'''<div\b[^>]*?\sdata-plusbar-id\s*=\s*(["'])(?P<p_id>[\w-]+)\1[^>]*?\sdata-plusbar-url=\1(?P<url>{ZDFIE._VALID_URL})\1''',
  383. webpage)
  384. if self._downloader.params.get('noplaylist', False):
  385. entry = next(
  386. (self.url_result(m.group('url'), ie=ZDFIE.ie_key()) for m in matches),
  387. None)
  388. self.to_screen('Downloading just the main video because of --no-playlist')
  389. if entry:
  390. return entry
  391. else:
  392. self.to_screen(f'Downloading playlist {channel_id} - add --no-playlist to download just the main video')
  393. def check_video(m):
  394. v_ref = self._search_regex(
  395. r'''(<a\b[^>]*?\shref\s*=[^>]+?\sdata-target-id\s*=\s*(["']){}\2[^>]*>)'''.format(m.group('p_id')),
  396. webpage, 'check id', default='')
  397. v_ref = extract_attributes(v_ref)
  398. return v_ref.get('data-target-video-type') != 'novideo'
  399. return self.playlist_from_matches(
  400. (m.group('url') for m in matches if check_video(m)),
  401. channel_id, self._og_search_title(webpage, fatal=False))