1 from __future__ import unicode_literals
3 import xml.etree.ElementTree
5 from .common import InfoExtractor
10 from ..compat import compat_HTTPError
13 class BBCCoUkIE(InfoExtractor):
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})'
18 mediaselector_url = 'http://open.live.bbc.co.uk/mediaselector/5/select/version/2.0/mediaset/pc/vpid/%s'
22 'url': 'http://www.bbc.co.uk/programmes/b039g8p7',
26 'title': 'Kaleidoscope, Leonard Cohen',
27 'description': 'The Canadian poet and songwriter reflects on his musical career.',
32 'skip_download': True,
36 'url': 'http://www.bbc.co.uk/iplayer/episode/b00yng5w/The_Man_in_Black_Series_3_The_Printed_Name/',
40 'title': 'The Man in Black: Series 3: The Printed Name',
41 'description': "Mark Gatiss introduces Nicholas Pierpan's chilling tale of a writer's devilish pact with a mysterious man. Stars Ewan Bailey.",
46 'skip_download': True,
48 'skip': 'Episode is no longer available on BBC iPlayer Radio',
51 'url': 'http://www.bbc.co.uk/iplayer/episode/b03vhd1f/The_Voice_UK_Series_3_Blind_Auditions_5/',
55 'title': 'The Voice UK: Series 3: Blind Auditions 5',
56 '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.",
61 'skip_download': True,
63 'skip': 'Currently BBC iPlayer TV programmes are available to play in the UK only',
66 'url': 'http://www.bbc.co.uk/iplayer/episode/p026c7jt/tomorrows-worlds-the-unearthly-history-of-science-fiction-2-invasion',
70 'title': "Tomorrow's Worlds: The Unearthly History of Science Fiction",
71 'description': '2. Invasion',
76 'skip_download': True,
78 'skip': 'Currently BBC iPlayer TV programmes are available to play in the UK only',
80 'url': 'http://www.bbc.co.uk/programmes/b04v20dw',
84 'title': 'Pete Tong, The Essential New Tune Special',
85 'description': "Pete has a very special mix - all of 2014's Essential New Tunes!",
90 'skip_download': True,
93 'url': 'http://www.bbc.co.uk/music/clips/p02frcc3',
98 'title': 'Pete Tong, Past, Present and Future Special, Madeon - After Hours mix',
99 'description': 'French house superstar Madeon takes us out of the club and onto the after party.',
104 'skip_download': True,
107 'url': 'http://www.bbc.co.uk/music/clips/p025c0zz',
112 'title': 'Reading and Leeds Festival, 2014, Rae Morris - Closer (Live on BBC Three)',
113 'description': 'Rae Morris performs Closer for BBC Three at Reading 2014',
118 'skip_download': True,
121 'url': 'http://www.bbc.co.uk/iplayer/episode/b054fn09/ad/natural-world-20152016-2-super-powered-owls',
125 'title': 'Natural World, 2015-2016: 2. Super Powered Owls',
126 'description': 'md5:e4db5c937d0e95a7c6b5e654d429183d',
131 'skip_download': True,
133 'skip': 'geolocation',
135 'url': 'http://www.bbc.co.uk/iplayer/episode/b05zmgwn/royal-academy-summer-exhibition',
139 '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.',
140 'title': 'Royal Academy Summer Exhibition',
145 'skip_download': True,
147 'skip': 'geolocation',
149 'url': 'http://www.bbc.co.uk/iplayer/playlist/p01dvks4',
150 'only_matching': True,
152 'url': 'http://www.bbc.co.uk/music/clips#p02frcc3',
153 'only_matching': True,
155 'url': 'http://www.bbc.co.uk/iplayer/cbeebies/episode/b0480276/bing-14-atchoo',
156 'only_matching': True,
160 def _extract_asx_playlist(self, connection, programme_id):
161 asx = self._download_xml(connection.get('href'), programme_id, 'Downloading ASX playlist')
162 return [ref.get('href') for ref in asx.findall('./Entry/ref')]
164 def _extract_connection(self, connection, programme_id):
166 protocol = connection.get('protocol')
167 supplier = connection.get('supplier')
168 if protocol == 'http':
169 href = connection.get('href')
171 if supplier == 'asx':
172 for i, ref in enumerate(self._extract_asx_playlist(connection, programme_id)):
175 'format_id': 'ref%s_%s' % (i, supplier),
181 'format_id': supplier,
183 elif protocol == 'rtmp':
184 application = connection.get('application', 'ondemand')
185 auth_string = connection.get('authString')
186 identifier = connection.get('identifier')
187 server = connection.get('server')
189 'url': '%s://%s/%s?%s' % (protocol, server, application, auth_string),
190 'play_path': identifier,
191 'app': '%s?%s' % (application, auth_string),
192 'page_url': 'http://www.bbc.co.uk',
193 'player_url': 'http://www.bbc.co.uk/emp/releases/iplayer/revisions/617463_618125_4/617463_618125_4_emp.swf',
196 'format_id': supplier,
200 def _extract_items(self, playlist):
201 return playlist.findall('./{http://bbc.co.uk/2008/emp/playlist}item')
203 def _extract_medias(self, media_selection):
204 error = media_selection.find('./{http://bbc.co.uk/2008/mp/mediaselection}error')
205 if error is not None:
206 raise ExtractorError(
207 '%s returned error: %s' % (self.IE_NAME, error.get('id')), expected=True)
208 return media_selection.findall('./{http://bbc.co.uk/2008/mp/mediaselection}media')
210 def _extract_connections(self, media):
211 return media.findall('./{http://bbc.co.uk/2008/mp/mediaselection}connection')
213 def _extract_video(self, media, programme_id):
215 vbr = int(media.get('bitrate'))
216 vcodec = media.get('encoding')
217 service = media.get('service')
218 width = int(media.get('width'))
219 height = int(media.get('height'))
220 file_size = int(media.get('media_file_size'))
221 for connection in self._extract_connections(media):
222 conn_formats = self._extract_connection(connection, programme_id)
223 for format in conn_formats:
225 'format_id': '%s_%s' % (service, format['format_id']),
230 'filesize': file_size,
232 formats.extend(conn_formats)
235 def _extract_audio(self, media, programme_id):
237 abr = int(media.get('bitrate'))
238 acodec = media.get('encoding')
239 service = media.get('service')
240 for connection in self._extract_connections(media):
241 conn_formats = self._extract_connection(connection, programme_id)
242 for format in conn_formats:
244 'format_id': '%s_%s' % (service, format['format_id']),
248 formats.extend(conn_formats)
251 def _get_subtitles(self, media, programme_id):
253 for connection in self._extract_connections(media):
254 captions = self._download_xml(connection.get('href'), programme_id, 'Downloading captions')
255 lang = captions.get('{http://www.w3.org/XML/1998/namespace}lang', 'en')
256 ps = captions.findall('./{0}body/{0}div/{0}p'.format('{http://www.w3.org/2006/10/ttaf1}'))
259 def _extract_text(p):
260 if p.text is not None:
261 stripped_text = p.text.strip()
264 return ' '.join(span.text.strip() for span in p.findall('{http://www.w3.org/2006/10/ttaf1}span'))
265 for pos, p in enumerate(ps):
266 srt += '%s\r\n%s --> %s\r\n%s\r\n\r\n' % (str(pos), p.get('begin'), p.get('end'), _extract_text(p))
269 'url': connection.get('href'),
279 def _download_media_selector(self, programme_id):
281 media_selection = self._download_xml(
282 self.mediaselector_url % programme_id,
283 programme_id, 'Downloading media selection XML')
284 except ExtractorError as ee:
285 if isinstance(ee.cause, compat_HTTPError) and ee.cause.code == 403:
286 media_selection = xml.etree.ElementTree.fromstring(ee.cause.read().decode('utf-8'))
293 for media in self._extract_medias(media_selection):
294 kind = media.get('kind')
296 formats.extend(self._extract_audio(media, programme_id))
297 elif kind == 'video':
298 formats.extend(self._extract_video(media, programme_id))
299 elif kind == 'captions':
300 subtitles = self.extract_subtitles(media, programme_id)
302 return formats, subtitles
304 def _download_playlist(self, playlist_id):
306 playlist = self._download_json(
307 'http://www.bbc.co.uk/programmes/%s/playlist.json' % playlist_id,
308 playlist_id, 'Downloading playlist JSON')
310 version = playlist.get('defaultAvailableVersion')
312 smp_config = version['smpConfig']
313 title = smp_config['title']
314 description = smp_config['summary']
315 for item in smp_config['items']:
317 if kind != 'programme' and kind != 'radioProgramme':
319 programme_id = item.get('vpid')
320 duration = int(item.get('duration'))
321 formats, subtitles = self._download_media_selector(programme_id)
322 return programme_id, title, description, duration, formats, subtitles
323 except ExtractorError as ee:
324 if not (isinstance(ee.cause, compat_HTTPError) and ee.cause.code == 404):
327 # fallback to legacy playlist
328 playlist = self._download_xml(
329 'http://www.bbc.co.uk/iplayer/playlist/%s' % playlist_id,
330 playlist_id, 'Downloading legacy playlist XML')
332 no_items = playlist.find('./{http://bbc.co.uk/2008/emp/playlist}noItems')
333 if no_items is not None:
334 reason = no_items.get('reason')
335 if reason == 'preAvailability':
336 msg = 'Episode %s is not yet available' % playlist_id
337 elif reason == 'postAvailability':
338 msg = 'Episode %s is no longer available' % playlist_id
339 elif reason == 'noMedia':
340 msg = 'Episode %s is not currently available' % playlist_id
342 msg = 'Episode %s is not available: %s' % (playlist_id, reason)
343 raise ExtractorError(msg, expected=True)
345 for item in self._extract_items(playlist):
346 kind = item.get('kind')
347 if kind != 'programme' and kind != 'radioProgramme':
349 title = playlist.find('./{http://bbc.co.uk/2008/emp/playlist}title').text
350 description = playlist.find('./{http://bbc.co.uk/2008/emp/playlist}summary').text
351 programme_id = item.get('identifier')
352 duration = int(item.get('duration'))
353 formats, subtitles = self._download_media_selector(programme_id)
355 return programme_id, title, description, duration, formats, subtitles
357 def _real_extract(self, url):
358 group_id = self._match_id(url)
360 webpage = self._download_webpage(url, group_id, 'Downloading video page')
364 tviplayer = self._search_regex(
365 r'mediator\.bind\(({.+?})\s*,\s*document\.getElementById',
366 webpage, 'player', default=None)
369 player = self._parse_json(tviplayer, group_id).get('player', {})
370 duration = int_or_none(player.get('duration'))
371 programme_id = player.get('vpid')
374 programme_id = self._search_regex(
375 r'"vpid"\s*:\s*"([\da-z]{8})"', webpage, 'vpid', fatal=False, default=None)
378 formats, subtitles = self._download_media_selector(programme_id)
379 title = self._og_search_title(webpage)
380 description = self._search_regex(
381 r'<p class="[^"]*medium-description[^"]*">([^<]+)</p>',
382 webpage, 'description', fatal=False)
384 programme_id, title, description, duration, formats, subtitles = self._download_playlist(group_id)
386 self._sort_formats(formats)
391 'description': description,
392 'thumbnail': self._og_search_thumbnail(webpage, default=None),
393 'duration': duration,
395 'subtitles': subtitles,