logo

youtube-dl

[mirror] Download/Watch videos from video hostersgit clone https://hacktivis.me/git/mirror/youtube-dl.git

zdf.py (17212B)


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