2 from __future__ import unicode_literals
5 import xml.etree.ElementTree
7 from .common import InfoExtractor
15 from ..compat import compat_HTTPError
18 class BBCCoUkIE(InfoExtractor):
20 IE_DESC = 'BBC iPlayer'
21 _VALID_URL = r'https?://(?:www\.)?bbc\.co\.uk/(?:(?:(?:programmes|iplayer(?:/[^/]+)?/(?:episode|playlist))/)|music/clips[/#])(?P<id>[\da-z]{8})'
23 _MEDIASELECTOR_URLS = [
24 'http://open.live.bbc.co.uk/mediaselector/5/select/version/2.0/mediaset/pc/vpid/%s',
29 'url': 'http://www.bbc.co.uk/programmes/b039g8p7',
33 'title': 'Kaleidoscope, Leonard Cohen',
34 'description': 'The Canadian poet and songwriter reflects on his musical career.',
39 'skip_download': True,
43 'url': 'http://www.bbc.co.uk/iplayer/episode/b00yng5w/The_Man_in_Black_Series_3_The_Printed_Name/',
47 'title': 'The Man in Black: Series 3: The Printed Name',
48 'description': "Mark Gatiss introduces Nicholas Pierpan's chilling tale of a writer's devilish pact with a mysterious man. Stars Ewan Bailey.",
53 'skip_download': True,
55 'skip': 'Episode is no longer available on BBC iPlayer Radio',
58 'url': 'http://www.bbc.co.uk/iplayer/episode/b03vhd1f/The_Voice_UK_Series_3_Blind_Auditions_5/',
62 'title': 'The Voice UK: Series 3: Blind Auditions 5',
63 '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.",
68 'skip_download': True,
70 'skip': 'Currently BBC iPlayer TV programmes are available to play in the UK only',
73 'url': 'http://www.bbc.co.uk/iplayer/episode/p026c7jt/tomorrows-worlds-the-unearthly-history-of-science-fiction-2-invasion',
77 'title': "Tomorrow's Worlds: The Unearthly History of Science Fiction",
78 'description': '2. Invasion',
83 'skip_download': True,
85 'skip': 'Currently BBC iPlayer TV programmes are available to play in the UK only',
87 'url': 'http://www.bbc.co.uk/programmes/b04v20dw',
91 'title': 'Pete Tong, The Essential New Tune Special',
92 'description': "Pete has a very special mix - all of 2014's Essential New Tunes!",
97 'skip_download': True,
100 'url': 'http://www.bbc.co.uk/music/clips/p02frcc3',
105 'title': 'Pete Tong, Past, Present and Future Special, Madeon - After Hours mix',
106 'description': 'French house superstar Madeon takes us out of the club and onto the after party.',
111 'skip_download': True,
114 'url': 'http://www.bbc.co.uk/music/clips/p025c0zz',
119 'title': 'Reading and Leeds Festival, 2014, Rae Morris - Closer (Live on BBC Three)',
120 'description': 'Rae Morris performs Closer for BBC Three at Reading 2014',
125 'skip_download': True,
128 'url': 'http://www.bbc.co.uk/iplayer/episode/b054fn09/ad/natural-world-20152016-2-super-powered-owls',
132 'title': 'Natural World, 2015-2016: 2. Super Powered Owls',
133 'description': 'md5:e4db5c937d0e95a7c6b5e654d429183d',
138 'skip_download': True,
140 'skip': 'geolocation',
142 'url': 'http://www.bbc.co.uk/iplayer/episode/b05zmgwn/royal-academy-summer-exhibition',
146 '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.',
147 'title': 'Royal Academy Summer Exhibition',
152 'skip_download': True,
154 'skip': 'geolocation',
156 'url': 'http://www.bbc.co.uk/iplayer/playlist/p01dvks4',
157 'only_matching': True,
159 'url': 'http://www.bbc.co.uk/music/clips#p02frcc3',
160 'only_matching': True,
162 'url': 'http://www.bbc.co.uk/iplayer/cbeebies/episode/b0480276/bing-14-atchoo',
163 'only_matching': True,
167 class MediaSelectionError(Exception):
168 def __init__(self, id):
171 def _extract_asx_playlist(self, connection, programme_id):
172 asx = self._download_xml(connection.get('href'), programme_id, 'Downloading ASX playlist')
173 return [ref.get('href') for ref in asx.findall('./Entry/ref')]
175 def _extract_connection(self, connection, programme_id):
177 protocol = connection.get('protocol')
178 supplier = connection.get('supplier')
179 if protocol == 'http':
180 href = connection.get('href')
181 transfer_format = connection.get('transferFormat')
183 if supplier == 'asx':
184 for i, ref in enumerate(self._extract_asx_playlist(connection, programme_id)):
187 'format_id': 'ref%s_%s' % (i, supplier),
189 # Skip DASH until supported
190 elif transfer_format == 'dash':
196 'format_id': supplier,
198 elif protocol == 'rtmp':
199 application = connection.get('application', 'ondemand')
200 auth_string = connection.get('authString')
201 identifier = connection.get('identifier')
202 server = connection.get('server')
204 'url': '%s://%s/%s?%s' % (protocol, server, application, auth_string),
205 'play_path': identifier,
206 'app': '%s?%s' % (application, auth_string),
207 'page_url': 'http://www.bbc.co.uk',
208 'player_url': 'http://www.bbc.co.uk/emp/releases/iplayer/revisions/617463_618125_4/617463_618125_4_emp.swf',
211 'format_id': supplier,
215 def _extract_items(self, playlist):
216 return playlist.findall('./{http://bbc.co.uk/2008/emp/playlist}item')
218 def _extract_medias(self, media_selection):
219 error = media_selection.find('./{http://bbc.co.uk/2008/mp/mediaselection}error')
220 if error is not None:
221 raise BBCCoUkIE.MediaSelectionError(error.get('id'))
222 return media_selection.findall('./{http://bbc.co.uk/2008/mp/mediaselection}media')
224 def _extract_connections(self, media):
225 return media.findall('./{http://bbc.co.uk/2008/mp/mediaselection}connection')
227 def _extract_video(self, media, programme_id):
229 vbr = int_or_none(media.get('bitrate'))
230 vcodec = media.get('encoding')
231 service = media.get('service')
232 width = int_or_none(media.get('width'))
233 height = int_or_none(media.get('height'))
234 file_size = int_or_none(media.get('media_file_size'))
235 for connection in self._extract_connections(media):
236 conn_formats = self._extract_connection(connection, programme_id)
237 for format in conn_formats:
239 'format_id': '%s_%s' % (service, format['format_id']),
244 'filesize': file_size,
246 formats.extend(conn_formats)
249 def _extract_audio(self, media, programme_id):
251 abr = int_or_none(media.get('bitrate'))
252 acodec = media.get('encoding')
253 service = media.get('service')
254 for connection in self._extract_connections(media):
255 conn_formats = self._extract_connection(connection, programme_id)
256 for format in conn_formats:
258 'format_id': '%s_%s' % (service, format['format_id']),
262 formats.extend(conn_formats)
265 def _get_subtitles(self, media, programme_id):
267 for connection in self._extract_connections(media):
268 captions = self._download_xml(connection.get('href'), programme_id, 'Downloading captions')
269 lang = captions.get('{http://www.w3.org/XML/1998/namespace}lang', 'en')
272 'url': connection.get('href'),
278 def _raise_extractor_error(self, media_selection_error):
279 raise ExtractorError(
280 '%s returned error: %s' % (self.IE_NAME, media_selection_error.id),
283 def _download_media_selector(self, programme_id):
284 last_exception = None
285 for mediaselector_url in self._MEDIASELECTOR_URLS:
287 return self._download_media_selector_url(
288 mediaselector_url % programme_id, programme_id)
289 except BBCCoUkIE.MediaSelectionError as e:
290 if e.id == 'notukerror':
293 self._raise_extractor_error(e)
294 self._raise_extractor_error(last_exception)
296 def _download_media_selector_url(self, url, programme_id=None):
298 media_selection = self._download_xml(
299 url, programme_id, 'Downloading media selection XML')
300 except ExtractorError as ee:
301 if isinstance(ee.cause, compat_HTTPError) and ee.cause.code == 403:
302 media_selection = xml.etree.ElementTree.fromstring(ee.cause.read().decode('utf-8'))
305 return self._process_media_selector(media_selection, programme_id)
307 def _process_media_selector(self, media_selection, programme_id):
311 for media in self._extract_medias(media_selection):
312 kind = media.get('kind')
314 formats.extend(self._extract_audio(media, programme_id))
315 elif kind == 'video':
316 formats.extend(self._extract_video(media, programme_id))
317 elif kind == 'captions':
318 subtitles = self.extract_subtitles(media, programme_id)
319 return formats, subtitles
321 def _download_playlist(self, playlist_id):
323 playlist = self._download_json(
324 'http://www.bbc.co.uk/programmes/%s/playlist.json' % playlist_id,
325 playlist_id, 'Downloading playlist JSON')
327 version = playlist.get('defaultAvailableVersion')
329 smp_config = version['smpConfig']
330 title = smp_config['title']
331 description = smp_config['summary']
332 for item in smp_config['items']:
334 if kind != 'programme' and kind != 'radioProgramme':
336 programme_id = item.get('vpid')
337 duration = int_or_none(item.get('duration'))
338 formats, subtitles = self._download_media_selector(programme_id)
339 return programme_id, title, description, duration, formats, subtitles
340 except ExtractorError as ee:
341 if not (isinstance(ee.cause, compat_HTTPError) and ee.cause.code == 404):
344 # fallback to legacy playlist
345 return self._process_legacy_playlist(playlist_id)
347 def _process_legacy_playlist_url(self, url, display_id):
348 playlist = self._download_legacy_playlist_url(url, display_id)
349 return self._extract_from_legacy_playlist(playlist, display_id)
351 def _process_legacy_playlist(self, playlist_id):
352 return self._process_legacy_playlist_url(
353 'http://www.bbc.co.uk/iplayer/playlist/%s' % playlist_id, playlist_id)
355 def _download_legacy_playlist_url(self, url, playlist_id=None):
356 return self._download_xml(
357 url, playlist_id, 'Downloading legacy playlist XML')
359 def _extract_from_legacy_playlist(self, playlist, playlist_id):
360 no_items = playlist.find('./{http://bbc.co.uk/2008/emp/playlist}noItems')
361 if no_items is not None:
362 reason = no_items.get('reason')
363 if reason == 'preAvailability':
364 msg = 'Episode %s is not yet available' % playlist_id
365 elif reason == 'postAvailability':
366 msg = 'Episode %s is no longer available' % playlist_id
367 elif reason == 'noMedia':
368 msg = 'Episode %s is not currently available' % playlist_id
370 msg = 'Episode %s is not available: %s' % (playlist_id, reason)
371 raise ExtractorError(msg, expected=True)
373 for item in self._extract_items(playlist):
374 kind = item.get('kind')
375 if kind != 'programme' and kind != 'radioProgramme':
377 title = playlist.find('./{http://bbc.co.uk/2008/emp/playlist}title').text
378 description = playlist.find('./{http://bbc.co.uk/2008/emp/playlist}summary').text
380 def get_programme_id(item):
381 def get_from_attributes(item):
382 for p in('identifier', 'group'):
384 if value and re.match(r'^[pb][\da-z]{7}$', value):
386 get_from_attributes(item)
387 mediator = item.find('./{http://bbc.co.uk/2008/emp/playlist}mediator')
388 if mediator is not None:
389 return get_from_attributes(mediator)
391 programme_id = get_programme_id(item)
392 duration = int_or_none(item.get('duration'))
393 # TODO: programme_id can be None and media items can be incorporated right inside
394 # playlist's item (e.g. http://www.bbc.com/turkce/haberler/2015/06/150615_telabyad_kentin_cogu)
396 formats, subtitles = self._download_media_selector(programme_id)
398 return programme_id, title, description, duration, formats, subtitles
400 def _real_extract(self, url):
401 group_id = self._match_id(url)
403 webpage = self._download_webpage(url, group_id, 'Downloading video page')
407 tviplayer = self._search_regex(
408 r'mediator\.bind\(({.+?})\s*,\s*document\.getElementById',
409 webpage, 'player', default=None)
412 player = self._parse_json(tviplayer, group_id).get('player', {})
413 duration = int_or_none(player.get('duration'))
414 programme_id = player.get('vpid')
417 programme_id = self._search_regex(
418 r'"vpid"\s*:\s*"([\da-z]{8})"', webpage, 'vpid', fatal=False, default=None)
421 formats, subtitles = self._download_media_selector(programme_id)
422 title = self._og_search_title(webpage)
423 description = self._search_regex(
424 r'<p class="[^"]*medium-description[^"]*">([^<]+)</p>',
425 webpage, 'description', fatal=False)
427 programme_id, title, description, duration, formats, subtitles = self._download_playlist(group_id)
429 self._sort_formats(formats)
434 'description': description,
435 'thumbnail': self._og_search_thumbnail(webpage, default=None),
436 'duration': duration,
438 'subtitles': subtitles,
442 class BBCIE(BBCCoUkIE):
445 _VALID_URL = r'https?://(?:www\.)?bbc\.(?:com|co\.uk)/(?:[^/]+/)+(?P<id>[^/#?]+)'
447 _MEDIASELECTOR_URLS = [
448 # Provides more formats, namely direct mp4 links, but fails on some videos with
449 # notukerror for non UK (?) users (e.g.
450 # http://www.bbc.com/travel/story/20150625-sri-lankas-spicy-secret)
451 'http://open.live.bbc.co.uk/mediaselector/4/mtis/stream/%s',
452 # Provides fewer formats, but works everywhere for everybody (hopefully)
453 'http://open.live.bbc.co.uk/mediaselector/5/select/version/2.0/mediaset/journalism-pc/vpid/%s',
457 # article with multiple videos embedded with data-media-meta containing
458 # playlist.sxml, externalId and no direct video links
459 'url': 'http://www.bbc.com/news/world-europe-32668511',
461 'id': 'world-europe-32668511',
462 'title': 'Russia stages massive WW2 parade despite Western boycott',
463 'description': 'md5:00ff61976f6081841f759a08bf78cc9c',
467 # article with multiple videos embedded with data-media-meta (more videos)
468 'url': 'http://www.bbc.com/news/business-28299555',
470 'id': 'business-28299555',
471 'title': 'Farnborough Airshow: Video highlights',
472 'description': 'BBC reports and video highlights at the Farnborough Airshow.',
477 # article with multiple videos embedded with `new SMP()`
478 'url': 'http://www.bbc.co.uk/blogs/adamcurtis/entries/3662a707-0af9-3149-963f-47bea720b460',
480 'id': '3662a707-0af9-3149-963f-47bea720b460',
481 'title': 'BBC Blogs - Adam Curtis - BUGGER',
483 'playlist_count': 18,
485 # single video embedded with mediaAssetPage.init()
486 'url': 'http://www.bbc.com/news/world-europe-32041533',
490 'title': 'Aerial footage showed the site of the crash in the Alps - courtesy BFM TV',
492 'timestamp': 1427219242,
493 'upload_date': '20150324',
497 'skip_download': True,
500 # article with single video embedded with data-media-meta containing
501 # direct video links (for now these are extracted) and playlist.xml (with
502 # media items as f4m and m3u8 - currently unsupported)
503 'url': 'http://www.bbc.com/turkce/haberler/2015/06/150615_telabyad_kentin_cogu',
505 'id': '150615_telabyad_kentin_cogu',
507 'title': "YPG: Tel Abyad'ın tamamı kontrolümüzde",
509 'timestamp': 1434397334,
510 'upload_date': '20150615',
513 'skip_download': True,
516 # single video embedded with mediaAssetPage.init() (regional section)
517 'url': 'http://www.bbc.com/mundo/video_fotos/2015/06/150619_video_honduras_militares_hospitales_corrupcion_aw',
519 'id': '150619_video_honduras_militares_hospitales_corrupcion_aw',
521 'title': 'Honduras militariza sus hospitales por nuevo escándalo de corrupción',
523 'timestamp': 1434713142,
524 'upload_date': '20150619',
527 'skip_download': True,
530 # single video from video playlist embedded with vxp-playlist-data JSON
531 'url': 'http://www.bbc.com/news/video_and_audio/must_see/33376376',
535 'title': '''Judge Mindy Glazer: "I'm sorry to see you here... I always wondered what happened to you"''',
539 'skip_download': True,
542 # single video story with digitalData
543 'url': 'http://www.bbc.com/travel/story/20150625-sri-lankas-spicy-secret',
547 'title': 'Sri Lanka’s spicy secret',
548 'description': 'As a new train line to Jaffna opens up the country’s north, travellers can experience a truly distinct slice of Tamil culture.',
549 'timestamp': 1437674293,
550 'upload_date': '20150723',
554 'skip_download': True,
557 # single video story without digitalData
558 'url': 'http://www.bbc.com/autos/story/20130513-hyundais-rock-star',
562 'title': 'Hyundai Santa Fe Sport: Rock star',
563 'description': 'md5:b042a26142c4154a6e472933cf20793d',
564 'timestamp': 1368473503,
565 'upload_date': '20130513',
569 'skip_download': True,
572 # single video with playlist.sxml URL
573 'url': 'http://www.bbc.com/sport/0/football/33653409',
577 'title': 'Transfers: Cristiano Ronaldo to Man Utd, Arsenal to spend?',
578 'description': 'md5:398fca0e2e701c609d726e034fa1fc89',
583 'skip_download': True,
586 # single video with playlist URL from weather section
587 'url': 'http://www.bbc.com/weather/features/33601775',
588 'only_matching': True,
590 # custom redirection to www.bbc.com
591 'url': 'http://www.bbc.co.uk/news/science-environment-33661876',
592 'only_matching': True,
596 def suitable(cls, url):
597 return False if BBCCoUkIE.suitable(url) else super(BBCIE, cls).suitable(url)
599 def _extract_from_media_meta(self, media_meta, video_id):
600 # Direct links to media in media metadata (e.g.
601 # http://www.bbc.com/turkce/haberler/2015/06/150615_telabyad_kentin_cogu)
602 # TODO: there are also f4m and m3u8 streams incorporated in playlist.sxml
603 source_files = media_meta.get('sourceFiles')
607 'format_id': format_id,
608 'ext': f.get('encoding'),
609 'tbr': float_or_none(f.get('bitrate'), 1000),
610 'filesize': int_or_none(f.get('filesize')),
611 } for format_id, f in source_files.items() if f.get('url')], []
613 programme_id = media_meta.get('externalId')
615 return self._download_media_selector(programme_id)
617 # Process playlist.sxml as legacy playlist
618 href = media_meta.get('href')
620 playlist = self._download_legacy_playlist_url(href)
621 _, _, _, _, formats, subtitles = self._extract_from_legacy_playlist(playlist, video_id)
622 return formats, subtitles
626 def _real_extract(self, url):
627 playlist_id = self._match_id(url)
629 webpage = self._download_webpage(url, playlist_id)
631 timestamp = parse_iso8601(self._search_regex(
632 [r'"datePublished":\s*"([^"]+)',
633 r'<meta[^>]+property="article:published_time"[^>]+content="([^"]+)"',
634 r'itemprop="datePublished"[^>]+datetime="([^"]+)"'],
635 webpage, 'date', default=None))
637 # single video with playlist.sxml URL (e.g. http://www.bbc.com/sport/0/football/3365340ng)
638 playlist = self._search_regex(
639 r'<param[^>]+name="playlist"[^>]+value="([^"]+)"',
640 webpage, 'playlist', default=None)
642 programme_id, title, description, duration, formats, subtitles = \
643 self._process_legacy_playlist_url(playlist, playlist_id)
644 self._sort_formats(formats)
648 'description': description,
649 'duration': duration,
650 'timestamp': timestamp,
652 'subtitles': subtitles,
655 # single video story (e.g. http://www.bbc.com/travel/story/20150625-sri-lankas-spicy-secret)
656 programme_id = self._search_regex(
657 [r'data-video-player-vpid="([\da-z]{8})"',
658 r'<param[^>]+name="externalIdentifier"[^>]+value="([\da-z]{8})"'],
659 webpage, 'vpid', default=None)
661 formats, subtitles = self._download_media_selector(programme_id)
662 self._sort_formats(formats)
663 # digitalData may be missing (e.g. http://www.bbc.com/autos/story/20130513-hyundais-rock-star)
664 digital_data = self._parse_json(
666 r'var\s+digitalData\s*=\s*({.+?});?\n', webpage, 'digital data', default='{}'),
667 programme_id, fatal=False)
668 page_info = digital_data.get('page', {}).get('pageInfo', {})
669 title = page_info.get('pageName') or self._og_search_title(webpage)
670 description = page_info.get('description') or self._og_search_description(webpage)
671 timestamp = parse_iso8601(page_info.get('publicationDate')) or timestamp
675 'description': description,
676 'timestamp': timestamp,
678 'subtitles': subtitles,
681 playlist_title = self._html_search_regex(
682 r'<title>(.*?)(?:\s*-\s*BBC [^ ]+)?</title>', webpage, 'playlist title')
683 playlist_description = self._og_search_description(webpage, default=None)
685 def extract_all(pattern):
686 return list(filter(None, map(
687 lambda s: self._parse_json(s, playlist_id, fatal=False),
688 re.findall(pattern, webpage))))
690 # Multiple video article (e.g.
691 # http://www.bbc.co.uk/blogs/adamcurtis/entries/3662a707-0af9-3149-963f-47bea720b460)
692 EMBED_URL = r'https?://(?:www\.)?bbc\.co\.uk/(?:[^/]+/)+[\da-z]{8}(?:\b[^"]+)?'
694 for match in extract_all(r'new\s+SMP\(({.+?})\)'):
695 embed_url = match.get('playerSettings', {}).get('externalEmbedUrl')
696 if embed_url and re.match(EMBED_URL, embed_url):
697 entries.append(embed_url)
698 entries.extend(re.findall(
699 r'setPlaylist\("(%s)"\)' % EMBED_URL, webpage))
701 return self.playlist_result(
702 [self.url_result(entry, 'BBCCoUk') for entry in entries],
703 playlist_id, playlist_title, playlist_description)
705 # Multiple video article (e.g. http://www.bbc.com/news/world-europe-32668511)
706 medias = extract_all(r"data-media-meta='({[^']+})'")
709 # Single video article (e.g. http://www.bbc.com/news/video_and_audio/international)
710 media_asset = self._search_regex(
711 r'mediaAssetPage\.init\(\s*({.+?}), "/',
712 webpage, 'media asset', default=None)
714 media_asset_page = self._parse_json(media_asset, playlist_id, fatal=False)
716 for video in media_asset_page.get('videos', {}).values():
717 medias.extend(video.values())
720 # Multiple video playlist with single `now playing` entry (e.g.
721 # http://www.bbc.com/news/video_and_audio/must_see/33767813)
722 vxp_playlist = self._parse_json(
724 r'<script[^>]+class="vxp-playlist-data"[^>]+type="application/json"[^>]*>([^<]+)</script>',
725 webpage, 'playlist data'),
728 for item in vxp_playlist:
729 media = item.get('media')
732 playlist_medias.append(media)
733 # Download single video if found media with asset id matching the video id from URL
734 if item.get('advert', {}).get('assetId') == playlist_id:
737 # Fallback to the whole playlist
739 medias = playlist_medias
742 for num, media_meta in enumerate(medias, start=1):
743 formats, subtitles = self._extract_from_media_meta(media_meta, playlist_id)
746 self._sort_formats(formats)
748 video_id = media_meta.get('externalId')
750 video_id = playlist_id if len(medias) == 1 else '%s-%s' % (playlist_id, num)
752 title = media_meta.get('caption')
754 title = playlist_title if len(medias) == 1 else '%s - Video %s' % (playlist_title, num)
756 duration = int_or_none(media_meta.get('durationInSeconds')) or parse_duration(media_meta.get('duration'))
759 for image in media_meta.get('images', {}).values():
760 images.extend(image.values())
761 if 'image' in media_meta:
762 images.append(media_meta['image'])
765 'url': image.get('href'),
766 'width': int_or_none(image.get('width')),
767 'height': int_or_none(image.get('height')),
768 } for image in images]
773 'thumbnails': thumbnails,
774 'duration': duration,
775 'timestamp': timestamp,
777 'subtitles': subtitles,
780 return self.playlist_result(entries, playlist_id, playlist_title, playlist_description)