]> Raphaël G. Git Repositories - youtubedl/blob - youtube_dl/extractor/cbc.py
New upstream version 2016.12.01
[youtubedl] / youtube_dl / extractor / cbc.py
1 # coding: utf-8
2 from __future__ import unicode_literals
3
4 import re
5
6 from .common import InfoExtractor
7 from ..compat import compat_str
8 from ..utils import (
9 js_to_json,
10 smuggle_url,
11 try_get,
12 xpath_text,
13 xpath_element,
14 xpath_with_ns,
15 find_xpath_attr,
16 parse_iso8601,
17 parse_age_limit,
18 int_or_none,
19 ExtractorError,
20 )
21
22
23 class CBCIE(InfoExtractor):
24 IE_NAME = 'cbc.ca'
25 _VALID_URL = r'https?://(?:www\.)?cbc\.ca/(?!player/)(?:[^/]+/)+(?P<id>[^/?#]+)'
26 _TESTS = [{
27 # with mediaId
28 'url': 'http://www.cbc.ca/22minutes/videos/clips-season-23/don-cherry-play-offs',
29 'md5': '97e24d09672fc4cf56256d6faa6c25bc',
30 'info_dict': {
31 'id': '2682904050',
32 'ext': 'mp4',
33 'title': 'Don Cherry – All-Stars',
34 'description': 'Don Cherry has a bee in his bonnet about AHL player John Scott because that guy’s got heart.',
35 'timestamp': 1454463000,
36 'upload_date': '20160203',
37 'uploader': 'CBCC-NEW',
38 },
39 'skip': 'Geo-restricted to Canada',
40 }, {
41 # with clipId, feed available via tpfeed.cbc.ca and feed.theplatform.com
42 'url': 'http://www.cbc.ca/22minutes/videos/22-minutes-update/22-minutes-update-episode-4',
43 'md5': '162adfa070274b144f4fdc3c3b8207db',
44 'info_dict': {
45 'id': '2414435309',
46 'ext': 'mp4',
47 'title': '22 Minutes Update: What Not To Wear Quebec',
48 'description': "This week's latest Canadian top political story is What Not To Wear Quebec.",
49 'upload_date': '20131025',
50 'uploader': 'CBCC-NEW',
51 'timestamp': 1382717907,
52 },
53 }, {
54 # with clipId, feed only available via tpfeed.cbc.ca
55 'url': 'http://www.cbc.ca/archives/entry/1978-robin-williams-freestyles-on-90-minutes-live',
56 'md5': '0274a90b51a9b4971fe005c63f592f12',
57 'info_dict': {
58 'id': '2487345465',
59 'ext': 'mp4',
60 'title': 'Robin Williams freestyles on 90 Minutes Live',
61 'description': 'Wacky American comedian Robin Williams shows off his infamous "freestyle" comedic talents while being interviewed on CBC\'s 90 Minutes Live.',
62 'upload_date': '19780210',
63 'uploader': 'CBCC-NEW',
64 'timestamp': 255977160,
65 },
66 }, {
67 # multiple iframes
68 'url': 'http://www.cbc.ca/natureofthings/blog/birds-eye-view-from-vancouvers-burrard-street-bridge-how-we-got-the-shot',
69 'playlist': [{
70 'md5': '377572d0b49c4ce0c9ad77470e0b96b4',
71 'info_dict': {
72 'id': '2680832926',
73 'ext': 'mp4',
74 'title': 'An Eagle\'s-Eye View Off Burrard Bridge',
75 'description': 'Hercules the eagle flies from Vancouver\'s Burrard Bridge down to a nearby park with a mini-camera strapped to his back.',
76 'upload_date': '20160201',
77 'timestamp': 1454342820,
78 'uploader': 'CBCC-NEW',
79 },
80 }, {
81 'md5': '415a0e3f586113894174dfb31aa5bb1a',
82 'info_dict': {
83 'id': '2658915080',
84 'ext': 'mp4',
85 'title': 'Fly like an eagle!',
86 'description': 'Eagle equipped with a mini camera flies from the world\'s tallest tower',
87 'upload_date': '20150315',
88 'timestamp': 1426443984,
89 'uploader': 'CBCC-NEW',
90 },
91 }],
92 'skip': 'Geo-restricted to Canada',
93 }]
94
95 @classmethod
96 def suitable(cls, url):
97 return False if CBCPlayerIE.suitable(url) else super(CBCIE, cls).suitable(url)
98
99 def _real_extract(self, url):
100 display_id = self._match_id(url)
101 webpage = self._download_webpage(url, display_id)
102 player_init = self._search_regex(
103 r'CBC\.APP\.Caffeine\.initInstance\(({.+?})\);', webpage, 'player init',
104 default=None)
105 if player_init:
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 'http://tpfeed.cbc.ca/f/ExhSPC/vms_5akSXx4Ng_Zn?byCustomValue={:mpsReleases}{%s}' % clip_id,
112 clip_id, fatal=False)
113 if feed:
114 media_id = try_get(feed, lambda x: x['entries'][0]['guid'], compat_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('cbcplayer:%s' % media_id, 'CBCPlayer', media_id)
120 else:
121 entries = [self.url_result('cbcplayer:%s' % media_id, 'CBCPlayer', media_id) for media_id in re.findall(r'<iframe[^>]+src="[^"]+?mediaId=(\d+)"', webpage)]
122 return self.playlist_result(entries)
123
124
125 class CBCPlayerIE(InfoExtractor):
126 IE_NAME = 'cbc.ca:player'
127 _VALID_URL = r'(?:cbcplayer:|https?://(?:www\.)?cbc\.ca/(?:player/play/|i/caffeine/syndicate/\?mediaId=))(?P<id>\d+)'
128 _TESTS = [{
129 'url': 'http://www.cbc.ca/player/play/2683190193',
130 'md5': '64d25f841ddf4ddb28a235338af32e2c',
131 'info_dict': {
132 'id': '2683190193',
133 'ext': 'mp4',
134 'title': 'Gerry Runs a Sweat Shop',
135 'description': 'md5:b457e1c01e8ff408d9d801c1c2cd29b0',
136 'timestamp': 1455071400,
137 'upload_date': '20160210',
138 'uploader': 'CBCC-NEW',
139 },
140 'skip': 'Geo-restricted to Canada',
141 }, {
142 # Redirected from http://www.cbc.ca/player/AudioMobile/All%20in%20a%20Weekend%20Montreal/ID/2657632011/
143 'url': 'http://www.cbc.ca/player/play/2657631896',
144 'md5': 'e5e708c34ae6fca156aafe17c43e8b75',
145 'info_dict': {
146 'id': '2657631896',
147 'ext': 'mp3',
148 'title': 'CBC Montreal is organizing its first ever community hackathon!',
149 '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.',
150 'timestamp': 1425704400,
151 'upload_date': '20150307',
152 'uploader': 'CBCC-NEW',
153 },
154 }, {
155 # available only when we add `formats=MPEG4,FLV,MP3` to theplatform url
156 'url': 'http://www.cbc.ca/player/play/2164402062',
157 'md5': '17a61eb813539abea40618d6323a7f82',
158 'info_dict': {
159 'id': '2164402062',
160 'ext': 'flv',
161 'title': 'Cancer survivor four times over',
162 'description': 'Tim Mayer has beaten three different forms of cancer four times in five years.',
163 'timestamp': 1320410746,
164 'upload_date': '20111104',
165 'uploader': 'CBCC-NEW',
166 },
167 }]
168
169 def _real_extract(self, url):
170 video_id = self._match_id(url)
171 return {
172 '_type': 'url_transparent',
173 'ie_key': 'ThePlatform',
174 'url': smuggle_url(
175 'http://link.theplatform.com/s/ExhSPC/media/guid/2655402169/%s?mbr=true&formats=MPEG4,FLV,MP3' % video_id, {
176 'force_smil_url': True
177 }),
178 'id': video_id,
179 }
180
181
182 class CBCWatchBaseIE(InfoExtractor):
183 _device_id = None
184 _device_token = None
185 _API_BASE_URL = 'https://api-cbc.cloud.clearleap.com/cloffice/client/'
186 _NS_MAP = {
187 'media': 'http://search.yahoo.com/mrss/',
188 'clearleap': 'http://www.clearleap.com/namespace/clearleap/1.0/',
189 }
190
191 def _call_api(self, path, video_id):
192 url = path if path.startswith('http') else self._API_BASE_URL + path
193 result = self._download_xml(url, video_id, headers={
194 'X-Clearleap-DeviceId': self._device_id,
195 'X-Clearleap-DeviceToken': self._device_token,
196 })
197 error_message = xpath_text(result, 'userMessage') or xpath_text(result, 'systemMessage')
198 if error_message:
199 raise ExtractorError('%s said: %s' % (self.IE_NAME, error_message))
200 return result
201
202 def _real_initialize(self):
203 if not self._device_id or not self._device_token:
204 device = self._downloader.cache.load('cbcwatch', 'device') or {}
205 self._device_id, self._device_token = device.get('id'), device.get('token')
206 if not self._device_id or not self._device_token:
207 result = self._download_xml(
208 self._API_BASE_URL + 'device/register',
209 None, data=b'<device><type>web</type></device>')
210 self._device_id = xpath_text(result, 'deviceId', fatal=True)
211 self._device_token = xpath_text(result, 'deviceToken', fatal=True)
212 self._downloader.cache.store(
213 'cbcwatch', 'device', {
214 'id': self._device_id,
215 'token': self._device_token,
216 })
217
218 def _parse_rss_feed(self, rss):
219 channel = xpath_element(rss, 'channel', fatal=True)
220
221 def _add_ns(path):
222 return xpath_with_ns(path, self._NS_MAP)
223
224 entries = []
225 for item in channel.findall('item'):
226 guid = xpath_text(item, 'guid', fatal=True)
227 title = xpath_text(item, 'title', fatal=True)
228
229 media_group = xpath_element(item, _add_ns('media:group'), fatal=True)
230 content = xpath_element(media_group, _add_ns('media:content'), fatal=True)
231 content_url = content.attrib['url']
232
233 thumbnails = []
234 for thumbnail in media_group.findall(_add_ns('media:thumbnail')):
235 thumbnail_url = thumbnail.get('url')
236 if not thumbnail_url:
237 continue
238 thumbnails.append({
239 'id': thumbnail.get('profile'),
240 'url': thumbnail_url,
241 'width': int_or_none(thumbnail.get('width')),
242 'height': int_or_none(thumbnail.get('height')),
243 })
244
245 timestamp = None
246 release_date = find_xpath_attr(
247 item, _add_ns('media:credit'), 'role', 'releaseDate')
248 if release_date is not None:
249 timestamp = parse_iso8601(release_date.text)
250
251 entries.append({
252 '_type': 'url_transparent',
253 'url': content_url,
254 'id': guid,
255 'title': title,
256 'description': xpath_text(item, 'description'),
257 'timestamp': timestamp,
258 'duration': int_or_none(content.get('duration')),
259 'age_limit': parse_age_limit(xpath_text(item, _add_ns('media:rating'))),
260 'episode': xpath_text(item, _add_ns('clearleap:episode')),
261 'episode_number': int_or_none(xpath_text(item, _add_ns('clearleap:episodeInSeason'))),
262 'series': xpath_text(item, _add_ns('clearleap:series')),
263 'season_number': int_or_none(xpath_text(item, _add_ns('clearleap:season'))),
264 'thumbnails': thumbnails,
265 'ie_key': 'CBCWatchVideo',
266 })
267
268 return self.playlist_result(
269 entries, xpath_text(channel, 'guid'),
270 xpath_text(channel, 'title'),
271 xpath_text(channel, 'description'))
272
273
274 class CBCWatchVideoIE(CBCWatchBaseIE):
275 IE_NAME = 'cbc.ca:watch:video'
276 _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})'
277
278 def _real_extract(self, url):
279 video_id = self._match_id(url)
280 result = self._call_api(url, video_id)
281
282 m3u8_url = xpath_text(result, 'url', fatal=True)
283 formats = self._extract_m3u8_formats(re.sub(r'/([^/]+)/[^/?]+\.m3u8', r'/\1/\1.m3u8', m3u8_url), video_id, 'mp4', fatal=False)
284 if len(formats) < 2:
285 formats = self._extract_m3u8_formats(m3u8_url, video_id, 'mp4')
286 # Despite metadata in m3u8 all video+audio formats are
287 # actually video-only (no audio)
288 for f in formats:
289 if f.get('acodec') != 'none' and f.get('vcodec') != 'none':
290 f['acodec'] = 'none'
291 self._sort_formats(formats)
292
293 info = {
294 'id': video_id,
295 'title': video_id,
296 'formats': formats,
297 }
298
299 rss = xpath_element(result, 'rss')
300 if rss:
301 info.update(self._parse_rss_feed(rss)['entries'][0])
302 del info['url']
303 del info['_type']
304 del info['ie_key']
305 return info
306
307
308 class CBCWatchIE(CBCWatchBaseIE):
309 IE_NAME = 'cbc.ca:watch'
310 _VALID_URL = r'https?://watch\.cbc\.ca/(?:[^/]+/)+(?P<id>[0-9a-f-]+)'
311 _TESTS = [{
312 'url': 'http://watch.cbc.ca/doc-zone/season-6/customer-disservice/38e815a-009e3ab12e4',
313 'info_dict': {
314 'id': '38e815a-009e3ab12e4',
315 'ext': 'mp4',
316 'title': 'Customer (Dis)Service',
317 'description': 'md5:8bdd6913a0fe03d4b2a17ebe169c7c87',
318 'upload_date': '20160219',
319 'timestamp': 1455840000,
320 },
321 'params': {
322 # m3u8 download
323 'skip_download': True,
324 'format': 'bestvideo',
325 },
326 'skip': 'Geo-restricted to Canada',
327 }, {
328 'url': 'http://watch.cbc.ca/arthur/all/1ed4b385-cd84-49cf-95f0-80f004680057',
329 'info_dict': {
330 'id': '1ed4b385-cd84-49cf-95f0-80f004680057',
331 'title': 'Arthur',
332 'description': 'Arthur, the sweetest 8-year-old aardvark, and his pals solve all kinds of problems with humour, kindness and teamwork.',
333 },
334 'playlist_mincount': 30,
335 'skip': 'Geo-restricted to Canada',
336 }]
337
338 def _real_extract(self, url):
339 video_id = self._match_id(url)
340 rss = self._call_api('web/browse/' + video_id, video_id)
341 return self._parse_rss_feed(rss)