]> Raphaƫl G. Git Repositories - youtubedl/blob - youtube_dl/extractor/bbccouk.py
5825d286774fa003d343f41c85e07e35340cb428
[youtubedl] / youtube_dl / extractor / bbccouk.py
1 from __future__ import unicode_literals
2
3 import xml.etree.ElementTree
4
5 from .common import InfoExtractor
6 from ..utils import (
7 ExtractorError,
8 int_or_none,
9 )
10 from ..compat import compat_HTTPError
11
12
13 class BBCCoUkIE(InfoExtractor):
14 IE_NAME = 'bbc.co.uk'
15 IE_DESC = 'BBC iPlayer'
16 _VALID_URL = r'https?://(?:www\.)?bbc\.co\.uk/(?:(?:(?:programmes|iplayer(?:/[^/]+)?/(?:episode|playlist))/)|music/clips[/#])(?P<id>[\da-z]{8})'
17
18 _TESTS = [
19 {
20 'url': 'http://www.bbc.co.uk/programmes/b039g8p7',
21 'info_dict': {
22 'id': 'b039d07m',
23 'ext': 'flv',
24 'title': 'Kaleidoscope, Leonard Cohen',
25 'description': 'The Canadian poet and songwriter reflects on his musical career.',
26 'duration': 1740,
27 },
28 'params': {
29 # rtmp download
30 'skip_download': True,
31 }
32 },
33 {
34 'url': 'http://www.bbc.co.uk/iplayer/episode/b00yng5w/The_Man_in_Black_Series_3_The_Printed_Name/',
35 'info_dict': {
36 'id': 'b00yng1d',
37 'ext': 'flv',
38 'title': 'The Man in Black: Series 3: The Printed Name',
39 'description': "Mark Gatiss introduces Nicholas Pierpan's chilling tale of a writer's devilish pact with a mysterious man. Stars Ewan Bailey.",
40 'duration': 1800,
41 },
42 'params': {
43 # rtmp download
44 'skip_download': True,
45 },
46 'skip': 'Episode is no longer available on BBC iPlayer Radio',
47 },
48 {
49 'url': 'http://www.bbc.co.uk/iplayer/episode/b03vhd1f/The_Voice_UK_Series_3_Blind_Auditions_5/',
50 'info_dict': {
51 'id': 'b00yng1d',
52 'ext': 'flv',
53 'title': 'The Voice UK: Series 3: Blind Auditions 5',
54 'description': "Emma Willis and Marvin Humes present the fifth set of blind auditions in the singing competition, as the coaches continue to build their teams based on voice alone.",
55 'duration': 5100,
56 },
57 'params': {
58 # rtmp download
59 'skip_download': True,
60 },
61 'skip': 'Currently BBC iPlayer TV programmes are available to play in the UK only',
62 },
63 {
64 'url': 'http://www.bbc.co.uk/iplayer/episode/p026c7jt/tomorrows-worlds-the-unearthly-history-of-science-fiction-2-invasion',
65 'info_dict': {
66 'id': 'b03k3pb7',
67 'ext': 'flv',
68 'title': "Tomorrow's Worlds: The Unearthly History of Science Fiction",
69 'description': '2. Invasion',
70 'duration': 3600,
71 },
72 'params': {
73 # rtmp download
74 'skip_download': True,
75 },
76 'skip': 'Currently BBC iPlayer TV programmes are available to play in the UK only',
77 }, {
78 'url': 'http://www.bbc.co.uk/programmes/b04v20dw',
79 'info_dict': {
80 'id': 'b04v209v',
81 'ext': 'flv',
82 'title': 'Pete Tong, The Essential New Tune Special',
83 'description': "Pete has a very special mix - all of 2014's Essential New Tunes!",
84 'duration': 10800,
85 },
86 'params': {
87 # rtmp download
88 'skip_download': True,
89 }
90 }, {
91 'url': 'http://www.bbc.co.uk/music/clips/p02frcc3',
92 'note': 'Audio',
93 'info_dict': {
94 'id': 'p02frcch',
95 'ext': 'flv',
96 'title': 'Pete Tong, Past, Present and Future Special, Madeon - After Hours mix',
97 'description': 'French house superstar Madeon takes us out of the club and onto the after party.',
98 'duration': 3507,
99 },
100 'params': {
101 # rtmp download
102 'skip_download': True,
103 }
104 }, {
105 'url': 'http://www.bbc.co.uk/music/clips/p025c0zz',
106 'note': 'Video',
107 'info_dict': {
108 'id': 'p025c103',
109 'ext': 'flv',
110 'title': 'Reading and Leeds Festival, 2014, Rae Morris - Closer (Live on BBC Three)',
111 'description': 'Rae Morris performs Closer for BBC Three at Reading 2014',
112 'duration': 226,
113 },
114 'params': {
115 # rtmp download
116 'skip_download': True,
117 }
118 }, {
119 'url': 'http://www.bbc.co.uk/iplayer/episode/b054fn09/ad/natural-world-20152016-2-super-powered-owls',
120 'info_dict': {
121 'id': 'p02n76xf',
122 'ext': 'flv',
123 'title': 'Natural World, 2015-2016: 2. Super Powered Owls',
124 'description': 'md5:e4db5c937d0e95a7c6b5e654d429183d',
125 'duration': 3540,
126 },
127 'params': {
128 # rtmp download
129 'skip_download': True,
130 },
131 'skip': 'geolocation',
132 }, {
133 'url': 'http://www.bbc.co.uk/iplayer/episode/b05zmgwn/royal-academy-summer-exhibition',
134 'info_dict': {
135 'id': 'b05zmgw1',
136 'ext': 'flv',
137 'description': 'Kirsty Wark and Morgan Quaintance visit the Royal Academy as it prepares for its annual artistic extravaganza, meeting people who have come together to make the show unique.',
138 'title': 'Royal Academy Summer Exhibition',
139 'duration': 3540,
140 },
141 'params': {
142 # rtmp download
143 'skip_download': True,
144 },
145 'skip': 'geolocation',
146 }, {
147 'url': 'http://www.bbc.co.uk/iplayer/playlist/p01dvks4',
148 'only_matching': True,
149 }, {
150 'url': 'http://www.bbc.co.uk/music/clips#p02frcc3',
151 'only_matching': True,
152 }, {
153 'url': 'http://www.bbc.co.uk/iplayer/cbeebies/episode/b0480276/bing-14-atchoo',
154 'only_matching': True,
155 }
156 ]
157
158 def _extract_asx_playlist(self, connection, programme_id):
159 asx = self._download_xml(connection.get('href'), programme_id, 'Downloading ASX playlist')
160 return [ref.get('href') for ref in asx.findall('./Entry/ref')]
161
162 def _extract_connection(self, connection, programme_id):
163 formats = []
164 protocol = connection.get('protocol')
165 supplier = connection.get('supplier')
166 if protocol == 'http':
167 href = connection.get('href')
168 # ASX playlist
169 if supplier == 'asx':
170 for i, ref in enumerate(self._extract_asx_playlist(connection, programme_id)):
171 formats.append({
172 'url': ref,
173 'format_id': 'ref%s_%s' % (i, supplier),
174 })
175 # Direct link
176 else:
177 formats.append({
178 'url': href,
179 'format_id': supplier,
180 })
181 elif protocol == 'rtmp':
182 application = connection.get('application', 'ondemand')
183 auth_string = connection.get('authString')
184 identifier = connection.get('identifier')
185 server = connection.get('server')
186 formats.append({
187 'url': '%s://%s/%s?%s' % (protocol, server, application, auth_string),
188 'play_path': identifier,
189 'app': '%s?%s' % (application, auth_string),
190 'page_url': 'http://www.bbc.co.uk',
191 'player_url': 'http://www.bbc.co.uk/emp/releases/iplayer/revisions/617463_618125_4/617463_618125_4_emp.swf',
192 'rtmp_live': False,
193 'ext': 'flv',
194 'format_id': supplier,
195 })
196 return formats
197
198 def _extract_items(self, playlist):
199 return playlist.findall('./{http://bbc.co.uk/2008/emp/playlist}item')
200
201 def _extract_medias(self, media_selection):
202 error = media_selection.find('./{http://bbc.co.uk/2008/mp/mediaselection}error')
203 if error is not None:
204 raise ExtractorError(
205 '%s returned error: %s' % (self.IE_NAME, error.get('id')), expected=True)
206 return media_selection.findall('./{http://bbc.co.uk/2008/mp/mediaselection}media')
207
208 def _extract_connections(self, media):
209 return media.findall('./{http://bbc.co.uk/2008/mp/mediaselection}connection')
210
211 def _extract_video(self, media, programme_id):
212 formats = []
213 vbr = int(media.get('bitrate'))
214 vcodec = media.get('encoding')
215 service = media.get('service')
216 width = int(media.get('width'))
217 height = int(media.get('height'))
218 file_size = int(media.get('media_file_size'))
219 for connection in self._extract_connections(media):
220 conn_formats = self._extract_connection(connection, programme_id)
221 for format in conn_formats:
222 format.update({
223 'format_id': '%s_%s' % (service, format['format_id']),
224 'width': width,
225 'height': height,
226 'vbr': vbr,
227 'vcodec': vcodec,
228 'filesize': file_size,
229 })
230 formats.extend(conn_formats)
231 return formats
232
233 def _extract_audio(self, media, programme_id):
234 formats = []
235 abr = int(media.get('bitrate'))
236 acodec = media.get('encoding')
237 service = media.get('service')
238 for connection in self._extract_connections(media):
239 conn_formats = self._extract_connection(connection, programme_id)
240 for format in conn_formats:
241 format.update({
242 'format_id': '%s_%s' % (service, format['format_id']),
243 'abr': abr,
244 'acodec': acodec,
245 })
246 formats.extend(conn_formats)
247 return formats
248
249 def _get_subtitles(self, media, programme_id):
250 subtitles = {}
251 for connection in self._extract_connections(media):
252 captions = self._download_xml(connection.get('href'), programme_id, 'Downloading captions')
253 lang = captions.get('{http://www.w3.org/XML/1998/namespace}lang', 'en')
254 subtitles[lang] = [
255 {
256 'url': connection.get('href'),
257 'ext': 'ttml',
258 },
259 ]
260 return subtitles
261
262 def _download_media_selector(self, programme_id):
263 try:
264 media_selection = self._download_xml(
265 'http://open.live.bbc.co.uk/mediaselector/5/select/version/2.0/mediaset/pc/vpid/%s' % programme_id,
266 programme_id, 'Downloading media selection XML')
267 except ExtractorError as ee:
268 if isinstance(ee.cause, compat_HTTPError) and ee.cause.code == 403:
269 media_selection = xml.etree.ElementTree.fromstring(ee.cause.read().decode('utf-8'))
270 else:
271 raise
272
273 formats = []
274 subtitles = None
275
276 for media in self._extract_medias(media_selection):
277 kind = media.get('kind')
278 if kind == 'audio':
279 formats.extend(self._extract_audio(media, programme_id))
280 elif kind == 'video':
281 formats.extend(self._extract_video(media, programme_id))
282 elif kind == 'captions':
283 subtitles = self.extract_subtitles(media, programme_id)
284
285 return formats, subtitles
286
287 def _download_playlist(self, playlist_id):
288 try:
289 playlist = self._download_json(
290 'http://www.bbc.co.uk/programmes/%s/playlist.json' % playlist_id,
291 playlist_id, 'Downloading playlist JSON')
292
293 version = playlist.get('defaultAvailableVersion')
294 if version:
295 smp_config = version['smpConfig']
296 title = smp_config['title']
297 description = smp_config['summary']
298 for item in smp_config['items']:
299 kind = item['kind']
300 if kind != 'programme' and kind != 'radioProgramme':
301 continue
302 programme_id = item.get('vpid')
303 duration = int(item.get('duration'))
304 formats, subtitles = self._download_media_selector(programme_id)
305 return programme_id, title, description, duration, formats, subtitles
306 except ExtractorError as ee:
307 if not (isinstance(ee.cause, compat_HTTPError) and ee.cause.code == 404):
308 raise
309
310 # fallback to legacy playlist
311 playlist = self._download_xml(
312 'http://www.bbc.co.uk/iplayer/playlist/%s' % playlist_id,
313 playlist_id, 'Downloading legacy playlist XML')
314
315 no_items = playlist.find('./{http://bbc.co.uk/2008/emp/playlist}noItems')
316 if no_items is not None:
317 reason = no_items.get('reason')
318 if reason == 'preAvailability':
319 msg = 'Episode %s is not yet available' % playlist_id
320 elif reason == 'postAvailability':
321 msg = 'Episode %s is no longer available' % playlist_id
322 elif reason == 'noMedia':
323 msg = 'Episode %s is not currently available' % playlist_id
324 else:
325 msg = 'Episode %s is not available: %s' % (playlist_id, reason)
326 raise ExtractorError(msg, expected=True)
327
328 for item in self._extract_items(playlist):
329 kind = item.get('kind')
330 if kind != 'programme' and kind != 'radioProgramme':
331 continue
332 title = playlist.find('./{http://bbc.co.uk/2008/emp/playlist}title').text
333 description = playlist.find('./{http://bbc.co.uk/2008/emp/playlist}summary').text
334 programme_id = item.get('identifier')
335 duration = int(item.get('duration'))
336 formats, subtitles = self._download_media_selector(programme_id)
337
338 return programme_id, title, description, duration, formats, subtitles
339
340 def _real_extract(self, url):
341 group_id = self._match_id(url)
342
343 webpage = self._download_webpage(url, group_id, 'Downloading video page')
344
345 programme_id = None
346
347 tviplayer = self._search_regex(
348 r'mediator\.bind\(({.+?})\s*,\s*document\.getElementById',
349 webpage, 'player', default=None)
350
351 if tviplayer:
352 player = self._parse_json(tviplayer, group_id).get('player', {})
353 duration = int_or_none(player.get('duration'))
354 programme_id = player.get('vpid')
355
356 if not programme_id:
357 programme_id = self._search_regex(
358 r'"vpid"\s*:\s*"([\da-z]{8})"', webpage, 'vpid', fatal=False, default=None)
359
360 if programme_id:
361 formats, subtitles = self._download_media_selector(programme_id)
362 title = self._og_search_title(webpage)
363 description = self._search_regex(
364 r'<p class="[^"]*medium-description[^"]*">([^<]+)</p>',
365 webpage, 'description', fatal=False)
366 else:
367 programme_id, title, description, duration, formats, subtitles = self._download_playlist(group_id)
368
369 self._sort_formats(formats)
370
371 return {
372 'id': programme_id,
373 'title': title,
374 'description': description,
375 'thumbnail': self._og_search_thumbnail(webpage, default=None),
376 'duration': duration,
377 'formats': formats,
378 'subtitles': subtitles,
379 }