zdf.py 17 KB

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