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