]> jfr.im git - yt-dlp.git/blob - yt_dlp/extractor/cbc.py
[ie/matchtv] Fix extractor (#10190)
[yt-dlp.git] / yt_dlp / extractor / cbc.py
1 import base64
2 import json
3 import re
4 import time
5 import urllib.parse
6 import xml.etree.ElementTree
7
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,
20 )
21
22
23 class CBCIE(InfoExtractor):
24 IE_NAME = 'cbc.ca'
25 _VALID_URL = r'https?://(?:www\.)?cbc\.ca/(?!player/)(?:[^/]+/)+(?P<id>[^/?#]+)'
26 _TESTS = [{
27 # with mediaId
28 'url': 'http://www.cbc.ca/22minutes/videos/clips-season-23/don-cherry-play-offs',
29 'md5': '97e24d09672fc4cf56256d6faa6c25bc',
30 'info_dict': {
31 'id': '2682904050',
32 'ext': 'mp4',
33 'title': 'Don Cherry – All-Stars',
34 'description': 'Don Cherry has a bee in his bonnet about AHL player John Scott because that guy’s got heart.',
35 'timestamp': 1454463000,
36 'upload_date': '20160203',
37 'uploader': 'CBCC-NEW',
38 },
39 'skip': 'Geo-restricted to Canada',
40 }, {
41 # with clipId, feed available via tpfeed.cbc.ca and feed.theplatform.com
42 'url': 'http://www.cbc.ca/22minutes/videos/22-minutes-update/22-minutes-update-episode-4',
43 'md5': '162adfa070274b144f4fdc3c3b8207db',
44 'info_dict': {
45 'id': '2414435309',
46 'ext': 'mp4',
47 'title': '22 Minutes Update: What Not To Wear Quebec',
48 'description': "This week's latest Canadian top political story is What Not To Wear Quebec.",
49 'upload_date': '20131025',
50 'uploader': 'CBCC-NEW',
51 'timestamp': 1382717907,
52 },
53 'skip': 'No longer available',
54 }, {
55 # with clipId, feed only available via tpfeed.cbc.ca
56 'url': 'http://www.cbc.ca/archives/entry/1978-robin-williams-freestyles-on-90-minutes-live',
57 'md5': '0274a90b51a9b4971fe005c63f592f12',
58 'info_dict': {
59 'id': '2487345465',
60 'ext': 'mp4',
61 'title': 'Robin Williams freestyles on 90 Minutes Live',
62 'description': 'Wacky American comedian Robin Williams shows off his infamous "freestyle" comedic talents while being interviewed on CBC\'s 90 Minutes Live.',
63 'upload_date': '19780210',
64 'uploader': 'CBCC-NEW',
65 'timestamp': 255977160,
66 },
67 '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',
81 },
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',
92 },
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',
102 },
103 'playlist_mincount': 6,
104 }]
105
106 @classmethod
107 def suitable(cls, url):
108 return False if CBCPlayerIE.suitable(url) else super().suitable(url)
109
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)
125
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))
147
148
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',
163 },
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',
186 },
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',
207 },
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',
230 },
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',
251 },
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',
276 },
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',
298 },
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,
308 }]
309
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']
317
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,
324 }),
325 'id': video_id,
326 '_format_sort_fields': ('res', 'proto'), # Prioritize direct http formats over HLS
327 }
328
329
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',
338 },
339 }, {
340 'url': 'https://www.cbc.ca/player/news/Canada/North',
341 'playlist_mincount': 25,
342 'info_dict': {
343 'id': 'news/canada/north',
344 },
345 }]
346
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)
352
353 def entries():
354 for video_id in traverse_obj(json_content, (
355 'video', 'clipsByCategory', lambda k, _: k.lower() == playlist_id, 'items', ..., 'id',
356 )):
357 yield self.url_result(f'https://www.cbc.ca/player/play/{video_id}', CBCPlayerIE)
358
359 return self.playlist_result(entries(), playlist_id)
360
361
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',
383 },
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'],
404 },
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,
410 }]
411
412 _GEO_COUNTRIES = ['CA']
413 _TOKEN_API_KEY = '3f4beddd-2061-49b0-ae80-6f1f2ed65b37'
414 _NETRC_MACHINE = 'cbcgem'
415 _claims_token = None
416
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']
427
428 query = {
429 'access_token': access_token,
430 'apikey': self._TOKEN_API_KEY,
431 'jwtapp': 'jwt',
432 }
433 resp = self._download_json('https://cloud-api.loginradius.com/sso/jwt/api/token',
434 None, headers=headers, query=query)
435 sig = resp['signature']
436
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']
442
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']
447
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']
455
456 def claims_token_expired(self):
457 exp = self._get_claims_token_expiry()
458 if exp - time.time() < 10:
459 # It will expire in less than 10 seconds, or has already expired
460 return True
461 return False
462
463 def claims_token_valid(self):
464 return self._claims_token is not None and not self.claims_token_expired()
465
466 def _get_claims_token(self, email, password):
467 if not self.claims_token_valid():
468 self._claims_token = self._new_claims_token(email, password)
469 self.cache.store(self._NETRC_MACHINE, 'claims_token', self._claims_token)
470 return self._claims_token
471
472 def _real_initialize(self):
473 if self.claims_token_valid():
474 return
475 self._claims_token = self.cache.load(self._NETRC_MACHINE, 'claims_token')
476
477 def _find_secret_formats(self, formats, video_id):
478 """ Find a valid video url and convert it to the secret variant """
479 base_format = next((f for f in formats if f.get('vcodec') != 'none'), None)
480 if not base_format:
481 return
482
483 base_url = re.sub(r'(Manifest\(.*?),filter=[\w-]+(.*?\))', r'\1\2', base_format['url'])
484 url = re.sub(r'(Manifest\(.*?),format=[\w-]+(.*?\))', r'\1\2', base_url)
485
486 secret_xml = self._download_xml(url, video_id, note='Downloading secret XML', fatal=False)
487 if not isinstance(secret_xml, xml.etree.ElementTree.Element):
488 return
489
490 for child in secret_xml:
491 if child.attrib.get('Type') != 'video':
492 continue
493 for video_quality in child:
494 bitrate = int_or_none(video_quality.attrib.get('Bitrate'))
495 if not bitrate or 'Index' not in video_quality.attrib:
496 continue
497 height = int_or_none(video_quality.attrib.get('MaxHeight'))
498
499 yield {
500 **base_format,
501 'format_id': join_nonempty('sec', height),
502 # Note: \g<1> is necessary instead of \1 since bitrate is a number
503 'url': re.sub(r'(QualityLevels\()\d+(\))', fr'\g<1>{bitrate}\2', base_url),
504 'width': int_or_none(video_quality.attrib.get('MaxWidth')),
505 'tbr': bitrate / 1000.0,
506 'height': height,
507 }
508
509 def _real_extract(self, url):
510 video_id = self._match_id(url)
511 video_info = self._download_json(
512 f'https://services.radio-canada.ca/ott/cbc-api/v2/assets/{video_id}',
513 video_id, expected_status=426)
514
515 email, password = self._get_login_info()
516 if email and password:
517 claims_token = self._get_claims_token(email, password)
518 headers = {'x-claims-token': claims_token}
519 else:
520 headers = {}
521 m3u8_info = self._download_json(video_info['playSession']['url'], video_id, headers=headers)
522 m3u8_url = m3u8_info.get('url')
523
524 if m3u8_info.get('errorCode') == 1:
525 self.raise_geo_restricted(countries=['CA'])
526 elif m3u8_info.get('errorCode') == 35:
527 self.raise_login_required(method='password')
528 elif m3u8_info.get('errorCode') != 0:
529 raise ExtractorError(f'{self.IE_NAME} said: {m3u8_info.get("errorCode")} - {m3u8_info.get("message")}')
530
531 formats = self._extract_m3u8_formats(m3u8_url, video_id, m3u8_id='hls')
532 self._remove_duplicate_formats(formats)
533 formats.extend(self._find_secret_formats(formats, video_id))
534
535 for fmt in formats:
536 if fmt.get('vcodec') == 'none':
537 if fmt.get('ext') is None:
538 fmt['ext'] = 'm4a'
539 if fmt.get('acodec') is None:
540 fmt['acodec'] = 'mp4a.40.2'
541
542 # Put described audio at the beginning of the list, so that it
543 # isn't chosen by default, as most people won't want it.
544 if 'descriptive' in fmt['format_id'].lower():
545 fmt['preference'] = -2
546
547 return {
548 'id': video_id,
549 'title': video_info['title'],
550 'description': video_info.get('description'),
551 'thumbnail': video_info.get('image'),
552 'series': video_info.get('series'),
553 'season_number': video_info.get('season'),
554 'season': f'Season {video_info.get("season")}',
555 'episode_number': video_info.get('episode'),
556 'episode': video_info.get('title'),
557 'episode_id': video_id,
558 'duration': video_info.get('duration'),
559 'categories': [video_info.get('category')],
560 'formats': formats,
561 'release_timestamp': video_info.get('airDate'),
562 'timestamp': video_info.get('availableDate'),
563 }
564
565
566 class CBCGemPlaylistIE(InfoExtractor):
567 IE_NAME = 'gem.cbc.ca:playlist'
568 _VALID_URL = r'https?://gem\.cbc\.ca/(?:media/)?(?P<id>(?P<show>[0-9a-z-]+)/s(?P<season>[0-9]+))/?(?:[?#]|$)'
569 _TESTS = [{
570 # TV show playlist, all public videos
571 'url': 'https://gem.cbc.ca/media/schitts-creek/s06',
572 'playlist_count': 16,
573 'info_dict': {
574 'id': 'schitts-creek/s06',
575 'title': 'Season 6',
576 'description': 'md5:6a92104a56cbeb5818cc47884d4326a2',
577 'series': 'Schitt\'s Creek',
578 'season_number': 6,
579 'season': 'Season 6',
580 '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',
581 },
582 }, {
583 'url': 'https://gem.cbc.ca/schitts-creek/s06',
584 'only_matching': True,
585 }]
586 _API_BASE = 'https://services.radio-canada.ca/ott/cbc-api/v2/shows/'
587
588 def _real_extract(self, url):
589 match = self._match_valid_url(url)
590 season_id = match.group('id')
591 show = match.group('show')
592 show_info = self._download_json(self._API_BASE + show, season_id, expected_status=426)
593 season = int(match.group('season'))
594
595 season_info = next((s for s in show_info['seasons'] if s.get('season') == season), None)
596
597 if season_info is None:
598 raise ExtractorError(f'Couldn\'t find season {season} of {show}')
599
600 episodes = []
601 for episode in season_info['assets']:
602 episodes.append({
603 '_type': 'url_transparent',
604 'ie_key': 'CBCGem',
605 'url': 'https://gem.cbc.ca/media/' + episode['id'],
606 'id': episode['id'],
607 'title': episode.get('title'),
608 'description': episode.get('description'),
609 'thumbnail': episode.get('image'),
610 'series': episode.get('series'),
611 'season_number': episode.get('season'),
612 'season': season_info['title'],
613 'season_id': season_info.get('id'),
614 'episode_number': episode.get('episode'),
615 'episode': episode.get('title'),
616 'episode_id': episode['id'],
617 'duration': episode.get('duration'),
618 'categories': [episode.get('category')],
619 })
620
621 thumbnail = None
622 tn_uri = season_info.get('image')
623 # the-national was observed to use a "data:image/png;base64"
624 # URI for their 'image' value. The image was 1x1, and is
625 # probably just a placeholder, so it is ignored.
626 if tn_uri is not None and not tn_uri.startswith('data:'):
627 thumbnail = tn_uri
628
629 return {
630 '_type': 'playlist',
631 'entries': episodes,
632 'id': season_id,
633 'title': season_info['title'],
634 'description': season_info.get('description'),
635 'thumbnail': thumbnail,
636 'series': show_info.get('title'),
637 'season_number': season_info.get('season'),
638 'season': season_info['title'],
639 }
640
641
642 class CBCGemLiveIE(InfoExtractor):
643 IE_NAME = 'gem.cbc.ca:live'
644 _VALID_URL = r'https?://gem\.cbc\.ca/live(?:-event)?/(?P<id>\d+)'
645 _TESTS = [
646 {
647 'url': 'https://gem.cbc.ca/live/920604739687',
648 'info_dict': {
649 'title': 'Ottawa',
650 'description': 'The live TV channel and local programming from Ottawa',
651 'thumbnail': 'https://thumbnails.cbc.ca/maven_legacy/thumbnails/CBC_OTT_VMS/Live_Channel_Static_Images/Ottawa_2880x1620.jpg',
652 'is_live': True,
653 'id': 'AyqZwxRqh8EH',
654 'ext': 'mp4',
655 'timestamp': 1492106160,
656 'upload_date': '20170413',
657 'uploader': 'CBCC-NEW',
658 },
659 'skip': 'Live might have ended',
660 },
661 {
662 'url': 'https://gem.cbc.ca/live/44',
663 'info_dict': {
664 'id': '44',
665 'ext': 'mp4',
666 'is_live': True,
667 'title': r're:^Ottawa [0-9\-: ]+',
668 'description': 'The live TV channel and local programming from Ottawa',
669 'live_status': 'is_live',
670 'thumbnail': r're:https://images.gem.cbc.ca/v1/cbc-gem/live/.*',
671 },
672 'params': {'skip_download': True},
673 'skip': 'Live might have ended',
674 },
675 {
676 'url': 'https://gem.cbc.ca/live-event/10835',
677 'info_dict': {
678 'id': '10835',
679 'ext': 'mp4',
680 'is_live': True,
681 'title': r're:^The National \| Biden’s trip wraps up, Paltrow testifies, Bird flu [0-9\-: ]+',
682 '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.',
683 'live_status': 'is_live',
684 'thumbnail': r're:https://images.gem.cbc.ca/v1/cbc-gem/live/.*',
685 'timestamp': 1679706000,
686 'upload_date': '20230325',
687 },
688 'params': {'skip_download': True},
689 'skip': 'Live might have ended',
690 },
691 ]
692
693 def _real_extract(self, url):
694 video_id = self._match_id(url)
695 webpage = self._download_webpage(url, video_id)
696 video_info = self._search_nextjs_data(webpage, video_id)['props']['pageProps']['data']
697
698 # Two types of metadata JSON
699 if not video_info.get('formattedIdMedia'):
700 video_info = traverse_obj(
701 video_info, (('freeTv', ('streams', ...)), 'items', lambda _, v: v['key'] == video_id, {dict}),
702 get_all=False, default={})
703
704 video_stream_id = video_info.get('formattedIdMedia')
705 if not video_stream_id:
706 raise ExtractorError('Couldn\'t find video metadata, maybe this livestream is now offline', expected=True)
707
708 stream_data = self._download_json(
709 'https://services.radio-canada.ca/media/validation/v2/', video_id, query={
710 'appCode': 'mpx',
711 'connectionType': 'hd',
712 'deviceType': 'ipad',
713 'idMedia': video_stream_id,
714 'multibitrate': 'true',
715 'output': 'json',
716 'tech': 'hls',
717 'manifestType': 'desktop',
718 })
719
720 return {
721 'id': video_id,
722 'formats': self._extract_m3u8_formats(stream_data['url'], video_id, 'mp4', live=True),
723 'is_live': True,
724 **traverse_obj(video_info, {
725 'title': 'title',
726 'description': 'description',
727 'thumbnail': ('images', 'card', 'url'),
728 'timestamp': ('airDate', {parse_iso8601}),
729 }),
730 }