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