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