cbc.py 30 KB

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