zdf.py 14 KB

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