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.

312 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):
  20. return self._download_json(
  21. url, video_id, 'Downloading JSON content',
  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, 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._download_json(urljoin(url, ptmd_path), video_id)
  105. formats = []
  106. track_uris = set()
  107. for p in ptmd['priorityList']:
  108. formitaeten = p.get('formitaeten')
  109. if not isinstance(formitaeten, list):
  110. continue
  111. for f in formitaeten:
  112. f_qualities = f.get('qualities')
  113. if not isinstance(f_qualities, list):
  114. continue
  115. for quality in f_qualities:
  116. tracks = try_get(quality, lambda x: x['audio']['tracks'], list)
  117. if not tracks:
  118. continue
  119. for track in tracks:
  120. self._extract_format(
  121. video_id, formats, track_uris, {
  122. 'url': track.get('uri'),
  123. 'type': f.get('type'),
  124. 'mimeType': f.get('mimeType'),
  125. 'quality': quality.get('quality'),
  126. 'language': track.get('language'),
  127. })
  128. self._sort_formats(formats)
  129. thumbnails = []
  130. layouts = try_get(
  131. content, lambda x: x['teaserImageRef']['layouts'], dict)
  132. if layouts:
  133. for layout_key, layout_url in layouts.items():
  134. if not isinstance(layout_url, compat_str):
  135. continue
  136. thumbnail = {
  137. 'url': layout_url,
  138. 'format_id': layout_key,
  139. }
  140. mobj = re.search(r'(?P<width>\d+)x(?P<height>\d+)', layout_key)
  141. if mobj:
  142. thumbnail.update({
  143. 'width': int(mobj.group('width')),
  144. 'height': int(mobj.group('height')),
  145. })
  146. thumbnails.append(thumbnail)
  147. return {
  148. 'id': video_id,
  149. 'title': title,
  150. 'description': content.get('leadParagraph') or content.get('teasertext'),
  151. 'duration': int_or_none(t.get('duration')),
  152. 'timestamp': unified_timestamp(content.get('editorialDate')),
  153. 'thumbnails': thumbnails,
  154. 'subtitles': self._extract_subtitles(ptmd),
  155. 'formats': formats,
  156. }
  157. def _extract_regular(self, url, player, video_id):
  158. content = self._call_api(player['content'], player, url, video_id)
  159. return self._extract_entry(player['content'], content, video_id)
  160. def _extract_mobile(self, video_id):
  161. document = self._download_json(
  162. 'https://zdf-cdn.live.cellular.de/mediathekV2/document/%s' % video_id,
  163. video_id)['document']
  164. title = document['titel']
  165. formats = []
  166. format_urls = set()
  167. for f in document['formitaeten']:
  168. self._extract_format(video_id, formats, format_urls, f)
  169. self._sort_formats(formats)
  170. thumbnails = []
  171. teaser_bild = document.get('teaserBild')
  172. if isinstance(teaser_bild, dict):
  173. for thumbnail_key, thumbnail in teaser_bild.items():
  174. thumbnail_url = try_get(
  175. thumbnail, lambda x: x['url'], compat_str)
  176. if thumbnail_url:
  177. thumbnails.append({
  178. 'url': thumbnail_url,
  179. 'id': thumbnail_key,
  180. 'width': int_or_none(thumbnail.get('width')),
  181. 'height': int_or_none(thumbnail.get('height')),
  182. })
  183. return {
  184. 'id': video_id,
  185. 'title': title,
  186. 'description': document.get('beschreibung'),
  187. 'duration': int_or_none(document.get('length')),
  188. 'timestamp': unified_timestamp(try_get(
  189. document, lambda x: x['meta']['editorialDate'], compat_str)),
  190. 'thumbnails': thumbnails,
  191. 'subtitles': self._extract_subtitles(document),
  192. 'formats': formats,
  193. }
  194. def _real_extract(self, url):
  195. video_id = self._match_id(url)
  196. webpage = self._download_webpage(url, video_id, fatal=False)
  197. if webpage:
  198. player = self._extract_player(webpage, url, fatal=False)
  199. if player:
  200. return self._extract_regular(url, player, video_id)
  201. return self._extract_mobile(video_id)
  202. class ZDFChannelIE(ZDFBaseIE):
  203. _VALID_URL = r'https?://www\.zdf\.de/(?:[^/]+/)*(?P<id>[^/?#&]+)'
  204. _TESTS = [{
  205. 'url': 'https://www.zdf.de/sport/das-aktuelle-sportstudio',
  206. 'info_dict': {
  207. 'id': 'das-aktuelle-sportstudio',
  208. 'title': 'das aktuelle sportstudio | ZDF',
  209. },
  210. 'playlist_count': 21,
  211. }, {
  212. 'url': 'https://www.zdf.de/dokumentation/planet-e',
  213. 'info_dict': {
  214. 'id': 'planet-e',
  215. 'title': 'planet e.',
  216. },
  217. 'playlist_count': 4,
  218. }, {
  219. 'url': 'https://www.zdf.de/filme/taunuskrimi/',
  220. 'only_matching': True,
  221. }]
  222. @classmethod
  223. def suitable(cls, url):
  224. return False if ZDFIE.suitable(url) else super(ZDFChannelIE, cls).suitable(url)
  225. def _real_extract(self, url):
  226. channel_id = self._match_id(url)
  227. webpage = self._download_webpage(url, channel_id)
  228. entries = [
  229. self.url_result(item_url, ie=ZDFIE.ie_key())
  230. for item_url in orderedSet(re.findall(
  231. r'data-plusbar-url=["\'](http.+?\.html)', webpage))]
  232. return self.playlist_result(
  233. entries, channel_id, self._og_search_title(webpage, fatal=False))
  234. r"""
  235. player = self._extract_player(webpage, channel_id)
  236. channel_id = self._search_regex(
  237. r'docId\s*:\s*(["\'])(?P<id>(?!\1).+?)\1', webpage,
  238. 'channel id', group='id')
  239. channel = self._call_api(
  240. 'https://api.zdf.de/content/documents/%s.json' % channel_id,
  241. player, url, channel_id)
  242. items = []
  243. for module in channel['module']:
  244. for teaser in try_get(module, lambda x: x['teaser'], list) or []:
  245. t = try_get(
  246. teaser, lambda x: x['http://zdf.de/rels/target'], dict)
  247. if not t:
  248. continue
  249. items.extend(try_get(
  250. t,
  251. lambda x: x['resultsWithVideo']['http://zdf.de/rels/search/results'],
  252. list) or [])
  253. items.extend(try_get(
  254. module,
  255. lambda x: x['filterRef']['resultsWithVideo']['http://zdf.de/rels/search/results'],
  256. list) or [])
  257. entries = []
  258. entry_urls = set()
  259. for item in items:
  260. t = try_get(item, lambda x: x['http://zdf.de/rels/target'], dict)
  261. if not t:
  262. continue
  263. sharing_url = t.get('http://zdf.de/rels/sharing-url')
  264. if not sharing_url or not isinstance(sharing_url, compat_str):
  265. continue
  266. if sharing_url in entry_urls:
  267. continue
  268. entry_urls.add(sharing_url)
  269. entries.append(self.url_result(
  270. sharing_url, ie=ZDFIE.ie_key(), video_id=t.get('id')))
  271. return self.playlist_result(entries, channel_id, channel.get('title'))
  272. """