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