[ie/dplay] Fix extractors (#10471)
[yt-dlp3.git] / yt_dlp / extractor / cbc.py
blob1522b08e25d520e83a614789f6acccaca9aa6ffb
1 import base64
2 import json
3 import re
4 import time
5 import urllib.parse
6 import xml.etree.ElementTree
8 from .common import InfoExtractor
9 from ..utils import (
10 ExtractorError,
11 int_or_none,
12 join_nonempty,
13 js_to_json,
14 orderedSet,
15 parse_iso8601,
16 smuggle_url,
17 strip_or_none,
18 traverse_obj,
19 try_get,
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',
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,
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,
67 'skip': '404 Not Found',
68 }, {
69 # multiple iframes
70 'url': 'http://www.cbc.ca/natureofthings/blog/birds-eye-view-from-vancouvers-burrard-street-bridge-how-we-got-the-shot',
71 'playlist': [{
72 'md5': '377572d0b49c4ce0c9ad77470e0b96b4',
73 'info_dict': {
74 'id': '2680832926',
75 'ext': 'mp4',
76 'title': 'An Eagle\'s-Eye View Off Burrard Bridge',
77 'description': 'Hercules the eagle flies from Vancouver\'s Burrard Bridge down to a nearby park with a mini-camera strapped to his back.',
78 'upload_date': '20160201',
79 'timestamp': 1454342820,
80 'uploader': 'CBCC-NEW',
82 }, {
83 'md5': '415a0e3f586113894174dfb31aa5bb1a',
84 'info_dict': {
85 'id': '2658915080',
86 'ext': 'mp4',
87 'title': 'Fly like an eagle!',
88 'description': 'Eagle equipped with a mini camera flies from the world\'s tallest tower',
89 'upload_date': '20150315',
90 'timestamp': 1426443984,
91 'uploader': 'CBCC-NEW',
93 }],
94 'skip': 'Geo-restricted to Canada',
95 }, {
96 # multiple CBC.APP.Caffeine.initInstance(...)
97 'url': 'http://www.cbc.ca/news/canada/calgary/dog-indoor-exercise-winter-1.3928238',
98 'info_dict': {
99 'title': 'Keep Rover active during the deep freeze with doggie pushups and other fun indoor tasks', # FIXME: actual title includes " | CBC News"
100 'id': 'dog-indoor-exercise-winter-1.3928238',
101 'description': 'md5:c18552e41726ee95bd75210d1ca9194c',
103 'playlist_mincount': 6,
106 @classmethod
107 def suitable(cls, url):
108 return False if CBCPlayerIE.suitable(url) else super().suitable(url)
110 def _extract_player_init(self, player_init, display_id):
111 player_info = self._parse_json(player_init, display_id, js_to_json)
112 media_id = player_info.get('mediaId')
113 if not media_id:
114 clip_id = player_info['clipId']
115 feed = self._download_json(
116 f'http://tpfeed.cbc.ca/f/ExhSPC/vms_5akSXx4Ng_Zn?byCustomValue={{:mpsReleases}}{{{clip_id}}}',
117 clip_id, fatal=False)
118 if feed:
119 media_id = try_get(feed, lambda x: x['entries'][0]['guid'], str)
120 if not media_id:
121 media_id = self._download_json(
122 'http://feed.theplatform.com/f/h9dtGB/punlNGjMlc1F?fields=id&byContent=byReleases%3DbyId%253D' + clip_id,
123 clip_id)['entries'][0]['id'].split('/')[-1]
124 return self.url_result(f'cbcplayer:{media_id}', 'CBCPlayer', media_id)
126 def _real_extract(self, url):
127 display_id = self._match_id(url)
128 webpage = self._download_webpage(url, display_id)
129 title = (self._og_search_title(webpage, default=None)
130 or self._html_search_meta('twitter:title', webpage, 'title', default=None)
131 or self._html_extract_title(webpage))
132 entries = [
133 self._extract_player_init(player_init, display_id)
134 for player_init in re.findall(r'CBC\.APP\.Caffeine\.initInstance\(({.+?})\);', webpage)]
135 media_ids = []
136 for media_id_re in (
137 r'<iframe[^>]+src="[^"]+?mediaId=(\d+)"',
138 r'<div[^>]+\bid=["\']player-(\d+)',
139 r'guid["\']\s*:\s*["\'](\d+)'):
140 media_ids.extend(re.findall(media_id_re, webpage))
141 entries.extend([
142 self.url_result(f'cbcplayer:{media_id}', 'CBCPlayer', media_id)
143 for media_id in orderedSet(media_ids)])
144 return self.playlist_result(
145 entries, display_id, strip_or_none(title),
146 self._og_search_description(webpage))
149 class CBCPlayerIE(InfoExtractor):
150 IE_NAME = 'cbc.ca:player'
151 _VALID_URL = r'(?:cbcplayer:|https?://(?:www\.)?cbc\.ca/(?:player/play/(?:video/)?|i/caffeine/syndicate/\?mediaId=))(?P<id>(?:\d\.)?\d+)'
152 _TESTS = [{
153 'url': 'http://www.cbc.ca/player/play/2683190193',
154 'md5': '64d25f841ddf4ddb28a235338af32e2c',
155 'info_dict': {
156 'id': '2683190193',
157 'ext': 'mp4',
158 'title': 'Gerry Runs a Sweat Shop',
159 'description': 'md5:b457e1c01e8ff408d9d801c1c2cd29b0',
160 'timestamp': 1455071400,
161 'upload_date': '20160210',
162 'uploader': 'CBCC-NEW',
164 'skip': 'Geo-restricted to Canada and no longer available',
165 }, {
166 'url': 'http://www.cbc.ca/i/caffeine/syndicate/?mediaId=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': 'md5:dd3b692f0a139b0369943150bd1c46a9',
173 'timestamp': 1425704400,
174 'upload_date': '20150307',
175 'uploader': 'CBCC-NEW',
176 'thumbnail': 'http://thumbnails.cbc.ca/maven_legacy/thumbnails/sonali-karnick-220.jpg',
177 'chapters': [],
178 'duration': 494.811,
179 'categories': ['AudioMobile/All in a Weekend Montreal'],
180 'tags': 'count:8',
181 'location': 'Quebec',
182 'series': 'All in a Weekend Montreal',
183 'season': 'Season 2015',
184 'season_number': 2015,
185 'media_type': 'Excerpt',
187 }, {
188 'url': 'http://www.cbc.ca/i/caffeine/syndicate/?mediaId=2164402062',
189 'md5': '33fcd8f6719b9dd60a5e73adcb83b9f6',
190 'info_dict': {
191 'id': '2164402062',
192 'ext': 'mp4',
193 'title': 'Cancer survivor four times over',
194 'description': 'Tim Mayer has beaten three different forms of cancer four times in five years.',
195 'timestamp': 1320410746,
196 'upload_date': '20111104',
197 'uploader': 'CBCC-NEW',
198 'thumbnail': 'https://thumbnails.cbc.ca/maven_legacy/thumbnails/277/67/cancer_852x480_2164412612.jpg',
199 'chapters': [],
200 'duration': 186.867,
201 'series': 'CBC News: Windsor at 6:00',
202 'categories': ['News/Canada/Windsor'],
203 'location': 'Windsor',
204 'tags': ['cancer'],
205 'creators': ['Allison Johnson'],
206 'media_type': 'Excerpt',
208 }, {
209 # Redirected from http://www.cbc.ca/player/AudioMobile/All%20in%20a%20Weekend%20Montreal/ID/2657632011/
210 'url': 'https://www.cbc.ca/player/play/1.2985700',
211 'md5': 'e5e708c34ae6fca156aafe17c43e8b75',
212 'info_dict': {
213 'id': '2657631896',
214 'ext': 'mp3',
215 'title': 'CBC Montreal is organizing its first ever community hackathon!',
216 '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.',
217 'timestamp': 1425704400,
218 'upload_date': '20150307',
219 'uploader': 'CBCC-NEW',
220 'thumbnail': 'http://thumbnails.cbc.ca/maven_legacy/thumbnails/sonali-karnick-220.jpg',
221 'chapters': [],
222 'duration': 494.811,
223 'categories': ['AudioMobile/All in a Weekend Montreal'],
224 'tags': 'count:8',
225 'location': 'Quebec',
226 'series': 'All in a Weekend Montreal',
227 'season': 'Season 2015',
228 'season_number': 2015,
229 'media_type': 'Excerpt',
231 }, {
232 'url': 'https://www.cbc.ca/player/play/1.1711287',
233 'md5': '33fcd8f6719b9dd60a5e73adcb83b9f6',
234 'info_dict': {
235 'id': '2164402062',
236 'ext': 'mp4',
237 'title': 'Cancer survivor four times over',
238 'description': 'Tim Mayer has beaten three different forms of cancer four times in five years.',
239 'timestamp': 1320410746,
240 'upload_date': '20111104',
241 'uploader': 'CBCC-NEW',
242 'thumbnail': 'https://thumbnails.cbc.ca/maven_legacy/thumbnails/277/67/cancer_852x480_2164412612.jpg',
243 'chapters': [],
244 'duration': 186.867,
245 'series': 'CBC News: Windsor at 6:00',
246 'categories': ['News/Canada/Windsor'],
247 'location': 'Windsor',
248 'tags': ['cancer'],
249 'creators': ['Allison Johnson'],
250 'media_type': 'Excerpt',
252 }, {
253 # Has subtitles
254 # These broadcasts expire after ~1 month, can find new test URL here:
255 # https://www.cbc.ca/player/news/TV%20Shows/The%20National/Latest%20Broadcast
256 'url': 'https://www.cbc.ca/player/play/1.7159484',
257 'md5': '6ed6cd0fc2ef568d2297ba68a763d455',
258 'info_dict': {
259 'id': '2324213316001',
260 'ext': 'mp4',
261 'title': 'The National | School boards sue social media giants',
262 'description': 'md5:4b4db69322fa32186c3ce426da07402c',
263 'timestamp': 1711681200,
264 'duration': 2743.400,
265 'subtitles': {'eng': [{'ext': 'vtt', 'protocol': 'm3u8_native'}]},
266 'thumbnail': 'https://thumbnails.cbc.ca/maven_legacy/thumbnails/607/559/thumbnail.jpeg',
267 'uploader': 'CBCC-NEW',
268 'chapters': 'count:5',
269 'upload_date': '20240329',
270 'categories': 'count:4',
271 'series': 'The National - Full Show',
272 'tags': 'count:1',
273 'creators': ['News'],
274 'location': 'Canada',
275 'media_type': 'Full Program',
277 }, {
278 'url': 'https://www.cbc.ca/player/play/video/1.7194274',
279 'md5': '188b96cf6bdcb2540e178a6caa957128',
280 'info_dict': {
281 'id': '2334524995812',
282 'ext': 'mp4',
283 'title': '#TheMoment a rare white spirit moose was spotted in Alberta',
284 'description': 'md5:18ae269a2d0265c5b0bbe4b2e1ac61a3',
285 'timestamp': 1714788791,
286 'duration': 77.678,
287 'subtitles': {'eng': [{'ext': 'vtt', 'protocol': 'm3u8_native'}]},
288 'thumbnail': 'https://thumbnails.cbc.ca/maven_legacy/thumbnails/201/543/THE_MOMENT.jpg',
289 'uploader': 'CBCC-NEW',
290 'chapters': 'count:0',
291 'upload_date': '20240504',
292 'categories': 'count:3',
293 'series': 'The National',
294 'tags': 'count:15',
295 'creators': ['encoder'],
296 'location': 'Canada',
297 'media_type': 'Excerpt',
299 }, {
300 'url': 'cbcplayer:1.7159484',
301 'only_matching': True,
302 }, {
303 'url': 'cbcplayer:2164402062',
304 'only_matching': True,
305 }, {
306 'url': 'http://www.cbc.ca/player/play/2657631896',
307 'only_matching': True,
310 def _real_extract(self, url):
311 video_id = self._match_id(url)
312 if '.' in video_id:
313 webpage = self._download_webpage(f'https://www.cbc.ca/player/play/{video_id}', video_id)
314 video_id = self._search_json(
315 r'window\.__INITIAL_STATE__\s*=', webpage,
316 'initial state', video_id)['video']['currentClip']['mediaId']
318 return {
319 '_type': 'url_transparent',
320 'ie_key': 'ThePlatform',
321 'url': smuggle_url(
322 f'http://link.theplatform.com/s/ExhSPC/media/guid/2655402169/{video_id}?mbr=true&formats=MPEG4,FLV,MP3', {
323 'force_smil_url': True,
325 'id': video_id,
326 '_format_sort_fields': ('res', 'proto'), # Prioritize direct http formats over HLS
330 class CBCPlayerPlaylistIE(InfoExtractor):
331 IE_NAME = 'cbc.ca:player:playlist'
332 _VALID_URL = r'https?://(?:www\.)?cbc\.ca/(?:player/)(?!play/)(?P<id>[^?#]+)'
333 _TESTS = [{
334 'url': 'https://www.cbc.ca/player/news/TV%20Shows/The%20National/Latest%20Broadcast',
335 'playlist_mincount': 25,
336 'info_dict': {
337 'id': 'news/tv shows/the national/latest broadcast',
339 }, {
340 'url': 'https://www.cbc.ca/player/news/Canada/North',
341 'playlist_mincount': 25,
342 'info_dict': {
343 'id': 'news/canada/north',
347 def _real_extract(self, url):
348 playlist_id = urllib.parse.unquote(self._match_id(url)).lower()
349 webpage = self._download_webpage(url, playlist_id)
350 json_content = self._search_json(
351 r'window\.__INITIAL_STATE__\s*=', webpage, 'initial state', playlist_id)
353 def entries():
354 for video_id in traverse_obj(json_content, (
355 'video', 'clipsByCategory', lambda k, _: k.lower() == playlist_id, 'items', ..., 'id',
357 yield self.url_result(f'https://www.cbc.ca/player/play/{video_id}', CBCPlayerIE)
359 return self.playlist_result(entries(), playlist_id)
362 class CBCGemIE(InfoExtractor):
363 IE_NAME = 'gem.cbc.ca'
364 _VALID_URL = r'https?://gem\.cbc\.ca/(?:media/)?(?P<id>[0-9a-z-]+/s[0-9]+[a-z][0-9]+)'
365 _TESTS = [{
366 # This is a normal, public, TV show video
367 'url': 'https://gem.cbc.ca/media/schitts-creek/s06e01',
368 'md5': '93dbb31c74a8e45b378cf13bd3f6f11e',
369 'info_dict': {
370 'id': 'schitts-creek/s06e01',
371 'ext': 'mp4',
372 'title': 'Smoke Signals',
373 'description': 'md5:929868d20021c924020641769eb3e7f1',
374 'thumbnail': 'https://images.radio-canada.ca/v1/synps-cbc/episode/perso/cbc_schitts_creek_season_06e01_thumbnail_v01.jpg?im=Resize=(Size)',
375 'duration': 1314,
376 'categories': ['comedy'],
377 'series': 'Schitt\'s Creek',
378 'season': 'Season 6',
379 'season_number': 6,
380 'episode': 'Smoke Signals',
381 'episode_number': 1,
382 'episode_id': 'schitts-creek/s06e01',
384 'params': {'format': 'bv'},
385 'skip': 'Geo-restricted to Canada',
386 }, {
387 # This video requires an account in the browser, but works fine in yt-dlp
388 'url': 'https://gem.cbc.ca/media/schitts-creek/s01e01',
389 'md5': '297a9600f554f2258aed01514226a697',
390 'info_dict': {
391 'id': 'schitts-creek/s01e01',
392 'ext': 'mp4',
393 'title': 'The Cup Runneth Over',
394 'description': 'md5:9bca14ea49ab808097530eb05a29e797',
395 'thumbnail': 'https://images.radio-canada.ca/v1/synps-cbc/episode/perso/cbc_schitts_creek_season_01e01_thumbnail_v01.jpg?im=Resize=(Size)',
396 'series': 'Schitt\'s Creek',
397 'season_number': 1,
398 'season': 'Season 1',
399 'episode_number': 1,
400 'episode': 'The Cup Runneth Over',
401 'episode_id': 'schitts-creek/s01e01',
402 'duration': 1309,
403 'categories': ['comedy'],
405 'params': {'format': 'bv'},
406 'skip': 'Geo-restricted to Canada',
407 }, {
408 'url': 'https://gem.cbc.ca/nadiyas-family-favourites/s01e01',
409 'only_matching': True,
412 _GEO_COUNTRIES = ['CA']
413 _TOKEN_API_KEY = '3f4beddd-2061-49b0-ae80-6f1f2ed65b37'
414 _NETRC_MACHINE = 'cbcgem'
415 _claims_token = None
417 def _new_claims_token(self, email, password):
418 data = json.dumps({
419 'email': email,
420 'password': password,
421 }).encode()
422 headers = {'content-type': 'application/json'}
423 query = {'apikey': self._TOKEN_API_KEY}
424 resp = self._download_json('https://api.loginradius.com/identity/v2/auth/login',
425 None, data=data, headers=headers, query=query)
426 access_token = resp['access_token']
428 query = {
429 'access_token': access_token,
430 'apikey': self._TOKEN_API_KEY,
431 'jwtapp': 'jwt',
433 resp = self._download_json('https://cloud-api.loginradius.com/sso/jwt/api/token',
434 None, headers=headers, query=query)
435 sig = resp['signature']
437 data = json.dumps({'jwt': sig}).encode()
438 headers = {'content-type': 'application/json', 'ott-device-type': 'web'}
439 resp = self._download_json('https://services.radio-canada.ca/ott/cbc-api/v2/token',
440 None, data=data, headers=headers, expected_status=426)
441 cbc_access_token = resp['accessToken']
443 headers = {'content-type': 'application/json', 'ott-device-type': 'web', 'ott-access-token': cbc_access_token}
444 resp = self._download_json('https://services.radio-canada.ca/ott/cbc-api/v2/profile',
445 None, headers=headers, expected_status=426)
446 return resp['claimsToken']
448 def _get_claims_token_expiry(self):
449 # Token is a JWT
450 # JWT is decoded here and 'exp' field is extracted
451 # It is a Unix timestamp for when the token expires
452 b64_data = self._claims_token.split('.')[1]
453 data = base64.urlsafe_b64decode(b64_data + '==')
454 return json.loads(data)['exp']
456 def claims_token_expired(self):
457 exp = self._get_claims_token_expiry()
458 # It will expire in less than 10 seconds, or has already expired
459 return exp - time.time() < 10
461 def claims_token_valid(self):
462 return self._claims_token is not None and not self.claims_token_expired()
464 def _get_claims_token(self, email, password):
465 if not self.claims_token_valid():
466 self._claims_token = self._new_claims_token(email, password)
467 self.cache.store(self._NETRC_MACHINE, 'claims_token', self._claims_token)
468 return self._claims_token
470 def _real_initialize(self):
471 if self.claims_token_valid():
472 return
473 self._claims_token = self.cache.load(self._NETRC_MACHINE, 'claims_token')
475 def _find_secret_formats(self, formats, video_id):
476 """ Find a valid video url and convert it to the secret variant """
477 base_format = next((f for f in formats if f.get('vcodec') != 'none'), None)
478 if not base_format:
479 return
481 base_url = re.sub(r'(Manifest\(.*?),filter=[\w-]+(.*?\))', r'\1\2', base_format['url'])
482 url = re.sub(r'(Manifest\(.*?),format=[\w-]+(.*?\))', r'\1\2', base_url)
484 secret_xml = self._download_xml(url, video_id, note='Downloading secret XML', fatal=False)
485 if not isinstance(secret_xml, xml.etree.ElementTree.Element):
486 return
488 for child in secret_xml:
489 if child.attrib.get('Type') != 'video':
490 continue
491 for video_quality in child:
492 bitrate = int_or_none(video_quality.attrib.get('Bitrate'))
493 if not bitrate or 'Index' not in video_quality.attrib:
494 continue
495 height = int_or_none(video_quality.attrib.get('MaxHeight'))
497 yield {
498 **base_format,
499 'format_id': join_nonempty('sec', height),
500 # Note: \g<1> is necessary instead of \1 since bitrate is a number
501 'url': re.sub(r'(QualityLevels\()\d+(\))', fr'\g<1>{bitrate}\2', base_url),
502 'width': int_or_none(video_quality.attrib.get('MaxWidth')),
503 'tbr': bitrate / 1000.0,
504 'height': height,
507 def _real_extract(self, url):
508 video_id = self._match_id(url)
509 video_info = self._download_json(
510 f'https://services.radio-canada.ca/ott/cbc-api/v2/assets/{video_id}',
511 video_id, expected_status=426)
513 email, password = self._get_login_info()
514 if email and password:
515 claims_token = self._get_claims_token(email, password)
516 headers = {'x-claims-token': claims_token}
517 else:
518 headers = {}
519 m3u8_info = self._download_json(video_info['playSession']['url'], video_id, headers=headers)
520 m3u8_url = m3u8_info.get('url')
522 if m3u8_info.get('errorCode') == 1:
523 self.raise_geo_restricted(countries=['CA'])
524 elif m3u8_info.get('errorCode') == 35:
525 self.raise_login_required(method='password')
526 elif m3u8_info.get('errorCode') != 0:
527 raise ExtractorError(f'{self.IE_NAME} said: {m3u8_info.get("errorCode")} - {m3u8_info.get("message")}')
529 formats = self._extract_m3u8_formats(m3u8_url, video_id, m3u8_id='hls')
530 self._remove_duplicate_formats(formats)
531 formats.extend(self._find_secret_formats(formats, video_id))
533 for fmt in formats:
534 if fmt.get('vcodec') == 'none':
535 if fmt.get('ext') is None:
536 fmt['ext'] = 'm4a'
537 if fmt.get('acodec') is None:
538 fmt['acodec'] = 'mp4a.40.2'
540 # Put described audio at the beginning of the list, so that it
541 # isn't chosen by default, as most people won't want it.
542 if 'descriptive' in fmt['format_id'].lower():
543 fmt['preference'] = -2
545 return {
546 'id': video_id,
547 'title': video_info['title'],
548 'description': video_info.get('description'),
549 'thumbnail': video_info.get('image'),
550 'series': video_info.get('series'),
551 'season_number': video_info.get('season'),
552 'season': f'Season {video_info.get("season")}',
553 'episode_number': video_info.get('episode'),
554 'episode': video_info.get('title'),
555 'episode_id': video_id,
556 'duration': video_info.get('duration'),
557 'categories': [video_info.get('category')],
558 'formats': formats,
559 'release_timestamp': video_info.get('airDate'),
560 'timestamp': video_info.get('availableDate'),
564 class CBCGemPlaylistIE(InfoExtractor):
565 IE_NAME = 'gem.cbc.ca:playlist'
566 _VALID_URL = r'https?://gem\.cbc\.ca/(?:media/)?(?P<id>(?P<show>[0-9a-z-]+)/s(?P<season>[0-9]+))/?(?:[?#]|$)'
567 _TESTS = [{
568 # TV show playlist, all public videos
569 'url': 'https://gem.cbc.ca/media/schitts-creek/s06',
570 'playlist_count': 16,
571 'info_dict': {
572 'id': 'schitts-creek/s06',
573 'title': 'Season 6',
574 'description': 'md5:6a92104a56cbeb5818cc47884d4326a2',
575 'series': 'Schitt\'s Creek',
576 'season_number': 6,
577 'season': 'Season 6',
578 'thumbnail': 'https://images.radio-canada.ca/v1/synps-cbc/season/perso/cbc_schitts_creek_season_06_carousel_v03.jpg?impolicy=ott&im=Resize=(_Size_)&quality=75',
580 }, {
581 'url': 'https://gem.cbc.ca/schitts-creek/s06',
582 'only_matching': True,
584 _API_BASE = 'https://services.radio-canada.ca/ott/cbc-api/v2/shows/'
586 def _real_extract(self, url):
587 match = self._match_valid_url(url)
588 season_id = match.group('id')
589 show = match.group('show')
590 show_info = self._download_json(self._API_BASE + show, season_id, expected_status=426)
591 season = int(match.group('season'))
593 season_info = next((s for s in show_info['seasons'] if s.get('season') == season), None)
595 if season_info is None:
596 raise ExtractorError(f'Couldn\'t find season {season} of {show}')
598 episodes = []
599 for episode in season_info['assets']:
600 episodes.append({
601 '_type': 'url_transparent',
602 'ie_key': 'CBCGem',
603 'url': 'https://gem.cbc.ca/media/' + episode['id'],
604 'id': episode['id'],
605 'title': episode.get('title'),
606 'description': episode.get('description'),
607 'thumbnail': episode.get('image'),
608 'series': episode.get('series'),
609 'season_number': episode.get('season'),
610 'season': season_info['title'],
611 'season_id': season_info.get('id'),
612 'episode_number': episode.get('episode'),
613 'episode': episode.get('title'),
614 'episode_id': episode['id'],
615 'duration': episode.get('duration'),
616 'categories': [episode.get('category')],
619 thumbnail = None
620 tn_uri = season_info.get('image')
621 # the-national was observed to use a "data:image/png;base64"
622 # URI for their 'image' value. The image was 1x1, and is
623 # probably just a placeholder, so it is ignored.
624 if tn_uri is not None and not tn_uri.startswith('data:'):
625 thumbnail = tn_uri
627 return {
628 '_type': 'playlist',
629 'entries': episodes,
630 'id': season_id,
631 'title': season_info['title'],
632 'description': season_info.get('description'),
633 'thumbnail': thumbnail,
634 'series': show_info.get('title'),
635 'season_number': season_info.get('season'),
636 'season': season_info['title'],
640 class CBCGemLiveIE(InfoExtractor):
641 IE_NAME = 'gem.cbc.ca:live'
642 _VALID_URL = r'https?://gem\.cbc\.ca/live(?:-event)?/(?P<id>\d+)'
643 _TESTS = [
645 'url': 'https://gem.cbc.ca/live/920604739687',
646 'info_dict': {
647 'title': 'Ottawa',
648 'description': 'The live TV channel and local programming from Ottawa',
649 'thumbnail': 'https://thumbnails.cbc.ca/maven_legacy/thumbnails/CBC_OTT_VMS/Live_Channel_Static_Images/Ottawa_2880x1620.jpg',
650 'is_live': True,
651 'id': 'AyqZwxRqh8EH',
652 'ext': 'mp4',
653 'timestamp': 1492106160,
654 'upload_date': '20170413',
655 'uploader': 'CBCC-NEW',
657 'skip': 'Live might have ended',
660 'url': 'https://gem.cbc.ca/live/44',
661 'info_dict': {
662 'id': '44',
663 'ext': 'mp4',
664 'is_live': True,
665 'title': r're:^Ottawa [0-9\-: ]+',
666 'description': 'The live TV channel and local programming from Ottawa',
667 'live_status': 'is_live',
668 'thumbnail': r're:https://images.gem.cbc.ca/v1/cbc-gem/live/.*',
670 'params': {'skip_download': True},
671 'skip': 'Live might have ended',
674 'url': 'https://gem.cbc.ca/live-event/10835',
675 'info_dict': {
676 'id': '10835',
677 'ext': 'mp4',
678 'is_live': True,
679 'title': r're:^The National \| Biden’s trip wraps up, Paltrow testifies, Bird flu [0-9\-: ]+',
680 'description': 'March 24, 2023 | President Biden’s Ottawa visit ends with big pledges from both countries. Plus, Gwyneth Paltrow testifies in her ski collision trial.',
681 'live_status': 'is_live',
682 'thumbnail': r're:https://images.gem.cbc.ca/v1/cbc-gem/live/.*',
683 'timestamp': 1679706000,
684 'upload_date': '20230325',
686 'params': {'skip_download': True},
687 'skip': 'Live might have ended',
691 def _real_extract(self, url):
692 video_id = self._match_id(url)
693 webpage = self._download_webpage(url, video_id)
694 video_info = self._search_nextjs_data(webpage, video_id)['props']['pageProps']['data']
696 # Two types of metadata JSON
697 if not video_info.get('formattedIdMedia'):
698 video_info = traverse_obj(
699 video_info, (('freeTv', ('streams', ...)), 'items', lambda _, v: v['key'] == video_id, {dict}),
700 get_all=False, default={})
702 video_stream_id = video_info.get('formattedIdMedia')
703 if not video_stream_id:
704 raise ExtractorError('Couldn\'t find video metadata, maybe this livestream is now offline', expected=True)
706 stream_data = self._download_json(
707 'https://services.radio-canada.ca/media/validation/v2/', video_id, query={
708 'appCode': 'mpx',
709 'connectionType': 'hd',
710 'deviceType': 'ipad',
711 'idMedia': video_stream_id,
712 'multibitrate': 'true',
713 'output': 'json',
714 'tech': 'hls',
715 'manifestType': 'desktop',
718 return {
719 'id': video_id,
720 'formats': self._extract_m3u8_formats(stream_data['url'], video_id, 'mp4', live=True),
721 'is_live': True,
722 **traverse_obj(video_info, {
723 'title': 'title',
724 'description': 'description',
725 'thumbnail': ('images', 'card', 'url'),
726 'timestamp': ('airDate', {parse_iso8601}),