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.

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