zdf.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398
  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. float_or_none,
  10. int_or_none,
  11. merge_dicts,
  12. NO_DEFAULT,
  13. orderedSet,
  14. parse_codecs,
  15. qualities,
  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:
  47. return
  48. if format_url in format_urls:
  49. return
  50. format_urls.add(format_url)
  51. mime_type = meta.get('mimeType')
  52. ext = determine_ext(format_url)
  53. if mime_type == 'application/x-mpegURL' or ext == 'm3u8':
  54. formats.extend(self._extract_m3u8_formats(
  55. format_url, video_id, 'mp4', m3u8_id='hls',
  56. entry_protocol='m3u8_native', fatal=False))
  57. elif mime_type == 'application/f4m+xml' or ext == 'f4m':
  58. formats.extend(self._extract_f4m_formats(
  59. update_url_query(format_url, {'hdcore': '3.7.0'}), video_id, f4m_id='hds', fatal=False))
  60. else:
  61. f = parse_codecs(meta.get('mimeCodec'))
  62. format_id = ['http']
  63. for p in (meta.get('type'), meta.get('quality')):
  64. if p and isinstance(p, compat_str):
  65. format_id.append(p)
  66. f.update({
  67. 'url': format_url,
  68. 'format_id': '-'.join(format_id),
  69. 'format_note': meta.get('quality'),
  70. 'language': meta.get('language'),
  71. 'quality': qualities(self._QUALITIES)(meta.get('quality')),
  72. 'preference': -10,
  73. })
  74. formats.append(f)
  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. 'language': track.get('language'),
  101. })
  102. self._sort_formats(formats)
  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. }
  112. def _extract_player(self, webpage, video_id, fatal=True):
  113. return self._parse_json(
  114. self._search_regex(
  115. r'(?s)data-zdfplayer-jsb=(["\'])(?P<json>{.+?})\1', webpage,
  116. 'player JSON', default='{}' if not fatal else NO_DEFAULT,
  117. group='json'),
  118. video_id)
  119. class ZDFIE(ZDFBaseIE):
  120. _VALID_URL = r'https?://www\.zdf\.de/(?:[^/]+/)*(?P<id>[^/?#&]+)\.html'
  121. _TESTS = [{
  122. # Same as https://www.phoenix.de/sendungen/ereignisse/corona-nachgehakt/wohin-fuehrt-der-protest-in-der-pandemie-a-2050630.html
  123. 'url': 'https://www.zdf.de/politik/phoenix-sendungen/wohin-fuehrt-der-protest-in-der-pandemie-100.html',
  124. 'md5': '34ec321e7eb34231fd88616c65c92db0',
  125. 'info_dict': {
  126. 'id': '210222_phx_nachgehakt_corona_protest',
  127. 'ext': 'mp4',
  128. 'title': 'Wohin führt der Protest in der Pandemie?',
  129. 'description': 'md5:7d643fe7f565e53a24aac036b2122fbd',
  130. 'duration': 1691,
  131. 'timestamp': 1613948400,
  132. 'upload_date': '20210221',
  133. },
  134. 'skip': 'No longer available: "Diese Seite wurde leider nicht gefunden"',
  135. }, {
  136. # Same as https://www.3sat.de/film/ab-18/10-wochen-sommer-108.html
  137. 'url': 'https://www.zdf.de/dokumentation/ab-18/10-wochen-sommer-102.html',
  138. 'md5': '0aff3e7bc72c8813f5e0fae333316a1d',
  139. 'info_dict': {
  140. 'id': '141007_ab18_10wochensommer_film',
  141. 'ext': 'mp4',
  142. 'title': 'Ab 18! - 10 Wochen Sommer',
  143. 'description': 'md5:8253f41dc99ce2c3ff892dac2d65fe26',
  144. 'duration': 2660,
  145. 'timestamp': 1608604200,
  146. 'upload_date': '20201222',
  147. },
  148. 'skip': 'No longer available: "Diese Seite wurde leider nicht gefunden"',
  149. }, {
  150. 'url': 'https://www.zdf.de/dokumentation/terra-x/die-magie-der-farben-von-koenigspurpur-und-jeansblau-100.html',
  151. 'info_dict': {
  152. 'id': '151025_magie_farben2_tex',
  153. 'ext': 'mp4',
  154. 'title': 'Die Magie der Farben (2/2)',
  155. 'description': 'md5:a89da10c928c6235401066b60a6d5c1a',
  156. 'duration': 2615,
  157. 'timestamp': 1465021200,
  158. 'upload_date': '20160604',
  159. },
  160. }, {
  161. # Same as https://www.phoenix.de/sendungen/dokumentationen/gesten-der-maechtigen-i-a-89468.html?ref=suche
  162. 'url': 'https://www.zdf.de/politik/phoenix-sendungen/die-gesten-der-maechtigen-100.html',
  163. 'only_matching': True,
  164. }, {
  165. # Same as https://www.3sat.de/film/spielfilm/der-hauptmann-100.html
  166. 'url': 'https://www.zdf.de/filme/filme-sonstige/der-hauptmann-112.html',
  167. 'only_matching': True,
  168. }, {
  169. # Same as https://www.3sat.de/wissen/nano/nano-21-mai-2019-102.html, equal media ids
  170. 'url': 'https://www.zdf.de/wissen/nano/nano-21-mai-2019-102.html',
  171. 'only_matching': True,
  172. }, {
  173. 'url': 'https://www.zdf.de/service-und-hilfe/die-neue-zdf-mediathek/zdfmediathek-trailer-100.html',
  174. 'only_matching': True,
  175. }, {
  176. 'url': 'https://www.zdf.de/filme/taunuskrimi/die-lebenden-und-die-toten-1---ein-taunuskrimi-100.html',
  177. 'only_matching': True,
  178. }, {
  179. 'url': 'https://www.zdf.de/dokumentation/planet-e/planet-e-uebersichtsseite-weitere-dokumentationen-von-planet-e-100.html',
  180. 'only_matching': True,
  181. }, {
  182. 'url': 'https://www.zdf.de/arte/todliche-flucht/page-video-artede-toedliche-flucht-16-100.html',
  183. 'info_dict': {
  184. 'id': 'video_artede_083871-001-A',
  185. 'ext': 'mp4',
  186. 'title': 'Tödliche Flucht (1/6)',
  187. 'description': 'md5:e34f96a9a5f8abd839ccfcebad3d5315',
  188. 'duration': 3193.0,
  189. 'timestamp': 1641355200,
  190. 'upload_date': '20220105',
  191. },
  192. }]
  193. def _extract_entry(self, url, player, content, video_id):
  194. title = content.get('title') or content['teaserHeadline']
  195. t = content['mainVideoContent']['http://zdf.de/rels/target']
  196. def get_ptmd_path(d):
  197. return (
  198. d.get('http://zdf.de/rels/streams/ptmd')
  199. or d.get('http://zdf.de/rels/streams/ptmd-template',
  200. '').replace('{playerId}', 'ngplayer_2_4'))
  201. ptmd_path = get_ptmd_path(try_get(t, lambda x: x['streams']['default'], dict) or {})
  202. if not ptmd_path:
  203. ptmd_path = get_ptmd_path(t)
  204. if not ptmd_path:
  205. raise ExtractorError('Could not extract ptmd_path')
  206. info = self._extract_ptmd(
  207. urljoin(url, ptmd_path), video_id, player['apiToken'], url)
  208. thumbnails = []
  209. layouts = try_get(
  210. content, lambda x: x['teaserImageRef']['layouts'], dict)
  211. if layouts:
  212. for layout_key, layout_url in layouts.items():
  213. layout_url = url_or_none(layout_url)
  214. if not layout_url:
  215. continue
  216. thumbnail = {
  217. 'url': layout_url,
  218. 'format_id': layout_key,
  219. }
  220. mobj = re.search(r'(?P<width>\d+)x(?P<height>\d+)', layout_key)
  221. if mobj:
  222. thumbnail.update({
  223. 'width': int(mobj.group('width')),
  224. 'height': int(mobj.group('height')),
  225. })
  226. thumbnails.append(thumbnail)
  227. return merge_dicts(info, {
  228. 'title': title,
  229. 'description': content.get('leadParagraph') or content.get('teasertext'),
  230. 'duration': int_or_none(t.get('duration')),
  231. 'timestamp': unified_timestamp(content.get('editorialDate')),
  232. 'thumbnails': thumbnails,
  233. })
  234. def _extract_regular(self, url, player, video_id):
  235. content = self._call_api(
  236. player['content'], video_id, 'content', player['apiToken'], url)
  237. return self._extract_entry(player['content'], player, content, video_id)
  238. def _extract_mobile(self, video_id):
  239. video = self._download_json(
  240. 'https://zdf-cdn.live.cellular.de/mediathekV2/document/%s' % video_id,
  241. video_id)
  242. document = video['document']
  243. title = document['titel']
  244. content_id = document['basename']
  245. formats = []
  246. format_urls = set()
  247. for f in document['formitaeten']:
  248. self._extract_format(content_id, formats, format_urls, f)
  249. self._sort_formats(formats)
  250. thumbnails = []
  251. teaser_bild = document.get('teaserBild')
  252. if isinstance(teaser_bild, dict):
  253. for thumbnail_key, thumbnail in teaser_bild.items():
  254. thumbnail_url = try_get(
  255. thumbnail, lambda x: x['url'], compat_str)
  256. if thumbnail_url:
  257. thumbnails.append({
  258. 'url': thumbnail_url,
  259. 'id': thumbnail_key,
  260. 'width': int_or_none(thumbnail.get('width')),
  261. 'height': int_or_none(thumbnail.get('height')),
  262. })
  263. return {
  264. 'id': content_id,
  265. 'title': title,
  266. 'description': document.get('beschreibung'),
  267. 'duration': int_or_none(document.get('length')),
  268. 'timestamp': unified_timestamp(document.get('date')) or unified_timestamp(
  269. try_get(video, lambda x: x['meta']['editorialDate'], compat_str)),
  270. 'thumbnails': thumbnails,
  271. 'subtitles': self._extract_subtitles(document),
  272. 'formats': formats,
  273. }
  274. def _real_extract(self, url):
  275. video_id = self._match_id(url)
  276. webpage = self._download_webpage(url, video_id, fatal=False)
  277. if webpage:
  278. player = self._extract_player(webpage, url, fatal=False)
  279. if player:
  280. return self._extract_regular(url, player, video_id)
  281. return self._extract_mobile(video_id)
  282. class ZDFChannelIE(ZDFBaseIE):
  283. _VALID_URL = r'https?://www\.zdf\.de/(?:[^/]+/)*(?P<id>[^/?#&]+)'
  284. _TESTS = [{
  285. 'url': 'https://www.zdf.de/sport/das-aktuelle-sportstudio',
  286. 'info_dict': {
  287. 'id': 'das-aktuelle-sportstudio',
  288. 'title': 'das aktuelle sportstudio | ZDF',
  289. },
  290. 'playlist_mincount': 23,
  291. }, {
  292. 'url': 'https://www.zdf.de/dokumentation/planet-e',
  293. 'info_dict': {
  294. 'id': 'planet-e',
  295. 'title': 'planet e.',
  296. },
  297. 'playlist_mincount': 50,
  298. }, {
  299. 'url': 'https://www.zdf.de/filme/taunuskrimi/',
  300. 'only_matching': True,
  301. }]
  302. @classmethod
  303. def suitable(cls, url):
  304. return False if ZDFIE.suitable(url) else super(ZDFChannelIE, cls).suitable(url)
  305. def _real_extract(self, url):
  306. channel_id = self._match_id(url)
  307. webpage = self._download_webpage(url, channel_id)
  308. entries = [
  309. self.url_result(item_url, ie=ZDFIE.ie_key())
  310. for item_url in orderedSet(re.findall(
  311. r'data-plusbar-url=["\'](http.+?\.html)', webpage))]
  312. return self.playlist_result(
  313. entries, channel_id, self._og_search_title(webpage, fatal=False))
  314. r"""
  315. player = self._extract_player(webpage, channel_id)
  316. channel_id = self._search_regex(
  317. r'docId\s*:\s*(["\'])(?P<id>(?!\1).+?)\1', webpage,
  318. 'channel id', group='id')
  319. channel = self._call_api(
  320. 'https://api.zdf.de/content/documents/%s.json' % channel_id,
  321. player, url, channel_id)
  322. items = []
  323. for module in channel['module']:
  324. for teaser in try_get(module, lambda x: x['teaser'], list) or []:
  325. t = try_get(
  326. teaser, lambda x: x['http://zdf.de/rels/target'], dict)
  327. if not t:
  328. continue
  329. items.extend(try_get(
  330. t,
  331. lambda x: x['resultsWithVideo']['http://zdf.de/rels/search/results'],
  332. list) or [])
  333. items.extend(try_get(
  334. module,
  335. lambda x: x['filterRef']['resultsWithVideo']['http://zdf.de/rels/search/results'],
  336. list) or [])
  337. entries = []
  338. entry_urls = set()
  339. for item in items:
  340. t = try_get(item, lambda x: x['http://zdf.de/rels/target'], dict)
  341. if not t:
  342. continue
  343. sharing_url = t.get('http://zdf.de/rels/sharing-url')
  344. if not sharing_url or not isinstance(sharing_url, compat_str):
  345. continue
  346. if sharing_url in entry_urls:
  347. continue
  348. entry_urls.add(sharing_url)
  349. entries.append(self.url_result(
  350. sharing_url, ie=ZDFIE.ie_key(), video_id=t.get('id')))
  351. return self.playlist_result(entries, channel_id, channel.get('title'))
  352. """