[canvas] Add support for vrt.be/vrtnu (closes #11873)
[youtube-dl] / 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
9
10 from ..compat import compat_HTTPError
11 from ..utils import (
12     ExtractorError,
13     strip_or_none,
14     float_or_none,
15     int_or_none,
16     parse_iso8601,
17 )
18
19
20 class CanvasIE(InfoExtractor):
21     _VALID_URL = r'https?://mediazone\.vrt\.be/api/v1/(?P<site_id>canvas|een|ketnet|vrtvideo)/assets/(?P<id>[^/?#&]+)'
22     _TESTS = [{
23         'url': 'https://mediazone.vrt.be/api/v1/ketnet/assets/md-ast-4ac54990-ce66-4d00-a8ca-9eac86f4c475',
24         'md5': '90139b746a0a9bd7bb631283f6e2a64e',
25         'info_dict': {
26             'id': 'md-ast-4ac54990-ce66-4d00-a8ca-9eac86f4c475',
27             'display_id': 'md-ast-4ac54990-ce66-4d00-a8ca-9eac86f4c475',
28             'ext': 'flv',
29             'title': 'Nachtwacht: De Greystook',
30             'description': 'md5:1db3f5dc4c7109c821261e7512975be7',
31             'thumbnail': r're:^https?://.*\.jpg$',
32             'duration': 1468.03,
33         },
34         'expected_warnings': ['is not a supported codec', 'Unknown MIME type'],
35     }, {
36         'url': 'https://mediazone.vrt.be/api/v1/canvas/assets/mz-ast-5e5f90b6-2d72-4c40-82c2-e134f884e93e',
37         'only_matching': True,
38     }]
39
40     def _real_extract(self, url):
41         mobj = re.match(self._VALID_URL, url)
42         site_id, video_id = mobj.group('site_id'), mobj.group('id')
43
44         data = self._download_json(
45             'https://mediazone.vrt.be/api/v1/%s/assets/%s'
46             % (site_id, video_id), video_id)
47
48         title = data['title']
49         description = data.get('description')
50
51         formats = []
52         for target in data['targetUrls']:
53             format_url, format_type = target.get('url'), target.get('type')
54             if not format_url or not format_type:
55                 continue
56             if format_type == 'HLS':
57                 formats.extend(self._extract_m3u8_formats(
58                     format_url, video_id, 'mp4', entry_protocol='m3u8_native',
59                     m3u8_id=format_type, fatal=False))
60             elif format_type == 'HDS':
61                 formats.extend(self._extract_f4m_formats(
62                     format_url, video_id, f4m_id=format_type, fatal=False))
63             elif format_type == 'MPEG_DASH':
64                 formats.extend(self._extract_mpd_formats(
65                     format_url, video_id, mpd_id=format_type, fatal=False))
66             elif format_type == 'HSS':
67                 formats.extend(self._extract_ism_formats(
68                     format_url, video_id, ism_id='mss', fatal=False))
69             else:
70                 formats.append({
71                     'format_id': format_type,
72                     'url': format_url,
73                 })
74         self._sort_formats(formats)
75
76         subtitles = {}
77         subtitle_urls = data.get('subtitleUrls')
78         if isinstance(subtitle_urls, list):
79             for subtitle in subtitle_urls:
80                 subtitle_url = subtitle.get('url')
81                 if subtitle_url and subtitle.get('type') == 'CLOSED':
82                     subtitles.setdefault('nl', []).append({'url': subtitle_url})
83
84         return {
85             'id': video_id,
86             'display_id': video_id,
87             'title': title,
88             'description': description,
89             'formats': formats,
90             'duration': float_or_none(data.get('duration'), 1000),
91             'thumbnail': data.get('posterImageUrl'),
92             'subtitles': subtitles,
93         }
94
95
96 class CanvasEenIE(InfoExtractor):
97     IE_DESC = 'canvas.be and een.be'
98     _VALID_URL = r'https?://(?:www\.)?(?P<site_id>canvas|een)\.be/(?:[^/]+/)*(?P<id>[^/?#&]+)'
99     _TESTS = [{
100         'url': 'http://www.canvas.be/video/de-afspraak/najaar-2015/de-afspraak-veilt-voor-de-warmste-week',
101         'md5': 'ed66976748d12350b118455979cca293',
102         'info_dict': {
103             'id': 'mz-ast-5e5f90b6-2d72-4c40-82c2-e134f884e93e',
104             'display_id': 'de-afspraak-veilt-voor-de-warmste-week',
105             'ext': 'flv',
106             'title': 'De afspraak veilt voor de Warmste Week',
107             'description': 'md5:24cb860c320dc2be7358e0e5aa317ba6',
108             'thumbnail': r're:^https?://.*\.jpg$',
109             'duration': 49.02,
110         },
111         'expected_warnings': ['is not a supported codec'],
112     }, {
113         # with subtitles
114         'url': 'http://www.canvas.be/video/panorama/2016/pieter-0167',
115         'info_dict': {
116             'id': 'mz-ast-5240ff21-2d30-4101-bba6-92b5ec67c625',
117             'display_id': 'pieter-0167',
118             'ext': 'mp4',
119             'title': 'Pieter 0167',
120             'description': 'md5:943cd30f48a5d29ba02c3a104dc4ec4e',
121             'thumbnail': r're:^https?://.*\.jpg$',
122             'duration': 2553.08,
123             'subtitles': {
124                 'nl': [{
125                     'ext': 'vtt',
126                 }],
127             },
128         },
129         'params': {
130             'skip_download': True,
131         },
132         'skip': 'Pagina niet gevonden',
133     }, {
134         'url': 'https://www.een.be/sorry-voor-alles/herbekijk-sorry-voor-alles',
135         'info_dict': {
136             'id': 'mz-ast-11a587f8-b921-4266-82e2-0bce3e80d07f',
137             'display_id': 'herbekijk-sorry-voor-alles',
138             'ext': 'mp4',
139             'title': 'Herbekijk Sorry voor alles',
140             'description': 'md5:8bb2805df8164e5eb95d6a7a29dc0dd3',
141             'thumbnail': r're:^https?://.*\.jpg$',
142             'duration': 3788.06,
143         },
144         'params': {
145             'skip_download': True,
146         },
147         'skip': 'Episode no longer available',
148     }, {
149         'url': 'https://www.canvas.be/check-point/najaar-2016/de-politie-uw-vriend',
150         'only_matching': True,
151     }]
152
153     def _real_extract(self, url):
154         mobj = re.match(self._VALID_URL, url)
155         site_id, display_id = mobj.group('site_id'), mobj.group('id')
156
157         webpage = self._download_webpage(url, display_id)
158
159         title = strip_or_none(self._search_regex(
160             r'<h1[^>]+class="video__body__header__title"[^>]*>(.+?)</h1>',
161             webpage, 'title', default=None) or self._og_search_title(
162             webpage, default=None))
163
164         video_id = self._html_search_regex(
165             r'data-video=(["\'])(?P<id>(?:(?!\1).)+)\1', webpage, 'video id',
166             group='id')
167
168         return {
169             '_type': 'url_transparent',
170             'url': 'https://mediazone.vrt.be/api/v1/%s/assets/%s' % (site_id, video_id),
171             'ie_key': CanvasIE.ie_key(),
172             'id': video_id,
173             'display_id': display_id,
174             'title': title,
175             'description': self._og_search_description(webpage),
176         }
177
178
179 class VrtNUIE(GigyaBaseIE):
180     IE_DESC = 'VrtNU.be'
181     _VALID_URL = r'https?://(?:www\.)?vrt\.be/(?P<site_id>vrtnu)/(?:[^/]+/)*(?P<id>[^/?#&]+)'
182     _TESTS = [{
183         'url': 'https://www.vrt.be/vrtnu/a-z/postbus-x/1/postbus-x-s1a1/',
184         'info_dict': {
185             'id': 'pbs-pub-2e2d8c27-df26-45c9-9dc6-90c78153044d$vid-90c932b1-e21d-4fb8-99b1-db7b49cf74de',
186             'ext': 'flv',
187             'title': 'De zwarte weduwe',
188             'description': 'md5:d90c21dced7db869a85db89a623998d4',
189             'duration': 1457.04,
190             'thumbnail': r're:^https?://.*\.jpg$',
191             'season': '1',
192             'season_number': 1,
193             'episode_number': 1,
194         },
195         # 'skip': 'This video is only available for registered users'
196     }]
197     _NETRC_MACHINE = 'vrtnu'
198     _APIKEY = '3_0Z2HujMtiWq_pkAjgnS2Md2E11a1AwZjYiBETtwNE-EoEHDINgtnvcAOpNgmrVGy'
199     _CONTEXT_ID = 'R3595707040'
200
201     def _real_initialize(self):
202         self._login()
203
204     def _login(self):
205         username, password = self._get_login_info()
206         if username is None:
207             self.raise_login_required()
208
209         auth_data = {
210             'APIKey': self._APIKEY,
211             'targetEnv': 'jssdk',
212             'loginID': username,
213             'password': password,
214             'authMode': 'cookie',
215         }
216
217         auth_info = self._gigya_login(auth_data)
218
219         # Sometimes authentication fails for no good reason, retry
220         login_attempt = 1
221         while login_attempt <= 3:
222             try:
223                 # When requesting a token, no actual token is returned, but the
224                 # necessary cookies are set.
225                 self._request_webpage(
226                     'https://token.vrt.be',
227                     None, note='Requesting a token', errnote='Could not get a token',
228                     headers={
229                         'Content-Type': 'application/json',
230                         'Referer': 'https://www.vrt.be/vrtnu/',
231                     },
232                     data=json.dumps({
233                         'uid': auth_info['UID'],
234                         'uidsig': auth_info['UIDSignature'],
235                         'ts': auth_info['signatureTimestamp'],
236                         'email': auth_info['profile']['email'],
237                     }).encode('utf-8'))
238             except ExtractorError as e:
239                 if isinstance(e.cause, compat_HTTPError) and e.cause.code == 401:
240                     login_attempt += 1
241                     self.report_warning('Authentication failed')
242                     self._sleep(1, None, msg_template='Waiting for %(timeout)s seconds before trying again')
243                 else:
244                     raise e
245             else:
246                 break
247
248     def _real_extract(self, url):
249         display_id = self._match_id(url)
250
251         webpage = self._download_webpage(url, display_id)
252
253         title = self._html_search_regex(
254             r'(?ms)<h1 class="content__heading">(.+?)</h1>',
255             webpage, 'title').strip()
256
257         description = self._html_search_regex(
258             r'(?ms)<div class="content__description">(.+?)</div>',
259             webpage, 'description', default=None)
260
261         season = self._html_search_regex(
262             [r'''(?xms)<div\ class="tabs__tab\ tabs__tab--active">\s*
263                     <span>seizoen\ (.+?)</span>\s*
264                 </div>''',
265              r'<option value="seizoen (\d{1,3})" data-href="[^"]+?" selected>'],
266             webpage, 'season', default=None)
267
268         season_number = int_or_none(season)
269
270         episode_number = int_or_none(self._html_search_regex(
271             r'''(?xms)<div\ class="content__episode">\s*
272                     <abbr\ title="aflevering">afl</abbr>\s*<span>(\d+)</span>
273                 </div>''',
274             webpage, 'episode_number', default=None))
275
276         release_date = parse_iso8601(self._html_search_regex(
277             r'(?ms)<div class="content__broadcastdate">\s*<time\ datetime="(.+?)"',
278             webpage, 'release_date', default=None))
279
280         # If there's a ? or a # in the URL, remove them and everything after
281         clean_url = url.split('?')[0].split('#')[0].strip('/')
282         securevideo_url = clean_url + '.mssecurevideo.json'
283
284         json = self._download_json(securevideo_url, display_id)
285         # We are dealing with a '../<show>.relevant' URL
286         redirect_url = json.get('url')
287         if redirect_url:
288             return self.url_result('https:' + redirect_url)
289         else:
290             # There is only one entry, but with an unknown key, so just get
291             # the first one
292             video_id = list(json.values())[0].get('videoid')
293
294         return {
295             '_type': 'url_transparent',
296             'url': 'https://mediazone.vrt.be/api/v1/vrtvideo/assets/%s' % video_id,
297             'ie_key': CanvasIE.ie_key(),
298             'id': video_id,
299             'display_id': display_id,
300             'title': title,
301             'description': description,
302             'season': season,
303             'season_number': season_number,
304             'episode_number': episode_number,
305             'release_date': release_date,
306         }