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.

306 lines
11 KiB

  1. # coding: utf-8
  2. from __future__ import unicode_literals
  3. import functools
  4. import re
  5. from .common import InfoExtractor
  6. from ..utils import (
  7. OnDemandPagedList,
  8. determine_ext,
  9. parse_iso8601,
  10. ExtractorError
  11. )
  12. from ..compat import compat_str
  13. class ZDFIE(InfoExtractor):
  14. _VALID_URL = r'https?://www\.zdf\.de/.*?/(?P<id>[^/?]*?)\.html'
  15. _TESTS = [{
  16. 'url': 'https://www.zdf.de/service-und-hilfe/die-neue-zdf-mediathek/zdfmediathek-trailer-100.html',
  17. 'info_dict': {
  18. 'id': 'zdfmediathek-trailer-100',
  19. 'ext': 'mp4',
  20. 'title': 'Trailer ZDFmediathek Supermarkt',
  21. }
  22. }]
  23. def _real_extract(self, url):
  24. video_id = self._match_id(url)
  25. try:
  26. extr_player = ZDFExtractorPlayer(self, url, video_id)
  27. formats = extr_player._real_extract()
  28. except (ExtractorError, KeyError) as e:
  29. self._downloader.report_warning('%s: %s\nusing fallback method (mobile url)' % (type(e).__name__, compat_str(e)))
  30. extr_mobile = ZDFExtractorMobile(self, url, video_id)
  31. formats = extr_mobile._real_extract()
  32. return formats
  33. class ZDFExtractor:
  34. """Super class for the 2 extraction methods"""
  35. def __init__(self, parent, url, video_id):
  36. self.parent = parent
  37. self.url = url
  38. self.video_id = video_id
  39. def _real_extract(self):
  40. formats = []
  41. for entry in self._fetch_entries():
  42. video_url = self._get_video_url(entry)
  43. if not video_url:
  44. continue
  45. format_id = self._get_format_id(entry)
  46. ext = determine_ext(video_url, None)
  47. if ext == 'meta':
  48. continue
  49. if ext == 'm3u8':
  50. formats.extend(self.parent._extract_m3u8_formats(
  51. video_url, self.video_id, 'mp4', m3u8_id=format_id, fatal=False))
  52. elif ext == 'f4m':
  53. formats.extend(self.parent._extract_f4m_formats(
  54. video_url, self.video_id, f4m_id=format_id, fatal=False))
  55. else:
  56. formats.append({
  57. 'format_id': format_id,
  58. 'url': video_url,
  59. 'format_note': self._get_format_note(entry)
  60. })
  61. self.parent._sort_formats(formats)
  62. return {
  63. 'id': self.video_id,
  64. 'title': self._get_title(),
  65. 'formats': formats,
  66. 'subtitles': self._get_subtitles(),
  67. 'thumbnail': self._get_thumbnail(),
  68. 'description': self._get_description(),
  69. 'timestamp': self._get_timestamp()
  70. }
  71. class ZDFExtractorMobile(ZDFExtractor):
  72. """Simple URL extraction method. Disadvantage: fewer formats, no subtitles"""
  73. def __init__(self, parent, url, video_id):
  74. ZDFExtractor.__init__(self, parent, url, video_id)
  75. def _fetch_entries(self):
  76. meta_data_url = 'https://zdf-cdn.live.cellular.de/mediathekV2/document/' + self.video_id
  77. self.meta_data = self.parent._download_json(meta_data_url, self.video_id, note='Downloading meta data')
  78. return self.meta_data['document']['formitaeten']
  79. def _get_title(self):
  80. return self.meta_data['document']['titel']
  81. def _get_video_url(self, entry):
  82. return entry['url']
  83. def _get_format_id(self, entry):
  84. format_id = entry['type']
  85. if 'quality' in entry:
  86. format_id += '-' + entry['quality']
  87. return format_id
  88. def _get_format_note(self, entry):
  89. return None
  90. def _get_subtitles(self):
  91. return None
  92. def _get_description(self):
  93. return self.meta_data['document'].get('beschreibung')
  94. def _get_timestamp(self):
  95. meta = self.meta_data['meta']
  96. if meta:
  97. return parse_iso8601(meta.get('editorialDate'))
  98. def _get_thumbnail(self):
  99. teaser_images = self.meta_data['document'].get('teaserBild')
  100. if teaser_images:
  101. max_res = max(teaser_images, key=int)
  102. return teaser_images[max_res].get('url')
  103. class ZDFExtractorPlayer(ZDFExtractor):
  104. """Extraction method that requires downloads of several pages.
  105. Follows the requests of the website."""
  106. def __init__(self, parent, url, video_id):
  107. ZDFExtractor.__init__(self, parent, url, video_id)
  108. def _fetch_entries(self):
  109. webpage = self.parent._download_webpage(self.url, self.video_id)
  110. jsb = self.parent._search_regex(r"data-zdfplayer-jsb='([^']*)'", webpage, 'zdfplayer jsb data')
  111. jsb_json = self.parent._parse_json(jsb, self.video_id)
  112. configuration_url = 'https://www.zdf.de' + jsb_json['config']
  113. configuration_json = self.parent._download_json(configuration_url, self.video_id, note='Downloading player configuration')
  114. api_token = configuration_json['apiToken']
  115. player_js = self.parent._download_webpage('https://www.zdf.de/ZDFplayer/latest-v2/skins/zdf/zdf-player.js', self.video_id, fatal=False, note='Downloading player script')
  116. if player_js:
  117. player_id = self.parent._search_regex(r'this\.ptmd_player_id="([^"]*)"', player_js, 'player id', fatal=False)
  118. else:
  119. player_id = None
  120. self.content_json = self.parent._download_json(jsb_json['content'], self.video_id, headers={'Api-Auth': 'Bearer %s' % api_token}, note='Downloading content description')
  121. main_video_content = self.content_json['mainVideoContent']['http://zdf.de/rels/target']
  122. meta_data_url = None
  123. if not player_id:
  124. # could not determine player_id => try alternativ generic URL
  125. meta_data_url = main_video_content.get('http://zdf.de/rels/streams/ptmd')
  126. if meta_data_url:
  127. meta_data_url = 'https://api.zdf.de' + meta_data_url
  128. else:
  129. # no generic URL found => 2nd fallback: hardcoded player_id
  130. player_id = 'ngplayer_2_3'
  131. if not meta_data_url:
  132. meta_data_url_template = main_video_content['http://zdf.de/rels/streams/ptmd-template']
  133. meta_data_url = 'https://api.zdf.de' + meta_data_url_template.replace('{playerId}', player_id)
  134. self.meta_data = self.parent._download_json(meta_data_url, self.video_id, note='Downloading meta data')
  135. formats = []
  136. for p_list_entry in self.meta_data['priorityList']:
  137. for formitaet in p_list_entry['formitaeten']:
  138. for entry in formitaet['qualities']:
  139. yield (formitaet, entry)
  140. def _get_title(self):
  141. return self.content_json['title']
  142. def _get_video_url(self, entry_tuple):
  143. (formitaet, entry) = entry_tuple
  144. tracks = entry['audio'].get('tracks')
  145. if not tracks:
  146. return
  147. if len(tracks) > 1:
  148. self._downloader.report_warning('unexpected input: multiple tracks')
  149. track = tracks[0]
  150. return track['uri']
  151. def _get_format_id(self, entry_tuple):
  152. (formitaet, entry) = entry_tuple
  153. facets = self._get_facets(formitaet)
  154. add = ''
  155. if 'adaptive' in facets:
  156. add += 'a'
  157. if 'restriction_useragent' in facets:
  158. add += 'b'
  159. if 'progressive' in facets:
  160. add += 'p'
  161. type_ = formitaet['type']
  162. format_id = type_ + '-'
  163. if add:
  164. format_id += add + '-'
  165. # named qualities are not very useful for sorting the formats:
  166. # a 'high' m3u8 entry can be better quality than a 'veryhigh' direct mp4 download
  167. format_id += entry['quality']
  168. return format_id
  169. def _get_facets(self, formitaet):
  170. facets = formitaet.get('facets') or []
  171. if formitaet.get('isAdaptive'):
  172. facets.append('adaptive')
  173. return facets
  174. def _get_format_note(self, entry_tuple):
  175. (formitaet, entry) = entry_tuple
  176. return ', '.join(self._get_facets(formitaet))
  177. def _get_subtitles(self):
  178. subtitles = {}
  179. if 'captions' in self.meta_data:
  180. for caption in self.meta_data['captions']:
  181. lang = caption.get('language')
  182. if not lang:
  183. continue
  184. if lang == 'deu':
  185. lang = 'de'
  186. subformat = {'url': caption.get('uri')}
  187. if caption.get('format') == 'webvtt':
  188. subformat['ext'] = 'vtt'
  189. elif caption.get('format') == 'ebu-tt-d-basic-de':
  190. subformat['ext'] = 'ttml'
  191. if not lang in subtitles:
  192. subtitles[lang] = []
  193. subtitles[lang].append(subformat)
  194. return subtitles
  195. def _get_description(self):
  196. return self.content_json.get('teasertext')
  197. def _get_timestamp(self):
  198. return parse_iso8601(self.content_json.get('editorialDate'))
  199. def _get_thumbnail(self):
  200. teaser_images = self.content_json.get('teaserImageRef')
  201. if teaser_images:
  202. teaser_images_layouts = teaser_images.get('layouts')
  203. if teaser_images_layouts:
  204. if 'original' in teaser_images_layouts:
  205. return teaser_images_layouts['original']
  206. teasers = {}
  207. for key in teaser_images_layouts:
  208. width = self.parent._search_regex(r'(\d+)x\d+', key, 'teaser width', fatal=False)
  209. if width:
  210. teasers[int(width)] = teaser_images_layouts[key]
  211. if teasers:
  212. best = max(teasers)
  213. return teasers[best]
  214. class ZDFChannelIE(InfoExtractor):
  215. _WORKING = False
  216. _VALID_URL = r'(?:zdf:topic:|https?://www\.zdf\.de/ZDFmediathek(?:#)?/.*kanaluebersicht/(?:[^/]+/)?)(?P<id>[0-9]+)'
  217. _TESTS = [{
  218. 'url': 'http://www.zdf.de/ZDFmediathek#/kanaluebersicht/1586442/sendung/Titanic',
  219. 'info_dict': {
  220. 'id': '1586442',
  221. },
  222. 'playlist_count': 3,
  223. }, {
  224. 'url': 'http://www.zdf.de/ZDFmediathek/kanaluebersicht/aktuellste/332',
  225. 'only_matching': True,
  226. }, {
  227. 'url': 'http://www.zdf.de/ZDFmediathek/kanaluebersicht/meist-gesehen/332',
  228. 'only_matching': True,
  229. }, {
  230. 'url': 'http://www.zdf.de/ZDFmediathek/kanaluebersicht/_/1798716?bc=nrt;nrm?flash=off',
  231. 'only_matching': True,
  232. }]
  233. _PAGE_SIZE = 50
  234. def _fetch_page(self, channel_id, page):
  235. offset = page * self._PAGE_SIZE
  236. xml_url = (
  237. 'http://www.zdf.de/ZDFmediathek/xmlservice/web/aktuellste?ak=web&offset=%d&maxLength=%d&id=%s'
  238. % (offset, self._PAGE_SIZE, channel_id))
  239. doc = self._download_xml(
  240. xml_url, channel_id,
  241. note='Downloading channel info',
  242. errnote='Failed to download channel info')
  243. title = doc.find('.//information/title').text
  244. description = doc.find('.//information/detail').text
  245. for asset in doc.findall('.//teasers/teaser'):
  246. a_type = asset.find('./type').text
  247. a_id = asset.find('./details/assetId').text
  248. if a_type not in ('video', 'topic'):
  249. continue
  250. yield {
  251. '_type': 'url',
  252. 'playlist_title': title,
  253. 'playlist_description': description,
  254. 'url': 'zdf:%s:%s' % (a_type, a_id),
  255. }
  256. def _real_extract(self, url):
  257. channel_id = self._match_id(url)
  258. entries = OnDemandPagedList(
  259. functools.partial(self._fetch_page, channel_id), self._PAGE_SIZE)
  260. return {
  261. '_type': 'playlist',
  262. 'id': channel_id,
  263. 'entries': entries,
  264. }