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.

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