logo

youtube-dl

[mirror] Download/Watch videos from video hostersgit clone https://hacktivis.me/git/mirror/youtube-dl.git

cbc.py (20649B)


  1. # coding: utf-8
  2. from __future__ import unicode_literals
  3. import hashlib
  4. import json
  5. import re
  6. from xml.sax.saxutils import escape
  7. from .common import InfoExtractor
  8. from ..compat import (
  9. compat_str,
  10. compat_HTTPError,
  11. )
  12. from ..utils import (
  13. js_to_json,
  14. smuggle_url,
  15. try_get,
  16. xpath_text,
  17. xpath_element,
  18. xpath_with_ns,
  19. find_xpath_attr,
  20. orderedSet,
  21. parse_duration,
  22. parse_iso8601,
  23. parse_age_limit,
  24. strip_or_none,
  25. int_or_none,
  26. ExtractorError,
  27. )
  28. class CBCIE(InfoExtractor):
  29. IE_NAME = 'cbc.ca'
  30. _VALID_URL = r'https?://(?:www\.)?cbc\.ca/(?!player/)(?:[^/]+/)+(?P<id>[^/?#]+)'
  31. _TESTS = [{
  32. # with mediaId
  33. 'url': 'http://www.cbc.ca/22minutes/videos/clips-season-23/don-cherry-play-offs',
  34. 'md5': '97e24d09672fc4cf56256d6faa6c25bc',
  35. 'info_dict': {
  36. 'id': '2682904050',
  37. 'ext': 'mp4',
  38. 'title': 'Don Cherry – All-Stars',
  39. 'description': 'Don Cherry has a bee in his bonnet about AHL player John Scott because that guy’s got heart.',
  40. 'timestamp': 1454463000,
  41. 'upload_date': '20160203',
  42. 'uploader': 'CBCC-NEW',
  43. },
  44. 'skip': 'Geo-restricted to Canada',
  45. }, {
  46. # with clipId, feed available via tpfeed.cbc.ca and feed.theplatform.com
  47. 'url': 'http://www.cbc.ca/22minutes/videos/22-minutes-update/22-minutes-update-episode-4',
  48. 'md5': '162adfa070274b144f4fdc3c3b8207db',
  49. 'info_dict': {
  50. 'id': '2414435309',
  51. 'ext': 'mp4',
  52. 'title': '22 Minutes Update: What Not To Wear Quebec',
  53. 'description': "This week's latest Canadian top political story is What Not To Wear Quebec.",
  54. 'upload_date': '20131025',
  55. 'uploader': 'CBCC-NEW',
  56. 'timestamp': 1382717907,
  57. },
  58. }, {
  59. # with clipId, feed only available via tpfeed.cbc.ca
  60. 'url': 'http://www.cbc.ca/archives/entry/1978-robin-williams-freestyles-on-90-minutes-live',
  61. 'md5': '0274a90b51a9b4971fe005c63f592f12',
  62. 'info_dict': {
  63. 'id': '2487345465',
  64. 'ext': 'mp4',
  65. 'title': 'Robin Williams freestyles on 90 Minutes Live',
  66. 'description': 'Wacky American comedian Robin Williams shows off his infamous "freestyle" comedic talents while being interviewed on CBC\'s 90 Minutes Live.',
  67. 'upload_date': '19780210',
  68. 'uploader': 'CBCC-NEW',
  69. 'timestamp': 255977160,
  70. },
  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',
  84. },
  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',
  95. },
  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',
  103. 'id': 'dog-indoor-exercise-winter-1.3928238',
  104. 'description': 'md5:c18552e41726ee95bd75210d1ca9194c',
  105. },
  106. 'playlist_mincount': 6,
  107. }]
  108. @classmethod
  109. def suitable(cls, url):
  110. return False if CBCPlayerIE.suitable(url) else super(CBCIE, cls).suitable(url)
  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. 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) or self._html_search_meta(
  130. 'twitter:title', webpage, 'title', default=None) or self._html_search_regex(
  131. r'<title>([^<]+)</title>', webpage, 'title', fatal=False)
  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('cbcplayer:%s' % 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. class CBCPlayerIE(InfoExtractor):
  148. IE_NAME = 'cbc.ca:player'
  149. _VALID_URL = r'(?:cbcplayer:|https?://(?:www\.)?cbc\.ca/(?:player/play/|i/caffeine/syndicate/\?mediaId=))(?P<id>\d+)'
  150. _TESTS = [{
  151. 'url': 'http://www.cbc.ca/player/play/2683190193',
  152. 'md5': '64d25f841ddf4ddb28a235338af32e2c',
  153. 'info_dict': {
  154. 'id': '2683190193',
  155. 'ext': 'mp4',
  156. 'title': 'Gerry Runs a Sweat Shop',
  157. 'description': 'md5:b457e1c01e8ff408d9d801c1c2cd29b0',
  158. 'timestamp': 1455071400,
  159. 'upload_date': '20160210',
  160. 'uploader': 'CBCC-NEW',
  161. },
  162. 'skip': 'Geo-restricted to Canada',
  163. }, {
  164. # Redirected from http://www.cbc.ca/player/AudioMobile/All%20in%20a%20Weekend%20Montreal/ID/2657632011/
  165. 'url': 'http://www.cbc.ca/player/play/2657631896',
  166. 'md5': 'e5e708c34ae6fca156aafe17c43e8b75',
  167. 'info_dict': {
  168. 'id': '2657631896',
  169. 'ext': 'mp3',
  170. 'title': 'CBC Montreal is organizing its first ever community hackathon!',
  171. '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.',
  172. 'timestamp': 1425704400,
  173. 'upload_date': '20150307',
  174. 'uploader': 'CBCC-NEW',
  175. },
  176. }, {
  177. 'url': 'http://www.cbc.ca/player/play/2164402062',
  178. 'md5': '33fcd8f6719b9dd60a5e73adcb83b9f6',
  179. 'info_dict': {
  180. 'id': '2164402062',
  181. 'ext': 'mp4',
  182. 'title': 'Cancer survivor four times over',
  183. 'description': 'Tim Mayer has beaten three different forms of cancer four times in five years.',
  184. 'timestamp': 1320410746,
  185. 'upload_date': '20111104',
  186. 'uploader': 'CBCC-NEW',
  187. },
  188. }]
  189. def _real_extract(self, url):
  190. video_id = self._match_id(url)
  191. return {
  192. '_type': 'url_transparent',
  193. 'ie_key': 'ThePlatform',
  194. 'url': smuggle_url(
  195. 'http://link.theplatform.com/s/ExhSPC/media/guid/2655402169/%s?mbr=true&formats=MPEG4,FLV,MP3' % video_id, {
  196. 'force_smil_url': True
  197. }),
  198. 'id': video_id,
  199. }
  200. class CBCWatchBaseIE(InfoExtractor):
  201. _device_id = None
  202. _device_token = None
  203. _API_BASE_URL = 'https://api-cbc.cloud.clearleap.com/cloffice/client/'
  204. _NS_MAP = {
  205. 'media': 'http://search.yahoo.com/mrss/',
  206. 'clearleap': 'http://www.clearleap.com/namespace/clearleap/1.0/',
  207. }
  208. _GEO_COUNTRIES = ['CA']
  209. _LOGIN_URL = 'https://api.loginradius.com/identity/v2/auth/login'
  210. _TOKEN_URL = 'https://cloud-api.loginradius.com/sso/jwt/api/token'
  211. _API_KEY = '3f4beddd-2061-49b0-ae80-6f1f2ed65b37'
  212. _NETRC_MACHINE = 'cbcwatch'
  213. def _signature(self, email, password):
  214. data = json.dumps({
  215. 'email': email,
  216. 'password': password,
  217. }).encode()
  218. headers = {'content-type': 'application/json'}
  219. query = {'apikey': self._API_KEY}
  220. resp = self._download_json(self._LOGIN_URL, None, data=data, headers=headers, query=query)
  221. access_token = resp['access_token']
  222. # token
  223. query = {
  224. 'access_token': access_token,
  225. 'apikey': self._API_KEY,
  226. 'jwtapp': 'jwt',
  227. }
  228. resp = self._download_json(self._TOKEN_URL, None, headers=headers, query=query)
  229. return resp['signature']
  230. def _call_api(self, path, video_id):
  231. url = path if path.startswith('http') else self._API_BASE_URL + path
  232. for _ in range(2):
  233. try:
  234. result = self._download_xml(url, video_id, headers={
  235. 'X-Clearleap-DeviceId': self._device_id,
  236. 'X-Clearleap-DeviceToken': self._device_token,
  237. })
  238. except ExtractorError as e:
  239. if isinstance(e.cause, compat_HTTPError) and e.cause.code == 401:
  240. # Device token has expired, re-acquiring device token
  241. self._register_device()
  242. continue
  243. raise
  244. error_message = xpath_text(result, 'userMessage') or xpath_text(result, 'systemMessage')
  245. if error_message:
  246. raise ExtractorError('%s said: %s' % (self.IE_NAME, error_message))
  247. return result
  248. def _real_initialize(self):
  249. if self._valid_device_token():
  250. return
  251. device = self._downloader.cache.load(
  252. 'cbcwatch', self._cache_device_key()) or {}
  253. self._device_id, self._device_token = device.get('id'), device.get('token')
  254. if self._valid_device_token():
  255. return
  256. self._register_device()
  257. def _valid_device_token(self):
  258. return self._device_id and self._device_token
  259. def _cache_device_key(self):
  260. email, _ = self._get_login_info()
  261. return '%s_device' % hashlib.sha256(email.encode()).hexdigest() if email else 'device'
  262. def _register_device(self):
  263. result = self._download_xml(
  264. self._API_BASE_URL + 'device/register',
  265. None, 'Acquiring device token',
  266. data=b'<device><type>web</type></device>')
  267. self._device_id = xpath_text(result, 'deviceId', fatal=True)
  268. email, password = self._get_login_info()
  269. if email and password:
  270. signature = self._signature(email, password)
  271. data = '<login><token>{0}</token><device><deviceId>{1}</deviceId><type>web</type></device></login>'.format(
  272. escape(signature), escape(self._device_id)).encode()
  273. url = self._API_BASE_URL + 'device/login'
  274. result = self._download_xml(
  275. url, None, data=data,
  276. headers={'content-type': 'application/xml'})
  277. self._device_token = xpath_text(result, 'token', fatal=True)
  278. else:
  279. self._device_token = xpath_text(result, 'deviceToken', fatal=True)
  280. self._downloader.cache.store(
  281. 'cbcwatch', self._cache_device_key(), {
  282. 'id': self._device_id,
  283. 'token': self._device_token,
  284. })
  285. def _parse_rss_feed(self, rss):
  286. channel = xpath_element(rss, 'channel', fatal=True)
  287. def _add_ns(path):
  288. return xpath_with_ns(path, self._NS_MAP)
  289. entries = []
  290. for item in channel.findall('item'):
  291. guid = xpath_text(item, 'guid', fatal=True)
  292. title = xpath_text(item, 'title', fatal=True)
  293. media_group = xpath_element(item, _add_ns('media:group'), fatal=True)
  294. content = xpath_element(media_group, _add_ns('media:content'), fatal=True)
  295. content_url = content.attrib['url']
  296. thumbnails = []
  297. for thumbnail in media_group.findall(_add_ns('media:thumbnail')):
  298. thumbnail_url = thumbnail.get('url')
  299. if not thumbnail_url:
  300. continue
  301. thumbnails.append({
  302. 'id': thumbnail.get('profile'),
  303. 'url': thumbnail_url,
  304. 'width': int_or_none(thumbnail.get('width')),
  305. 'height': int_or_none(thumbnail.get('height')),
  306. })
  307. timestamp = None
  308. release_date = find_xpath_attr(
  309. item, _add_ns('media:credit'), 'role', 'releaseDate')
  310. if release_date is not None:
  311. timestamp = parse_iso8601(release_date.text)
  312. entries.append({
  313. '_type': 'url_transparent',
  314. 'url': content_url,
  315. 'id': guid,
  316. 'title': title,
  317. 'description': xpath_text(item, 'description'),
  318. 'timestamp': timestamp,
  319. 'duration': int_or_none(content.get('duration')),
  320. 'age_limit': parse_age_limit(xpath_text(item, _add_ns('media:rating'))),
  321. 'episode': xpath_text(item, _add_ns('clearleap:episode')),
  322. 'episode_number': int_or_none(xpath_text(item, _add_ns('clearleap:episodeInSeason'))),
  323. 'series': xpath_text(item, _add_ns('clearleap:series')),
  324. 'season_number': int_or_none(xpath_text(item, _add_ns('clearleap:season'))),
  325. 'thumbnails': thumbnails,
  326. 'ie_key': 'CBCWatchVideo',
  327. })
  328. return self.playlist_result(
  329. entries, xpath_text(channel, 'guid'),
  330. xpath_text(channel, 'title'),
  331. xpath_text(channel, 'description'))
  332. class CBCWatchVideoIE(CBCWatchBaseIE):
  333. IE_NAME = 'cbc.ca:watch:video'
  334. _VALID_URL = r'https?://api-cbc\.cloud\.clearleap\.com/cloffice/client/web/play/?\?.*?\bcontentId=(?P<id>[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12})'
  335. _TEST = {
  336. # geo-restricted to Canada, bypassable
  337. 'url': 'https://api-cbc.cloud.clearleap.com/cloffice/client/web/play/?contentId=3c84472a-1eea-4dee-9267-2655d5055dcf&categoryId=ebc258f5-ee40-4cca-b66b-ba6bd55b7235',
  338. 'only_matching': True,
  339. }
  340. def _real_extract(self, url):
  341. video_id = self._match_id(url)
  342. result = self._call_api(url, video_id)
  343. m3u8_url = xpath_text(result, 'url', fatal=True)
  344. formats = self._extract_m3u8_formats(re.sub(r'/([^/]+)/[^/?]+\.m3u8', r'/\1/\1.m3u8', m3u8_url), video_id, 'mp4', fatal=False)
  345. if len(formats) < 2:
  346. formats = self._extract_m3u8_formats(m3u8_url, video_id, 'mp4')
  347. for f in formats:
  348. format_id = f.get('format_id')
  349. if format_id.startswith('AAC'):
  350. f['acodec'] = 'aac'
  351. elif format_id.startswith('AC3'):
  352. f['acodec'] = 'ac-3'
  353. self._sort_formats(formats)
  354. info = {
  355. 'id': video_id,
  356. 'title': video_id,
  357. 'formats': formats,
  358. }
  359. rss = xpath_element(result, 'rss')
  360. if rss:
  361. info.update(self._parse_rss_feed(rss)['entries'][0])
  362. del info['url']
  363. del info['_type']
  364. del info['ie_key']
  365. return info
  366. class CBCWatchIE(CBCWatchBaseIE):
  367. IE_NAME = 'cbc.ca:watch'
  368. _VALID_URL = r'https?://(?:gem|watch)\.cbc\.ca/(?:[^/]+/)+(?P<id>[0-9a-f-]+)'
  369. _TESTS = [{
  370. # geo-restricted to Canada, bypassable
  371. 'url': 'http://watch.cbc.ca/doc-zone/season-6/customer-disservice/38e815a-009e3ab12e4',
  372. 'info_dict': {
  373. 'id': '9673749a-5e77-484c-8b62-a1092a6b5168',
  374. 'ext': 'mp4',
  375. 'title': 'Customer (Dis)Service',
  376. 'description': 'md5:8bdd6913a0fe03d4b2a17ebe169c7c87',
  377. 'upload_date': '20160219',
  378. 'timestamp': 1455840000,
  379. },
  380. 'params': {
  381. # m3u8 download
  382. 'skip_download': True,
  383. 'format': 'bestvideo',
  384. },
  385. }, {
  386. # geo-restricted to Canada, bypassable
  387. 'url': 'http://watch.cbc.ca/arthur/all/1ed4b385-cd84-49cf-95f0-80f004680057',
  388. 'info_dict': {
  389. 'id': '1ed4b385-cd84-49cf-95f0-80f004680057',
  390. 'title': 'Arthur',
  391. 'description': 'Arthur, the sweetest 8-year-old aardvark, and his pals solve all kinds of problems with humour, kindness and teamwork.',
  392. },
  393. 'playlist_mincount': 30,
  394. }, {
  395. 'url': 'https://gem.cbc.ca/media/this-hour-has-22-minutes/season-26/episode-20/38e815a-0108c6c6a42',
  396. 'only_matching': True,
  397. }]
  398. def _real_extract(self, url):
  399. video_id = self._match_id(url)
  400. rss = self._call_api('web/browse/' + video_id, video_id)
  401. return self._parse_rss_feed(rss)
  402. class CBCOlympicsIE(InfoExtractor):
  403. IE_NAME = 'cbc.ca:olympics'
  404. _VALID_URL = r'https?://olympics\.cbc\.ca/video/[^/]+/(?P<id>[^/?#]+)'
  405. _TESTS = [{
  406. 'url': 'https://olympics.cbc.ca/video/whats-on-tv/olympic-morning-featuring-the-opening-ceremony/',
  407. 'only_matching': True,
  408. }]
  409. def _real_extract(self, url):
  410. display_id = self._match_id(url)
  411. webpage = self._download_webpage(url, display_id)
  412. video_id = self._hidden_inputs(webpage)['videoId']
  413. video_doc = self._download_xml(
  414. 'https://olympics.cbc.ca/videodata/%s.xml' % video_id, video_id)
  415. title = xpath_text(video_doc, 'title', fatal=True)
  416. is_live = xpath_text(video_doc, 'kind') == 'Live'
  417. if is_live:
  418. title = self._live_title(title)
  419. formats = []
  420. for video_source in video_doc.findall('videoSources/videoSource'):
  421. uri = xpath_text(video_source, 'uri')
  422. if not uri:
  423. continue
  424. tokenize = self._download_json(
  425. 'https://olympics.cbc.ca/api/api-akamai/tokenize',
  426. video_id, data=json.dumps({
  427. 'VideoSource': uri,
  428. }).encode(), headers={
  429. 'Content-Type': 'application/json',
  430. 'Referer': url,
  431. # d3.VideoPlayer._init in https://olympics.cbc.ca/components/script/base.js
  432. 'Cookie': '_dvp=TK:C0ObxjerU', # AKAMAI CDN cookie
  433. }, fatal=False)
  434. if not tokenize:
  435. continue
  436. content_url = tokenize['ContentUrl']
  437. video_source_format = video_source.get('format')
  438. if video_source_format == 'IIS':
  439. formats.extend(self._extract_ism_formats(
  440. content_url, video_id, ism_id=video_source_format, fatal=False))
  441. else:
  442. formats.extend(self._extract_m3u8_formats(
  443. content_url, video_id, 'mp4',
  444. 'm3u8' if is_live else 'm3u8_native',
  445. m3u8_id=video_source_format, fatal=False))
  446. self._sort_formats(formats)
  447. return {
  448. 'id': video_id,
  449. 'display_id': display_id,
  450. 'title': title,
  451. 'description': xpath_text(video_doc, 'description'),
  452. 'thumbnail': xpath_text(video_doc, 'thumbnailUrl'),
  453. 'duration': parse_duration(xpath_text(video_doc, 'duration')),
  454. 'formats': formats,
  455. 'is_live': is_live,
  456. }