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