You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

317 lines
12 KiB

  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. int_or_none,
  9. NO_DEFAULT,
  10. orderedSet,
  11. parse_codecs,
  12. qualities,
  13. try_get,
  14. unified_timestamp,
  15. update_url_query,
  16. urljoin,
  17. )
  18. class ZDFBaseIE(InfoExtractor):
  19. def _call_api(self, url, player, referrer, video_id, item):
  20. return self._download_json(
  21. url, video_id, 'Downloading JSON %s' % item,
  22. headers={
  23. 'Referer': referrer,
  24. 'Api-Auth': 'Bearer %s' % player['apiToken'],
  25. })
  26. def _extract_player(self, webpage, video_id, fatal=True):
  27. return self._parse_json(
  28. self._search_regex(
  29. r'(?s)data-zdfplayer-jsb=(["\'])(?P<json>{.+?})\1', webpage,
  30. 'player JSON', default='{}' if not fatal else NO_DEFAULT,
  31. group='json'),
  32. video_id)
  33. class ZDFIE(ZDFBaseIE):
  34. _VALID_URL = r'https?://www\.zdf\.de/(?:[^/]+/)*(?P<id>[^/?]+)\.html'
  35. _QUALITIES = ('auto', 'low', 'med', 'high', 'veryhigh')
  36. _TESTS = [{
  37. 'url': 'https://www.zdf.de/dokumentation/terra-x/die-magie-der-farben-von-koenigspurpur-und-jeansblau-100.html',
  38. 'info_dict': {
  39. 'id': 'die-magie-der-farben-von-koenigspurpur-und-jeansblau-100',
  40. 'ext': 'mp4',
  41. 'title': 'Die Magie der Farben (2/2)',
  42. 'description': 'md5:a89da10c928c6235401066b60a6d5c1a',
  43. 'duration': 2615,
  44. 'timestamp': 1465021200,
  45. 'upload_date': '20160604',
  46. },
  47. }, {
  48. 'url': 'https://www.zdf.de/service-und-hilfe/die-neue-zdf-mediathek/zdfmediathek-trailer-100.html',
  49. 'only_matching': True,
  50. }, {
  51. 'url': 'https://www.zdf.de/filme/taunuskrimi/die-lebenden-und-die-toten-1---ein-taunuskrimi-100.html',
  52. 'only_matching': True,
  53. }, {
  54. 'url': 'https://www.zdf.de/dokumentation/planet-e/planet-e-uebersichtsseite-weitere-dokumentationen-von-planet-e-100.html',
  55. 'only_matching': True,
  56. }]
  57. @staticmethod
  58. def _extract_subtitles(src):
  59. subtitles = {}
  60. for caption in try_get(src, lambda x: x['captions'], list) or []:
  61. subtitle_url = caption.get('uri')
  62. if subtitle_url and isinstance(subtitle_url, compat_str):
  63. lang = caption.get('language', 'deu')
  64. subtitles.setdefault(lang, []).append({
  65. 'url': subtitle_url,
  66. })
  67. return subtitles
  68. def _extract_format(self, video_id, formats, format_urls, meta):
  69. format_url = meta.get('url')
  70. if not format_url or not isinstance(format_url, compat_str):
  71. return
  72. if format_url in format_urls:
  73. return
  74. format_urls.add(format_url)
  75. mime_type = meta.get('mimeType')
  76. ext = determine_ext(format_url)
  77. if mime_type == 'application/x-mpegURL' or ext == 'm3u8':
  78. formats.extend(self._extract_m3u8_formats(
  79. format_url, video_id, 'mp4', m3u8_id='hls',
  80. entry_protocol='m3u8_native', fatal=False))
  81. elif mime_type == 'application/f4m+xml' or ext == 'f4m':
  82. formats.extend(self._extract_f4m_formats(
  83. update_url_query(format_url, {'hdcore': '3.7.0'}), video_id, f4m_id='hds', fatal=False))
  84. else:
  85. f = parse_codecs(meta.get('mimeCodec'))
  86. format_id = ['http']
  87. for p in (meta.get('type'), meta.get('quality')):
  88. if p and isinstance(p, compat_str):
  89. format_id.append(p)
  90. f.update({
  91. 'url': format_url,
  92. 'format_id': '-'.join(format_id),
  93. 'format_note': meta.get('quality'),
  94. 'language': meta.get('language'),
  95. 'quality': qualities(self._QUALITIES)(meta.get('quality')),
  96. 'preference': -10,
  97. })
  98. formats.append(f)
  99. def _extract_entry(self, url, player, content, video_id):
  100. title = content.get('title') or content['teaserHeadline']
  101. t = content['mainVideoContent']['http://zdf.de/rels/target']
  102. ptmd_path = t.get('http://zdf.de/rels/streams/ptmd')
  103. if not ptmd_path:
  104. ptmd_path = t[
  105. 'http://zdf.de/rels/streams/ptmd-template'].replace(
  106. '{playerId}', 'portal')
  107. ptmd = self._call_api(
  108. urljoin(url, ptmd_path), player, url, video_id, 'metadata')
  109. formats = []
  110. track_uris = set()
  111. for p in ptmd['priorityList']:
  112. formitaeten = p.get('formitaeten')
  113. if not isinstance(formitaeten, list):
  114. continue
  115. for f in formitaeten:
  116. f_qualities = f.get('qualities')
  117. if not isinstance(f_qualities, list):
  118. continue
  119. for quality in f_qualities:
  120. tracks = try_get(quality, lambda x: x['audio']['tracks'], list)
  121. if not tracks:
  122. continue
  123. for track in tracks:
  124. self._extract_format(
  125. video_id, formats, track_uris, {
  126. 'url': track.get('uri'),
  127. 'type': f.get('type'),
  128. 'mimeType': f.get('mimeType'),
  129. 'quality': quality.get('quality'),
  130. 'language': track.get('language'),
  131. })
  132. self._sort_formats(formats)
  133. thumbnails = []
  134. layouts = try_get(
  135. content, lambda x: x['teaserImageRef']['layouts'], dict)
  136. if layouts:
  137. for layout_key, layout_url in layouts.items():
  138. if not isinstance(layout_url, compat_str):
  139. continue
  140. thumbnail = {
  141. 'url': layout_url,
  142. 'format_id': layout_key,
  143. }
  144. mobj = re.search(r'(?P<width>\d+)x(?P<height>\d+)', layout_key)
  145. if mobj:
  146. thumbnail.update({
  147. 'width': int(mobj.group('width')),
  148. 'height': int(mobj.group('height')),
  149. })
  150. thumbnails.append(thumbnail)
  151. return {
  152. 'id': video_id,
  153. 'title': title,
  154. 'description': content.get('leadParagraph') or content.get('teasertext'),
  155. 'duration': int_or_none(t.get('duration')),
  156. 'timestamp': unified_timestamp(content.get('editorialDate')),
  157. 'thumbnails': thumbnails,
  158. 'subtitles': self._extract_subtitles(ptmd),
  159. 'formats': formats,
  160. }
  161. def _extract_regular(self, url, player, video_id):
  162. content = self._call_api(
  163. player['content'], player, url, video_id, 'content')
  164. return self._extract_entry(player['content'], player, content, video_id)
  165. def _extract_mobile(self, video_id):
  166. document = self._download_json(
  167. 'https://zdf-cdn.live.cellular.de/mediathekV2/document/%s' % video_id,
  168. video_id)['document']
  169. title = document['titel']
  170. formats = []
  171. format_urls = set()
  172. for f in document['formitaeten']:
  173. self._extract_format(video_id, formats, format_urls, f)
  174. self._sort_formats(formats)
  175. thumbnails = []
  176. teaser_bild = document.get('teaserBild')
  177. if isinstance(teaser_bild, dict):
  178. for thumbnail_key, thumbnail in teaser_bild.items():
  179. thumbnail_url = try_get(
  180. thumbnail, lambda x: x['url'], compat_str)
  181. if thumbnail_url:
  182. thumbnails.append({
  183. 'url': thumbnail_url,
  184. 'id': thumbnail_key,
  185. 'width': int_or_none(thumbnail.get('width')),
  186. 'height': int_or_none(thumbnail.get('height')),
  187. })
  188. return {
  189. 'id': video_id,
  190. 'title': title,
  191. 'description': document.get('beschreibung'),
  192. 'duration': int_or_none(document.get('length')),
  193. 'timestamp': unified_timestamp(try_get(
  194. document, lambda x: x['meta']['editorialDate'], compat_str)),
  195. 'thumbnails': thumbnails,
  196. 'subtitles': self._extract_subtitles(document),
  197. 'formats': formats,
  198. }
  199. def _real_extract(self, url):
  200. video_id = self._match_id(url)
  201. webpage = self._download_webpage(url, video_id, fatal=False)
  202. if webpage:
  203. player = self._extract_player(webpage, url, fatal=False)
  204. if player:
  205. return self._extract_regular(url, player, video_id)
  206. return self._extract_mobile(video_id)
  207. class ZDFChannelIE(ZDFBaseIE):
  208. _VALID_URL = r'https?://www\.zdf\.de/(?:[^/]+/)*(?P<id>[^/?#&]+)'
  209. _TESTS = [{
  210. 'url': 'https://www.zdf.de/sport/das-aktuelle-sportstudio',
  211. 'info_dict': {
  212. 'id': 'das-aktuelle-sportstudio',
  213. 'title': 'das aktuelle sportstudio | ZDF',
  214. },
  215. 'playlist_count': 21,
  216. }, {
  217. 'url': 'https://www.zdf.de/dokumentation/planet-e',
  218. 'info_dict': {
  219. 'id': 'planet-e',
  220. 'title': 'planet e.',
  221. },
  222. 'playlist_count': 4,
  223. }, {
  224. 'url': 'https://www.zdf.de/filme/taunuskrimi/',
  225. 'only_matching': True,
  226. }]
  227. @classmethod
  228. def suitable(cls, url):
  229. return False if ZDFIE.suitable(url) else super(ZDFChannelIE, cls).suitable(url)
  230. def _real_extract(self, url):
  231. channel_id = self._match_id(url)
  232. webpage = self._download_webpage(url, channel_id)
  233. entries = [
  234. self.url_result(item_url, ie=ZDFIE.ie_key())
  235. for item_url in orderedSet(re.findall(
  236. r'data-plusbar-url=["\'](http.+?\.html)', webpage))]
  237. return self.playlist_result(
  238. entries, channel_id, self._og_search_title(webpage, fatal=False))
  239. r"""
  240. player = self._extract_player(webpage, channel_id)
  241. channel_id = self._search_regex(
  242. r'docId\s*:\s*(["\'])(?P<id>(?!\1).+?)\1', webpage,
  243. 'channel id', group='id')
  244. channel = self._call_api(
  245. 'https://api.zdf.de/content/documents/%s.json' % channel_id,
  246. player, url, channel_id)
  247. items = []
  248. for module in channel['module']:
  249. for teaser in try_get(module, lambda x: x['teaser'], list) or []:
  250. t = try_get(
  251. teaser, lambda x: x['http://zdf.de/rels/target'], dict)
  252. if not t:
  253. continue
  254. items.extend(try_get(
  255. t,
  256. lambda x: x['resultsWithVideo']['http://zdf.de/rels/search/results'],
  257. list) or [])
  258. items.extend(try_get(
  259. module,
  260. lambda x: x['filterRef']['resultsWithVideo']['http://zdf.de/rels/search/results'],
  261. list) or [])
  262. entries = []
  263. entry_urls = set()
  264. for item in items:
  265. t = try_get(item, lambda x: x['http://zdf.de/rels/target'], dict)
  266. if not t:
  267. continue
  268. sharing_url = t.get('http://zdf.de/rels/sharing-url')
  269. if not sharing_url or not isinstance(sharing_url, compat_str):
  270. continue
  271. if sharing_url in entry_urls:
  272. continue
  273. entry_urls.add(sharing_url)
  274. entries.append(self.url_result(
  275. sharing_url, ie=ZDFIE.ie_key(), video_id=t.get('id')))
  276. return self.playlist_result(entries, channel_id, channel.get('title'))
  277. """