]> jfr.im git - yt-dlp.git/blame - youtube_dl/extractor/canvas.py
pull changes from remote master (#190)
[yt-dlp.git] / youtube_dl / extractor / canvas.py
CommitLineData
be2d40a5
TG
1from __future__ import unicode_literals
2
bb5ebd44 3import re
7913e0fc 4import json
bb5ebd44 5
be2d40a5 6from .common import InfoExtractor
7913e0fc 7from .gigya import GigyaBaseIE
7913e0fc 8from ..compat import compat_HTTPError
117589df 9from ..utils import (
7913e0fc 10 ExtractorError,
117589df 11 strip_or_none,
7913e0fc 12 float_or_none,
13 int_or_none,
fd62b366 14 merge_dicts,
7913e0fc 15 parse_iso8601,
b827ee92
AG
16 str_or_none,
17 url_or_none,
117589df 18)
be2d40a5
TG
19
20
21class CanvasIE(InfoExtractor):
170d6444 22 _VALID_URL = r'https?://mediazone\.vrt\.be/api/v1/(?P<site_id>canvas|een|ketnet|vrt(?:video|nieuws)|sporza)/assets/(?P<id>[^/?#&]+)'
117589df
S
23 _TESTS = [{
24 'url': 'https://mediazone.vrt.be/api/v1/ketnet/assets/md-ast-4ac54990-ce66-4d00-a8ca-9eac86f4c475',
b827ee92 25 'md5': '68993eda72ef62386a15ea2cf3c93107',
117589df
S
26 'info_dict': {
27 'id': 'md-ast-4ac54990-ce66-4d00-a8ca-9eac86f4c475',
28 'display_id': 'md-ast-4ac54990-ce66-4d00-a8ca-9eac86f4c475',
b827ee92 29 'ext': 'mp4',
117589df 30 'title': 'Nachtwacht: De Greystook',
b827ee92 31 'description': 'Nachtwacht: De Greystook',
117589df 32 'thumbnail': r're:^https?://.*\.jpg$',
b827ee92 33 'duration': 1468.04,
117589df
S
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 }]
170d6444
RA
40 _HLS_ENTRY_PROTOCOLS_MAP = {
41 'HLS': 'm3u8_native',
42 'HLS_AES': 'm3u8',
43 }
b827ee92 44 _REST_API_BASE = 'https://media-services-public.vrt.be/vualto-video-aggregator-web/rest/external/v1'
117589df
S
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
b827ee92 50 # Old API endpoint, serves more formats but may fail for some videos
117589df
S
51 data = self._download_json(
52 'https://mediazone.vrt.be/api/v1/%s/assets/%s'
b827ee92
AG
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)
117589df
S
73
74 title = data['title']
75 description = data.get('description')
76
77 formats = []
78 for target in data['targetUrls']:
b827ee92 79 format_url, format_type = url_or_none(target.get('url')), str_or_none(target.get('type'))
117589df
S
80 if not format_url or not format_type:
81 continue
b827ee92 82 format_type = format_type.upper()
170d6444 83 if format_type in self._HLS_ENTRY_PROTOCOLS_MAP:
117589df 84 formats.extend(self._extract_m3u8_formats(
170d6444 85 format_url, video_id, 'mp4', self._HLS_ENTRY_PROTOCOLS_MAP[format_type],
117589df
S
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
123class CanvasEenIE(InfoExtractor):
41b263ac 124 IE_DESC = 'canvas.be and een.be'
bb5ebd44 125 _VALID_URL = r'https?://(?:www\.)?(?P<site_id>canvas|een)\.be/(?:[^/]+/)*(?P<id>[^/?#&]+)'
6eff2605 126 _TESTS = [{
be2d40a5 127 'url': 'http://www.canvas.be/video/de-afspraak/najaar-2015/de-afspraak-veilt-voor-de-warmste-week',
117589df 128 'md5': 'ed66976748d12350b118455979cca293',
be2d40a5 129 'info_dict': {
4e2743ab
S
130 'id': 'mz-ast-5e5f90b6-2d72-4c40-82c2-e134f884e93e',
131 'display_id': 'de-afspraak-veilt-voor-de-warmste-week',
117589df 132 'ext': 'flv',
4e2743ab
S
133 'title': 'De afspraak veilt voor de Warmste Week',
134 'description': 'md5:24cb860c320dc2be7358e0e5aa317ba6',
ec85ded8 135 'thumbnail': r're:^https?://.*\.jpg$',
4e2743ab 136 'duration': 49.02,
117589df
S
137 },
138 'expected_warnings': ['is not a supported codec'],
6eff2605
S
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',
ec85ded8 148 'thumbnail': r're:^https?://.*\.jpg$',
6eff2605
S
149 'duration': 2553.08,
150 'subtitles': {
151 'nl': [{
152 'ext': 'vtt',
153 }],
154 },
155 },
156 'params': {
157 'skip_download': True,
117589df
S
158 },
159 'skip': 'Pagina niet gevonden',
bb5ebd44 160 }, {
b827ee92 161 'url': 'https://www.een.be/thuis/emma-pakt-thilly-aan',
bb5ebd44 162 'info_dict': {
b827ee92
AG
163 'id': 'md-ast-3a24ced2-64d7-44fb-b4ed-ed1aafbf90b8',
164 'display_id': 'emma-pakt-thilly-aan',
bb5ebd44 165 'ext': 'mp4',
b827ee92
AG
166 'title': 'Emma pakt Thilly aan',
167 'description': 'md5:c5c9b572388a99b2690030afa3f3bad7',
ec85ded8 168 'thumbnail': r're:^https?://.*\.jpg$',
b827ee92 169 'duration': 118.24,
bb5ebd44
S
170 },
171 'params': {
172 'skip_download': True,
117589df 173 },
b827ee92 174 'expected_warnings': ['is not a supported codec'],
bb5ebd44
S
175 }, {
176 'url': 'https://www.canvas.be/check-point/najaar-2016/de-politie-uw-vriend',
177 'only_matching': True,
6eff2605 178 }]
be2d40a5
TG
179
180 def _real_extract(self, url):
bb5ebd44
S
181 mobj = re.match(self._VALID_URL, url)
182 site_id, display_id = mobj.group('site_id'), mobj.group('id')
be2d40a5 183
4e2743ab 184 webpage = self._download_webpage(url, display_id)
be2d40a5 185
117589df 186 title = strip_or_none(self._search_regex(
4e2743ab 187 r'<h1[^>]+class="video__body__header__title"[^>]*>(.+?)</h1>',
bb5ebd44 188 webpage, 'title', default=None) or self._og_search_title(
117589df 189 webpage, default=None))
4e2743ab
S
190
191 video_id = self._html_search_regex(
117589df
S
192 r'data-video=(["\'])(?P<id>(?:(?!\1).)+)\1', webpage, 'video id',
193 group='id')
4e2743ab 194
be2d40a5 195 return {
117589df
S
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(),
be2d40a5 199 'id': video_id,
4e2743ab 200 'display_id': display_id,
be2d40a5 201 'title': title,
4e2743ab 202 'description': self._og_search_description(webpage),
be2d40a5 203 }
7913e0fc 204
205
206class VrtNUIE(GigyaBaseIE):
207 IE_DESC = 'VrtNU.be'
208 _VALID_URL = r'https?://(?:www\.)?vrt\.be/(?P<site_id>vrtnu)/(?:[^/]+/)*(?P<id>[^/?#&]+)'
209 _TESTS = [{
b827ee92 210 # Available via old API endpoint
7913e0fc 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',
b827ee92 214 'ext': 'mp4',
7913e0fc 215 'title': 'De zwarte weduwe',
b827ee92 216 'description': 'md5:db1227b0f318c849ba5eab1fef895ee4',
7913e0fc 217 'duration': 1457.04,
218 'thumbnail': r're:^https?://.*\.jpg$',
b827ee92 219 'season': 'Season 1',
7913e0fc 220 'season_number': 1,
221 'episode_number': 1,
222 },
b827ee92
AG
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'],
7913e0fc 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:
b8c6ffc5 259 return
7913e0fc 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
64f34528 303 webpage, urlh = self._download_webpage_handle(url, display_id)
7913e0fc 304
fd62b366
S
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(
7913e0fc 310 r'(?ms)<h1 class="content__heading">(.+?)</h1>',
fd62b366 311 webpage, 'title', default=None))
7913e0fc 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
64f34528 337 clean_url = urlh.geturl().split('?')[0].split('#')[0].strip('/')
7913e0fc 338 securevideo_url = clean_url + '.mssecurevideo.json'
339
b8c6ffc5
S
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
7913e0fc 347 # We are dealing with a '../<show>.relevant' URL
b8c6ffc5 348 redirect_url = video.get('url')
7913e0fc 349 if redirect_url:
b8c6ffc5
S
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')
7913e0fc 355
fd62b366 356 return merge_dicts(info, {
7913e0fc 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,
fd62b366 368 })