]> jfr.im git - yt-dlp.git/blob - yt_dlp/extractor/cbc.py
[FormatSort] `eac3` is better than `ac3`
[yt-dlp.git] / yt_dlp / extractor / cbc.py
1 # coding: utf-8
2 from __future__ import unicode_literals
3
4 import re
5 import json
6 import base64
7 import time
8
9 from .common import InfoExtractor
10 from ..compat import (
11 compat_str,
12 )
13 from ..utils import (
14 js_to_json,
15 smuggle_url,
16 try_get,
17 orderedSet,
18 strip_or_none,
19 ExtractorError,
20 )
21
22
23 class CBCIE(InfoExtractor):
24 IE_NAME = 'cbc.ca'
25 _VALID_URL = r'https?://(?:www\.)?cbc\.ca/(?!player/)(?:[^/]+/)+(?P<id>[^/?#]+)'
26 _TESTS = [{
27 # with mediaId
28 'url': 'http://www.cbc.ca/22minutes/videos/clips-season-23/don-cherry-play-offs',
29 'md5': '97e24d09672fc4cf56256d6faa6c25bc',
30 'info_dict': {
31 'id': '2682904050',
32 'ext': 'mp4',
33 'title': 'Don Cherry – All-Stars',
34 'description': 'Don Cherry has a bee in his bonnet about AHL player John Scott because that guy’s got heart.',
35 'timestamp': 1454463000,
36 'upload_date': '20160203',
37 'uploader': 'CBCC-NEW',
38 },
39 'skip': 'Geo-restricted to Canada',
40 }, {
41 # with clipId, feed available via tpfeed.cbc.ca and feed.theplatform.com
42 'url': 'http://www.cbc.ca/22minutes/videos/22-minutes-update/22-minutes-update-episode-4',
43 'md5': '162adfa070274b144f4fdc3c3b8207db',
44 'info_dict': {
45 'id': '2414435309',
46 'ext': 'mp4',
47 'title': '22 Minutes Update: What Not To Wear Quebec',
48 'description': "This week's latest Canadian top political story is What Not To Wear Quebec.",
49 'upload_date': '20131025',
50 'uploader': 'CBCC-NEW',
51 'timestamp': 1382717907,
52 },
53 'skip': 'No longer available',
54 }, {
55 # with clipId, feed only available via tpfeed.cbc.ca
56 'url': 'http://www.cbc.ca/archives/entry/1978-robin-williams-freestyles-on-90-minutes-live',
57 'md5': '0274a90b51a9b4971fe005c63f592f12',
58 'info_dict': {
59 'id': '2487345465',
60 'ext': 'mp4',
61 'title': 'Robin Williams freestyles on 90 Minutes Live',
62 'description': 'Wacky American comedian Robin Williams shows off his infamous "freestyle" comedic talents while being interviewed on CBC\'s 90 Minutes Live.',
63 'upload_date': '19780210',
64 'uploader': 'CBCC-NEW',
65 'timestamp': 255977160,
66 },
67 }, {
68 # multiple iframes
69 'url': 'http://www.cbc.ca/natureofthings/blog/birds-eye-view-from-vancouvers-burrard-street-bridge-how-we-got-the-shot',
70 'playlist': [{
71 'md5': '377572d0b49c4ce0c9ad77470e0b96b4',
72 'info_dict': {
73 'id': '2680832926',
74 'ext': 'mp4',
75 'title': 'An Eagle\'s-Eye View Off Burrard Bridge',
76 'description': 'Hercules the eagle flies from Vancouver\'s Burrard Bridge down to a nearby park with a mini-camera strapped to his back.',
77 'upload_date': '20160201',
78 'timestamp': 1454342820,
79 'uploader': 'CBCC-NEW',
80 },
81 }, {
82 'md5': '415a0e3f586113894174dfb31aa5bb1a',
83 'info_dict': {
84 'id': '2658915080',
85 'ext': 'mp4',
86 'title': 'Fly like an eagle!',
87 'description': 'Eagle equipped with a mini camera flies from the world\'s tallest tower',
88 'upload_date': '20150315',
89 'timestamp': 1426443984,
90 'uploader': 'CBCC-NEW',
91 },
92 }],
93 'skip': 'Geo-restricted to Canada',
94 }, {
95 # multiple CBC.APP.Caffeine.initInstance(...)
96 'url': 'http://www.cbc.ca/news/canada/calgary/dog-indoor-exercise-winter-1.3928238',
97 'info_dict': {
98 'title': 'Keep Rover active during the deep freeze with doggie pushups and other fun indoor tasks',
99 'id': 'dog-indoor-exercise-winter-1.3928238',
100 'description': 'md5:c18552e41726ee95bd75210d1ca9194c',
101 },
102 'playlist_mincount': 6,
103 }]
104
105 @classmethod
106 def suitable(cls, url):
107 return False if CBCPlayerIE.suitable(url) else super(CBCIE, cls).suitable(url)
108
109 def _extract_player_init(self, player_init, display_id):
110 player_info = self._parse_json(player_init, display_id, js_to_json)
111 media_id = player_info.get('mediaId')
112 if not media_id:
113 clip_id = player_info['clipId']
114 feed = self._download_json(
115 'http://tpfeed.cbc.ca/f/ExhSPC/vms_5akSXx4Ng_Zn?byCustomValue={:mpsReleases}{%s}' % clip_id,
116 clip_id, fatal=False)
117 if feed:
118 media_id = try_get(feed, lambda x: x['entries'][0]['guid'], compat_str)
119 if not media_id:
120 media_id = self._download_json(
121 'http://feed.theplatform.com/f/h9dtGB/punlNGjMlc1F?fields=id&byContent=byReleases%3DbyId%253D' + clip_id,
122 clip_id)['entries'][0]['id'].split('/')[-1]
123 return self.url_result('cbcplayer:%s' % media_id, 'CBCPlayer', media_id)
124
125 def _real_extract(self, url):
126 display_id = self._match_id(url)
127 webpage = self._download_webpage(url, display_id)
128 title = self._og_search_title(webpage, default=None) or self._html_search_meta(
129 'twitter:title', webpage, 'title', default=None) or self._html_search_regex(
130 r'<title>([^<]+)</title>', webpage, 'title', fatal=False)
131 entries = [
132 self._extract_player_init(player_init, display_id)
133 for player_init in re.findall(r'CBC\.APP\.Caffeine\.initInstance\(({.+?})\);', webpage)]
134 media_ids = []
135 for media_id_re in (
136 r'<iframe[^>]+src="[^"]+?mediaId=(\d+)"',
137 r'<div[^>]+\bid=["\']player-(\d+)',
138 r'guid["\']\s*:\s*["\'](\d+)'):
139 media_ids.extend(re.findall(media_id_re, webpage))
140 entries.extend([
141 self.url_result('cbcplayer:%s' % media_id, 'CBCPlayer', media_id)
142 for media_id in orderedSet(media_ids)])
143 return self.playlist_result(
144 entries, display_id, strip_or_none(title),
145 self._og_search_description(webpage))
146
147
148 class CBCPlayerIE(InfoExtractor):
149 IE_NAME = 'cbc.ca:player'
150 _VALID_URL = r'(?:cbcplayer:|https?://(?:www\.)?cbc\.ca/(?:player/play/|i/caffeine/syndicate/\?mediaId=))(?P<id>\d+)'
151 _TESTS = [{
152 'url': 'http://www.cbc.ca/player/play/2683190193',
153 'md5': '64d25f841ddf4ddb28a235338af32e2c',
154 'info_dict': {
155 'id': '2683190193',
156 'ext': 'mp4',
157 'title': 'Gerry Runs a Sweat Shop',
158 'description': 'md5:b457e1c01e8ff408d9d801c1c2cd29b0',
159 'timestamp': 1455071400,
160 'upload_date': '20160210',
161 'uploader': 'CBCC-NEW',
162 },
163 'skip': 'Geo-restricted to Canada',
164 }, {
165 # Redirected from http://www.cbc.ca/player/AudioMobile/All%20in%20a%20Weekend%20Montreal/ID/2657632011/
166 'url': 'http://www.cbc.ca/player/play/2657631896',
167 'md5': 'e5e708c34ae6fca156aafe17c43e8b75',
168 'info_dict': {
169 'id': '2657631896',
170 'ext': 'mp3',
171 'title': 'CBC Montreal is organizing its first ever community hackathon!',
172 'description': 'The modern technology we tend to depend on so heavily, is never without it\'s share of hiccups and headaches. Next weekend - CBC Montreal will be getting members of the public for its first Hackathon.',
173 'timestamp': 1425704400,
174 'upload_date': '20150307',
175 'uploader': 'CBCC-NEW',
176 },
177 }, {
178 'url': 'http://www.cbc.ca/player/play/2164402062',
179 'md5': '33fcd8f6719b9dd60a5e73adcb83b9f6',
180 'info_dict': {
181 'id': '2164402062',
182 'ext': 'mp4',
183 'title': 'Cancer survivor four times over',
184 'description': 'Tim Mayer has beaten three different forms of cancer four times in five years.',
185 'timestamp': 1320410746,
186 'upload_date': '20111104',
187 'uploader': 'CBCC-NEW',
188 },
189 }]
190
191 def _real_extract(self, url):
192 video_id = self._match_id(url)
193 return {
194 '_type': 'url_transparent',
195 'ie_key': 'ThePlatform',
196 'url': smuggle_url(
197 'http://link.theplatform.com/s/ExhSPC/media/guid/2655402169/%s?mbr=true&formats=MPEG4,FLV,MP3' % video_id, {
198 'force_smil_url': True
199 }),
200 'id': video_id,
201 }
202
203
204 class CBCGemIE(InfoExtractor):
205 IE_NAME = 'gem.cbc.ca'
206 _VALID_URL = r'https?://gem\.cbc\.ca/media/(?P<id>[0-9a-z-]+/s[0-9]+[a-z][0-9]+)'
207 _TESTS = [{
208 # This is a normal, public, TV show video
209 'url': 'https://gem.cbc.ca/media/schitts-creek/s06e01',
210 'md5': '93dbb31c74a8e45b378cf13bd3f6f11e',
211 'info_dict': {
212 'id': 'schitts-creek/s06e01',
213 'ext': 'mp4',
214 'title': 'Smoke Signals',
215 'description': 'md5:929868d20021c924020641769eb3e7f1',
216 'thumbnail': 'https://images.radio-canada.ca/v1/synps-cbc/episode/perso/cbc_schitts_creek_season_06e01_thumbnail_v01.jpg?im=Resize=(Size)',
217 'duration': 1314,
218 'categories': ['comedy'],
219 'series': 'Schitt\'s Creek',
220 'season': 'Season 6',
221 'season_number': 6,
222 'episode': 'Smoke Signals',
223 'episode_number': 1,
224 'episode_id': 'schitts-creek/s06e01',
225 },
226 'params': {'format': 'bv'},
227 'skip': 'Geo-restricted to Canada',
228 }, {
229 # This video requires an account in the browser, but works fine in yt-dlp
230 'url': 'https://gem.cbc.ca/media/schitts-creek/s01e01',
231 'md5': '297a9600f554f2258aed01514226a697',
232 'info_dict': {
233 'id': 'schitts-creek/s01e01',
234 'ext': 'mp4',
235 'title': 'The Cup Runneth Over',
236 'description': 'md5:9bca14ea49ab808097530eb05a29e797',
237 'thumbnail': 'https://images.radio-canada.ca/v1/synps-cbc/episode/perso/cbc_schitts_creek_season_01e01_thumbnail_v01.jpg?im=Resize=(Size)',
238 'series': 'Schitt\'s Creek',
239 'season_number': 1,
240 'season': 'Season 1',
241 'episode_number': 1,
242 'episode': 'The Cup Runneth Over',
243 'episode_id': 'schitts-creek/s01e01',
244 'duration': 1309,
245 'categories': ['comedy'],
246 },
247 'params': {'format': 'bv'},
248 'skip': 'Geo-restricted to Canada',
249 }]
250
251 _GEO_COUNTRIES = ['CA']
252 _TOKEN_API_KEY = '3f4beddd-2061-49b0-ae80-6f1f2ed65b37'
253 _NETRC_MACHINE = 'cbcgem'
254 _claims_token = None
255
256 def _new_claims_token(self, email, password):
257 data = json.dumps({
258 'email': email,
259 'password': password,
260 }).encode()
261 headers = {'content-type': 'application/json'}
262 query = {'apikey': self._TOKEN_API_KEY}
263 resp = self._download_json('https://api.loginradius.com/identity/v2/auth/login',
264 None, data=data, headers=headers, query=query)
265 access_token = resp['access_token']
266
267 query = {
268 'access_token': access_token,
269 'apikey': self._TOKEN_API_KEY,
270 'jwtapp': 'jwt',
271 }
272 resp = self._download_json('https://cloud-api.loginradius.com/sso/jwt/api/token',
273 None, headers=headers, query=query)
274 sig = resp['signature']
275
276 data = json.dumps({'jwt': sig}).encode()
277 headers = {'content-type': 'application/json', 'ott-device-type': 'web'}
278 resp = self._download_json('https://services.radio-canada.ca/ott/cbc-api/v2/token',
279 None, data=data, headers=headers)
280 cbc_access_token = resp['accessToken']
281
282 headers = {'content-type': 'application/json', 'ott-device-type': 'web', 'ott-access-token': cbc_access_token}
283 resp = self._download_json('https://services.radio-canada.ca/ott/cbc-api/v2/profile',
284 None, headers=headers)
285 return resp['claimsToken']
286
287 def _get_claims_token_expiry(self):
288 # Token is a JWT
289 # JWT is decoded here and 'exp' field is extracted
290 # It is a Unix timestamp for when the token expires
291 b64_data = self._claims_token.split('.')[1]
292 data = base64.urlsafe_b64decode(b64_data + "==")
293 return json.loads(data)['exp']
294
295 def claims_token_expired(self):
296 exp = self._get_claims_token_expiry()
297 if exp - time.time() < 10:
298 # It will expire in less than 10 seconds, or has already expired
299 return True
300 return False
301
302 def claims_token_valid(self):
303 return self._claims_token is not None and not self.claims_token_expired()
304
305 def _get_claims_token(self, email, password):
306 if not self.claims_token_valid():
307 self._claims_token = self._new_claims_token(email, password)
308 self._downloader.cache.store(self._NETRC_MACHINE, 'claims_token', self._claims_token)
309 return self._claims_token
310
311 def _real_initialize(self):
312 if self.claims_token_valid():
313 return
314 self._claims_token = self._downloader.cache.load(self._NETRC_MACHINE, 'claims_token')
315
316 def _real_extract(self, url):
317 video_id = self._match_id(url)
318 video_info = self._download_json('https://services.radio-canada.ca/ott/cbc-api/v2/assets/' + video_id, video_id)
319
320 email, password = self._get_login_info()
321 if email and password:
322 claims_token = self._get_claims_token(email, password)
323 headers = {'x-claims-token': claims_token}
324 else:
325 headers = {}
326 m3u8_info = self._download_json(video_info['playSession']['url'], video_id, headers=headers)
327 m3u8_url = m3u8_info.get('url')
328
329 if m3u8_info.get('errorCode') == 1:
330 self.raise_geo_restricted(countries=['CA'])
331 elif m3u8_info.get('errorCode') == 35:
332 self.raise_login_required(method='password')
333 elif m3u8_info.get('errorCode') != 0:
334 raise ExtractorError(f'{self.IE_NAME} said: {m3u8_info.get("errorCode")} - {m3u8_info.get("message")}')
335
336 formats = self._extract_m3u8_formats(m3u8_url, video_id, m3u8_id='hls')
337 self._remove_duplicate_formats(formats)
338
339 for format in formats:
340 if format.get('vcodec') == 'none':
341 if format.get('ext') is None:
342 format['ext'] = 'm4a'
343 if format.get('acodec') is None:
344 format['acodec'] = 'mp4a.40.2'
345
346 # Put described audio at the beginning of the list, so that it
347 # isn't chosen by default, as most people won't want it.
348 if 'descriptive' in format['format_id'].lower():
349 format['preference'] = -2
350
351 self._sort_formats(formats)
352
353 return {
354 'id': video_id,
355 'title': video_info['title'],
356 'description': video_info.get('description'),
357 'thumbnail': video_info.get('image'),
358 'series': video_info.get('series'),
359 'season_number': video_info.get('season'),
360 'season': f'Season {video_info.get("season")}',
361 'episode_number': video_info.get('episode'),
362 'episode': video_info.get('title'),
363 'episode_id': video_id,
364 'duration': video_info.get('duration'),
365 'categories': [video_info.get('category')],
366 'formats': formats,
367 'release_timestamp': video_info.get('airDate'),
368 'timestamp': video_info.get('availableDate'),
369 }
370
371
372 class CBCGemPlaylistIE(InfoExtractor):
373 IE_NAME = 'gem.cbc.ca:playlist'
374 _VALID_URL = r'https?://gem\.cbc\.ca/media/(?P<id>(?P<show>[0-9a-z-]+)/s(?P<season>[0-9]+))/?(?:[?#]|$)'
375 _TESTS = [{
376 # TV show playlist, all public videos
377 'url': 'https://gem.cbc.ca/media/schitts-creek/s06',
378 'playlist_count': 16,
379 'info_dict': {
380 'id': 'schitts-creek/s06',
381 'title': 'Season 6',
382 'description': 'md5:6a92104a56cbeb5818cc47884d4326a2',
383 },
384 }]
385 _API_BASE = 'https://services.radio-canada.ca/ott/cbc-api/v2/shows/'
386
387 def _real_extract(self, url):
388 match = self._match_valid_url(url)
389 season_id = match.group('id')
390 show = match.group('show')
391 show_info = self._download_json(self._API_BASE + show, season_id)
392 season = int(match.group('season'))
393 season_info = try_get(show_info, lambda x: x['seasons'][season - 1])
394
395 if season_info is None:
396 raise ExtractorError(f'Couldn\'t find season {season} of {show}')
397
398 episodes = []
399 for episode in season_info['assets']:
400 episodes.append({
401 '_type': 'url_transparent',
402 'ie_key': 'CBCGem',
403 'url': 'https://gem.cbc.ca/media/' + episode['id'],
404 'id': episode['id'],
405 'title': episode.get('title'),
406 'description': episode.get('description'),
407 'thumbnail': episode.get('image'),
408 'series': episode.get('series'),
409 'season_number': episode.get('season'),
410 'season': season_info['title'],
411 'season_id': season_info.get('id'),
412 'episode_number': episode.get('episode'),
413 'episode': episode.get('title'),
414 'episode_id': episode['id'],
415 'duration': episode.get('duration'),
416 'categories': [episode.get('category')],
417 })
418
419 thumbnail = None
420 tn_uri = season_info.get('image')
421 # the-national was observed to use a "data:image/png;base64"
422 # URI for their 'image' value. The image was 1x1, and is
423 # probably just a placeholder, so it is ignored.
424 if tn_uri is not None and not tn_uri.startswith('data:'):
425 thumbnail = tn_uri
426
427 return {
428 '_type': 'playlist',
429 'entries': episodes,
430 'id': season_id,
431 'title': season_info['title'],
432 'description': season_info.get('description'),
433 'thumbnail': thumbnail,
434 'series': show_info.get('title'),
435 'season_number': season_info.get('season'),
436 'season': season_info['title'],
437 }
438
439
440 class CBCGemLiveIE(InfoExtractor):
441 IE_NAME = 'gem.cbc.ca:live'
442 _VALID_URL = r'https?://gem\.cbc\.ca/live/(?P<id>\d+)'
443 _TEST = {
444 'url': 'https://gem.cbc.ca/live/920604739687',
445 'info_dict': {
446 'title': 'Ottawa',
447 'description': 'The live TV channel and local programming from Ottawa',
448 'thumbnail': 'https://thumbnails.cbc.ca/maven_legacy/thumbnails/CBC_OTT_VMS/Live_Channel_Static_Images/Ottawa_2880x1620.jpg',
449 'is_live': True,
450 'id': 'AyqZwxRqh8EH',
451 'ext': 'mp4',
452 'timestamp': 1492106160,
453 'upload_date': '20170413',
454 'uploader': 'CBCC-NEW',
455 },
456 'skip': 'Live might have ended',
457 }
458
459 # It's unclear where the chars at the end come from, but they appear to be
460 # constant. Might need updating in the future.
461 # There are two URLs, some livestreams are in one, and some
462 # in the other. The JSON schema is the same for both.
463 _API_URLS = ['https://tpfeed.cbc.ca/f/ExhSPC/t_t3UKJR6MAT', 'https://tpfeed.cbc.ca/f/ExhSPC/FNiv9xQx_BnT']
464
465 def _real_extract(self, url):
466 video_id = self._match_id(url)
467
468 for api_url in self._API_URLS:
469 video_info = next((
470 stream for stream in self._download_json(api_url, video_id)['entries']
471 if stream.get('guid') == video_id), None)
472 if video_info:
473 break
474 else:
475 raise ExtractorError('Couldn\'t find video metadata, maybe this livestream is now offline', expected=True)
476
477 return {
478 '_type': 'url_transparent',
479 'ie_key': 'ThePlatform',
480 'url': video_info['content'][0]['url'],
481 'id': video_id,
482 'title': video_info.get('title'),
483 'description': video_info.get('description'),
484 'tags': try_get(video_info, lambda x: x['keywords'].split(', ')),
485 'thumbnail': video_info.get('cbc$staticImage'),
486 'is_live': True,
487 }