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