[ie] Do not test truth value of `xml.etree.ElementTree.Element` (#8582)
[yt-dlp3.git] / yt_dlp / extractor / cbc.py
blob29f0e307d132908255a735abcbf5da485fbdabd0
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 ..compat import (
10 compat_str,
12 from ..utils import (
13 ExtractorError,
14 int_or_none,
15 join_nonempty,
16 js_to_json,
17 orderedSet,
18 parse_iso8601,
19 smuggle_url,
20 strip_or_none,
21 traverse_obj,
22 try_get,
26 class CBCIE(InfoExtractor):
27 IE_NAME = 'cbc.ca'
28 _VALID_URL = r'https?://(?:www\.)?cbc\.ca/(?!player/)(?:[^/]+/)+(?P<id>[^/?#]+)'
29 _TESTS = [{
30 # with mediaId
31 'url': 'http://www.cbc.ca/22minutes/videos/clips-season-23/don-cherry-play-offs',
32 'md5': '97e24d09672fc4cf56256d6faa6c25bc',
33 'info_dict': {
34 'id': '2682904050',
35 'ext': 'mp4',
36 'title': 'Don Cherry – All-Stars',
37 'description': 'Don Cherry has a bee in his bonnet about AHL player John Scott because that guy’s got heart.',
38 'timestamp': 1454463000,
39 'upload_date': '20160203',
40 'uploader': 'CBCC-NEW',
42 'skip': 'Geo-restricted to Canada',
43 }, {
44 # with clipId, feed available via tpfeed.cbc.ca and feed.theplatform.com
45 'url': 'http://www.cbc.ca/22minutes/videos/22-minutes-update/22-minutes-update-episode-4',
46 'md5': '162adfa070274b144f4fdc3c3b8207db',
47 'info_dict': {
48 'id': '2414435309',
49 'ext': 'mp4',
50 'title': '22 Minutes Update: What Not To Wear Quebec',
51 'description': "This week's latest Canadian top political story is What Not To Wear Quebec.",
52 'upload_date': '20131025',
53 'uploader': 'CBCC-NEW',
54 'timestamp': 1382717907,
56 'skip': 'No longer available',
57 }, {
58 # with clipId, feed only available via tpfeed.cbc.ca
59 'url': 'http://www.cbc.ca/archives/entry/1978-robin-williams-freestyles-on-90-minutes-live',
60 'md5': '0274a90b51a9b4971fe005c63f592f12',
61 'info_dict': {
62 'id': '2487345465',
63 'ext': 'mp4',
64 'title': 'Robin Williams freestyles on 90 Minutes Live',
65 'description': 'Wacky American comedian Robin Williams shows off his infamous "freestyle" comedic talents while being interviewed on CBC\'s 90 Minutes Live.',
66 'upload_date': '19780210',
67 'uploader': 'CBCC-NEW',
68 'timestamp': 255977160,
70 'skip': '404 Not Found',
71 }, {
72 # multiple iframes
73 'url': 'http://www.cbc.ca/natureofthings/blog/birds-eye-view-from-vancouvers-burrard-street-bridge-how-we-got-the-shot',
74 'playlist': [{
75 'md5': '377572d0b49c4ce0c9ad77470e0b96b4',
76 'info_dict': {
77 'id': '2680832926',
78 'ext': 'mp4',
79 'title': 'An Eagle\'s-Eye View Off Burrard Bridge',
80 'description': 'Hercules the eagle flies from Vancouver\'s Burrard Bridge down to a nearby park with a mini-camera strapped to his back.',
81 'upload_date': '20160201',
82 'timestamp': 1454342820,
83 'uploader': 'CBCC-NEW',
85 }, {
86 'md5': '415a0e3f586113894174dfb31aa5bb1a',
87 'info_dict': {
88 'id': '2658915080',
89 'ext': 'mp4',
90 'title': 'Fly like an eagle!',
91 'description': 'Eagle equipped with a mini camera flies from the world\'s tallest tower',
92 'upload_date': '20150315',
93 'timestamp': 1426443984,
94 'uploader': 'CBCC-NEW',
96 }],
97 'skip': 'Geo-restricted to Canada',
98 }, {
99 # multiple CBC.APP.Caffeine.initInstance(...)
100 'url': 'http://www.cbc.ca/news/canada/calgary/dog-indoor-exercise-winter-1.3928238',
101 'info_dict': {
102 'title': 'Keep Rover active during the deep freeze with doggie pushups and other fun indoor tasks', # FIXME
103 'id': 'dog-indoor-exercise-winter-1.3928238',
104 'description': 'md5:c18552e41726ee95bd75210d1ca9194c',
106 'playlist_mincount': 6,
109 @classmethod
110 def suitable(cls, url):
111 return False if CBCPlayerIE.suitable(url) else super(CBCIE, cls).suitable(url)
113 def _extract_player_init(self, player_init, display_id):
114 player_info = self._parse_json(player_init, display_id, js_to_json)
115 media_id = player_info.get('mediaId')
116 if not media_id:
117 clip_id = player_info['clipId']
118 feed = self._download_json(
119 'http://tpfeed.cbc.ca/f/ExhSPC/vms_5akSXx4Ng_Zn?byCustomValue={:mpsReleases}{%s}' % clip_id,
120 clip_id, fatal=False)
121 if feed:
122 media_id = try_get(feed, lambda x: x['entries'][0]['guid'], compat_str)
123 if not media_id:
124 media_id = self._download_json(
125 'http://feed.theplatform.com/f/h9dtGB/punlNGjMlc1F?fields=id&byContent=byReleases%3DbyId%253D' + clip_id,
126 clip_id)['entries'][0]['id'].split('/')[-1]
127 return self.url_result('cbcplayer:%s' % media_id, 'CBCPlayer', media_id)
129 def _real_extract(self, url):
130 display_id = self._match_id(url)
131 webpage = self._download_webpage(url, display_id)
132 title = (self._og_search_title(webpage, default=None)
133 or self._html_search_meta('twitter:title', webpage, 'title', default=None)
134 or self._html_extract_title(webpage))
135 entries = [
136 self._extract_player_init(player_init, display_id)
137 for player_init in re.findall(r'CBC\.APP\.Caffeine\.initInstance\(({.+?})\);', webpage)]
138 media_ids = []
139 for media_id_re in (
140 r'<iframe[^>]+src="[^"]+?mediaId=(\d+)"',
141 r'<div[^>]+\bid=["\']player-(\d+)',
142 r'guid["\']\s*:\s*["\'](\d+)'):
143 media_ids.extend(re.findall(media_id_re, webpage))
144 entries.extend([
145 self.url_result('cbcplayer:%s' % media_id, 'CBCPlayer', media_id)
146 for media_id in orderedSet(media_ids)])
147 return self.playlist_result(
148 entries, display_id, strip_or_none(title),
149 self._og_search_description(webpage))
152 class CBCPlayerIE(InfoExtractor):
153 IE_NAME = 'cbc.ca:player'
154 _VALID_URL = r'(?:cbcplayer:|https?://(?:www\.)?cbc\.ca/(?:player/play/|i/caffeine/syndicate/\?mediaId=))(?P<id>\d+)'
155 _TESTS = [{
156 'url': 'http://www.cbc.ca/player/play/2683190193',
157 'md5': '64d25f841ddf4ddb28a235338af32e2c',
158 'info_dict': {
159 'id': '2683190193',
160 'ext': 'mp4',
161 'title': 'Gerry Runs a Sweat Shop',
162 'description': 'md5:b457e1c01e8ff408d9d801c1c2cd29b0',
163 'timestamp': 1455071400,
164 'upload_date': '20160210',
165 'uploader': 'CBCC-NEW',
167 'skip': 'Geo-restricted to Canada and no longer available',
168 }, {
169 # Redirected from http://www.cbc.ca/player/AudioMobile/All%20in%20a%20Weekend%20Montreal/ID/2657632011/
170 'url': 'http://www.cbc.ca/player/play/2657631896',
171 'md5': 'e5e708c34ae6fca156aafe17c43e8b75',
172 'info_dict': {
173 'id': '2657631896',
174 'ext': 'mp3',
175 'title': 'CBC Montreal is organizing its first ever community hackathon!',
176 '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.',
177 'timestamp': 1425704400,
178 'upload_date': '20150307',
179 'uploader': 'CBCC-NEW',
180 'thumbnail': 'http://thumbnails.cbc.ca/maven_legacy/thumbnails/sonali-karnick-220.jpg',
181 'chapters': [],
182 'duration': 494.811,
184 }, {
185 'url': 'http://www.cbc.ca/player/play/2164402062',
186 'md5': '33fcd8f6719b9dd60a5e73adcb83b9f6',
187 'info_dict': {
188 'id': '2164402062',
189 'ext': 'mp4',
190 'title': 'Cancer survivor four times over',
191 'description': 'Tim Mayer has beaten three different forms of cancer four times in five years.',
192 'timestamp': 1320410746,
193 'upload_date': '20111104',
194 'uploader': 'CBCC-NEW',
195 'thumbnail': 'https://thumbnails.cbc.ca/maven_legacy/thumbnails/277/67/cancer_852x480_2164412612.jpg',
196 'chapters': [],
197 'duration': 186.867,
199 }, {
200 # Has subtitles
201 # These broadcasts expire after ~1 month, can find new test URL here:
202 # https://www.cbc.ca/player/news/TV%20Shows/The%20National/Latest%20Broadcast
203 'url': 'http://www.cbc.ca/player/play/2249992771553',
204 'md5': '2f2fb675dd4f0f8a5bb7588d1b13bacd',
205 'info_dict': {
206 'id': '2249992771553',
207 'ext': 'mp4',
208 'title': 'The National | Women’s soccer pay, Florida seawater, Swift quake',
209 'description': 'md5:adba28011a56cfa47a080ff198dad27a',
210 'timestamp': 1690596000,
211 'duration': 2716.333,
212 'subtitles': {'eng': [{'ext': 'vtt', 'protocol': 'm3u8_native'}]},
213 'thumbnail': 'https://thumbnails.cbc.ca/maven_legacy/thumbnails/481/326/thumbnail.jpeg',
214 'uploader': 'CBCC-NEW',
215 'chapters': 'count:5',
216 'upload_date': '20230729',
220 def _real_extract(self, url):
221 video_id = self._match_id(url)
222 return {
223 '_type': 'url_transparent',
224 'ie_key': 'ThePlatform',
225 'url': smuggle_url(
226 'http://link.theplatform.com/s/ExhSPC/media/guid/2655402169/%s?mbr=true&formats=MPEG4,FLV,MP3' % video_id, {
227 'force_smil_url': True
229 'id': video_id,
230 '_format_sort_fields': ('res', 'proto') # Prioritize direct http formats over HLS
234 class CBCPlayerPlaylistIE(InfoExtractor):
235 IE_NAME = 'cbc.ca:player:playlist'
236 _VALID_URL = r'https?://(?:www\.)?cbc\.ca/(?:player/)(?!play/)(?P<id>[^?#]+)'
237 _TESTS = [{
238 'url': 'https://www.cbc.ca/player/news/TV%20Shows/The%20National/Latest%20Broadcast',
239 'playlist_mincount': 25,
240 'info_dict': {
241 'id': 'news/tv shows/the national/latest broadcast',
243 }, {
244 'url': 'https://www.cbc.ca/player/news/Canada/North',
245 'playlist_mincount': 25,
246 'info_dict': {
247 'id': 'news/canada/north',
251 def _real_extract(self, url):
252 playlist_id = urllib.parse.unquote(self._match_id(url)).lower()
253 webpage = self._download_webpage(url, playlist_id)
254 json_content = self._search_json(
255 r'window\.__INITIAL_STATE__\s*=', webpage, 'initial state', playlist_id)
257 def entries():
258 for video_id in traverse_obj(json_content, (
259 'video', 'clipsByCategory', lambda k, _: k.lower() == playlist_id, 'items', ..., 'id'
261 yield self.url_result(f'https://www.cbc.ca/player/play/{video_id}', CBCPlayerIE)
263 return self.playlist_result(entries(), playlist_id)
266 class CBCGemIE(InfoExtractor):
267 IE_NAME = 'gem.cbc.ca'
268 _VALID_URL = r'https?://gem\.cbc\.ca/(?:media/)?(?P<id>[0-9a-z-]+/s[0-9]+[a-z][0-9]+)'
269 _TESTS = [{
270 # This is a normal, public, TV show video
271 'url': 'https://gem.cbc.ca/media/schitts-creek/s06e01',
272 'md5': '93dbb31c74a8e45b378cf13bd3f6f11e',
273 'info_dict': {
274 'id': 'schitts-creek/s06e01',
275 'ext': 'mp4',
276 'title': 'Smoke Signals',
277 'description': 'md5:929868d20021c924020641769eb3e7f1',
278 'thumbnail': 'https://images.radio-canada.ca/v1/synps-cbc/episode/perso/cbc_schitts_creek_season_06e01_thumbnail_v01.jpg?im=Resize=(Size)',
279 'duration': 1314,
280 'categories': ['comedy'],
281 'series': 'Schitt\'s Creek',
282 'season': 'Season 6',
283 'season_number': 6,
284 'episode': 'Smoke Signals',
285 'episode_number': 1,
286 'episode_id': 'schitts-creek/s06e01',
288 'params': {'format': 'bv'},
289 'skip': 'Geo-restricted to Canada',
290 }, {
291 # This video requires an account in the browser, but works fine in yt-dlp
292 'url': 'https://gem.cbc.ca/media/schitts-creek/s01e01',
293 'md5': '297a9600f554f2258aed01514226a697',
294 'info_dict': {
295 'id': 'schitts-creek/s01e01',
296 'ext': 'mp4',
297 'title': 'The Cup Runneth Over',
298 'description': 'md5:9bca14ea49ab808097530eb05a29e797',
299 'thumbnail': 'https://images.radio-canada.ca/v1/synps-cbc/episode/perso/cbc_schitts_creek_season_01e01_thumbnail_v01.jpg?im=Resize=(Size)',
300 'series': 'Schitt\'s Creek',
301 'season_number': 1,
302 'season': 'Season 1',
303 'episode_number': 1,
304 'episode': 'The Cup Runneth Over',
305 'episode_id': 'schitts-creek/s01e01',
306 'duration': 1309,
307 'categories': ['comedy'],
309 'params': {'format': 'bv'},
310 'skip': 'Geo-restricted to Canada',
311 }, {
312 'url': 'https://gem.cbc.ca/nadiyas-family-favourites/s01e01',
313 'only_matching': True,
316 _GEO_COUNTRIES = ['CA']
317 _TOKEN_API_KEY = '3f4beddd-2061-49b0-ae80-6f1f2ed65b37'
318 _NETRC_MACHINE = 'cbcgem'
319 _claims_token = None
321 def _new_claims_token(self, email, password):
322 data = json.dumps({
323 'email': email,
324 'password': password,
325 }).encode()
326 headers = {'content-type': 'application/json'}
327 query = {'apikey': self._TOKEN_API_KEY}
328 resp = self._download_json('https://api.loginradius.com/identity/v2/auth/login',
329 None, data=data, headers=headers, query=query)
330 access_token = resp['access_token']
332 query = {
333 'access_token': access_token,
334 'apikey': self._TOKEN_API_KEY,
335 'jwtapp': 'jwt',
337 resp = self._download_json('https://cloud-api.loginradius.com/sso/jwt/api/token',
338 None, headers=headers, query=query)
339 sig = resp['signature']
341 data = json.dumps({'jwt': sig}).encode()
342 headers = {'content-type': 'application/json', 'ott-device-type': 'web'}
343 resp = self._download_json('https://services.radio-canada.ca/ott/cbc-api/v2/token',
344 None, data=data, headers=headers, expected_status=426)
345 cbc_access_token = resp['accessToken']
347 headers = {'content-type': 'application/json', 'ott-device-type': 'web', 'ott-access-token': cbc_access_token}
348 resp = self._download_json('https://services.radio-canada.ca/ott/cbc-api/v2/profile',
349 None, headers=headers, expected_status=426)
350 return resp['claimsToken']
352 def _get_claims_token_expiry(self):
353 # Token is a JWT
354 # JWT is decoded here and 'exp' field is extracted
355 # It is a Unix timestamp for when the token expires
356 b64_data = self._claims_token.split('.')[1]
357 data = base64.urlsafe_b64decode(b64_data + "==")
358 return json.loads(data)['exp']
360 def claims_token_expired(self):
361 exp = self._get_claims_token_expiry()
362 if exp - time.time() < 10:
363 # It will expire in less than 10 seconds, or has already expired
364 return True
365 return False
367 def claims_token_valid(self):
368 return self._claims_token is not None and not self.claims_token_expired()
370 def _get_claims_token(self, email, password):
371 if not self.claims_token_valid():
372 self._claims_token = self._new_claims_token(email, password)
373 self.cache.store(self._NETRC_MACHINE, 'claims_token', self._claims_token)
374 return self._claims_token
376 def _real_initialize(self):
377 if self.claims_token_valid():
378 return
379 self._claims_token = self.cache.load(self._NETRC_MACHINE, 'claims_token')
381 def _find_secret_formats(self, formats, video_id):
382 """ Find a valid video url and convert it to the secret variant """
383 base_format = next((f for f in formats if f.get('vcodec') != 'none'), None)
384 if not base_format:
385 return
387 base_url = re.sub(r'(Manifest\(.*?),filter=[\w-]+(.*?\))', r'\1\2', base_format['url'])
388 url = re.sub(r'(Manifest\(.*?),format=[\w-]+(.*?\))', r'\1\2', base_url)
390 secret_xml = self._download_xml(url, video_id, note='Downloading secret XML', fatal=False)
391 if not isinstance(secret_xml, xml.etree.ElementTree.Element):
392 return
394 for child in secret_xml:
395 if child.attrib.get('Type') != 'video':
396 continue
397 for video_quality in child:
398 bitrate = int_or_none(video_quality.attrib.get('Bitrate'))
399 if not bitrate or 'Index' not in video_quality.attrib:
400 continue
401 height = int_or_none(video_quality.attrib.get('MaxHeight'))
403 yield {
404 **base_format,
405 'format_id': join_nonempty('sec', height),
406 # Note: \g<1> is necessary instead of \1 since bitrate is a number
407 'url': re.sub(r'(QualityLevels\()\d+(\))', fr'\g<1>{bitrate}\2', base_url),
408 'width': int_or_none(video_quality.attrib.get('MaxWidth')),
409 'tbr': bitrate / 1000.0,
410 'height': height,
413 def _real_extract(self, url):
414 video_id = self._match_id(url)
415 video_info = self._download_json(
416 f'https://services.radio-canada.ca/ott/cbc-api/v2/assets/{video_id}',
417 video_id, expected_status=426)
419 email, password = self._get_login_info()
420 if email and password:
421 claims_token = self._get_claims_token(email, password)
422 headers = {'x-claims-token': claims_token}
423 else:
424 headers = {}
425 m3u8_info = self._download_json(video_info['playSession']['url'], video_id, headers=headers)
426 m3u8_url = m3u8_info.get('url')
428 if m3u8_info.get('errorCode') == 1:
429 self.raise_geo_restricted(countries=['CA'])
430 elif m3u8_info.get('errorCode') == 35:
431 self.raise_login_required(method='password')
432 elif m3u8_info.get('errorCode') != 0:
433 raise ExtractorError(f'{self.IE_NAME} said: {m3u8_info.get("errorCode")} - {m3u8_info.get("message")}')
435 formats = self._extract_m3u8_formats(m3u8_url, video_id, m3u8_id='hls')
436 self._remove_duplicate_formats(formats)
437 formats.extend(self._find_secret_formats(formats, video_id))
439 for format in formats:
440 if format.get('vcodec') == 'none':
441 if format.get('ext') is None:
442 format['ext'] = 'm4a'
443 if format.get('acodec') is None:
444 format['acodec'] = 'mp4a.40.2'
446 # Put described audio at the beginning of the list, so that it
447 # isn't chosen by default, as most people won't want it.
448 if 'descriptive' in format['format_id'].lower():
449 format['preference'] = -2
451 return {
452 'id': video_id,
453 'title': video_info['title'],
454 'description': video_info.get('description'),
455 'thumbnail': video_info.get('image'),
456 'series': video_info.get('series'),
457 'season_number': video_info.get('season'),
458 'season': f'Season {video_info.get("season")}',
459 'episode_number': video_info.get('episode'),
460 'episode': video_info.get('title'),
461 'episode_id': video_id,
462 'duration': video_info.get('duration'),
463 'categories': [video_info.get('category')],
464 'formats': formats,
465 'release_timestamp': video_info.get('airDate'),
466 'timestamp': video_info.get('availableDate'),
470 class CBCGemPlaylistIE(InfoExtractor):
471 IE_NAME = 'gem.cbc.ca:playlist'
472 _VALID_URL = r'https?://gem\.cbc\.ca/(?:media/)?(?P<id>(?P<show>[0-9a-z-]+)/s(?P<season>[0-9]+))/?(?:[?#]|$)'
473 _TESTS = [{
474 # TV show playlist, all public videos
475 'url': 'https://gem.cbc.ca/media/schitts-creek/s06',
476 'playlist_count': 16,
477 'info_dict': {
478 'id': 'schitts-creek/s06',
479 'title': 'Season 6',
480 'description': 'md5:6a92104a56cbeb5818cc47884d4326a2',
481 'series': 'Schitt\'s Creek',
482 'season_number': 6,
483 'season': 'Season 6',
484 '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',
486 }, {
487 'url': 'https://gem.cbc.ca/schitts-creek/s06',
488 'only_matching': True,
490 _API_BASE = 'https://services.radio-canada.ca/ott/cbc-api/v2/shows/'
492 def _real_extract(self, url):
493 match = self._match_valid_url(url)
494 season_id = match.group('id')
495 show = match.group('show')
496 show_info = self._download_json(self._API_BASE + show, season_id, expected_status=426)
497 season = int(match.group('season'))
499 season_info = next((s for s in show_info['seasons'] if s.get('season') == season), None)
501 if season_info is None:
502 raise ExtractorError(f'Couldn\'t find season {season} of {show}')
504 episodes = []
505 for episode in season_info['assets']:
506 episodes.append({
507 '_type': 'url_transparent',
508 'ie_key': 'CBCGem',
509 'url': 'https://gem.cbc.ca/media/' + episode['id'],
510 'id': episode['id'],
511 'title': episode.get('title'),
512 'description': episode.get('description'),
513 'thumbnail': episode.get('image'),
514 'series': episode.get('series'),
515 'season_number': episode.get('season'),
516 'season': season_info['title'],
517 'season_id': season_info.get('id'),
518 'episode_number': episode.get('episode'),
519 'episode': episode.get('title'),
520 'episode_id': episode['id'],
521 'duration': episode.get('duration'),
522 'categories': [episode.get('category')],
525 thumbnail = None
526 tn_uri = season_info.get('image')
527 # the-national was observed to use a "data:image/png;base64"
528 # URI for their 'image' value. The image was 1x1, and is
529 # probably just a placeholder, so it is ignored.
530 if tn_uri is not None and not tn_uri.startswith('data:'):
531 thumbnail = tn_uri
533 return {
534 '_type': 'playlist',
535 'entries': episodes,
536 'id': season_id,
537 'title': season_info['title'],
538 'description': season_info.get('description'),
539 'thumbnail': thumbnail,
540 'series': show_info.get('title'),
541 'season_number': season_info.get('season'),
542 'season': season_info['title'],
546 class CBCGemLiveIE(InfoExtractor):
547 IE_NAME = 'gem.cbc.ca:live'
548 _VALID_URL = r'https?://gem\.cbc\.ca/live(?:-event)?/(?P<id>\d+)'
549 _TESTS = [
551 'url': 'https://gem.cbc.ca/live/920604739687',
552 'info_dict': {
553 'title': 'Ottawa',
554 'description': 'The live TV channel and local programming from Ottawa',
555 'thumbnail': 'https://thumbnails.cbc.ca/maven_legacy/thumbnails/CBC_OTT_VMS/Live_Channel_Static_Images/Ottawa_2880x1620.jpg',
556 'is_live': True,
557 'id': 'AyqZwxRqh8EH',
558 'ext': 'mp4',
559 'timestamp': 1492106160,
560 'upload_date': '20170413',
561 'uploader': 'CBCC-NEW',
563 'skip': 'Live might have ended',
566 'url': 'https://gem.cbc.ca/live/44',
567 'info_dict': {
568 'id': '44',
569 'ext': 'mp4',
570 'is_live': True,
571 'title': r're:^Ottawa [0-9\-: ]+',
572 'description': 'The live TV channel and local programming from Ottawa',
573 'live_status': 'is_live',
574 'thumbnail': r're:https://images.gem.cbc.ca/v1/cbc-gem/live/.*'
576 'params': {'skip_download': True},
577 'skip': 'Live might have ended',
580 'url': 'https://gem.cbc.ca/live-event/10835',
581 'info_dict': {
582 'id': '10835',
583 'ext': 'mp4',
584 'is_live': True,
585 'title': r're:^The National \| Biden’s trip wraps up, Paltrow testifies, Bird flu [0-9\-: ]+',
586 '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.',
587 'live_status': 'is_live',
588 'thumbnail': r're:https://images.gem.cbc.ca/v1/cbc-gem/live/.*',
589 'timestamp': 1679706000,
590 'upload_date': '20230325',
592 'params': {'skip_download': True},
593 'skip': 'Live might have ended',
597 def _real_extract(self, url):
598 video_id = self._match_id(url)
599 webpage = self._download_webpage(url, video_id)
600 video_info = self._search_nextjs_data(webpage, video_id)['props']['pageProps']['data']
602 # Two types of metadata JSON
603 if not video_info.get('formattedIdMedia'):
604 video_info = traverse_obj(
605 video_info, (('freeTv', ('streams', ...)), 'items', lambda _, v: v['key'] == video_id, {dict}),
606 get_all=False, default={})
608 video_stream_id = video_info.get('formattedIdMedia')
609 if not video_stream_id:
610 raise ExtractorError('Couldn\'t find video metadata, maybe this livestream is now offline', expected=True)
612 stream_data = self._download_json(
613 'https://services.radio-canada.ca/media/validation/v2/', video_id, query={
614 'appCode': 'mpx',
615 'connectionType': 'hd',
616 'deviceType': 'ipad',
617 'idMedia': video_stream_id,
618 'multibitrate': 'true',
619 'output': 'json',
620 'tech': 'hls',
621 'manifestType': 'desktop',
624 return {
625 'id': video_id,
626 'formats': self._extract_m3u8_formats(stream_data['url'], video_id, 'mp4', live=True),
627 'is_live': True,
628 **traverse_obj(video_info, {
629 'title': 'title',
630 'description': 'description',
631 'thumbnail': ('images', 'card', 'url'),
632 'timestamp': ('airDate', {parse_iso8601}),