You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

457 lines
18 KiB

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