]> Raphaƫl G. Git Repositories - youtubedl/blob - youtube_dl/extractor/canvas.py
Update upstream source from tag 'upstream/2020.05.08'
[youtubedl] / youtube_dl / extractor / canvas.py
1 from __future__ import unicode_literals
2
3 import re
4 import json
5
6 from .common import InfoExtractor
7 from .gigya import GigyaBaseIE
8 from ..compat import compat_HTTPError
9 from ..utils import (
10 ExtractorError,
11 strip_or_none,
12 float_or_none,
13 int_or_none,
14 merge_dicts,
15 parse_iso8601,
16 str_or_none,
17 url_or_none,
18 )
19
20
21 class CanvasIE(InfoExtractor):
22 _VALID_URL = r'https?://mediazone\.vrt\.be/api/v1/(?P<site_id>canvas|een|ketnet|vrt(?:video|nieuws)|sporza)/assets/(?P<id>[^/?#&]+)'
23 _TESTS = [{
24 'url': 'https://mediazone.vrt.be/api/v1/ketnet/assets/md-ast-4ac54990-ce66-4d00-a8ca-9eac86f4c475',
25 'md5': '68993eda72ef62386a15ea2cf3c93107',
26 'info_dict': {
27 'id': 'md-ast-4ac54990-ce66-4d00-a8ca-9eac86f4c475',
28 'display_id': 'md-ast-4ac54990-ce66-4d00-a8ca-9eac86f4c475',
29 'ext': 'mp4',
30 'title': 'Nachtwacht: De Greystook',
31 'description': 'Nachtwacht: De Greystook',
32 'thumbnail': r're:^https?://.*\.jpg$',
33 'duration': 1468.04,
34 },
35 'expected_warnings': ['is not a supported codec', 'Unknown MIME type'],
36 }, {
37 'url': 'https://mediazone.vrt.be/api/v1/canvas/assets/mz-ast-5e5f90b6-2d72-4c40-82c2-e134f884e93e',
38 'only_matching': True,
39 }]
40 _HLS_ENTRY_PROTOCOLS_MAP = {
41 'HLS': 'm3u8_native',
42 'HLS_AES': 'm3u8',
43 }
44 _REST_API_BASE = 'https://media-services-public.vrt.be/vualto-video-aggregator-web/rest/external/v1'
45
46 def _real_extract(self, url):
47 mobj = re.match(self._VALID_URL, url)
48 site_id, video_id = mobj.group('site_id'), mobj.group('id')
49
50 # Old API endpoint, serves more formats but may fail for some videos
51 data = self._download_json(
52 'https://mediazone.vrt.be/api/v1/%s/assets/%s'
53 % (site_id, video_id), video_id, 'Downloading asset JSON',
54 'Unable to download asset JSON', fatal=False)
55
56 # New API endpoint
57 if not data:
58 token = self._download_json(
59 '%s/tokens' % self._REST_API_BASE, video_id,
60 'Downloading token', data=b'',
61 headers={'Content-Type': 'application/json'})['vrtPlayerToken']
62 data = self._download_json(
63 '%s/videos/%s' % (self._REST_API_BASE, video_id),
64 video_id, 'Downloading video JSON', fatal=False, query={
65 'vrtPlayerToken': token,
66 'client': '%s@PROD' % site_id,
67 }, expected_status=400)
68 message = data.get('message')
69 if message and not data.get('title'):
70 if data.get('code') == 'AUTHENTICATION_REQUIRED':
71 self.raise_login_required(message)
72 raise ExtractorError(message, expected=True)
73
74 title = data['title']
75 description = data.get('description')
76
77 formats = []
78 for target in data['targetUrls']:
79 format_url, format_type = url_or_none(target.get('url')), str_or_none(target.get('type'))
80 if not format_url or not format_type:
81 continue
82 format_type = format_type.upper()
83 if format_type in self._HLS_ENTRY_PROTOCOLS_MAP:
84 formats.extend(self._extract_m3u8_formats(
85 format_url, video_id, 'mp4', self._HLS_ENTRY_PROTOCOLS_MAP[format_type],
86 m3u8_id=format_type, fatal=False))
87 elif format_type == 'HDS':
88 formats.extend(self._extract_f4m_formats(
89 format_url, video_id, f4m_id=format_type, fatal=False))
90 elif format_type == 'MPEG_DASH':
91 formats.extend(self._extract_mpd_formats(
92 format_url, video_id, mpd_id=format_type, fatal=False))
93 elif format_type == 'HSS':
94 formats.extend(self._extract_ism_formats(
95 format_url, video_id, ism_id='mss', fatal=False))
96 else:
97 formats.append({
98 'format_id': format_type,
99 'url': format_url,
100 })
101 self._sort_formats(formats)
102
103 subtitles = {}
104 subtitle_urls = data.get('subtitleUrls')
105 if isinstance(subtitle_urls, list):
106 for subtitle in subtitle_urls:
107 subtitle_url = subtitle.get('url')
108 if subtitle_url and subtitle.get('type') == 'CLOSED':
109 subtitles.setdefault('nl', []).append({'url': subtitle_url})
110
111 return {
112 'id': video_id,
113 'display_id': video_id,
114 'title': title,
115 'description': description,
116 'formats': formats,
117 'duration': float_or_none(data.get('duration'), 1000),
118 'thumbnail': data.get('posterImageUrl'),
119 'subtitles': subtitles,
120 }
121
122
123 class CanvasEenIE(InfoExtractor):
124 IE_DESC = 'canvas.be and een.be'
125 _VALID_URL = r'https?://(?:www\.)?(?P<site_id>canvas|een)\.be/(?:[^/]+/)*(?P<id>[^/?#&]+)'
126 _TESTS = [{
127 'url': 'http://www.canvas.be/video/de-afspraak/najaar-2015/de-afspraak-veilt-voor-de-warmste-week',
128 'md5': 'ed66976748d12350b118455979cca293',
129 'info_dict': {
130 'id': 'mz-ast-5e5f90b6-2d72-4c40-82c2-e134f884e93e',
131 'display_id': 'de-afspraak-veilt-voor-de-warmste-week',
132 'ext': 'flv',
133 'title': 'De afspraak veilt voor de Warmste Week',
134 'description': 'md5:24cb860c320dc2be7358e0e5aa317ba6',
135 'thumbnail': r're:^https?://.*\.jpg$',
136 'duration': 49.02,
137 },
138 'expected_warnings': ['is not a supported codec'],
139 }, {
140 # with subtitles
141 'url': 'http://www.canvas.be/video/panorama/2016/pieter-0167',
142 'info_dict': {
143 'id': 'mz-ast-5240ff21-2d30-4101-bba6-92b5ec67c625',
144 'display_id': 'pieter-0167',
145 'ext': 'mp4',
146 'title': 'Pieter 0167',
147 'description': 'md5:943cd30f48a5d29ba02c3a104dc4ec4e',
148 'thumbnail': r're:^https?://.*\.jpg$',
149 'duration': 2553.08,
150 'subtitles': {
151 'nl': [{
152 'ext': 'vtt',
153 }],
154 },
155 },
156 'params': {
157 'skip_download': True,
158 },
159 'skip': 'Pagina niet gevonden',
160 }, {
161 'url': 'https://www.een.be/thuis/emma-pakt-thilly-aan',
162 'info_dict': {
163 'id': 'md-ast-3a24ced2-64d7-44fb-b4ed-ed1aafbf90b8',
164 'display_id': 'emma-pakt-thilly-aan',
165 'ext': 'mp4',
166 'title': 'Emma pakt Thilly aan',
167 'description': 'md5:c5c9b572388a99b2690030afa3f3bad7',
168 'thumbnail': r're:^https?://.*\.jpg$',
169 'duration': 118.24,
170 },
171 'params': {
172 'skip_download': True,
173 },
174 'expected_warnings': ['is not a supported codec'],
175 }, {
176 'url': 'https://www.canvas.be/check-point/najaar-2016/de-politie-uw-vriend',
177 'only_matching': True,
178 }]
179
180 def _real_extract(self, url):
181 mobj = re.match(self._VALID_URL, url)
182 site_id, display_id = mobj.group('site_id'), mobj.group('id')
183
184 webpage = self._download_webpage(url, display_id)
185
186 title = strip_or_none(self._search_regex(
187 r'<h1[^>]+class="video__body__header__title"[^>]*>(.+?)</h1>',
188 webpage, 'title', default=None) or self._og_search_title(
189 webpage, default=None))
190
191 video_id = self._html_search_regex(
192 r'data-video=(["\'])(?P<id>(?:(?!\1).)+)\1', webpage, 'video id',
193 group='id')
194
195 return {
196 '_type': 'url_transparent',
197 'url': 'https://mediazone.vrt.be/api/v1/%s/assets/%s' % (site_id, video_id),
198 'ie_key': CanvasIE.ie_key(),
199 'id': video_id,
200 'display_id': display_id,
201 'title': title,
202 'description': self._og_search_description(webpage),
203 }
204
205
206 class VrtNUIE(GigyaBaseIE):
207 IE_DESC = 'VrtNU.be'
208 _VALID_URL = r'https?://(?:www\.)?vrt\.be/(?P<site_id>vrtnu)/(?:[^/]+/)*(?P<id>[^/?#&]+)'
209 _TESTS = [{
210 # Available via old API endpoint
211 'url': 'https://www.vrt.be/vrtnu/a-z/postbus-x/1/postbus-x-s1a1/',
212 'info_dict': {
213 'id': 'pbs-pub-2e2d8c27-df26-45c9-9dc6-90c78153044d$vid-90c932b1-e21d-4fb8-99b1-db7b49cf74de',
214 'ext': 'mp4',
215 'title': 'De zwarte weduwe',
216 'description': 'md5:db1227b0f318c849ba5eab1fef895ee4',
217 'duration': 1457.04,
218 'thumbnail': r're:^https?://.*\.jpg$',
219 'season': 'Season 1',
220 'season_number': 1,
221 'episode_number': 1,
222 },
223 'skip': 'This video is only available for registered users',
224 'params': {
225 'username': '<snip>',
226 'password': '<snip>',
227 },
228 'expected_warnings': ['is not a supported codec'],
229 }, {
230 # Only available via new API endpoint
231 'url': 'https://www.vrt.be/vrtnu/a-z/kamp-waes/1/kamp-waes-s1a5/',
232 'info_dict': {
233 'id': 'pbs-pub-0763b56c-64fb-4d38-b95b-af60bf433c71$vid-ad36a73c-4735-4f1f-b2c0-a38e6e6aa7e1',
234 'ext': 'mp4',
235 'title': 'Aflevering 5',
236 'description': 'Wie valt door de mand tijdens een missie?',
237 'duration': 2967.06,
238 'season': 'Season 1',
239 'season_number': 1,
240 'episode_number': 5,
241 },
242 'skip': 'This video is only available for registered users',
243 'params': {
244 'username': '<snip>',
245 'password': '<snip>',
246 },
247 'expected_warnings': ['Unable to download asset JSON', 'is not a supported codec', 'Unknown MIME type'],
248 }]
249 _NETRC_MACHINE = 'vrtnu'
250 _APIKEY = '3_0Z2HujMtiWq_pkAjgnS2Md2E11a1AwZjYiBETtwNE-EoEHDINgtnvcAOpNgmrVGy'
251 _CONTEXT_ID = 'R3595707040'
252
253 def _real_initialize(self):
254 self._login()
255
256 def _login(self):
257 username, password = self._get_login_info()
258 if username is None:
259 return
260
261 auth_data = {
262 'APIKey': self._APIKEY,
263 'targetEnv': 'jssdk',
264 'loginID': username,
265 'password': password,
266 'authMode': 'cookie',
267 }
268
269 auth_info = self._gigya_login(auth_data)
270
271 # Sometimes authentication fails for no good reason, retry
272 login_attempt = 1
273 while login_attempt <= 3:
274 try:
275 # When requesting a token, no actual token is returned, but the
276 # necessary cookies are set.
277 self._request_webpage(
278 'https://token.vrt.be',
279 None, note='Requesting a token', errnote='Could not get a token',
280 headers={
281 'Content-Type': 'application/json',
282 'Referer': 'https://www.vrt.be/vrtnu/',
283 },
284 data=json.dumps({
285 'uid': auth_info['UID'],
286 'uidsig': auth_info['UIDSignature'],
287 'ts': auth_info['signatureTimestamp'],
288 'email': auth_info['profile']['email'],
289 }).encode('utf-8'))
290 except ExtractorError as e:
291 if isinstance(e.cause, compat_HTTPError) and e.cause.code == 401:
292 login_attempt += 1
293 self.report_warning('Authentication failed')
294 self._sleep(1, None, msg_template='Waiting for %(timeout)s seconds before trying again')
295 else:
296 raise e
297 else:
298 break
299
300 def _real_extract(self, url):
301 display_id = self._match_id(url)
302
303 webpage, urlh = self._download_webpage_handle(url, display_id)
304
305 info = self._search_json_ld(webpage, display_id, default={})
306
307 # title is optional here since it may be extracted by extractor
308 # that is delegated from here
309 title = strip_or_none(self._html_search_regex(
310 r'(?ms)<h1 class="content__heading">(.+?)</h1>',
311 webpage, 'title', default=None))
312
313 description = self._html_search_regex(
314 r'(?ms)<div class="content__description">(.+?)</div>',
315 webpage, 'description', default=None)
316
317 season = self._html_search_regex(
318 [r'''(?xms)<div\ class="tabs__tab\ tabs__tab--active">\s*
319 <span>seizoen\ (.+?)</span>\s*
320 </div>''',
321 r'<option value="seizoen (\d{1,3})" data-href="[^"]+?" selected>'],
322 webpage, 'season', default=None)
323
324 season_number = int_or_none(season)
325
326 episode_number = int_or_none(self._html_search_regex(
327 r'''(?xms)<div\ class="content__episode">\s*
328 <abbr\ title="aflevering">afl</abbr>\s*<span>(\d+)</span>
329 </div>''',
330 webpage, 'episode_number', default=None))
331
332 release_date = parse_iso8601(self._html_search_regex(
333 r'(?ms)<div class="content__broadcastdate">\s*<time\ datetime="(.+?)"',
334 webpage, 'release_date', default=None))
335
336 # If there's a ? or a # in the URL, remove them and everything after
337 clean_url = urlh.geturl().split('?')[0].split('#')[0].strip('/')
338 securevideo_url = clean_url + '.mssecurevideo.json'
339
340 try:
341 video = self._download_json(securevideo_url, display_id)
342 except ExtractorError as e:
343 if isinstance(e.cause, compat_HTTPError) and e.cause.code == 401:
344 self.raise_login_required()
345 raise
346
347 # We are dealing with a '../<show>.relevant' URL
348 redirect_url = video.get('url')
349 if redirect_url:
350 return self.url_result(self._proto_relative_url(redirect_url, 'https:'))
351
352 # There is only one entry, but with an unknown key, so just get
353 # the first one
354 video_id = list(video.values())[0].get('videoid')
355
356 return merge_dicts(info, {
357 '_type': 'url_transparent',
358 'url': 'https://mediazone.vrt.be/api/v1/vrtvideo/assets/%s' % video_id,
359 'ie_key': CanvasIE.ie_key(),
360 'id': video_id,
361 'display_id': display_id,
362 'title': title,
363 'description': description,
364 'season': season,
365 'season_number': season_number,
366 'episode_number': episode_number,
367 'release_date': release_date,
368 })