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})'
20 'url': 'http://www.bbc.co.uk/programmes/b039g8p7',
24 'title': 'Kaleidoscope, Leonard Cohen',
25 'description': 'The Canadian poet and songwriter reflects on his musical career.',
30 'skip_download': True,
34 'url': 'http://www.bbc.co.uk/iplayer/episode/b00yng5w/The_Man_in_Black_Series_3_The_Printed_Name/',
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.",
44 'skip_download': True,
46 'skip': 'Episode is no longer available on BBC iPlayer Radio',
49 'url': 'http://www.bbc.co.uk/iplayer/episode/b03vhd1f/The_Voice_UK_Series_3_Blind_Auditions_5/',
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.",
59 'skip_download': True,
61 'skip': 'Currently BBC iPlayer TV programmes are available to play in the UK only',
64 'url': 'http://www.bbc.co.uk/iplayer/episode/p026c7jt/tomorrows-worlds-the-unearthly-history-of-science-fiction-2-invasion',
68 'title': "Tomorrow's Worlds: The Unearthly History of Science Fiction",
69 'description': '2. Invasion',
74 'skip_download': True,
76 'skip': 'Currently BBC iPlayer TV programmes are available to play in the UK only',
78 'url': 'http://www.bbc.co.uk/programmes/b04v20dw',
82 'title': 'Pete Tong, The Essential New Tune Special',
83 'description': "Pete has a very special mix - all of 2014's Essential New Tunes!",
88 'skip_download': True,
91 'url': 'http://www.bbc.co.uk/music/clips/p02frcc3',
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.',
102 'skip_download': True,
105 'url': 'http://www.bbc.co.uk/music/clips/p025c0zz',
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',
116 'skip_download': True,
119 'url': 'http://www.bbc.co.uk/iplayer/episode/b054fn09/ad/natural-world-20152016-2-super-powered-owls',
123 'title': 'Natural World, 2015-2016: 2. Super Powered Owls',
124 'description': 'md5:e4db5c937d0e95a7c6b5e654d429183d',
129 'skip_download': True,
131 'skip': 'geolocation',
133 'url': 'http://www.bbc.co.uk/iplayer/episode/b05zmgwn/royal-academy-summer-exhibition',
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',
143 'skip_download': True,
145 'skip': 'geolocation',
147 'url': 'http://www.bbc.co.uk/iplayer/playlist/p01dvks4',
148 'only_matching': True,
150 'url': 'http://www.bbc.co.uk/music/clips#p02frcc3',
151 'only_matching': True,
153 'url': 'http://www.bbc.co.uk/iplayer/cbeebies/episode/b0480276/bing-14-atchoo',
154 'only_matching': True,
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')]
162 def _extract_connection(self, connection, programme_id):
164 protocol = connection.get('protocol')
165 supplier = connection.get('supplier')
166 if protocol == 'http':
167 href = connection.get('href')
169 if supplier == 'asx':
170 for i, ref in enumerate(self._extract_asx_playlist(connection, programme_id)):
173 'format_id': 'ref%s_%s' % (i, supplier),
179 'format_id': supplier,
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')
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',
194 'format_id': supplier,
198 def _extract_items(self, playlist):
199 return playlist.findall('./{http://bbc.co.uk/2008/emp/playlist}item')
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')
208 def _extract_connections(self, media):
209 return media.findall('./{http://bbc.co.uk/2008/mp/mediaselection}connection')
211 def _extract_video(self, media, programme_id):
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:
223 'format_id': '%s_%s' % (service, format['format_id']),
228 'filesize': file_size,
230 formats.extend(conn_formats)
233 def _extract_audio(self, media, programme_id):
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:
242 'format_id': '%s_%s' % (service, format['format_id']),
246 formats.extend(conn_formats)
249 def _get_subtitles(self, media, programme_id):
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 ps = captions.findall('./{0}body/{0}div/{0}p'.format('{http://www.w3.org/2006/10/ttaf1}'))
257 def _extract_text(p):
258 if p.text is not None:
259 stripped_text = p.text.strip()
262 return ' '.join(span.text.strip() for span in p.findall('{http://www.w3.org/2006/10/ttaf1}span'))
263 for pos, p in enumerate(ps):
264 srt += '%s\r\n%s --> %s\r\n%s\r\n\r\n' % (str(pos), p.get('begin'), p.get('end'), _extract_text(p))
267 'url': connection.get('href'),
277 def _download_media_selector(self, programme_id):
279 media_selection = self._download_xml(
280 'http://open.live.bbc.co.uk/mediaselector/5/select/version/2.0/mediaset/pc/vpid/%s' % programme_id,
281 programme_id, 'Downloading media selection XML')
282 except ExtractorError as ee:
283 if isinstance(ee.cause, compat_HTTPError) and ee.cause.code == 403:
284 media_selection = xml.etree.ElementTree.fromstring(ee.cause.read().decode('utf-8'))
291 for media in self._extract_medias(media_selection):
292 kind = media.get('kind')
294 formats.extend(self._extract_audio(media, programme_id))
295 elif kind == 'video':
296 formats.extend(self._extract_video(media, programme_id))
297 elif kind == 'captions':
298 subtitles = self.extract_subtitles(media, programme_id)
300 return formats, subtitles
302 def _download_playlist(self, playlist_id):
304 playlist = self._download_json(
305 'http://www.bbc.co.uk/programmes/%s/playlist.json' % playlist_id,
306 playlist_id, 'Downloading playlist JSON')
308 version = playlist.get('defaultAvailableVersion')
310 smp_config = version['smpConfig']
311 title = smp_config['title']
312 description = smp_config['summary']
313 for item in smp_config['items']:
315 if kind != 'programme' and kind != 'radioProgramme':
317 programme_id = item.get('vpid')
318 duration = int(item.get('duration'))
319 formats, subtitles = self._download_media_selector(programme_id)
320 return programme_id, title, description, duration, formats, subtitles
321 except ExtractorError as ee:
322 if not (isinstance(ee.cause, compat_HTTPError) and ee.cause.code == 404):
325 # fallback to legacy playlist
326 playlist = self._download_xml(
327 'http://www.bbc.co.uk/iplayer/playlist/%s' % playlist_id,
328 playlist_id, 'Downloading legacy playlist XML')
330 no_items = playlist.find('./{http://bbc.co.uk/2008/emp/playlist}noItems')
331 if no_items is not None:
332 reason = no_items.get('reason')
333 if reason == 'preAvailability':
334 msg = 'Episode %s is not yet available' % playlist_id
335 elif reason == 'postAvailability':
336 msg = 'Episode %s is no longer available' % playlist_id
337 elif reason == 'noMedia':
338 msg = 'Episode %s is not currently available' % playlist_id
340 msg = 'Episode %s is not available: %s' % (playlist_id, reason)
341 raise ExtractorError(msg, expected=True)
343 for item in self._extract_items(playlist):
344 kind = item.get('kind')
345 if kind != 'programme' and kind != 'radioProgramme':
347 title = playlist.find('./{http://bbc.co.uk/2008/emp/playlist}title').text
348 description = playlist.find('./{http://bbc.co.uk/2008/emp/playlist}summary').text
349 programme_id = item.get('identifier')
350 duration = int(item.get('duration'))
351 formats, subtitles = self._download_media_selector(programme_id)
353 return programme_id, title, description, duration, formats, subtitles
355 def _real_extract(self, url):
356 group_id = self._match_id(url)
358 webpage = self._download_webpage(url, group_id, 'Downloading video page')
362 tviplayer = self._search_regex(
363 r'mediator\.bind\(({.+?})\s*,\s*document\.getElementById',
364 webpage, 'player', default=None)
367 player = self._parse_json(tviplayer, group_id).get('player', {})
368 duration = int_or_none(player.get('duration'))
369 programme_id = player.get('vpid')
372 programme_id = self._search_regex(
373 r'"vpid"\s*:\s*"([\da-z]{8})"', webpage, 'vpid', fatal=False, default=None)
376 formats, subtitles = self._download_media_selector(programme_id)
377 title = self._og_search_title(webpage)
378 description = self._search_regex(
379 r'<p class="[^"]*medium-description[^"]*">([^<]+)</p>',
380 webpage, 'description', fatal=False)
382 programme_id, title, description, duration, formats, subtitles = self._download_playlist(group_id)
384 self._sort_formats(formats)
389 'description': description,
390 'thumbnail': self._og_search_thumbnail(webpage, default=None),
391 'duration': duration,
393 'subtitles': subtitles,