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_URL = 'http://open.live.bbc.co.uk/mediaselector/5/select/version/2.0/mediaset/pc/vpid/%s'
27 'url': 'http://www.bbc.co.uk/programmes/b039g8p7',
31 'title': 'Kaleidoscope, Leonard Cohen',
32 'description': 'The Canadian poet and songwriter reflects on his musical career.',
37 'skip_download': True,
41 'url': 'http://www.bbc.co.uk/iplayer/episode/b00yng5w/The_Man_in_Black_Series_3_The_Printed_Name/',
45 'title': 'The Man in Black: Series 3: The Printed Name',
46 'description': "Mark Gatiss introduces Nicholas Pierpan's chilling tale of a writer's devilish pact with a mysterious man. Stars Ewan Bailey.",
51 'skip_download': True,
53 'skip': 'Episode is no longer available on BBC iPlayer Radio',
56 'url': 'http://www.bbc.co.uk/iplayer/episode/b03vhd1f/The_Voice_UK_Series_3_Blind_Auditions_5/',
60 'title': 'The Voice UK: Series 3: Blind Auditions 5',
61 '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.",
66 'skip_download': True,
68 'skip': 'Currently BBC iPlayer TV programmes are available to play in the UK only',
71 'url': 'http://www.bbc.co.uk/iplayer/episode/p026c7jt/tomorrows-worlds-the-unearthly-history-of-science-fiction-2-invasion',
75 'title': "Tomorrow's Worlds: The Unearthly History of Science Fiction",
76 'description': '2. Invasion',
81 'skip_download': True,
83 'skip': 'Currently BBC iPlayer TV programmes are available to play in the UK only',
85 'url': 'http://www.bbc.co.uk/programmes/b04v20dw',
89 'title': 'Pete Tong, The Essential New Tune Special',
90 'description': "Pete has a very special mix - all of 2014's Essential New Tunes!",
95 'skip_download': True,
98 'url': 'http://www.bbc.co.uk/music/clips/p02frcc3',
103 'title': 'Pete Tong, Past, Present and Future Special, Madeon - After Hours mix',
104 'description': 'French house superstar Madeon takes us out of the club and onto the after party.',
109 'skip_download': True,
112 'url': 'http://www.bbc.co.uk/music/clips/p025c0zz',
117 'title': 'Reading and Leeds Festival, 2014, Rae Morris - Closer (Live on BBC Three)',
118 'description': 'Rae Morris performs Closer for BBC Three at Reading 2014',
123 'skip_download': True,
126 'url': 'http://www.bbc.co.uk/iplayer/episode/b054fn09/ad/natural-world-20152016-2-super-powered-owls',
130 'title': 'Natural World, 2015-2016: 2. Super Powered Owls',
131 'description': 'md5:e4db5c937d0e95a7c6b5e654d429183d',
136 'skip_download': True,
138 'skip': 'geolocation',
140 'url': 'http://www.bbc.co.uk/iplayer/episode/b05zmgwn/royal-academy-summer-exhibition',
144 '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.',
145 'title': 'Royal Academy Summer Exhibition',
150 'skip_download': True,
152 'skip': 'geolocation',
154 'url': 'http://www.bbc.co.uk/iplayer/playlist/p01dvks4',
155 'only_matching': True,
157 'url': 'http://www.bbc.co.uk/music/clips#p02frcc3',
158 'only_matching': True,
160 'url': 'http://www.bbc.co.uk/iplayer/cbeebies/episode/b0480276/bing-14-atchoo',
161 'only_matching': True,
165 def _extract_asx_playlist(self, connection, programme_id):
166 asx = self._download_xml(connection.get('href'), programme_id, 'Downloading ASX playlist')
167 return [ref.get('href') for ref in asx.findall('./Entry/ref')]
169 def _extract_connection(self, connection, programme_id):
171 protocol = connection.get('protocol')
172 supplier = connection.get('supplier')
173 if protocol == 'http':
174 href = connection.get('href')
175 transfer_format = connection.get('transferFormat')
177 if supplier == 'asx':
178 for i, ref in enumerate(self._extract_asx_playlist(connection, programme_id)):
181 'format_id': 'ref%s_%s' % (i, supplier),
183 # Skip DASH until supported
184 elif transfer_format == 'dash':
190 'format_id': supplier,
192 elif protocol == 'rtmp':
193 application = connection.get('application', 'ondemand')
194 auth_string = connection.get('authString')
195 identifier = connection.get('identifier')
196 server = connection.get('server')
198 'url': '%s://%s/%s?%s' % (protocol, server, application, auth_string),
199 'play_path': identifier,
200 'app': '%s?%s' % (application, auth_string),
201 'page_url': 'http://www.bbc.co.uk',
202 'player_url': 'http://www.bbc.co.uk/emp/releases/iplayer/revisions/617463_618125_4/617463_618125_4_emp.swf',
205 'format_id': supplier,
209 def _extract_items(self, playlist):
210 return playlist.findall('./{http://bbc.co.uk/2008/emp/playlist}item')
212 def _extract_medias(self, media_selection):
213 error = media_selection.find('./{http://bbc.co.uk/2008/mp/mediaselection}error')
214 if error is not None:
215 raise ExtractorError(
216 '%s returned error: %s' % (self.IE_NAME, error.get('id')), expected=True)
217 return media_selection.findall('./{http://bbc.co.uk/2008/mp/mediaselection}media')
219 def _extract_connections(self, media):
220 return media.findall('./{http://bbc.co.uk/2008/mp/mediaselection}connection')
222 def _extract_video(self, media, programme_id):
224 vbr = int_or_none(media.get('bitrate'))
225 vcodec = media.get('encoding')
226 service = media.get('service')
227 width = int_or_none(media.get('width'))
228 height = int_or_none(media.get('height'))
229 file_size = int_or_none(media.get('media_file_size'))
230 for connection in self._extract_connections(media):
231 conn_formats = self._extract_connection(connection, programme_id)
232 for format in conn_formats:
234 'format_id': '%s_%s' % (service, format['format_id']),
239 'filesize': file_size,
241 formats.extend(conn_formats)
244 def _extract_audio(self, media, programme_id):
246 abr = int_or_none(media.get('bitrate'))
247 acodec = media.get('encoding')
248 service = media.get('service')
249 for connection in self._extract_connections(media):
250 conn_formats = self._extract_connection(connection, programme_id)
251 for format in conn_formats:
253 'format_id': '%s_%s' % (service, format['format_id']),
257 formats.extend(conn_formats)
260 def _get_subtitles(self, media, programme_id):
262 for connection in self._extract_connections(media):
263 captions = self._download_xml(connection.get('href'), programme_id, 'Downloading captions')
264 lang = captions.get('{http://www.w3.org/XML/1998/namespace}lang', 'en')
267 'url': connection.get('href'),
273 def _download_media_selector(self, programme_id):
274 return self._download_media_selector_url(
275 self._MEDIASELECTOR_URL % programme_id, programme_id)
277 def _download_media_selector_url(self, url, programme_id=None):
279 media_selection = self._download_xml(
280 url, programme_id, 'Downloading media selection XML')
281 except ExtractorError as ee:
282 if isinstance(ee.cause, compat_HTTPError) and ee.cause.code == 403:
283 media_selection = xml.etree.ElementTree.fromstring(ee.cause.read().decode('utf-8'))
286 return self._process_media_selector(media_selection, programme_id)
288 def _process_media_selector(self, media_selection, programme_id):
292 for media in self._extract_medias(media_selection):
293 kind = media.get('kind')
295 formats.extend(self._extract_audio(media, programme_id))
296 elif kind == 'video':
297 formats.extend(self._extract_video(media, programme_id))
298 elif kind == 'captions':
299 subtitles = self.extract_subtitles(media, programme_id)
301 return formats, subtitles
303 def _download_playlist(self, playlist_id):
305 playlist = self._download_json(
306 'http://www.bbc.co.uk/programmes/%s/playlist.json' % playlist_id,
307 playlist_id, 'Downloading playlist JSON')
309 version = playlist.get('defaultAvailableVersion')
311 smp_config = version['smpConfig']
312 title = smp_config['title']
313 description = smp_config['summary']
314 for item in smp_config['items']:
316 if kind != 'programme' and kind != 'radioProgramme':
318 programme_id = item.get('vpid')
319 duration = int_or_none(item.get('duration'))
320 formats, subtitles = self._download_media_selector(programme_id)
321 return programme_id, title, description, duration, formats, subtitles
322 except ExtractorError as ee:
323 if not (isinstance(ee.cause, compat_HTTPError) and ee.cause.code == 404):
326 # fallback to legacy playlist
327 return self._process_legacy_playlist(playlist_id)
329 def _process_legacy_playlist_url(self, url, display_id):
330 playlist = self._download_legacy_playlist_url(url, display_id)
331 return self._extract_from_legacy_playlist(playlist, display_id)
333 def _process_legacy_playlist(self, playlist_id):
334 return self._process_legacy_playlist_url(
335 'http://www.bbc.co.uk/iplayer/playlist/%s' % playlist_id, playlist_id)
337 def _download_legacy_playlist_url(self, url, playlist_id=None):
338 return self._download_xml(
339 url, playlist_id, 'Downloading legacy playlist XML')
341 def _extract_from_legacy_playlist(self, playlist, playlist_id):
342 no_items = playlist.find('./{http://bbc.co.uk/2008/emp/playlist}noItems')
343 if no_items is not None:
344 reason = no_items.get('reason')
345 if reason == 'preAvailability':
346 msg = 'Episode %s is not yet available' % playlist_id
347 elif reason == 'postAvailability':
348 msg = 'Episode %s is no longer available' % playlist_id
349 elif reason == 'noMedia':
350 msg = 'Episode %s is not currently available' % playlist_id
352 msg = 'Episode %s is not available: %s' % (playlist_id, reason)
353 raise ExtractorError(msg, expected=True)
355 for item in self._extract_items(playlist):
356 kind = item.get('kind')
357 if kind != 'programme' and kind != 'radioProgramme':
359 title = playlist.find('./{http://bbc.co.uk/2008/emp/playlist}title').text
360 description = playlist.find('./{http://bbc.co.uk/2008/emp/playlist}summary').text
362 def get_programme_id(item):
363 def get_from_attributes(item):
364 for p in('identifier', 'group'):
366 if value and re.match(r'^[pb][\da-z]{7}$', value):
368 get_from_attributes(item)
369 mediator = item.find('./{http://bbc.co.uk/2008/emp/playlist}mediator')
370 if mediator is not None:
371 return get_from_attributes(mediator)
373 programme_id = get_programme_id(item)
374 duration = int_or_none(item.get('duration'))
375 # TODO: programme_id can be None and media items can be incorporated right inside
376 # playlist's item (e.g. http://www.bbc.com/turkce/haberler/2015/06/150615_telabyad_kentin_cogu)
378 formats, subtitles = self._download_media_selector(programme_id)
380 return programme_id, title, description, duration, formats, subtitles
382 def _real_extract(self, url):
383 group_id = self._match_id(url)
385 webpage = self._download_webpage(url, group_id, 'Downloading video page')
389 tviplayer = self._search_regex(
390 r'mediator\.bind\(({.+?})\s*,\s*document\.getElementById',
391 webpage, 'player', default=None)
394 player = self._parse_json(tviplayer, group_id).get('player', {})
395 duration = int_or_none(player.get('duration'))
396 programme_id = player.get('vpid')
399 programme_id = self._search_regex(
400 r'"vpid"\s*:\s*"([\da-z]{8})"', webpage, 'vpid', fatal=False, default=None)
403 formats, subtitles = self._download_media_selector(programme_id)
404 title = self._og_search_title(webpage)
405 description = self._search_regex(
406 r'<p class="[^"]*medium-description[^"]*">([^<]+)</p>',
407 webpage, 'description', fatal=False)
409 programme_id, title, description, duration, formats, subtitles = self._download_playlist(group_id)
411 self._sort_formats(formats)
416 'description': description,
417 'thumbnail': self._og_search_thumbnail(webpage, default=None),
418 'duration': duration,
420 'subtitles': subtitles,
424 class BBCIE(BBCCoUkIE):
427 _VALID_URL = r'https?://(?:www\.)?bbc\.(?:com|co\.uk)/(?:[^/]+/)+(?P<id>[^/#?]+)'
429 # fails with notukerror for some videos
430 # _MEDIASELECTOR_URL = 'http://open.live.bbc.co.uk/mediaselector/4/mtis/stream/%s'
431 _MEDIASELECTOR_URL = 'http://open.live.bbc.co.uk/mediaselector/5/select/version/2.0/mediaset/journalism-pc/vpid/%s'
434 # article with multiple videos embedded with data-media-meta containing
435 # playlist.sxml, externalId and no direct video links
436 'url': 'http://www.bbc.com/news/world-europe-32668511',
438 'id': 'world-europe-32668511',
439 'title': 'Russia stages massive WW2 parade despite Western boycott',
440 'description': 'md5:00ff61976f6081841f759a08bf78cc9c',
444 # article with multiple videos embedded with data-media-meta (more videos)
445 'url': 'http://www.bbc.com/news/business-28299555',
447 'id': 'business-28299555',
448 'title': 'Farnborough Airshow: Video highlights',
449 'description': 'BBC reports and video highlights at the Farnborough Airshow.',
454 # article with multiple videos embedded with `new SMP()`
455 'url': 'http://www.bbc.co.uk/blogs/adamcurtis/entries/3662a707-0af9-3149-963f-47bea720b460',
457 'id': '3662a707-0af9-3149-963f-47bea720b460',
458 'title': 'BBC Blogs - Adam Curtis - BUGGER',
460 'playlist_count': 18,
462 # single video embedded with mediaAssetPage.init()
463 'url': 'http://www.bbc.com/news/world-europe-32041533',
467 'title': 'Aerial footage showed the site of the crash in the Alps - courtesy BFM TV',
469 'timestamp': 1427219242,
470 'upload_date': '20150324',
474 'skip_download': True,
477 # article with single video embedded with data-media-meta containing
478 # direct video links (for now these are extracted) and playlist.xml (with
479 # media items as f4m and m3u8 - currently unsupported)
480 'url': 'http://www.bbc.com/turkce/haberler/2015/06/150615_telabyad_kentin_cogu',
482 'id': '150615_telabyad_kentin_cogu',
484 'title': "YPG: Tel Abyad'ın tamamı kontrolümüzde",
486 'timestamp': 1434397334,
487 'upload_date': '20150615',
490 'skip_download': True,
493 # single video embedded with mediaAssetPage.init() (regional section)
494 'url': 'http://www.bbc.com/mundo/video_fotos/2015/06/150619_video_honduras_militares_hospitales_corrupcion_aw',
496 'id': '150619_video_honduras_militares_hospitales_corrupcion_aw',
498 'title': 'Honduras militariza sus hospitales por nuevo escándalo de corrupción',
500 'timestamp': 1434713142,
501 'upload_date': '20150619',
504 'skip_download': True,
507 # single video story with digitalData
508 'url': 'http://www.bbc.com/travel/story/20150625-sri-lankas-spicy-secret',
512 'title': 'Sri Lanka’s spicy secret',
513 'description': 'As a new train line to Jaffna opens up the country’s north, travellers can experience a truly distinct slice of Tamil culture.',
514 'timestamp': 1437674293,
515 'upload_date': '20150723',
519 'skip_download': True,
522 # single video story without digitalData
523 'url': 'http://www.bbc.com/autos/story/20130513-hyundais-rock-star',
527 'title': 'Hyundai Santa Fe Sport: Rock star',
528 'description': 'md5:b042a26142c4154a6e472933cf20793d',
529 'timestamp': 1368473503,
530 'upload_date': '20130513',
534 'skip_download': True,
537 # single video with playlist.sxml URL
538 'url': 'http://www.bbc.com/sport/0/football/33653409',
542 'title': 'Transfers: Cristiano Ronaldo to Man Utd, Arsenal to spend?',
543 'description': 'md5:398fca0e2e701c609d726e034fa1fc89',
548 'skip_download': True,
551 # single video with playlist URL from weather section
552 'url': 'http://www.bbc.com/weather/features/33601775',
553 'only_matching': True,
555 # custom redirection to www.bbc.com
556 'url': 'http://www.bbc.co.uk/news/science-environment-33661876',
557 'only_matching': True,
561 def suitable(cls, url):
562 return False if BBCCoUkIE.suitable(url) else super(BBCIE, cls).suitable(url)
564 def _extract_from_media_meta(self, media_meta, video_id):
565 # Direct links to media in media metadata (e.g.
566 # http://www.bbc.com/turkce/haberler/2015/06/150615_telabyad_kentin_cogu)
567 # TODO: there are also f4m and m3u8 streams incorporated in playlist.sxml
568 source_files = media_meta.get('sourceFiles')
572 'format_id': format_id,
573 'ext': f.get('encoding'),
574 'tbr': float_or_none(f.get('bitrate'), 1000),
575 'filesize': int_or_none(f.get('filesize')),
576 } for format_id, f in source_files.items() if f.get('url')], []
578 programme_id = media_meta.get('externalId')
580 return self._download_media_selector(programme_id)
582 # Process playlist.sxml as legacy playlist
583 href = media_meta.get('href')
585 playlist = self._download_legacy_playlist_url(href)
586 _, _, _, _, formats, subtitles = self._extract_from_legacy_playlist(playlist, video_id)
587 return formats, subtitles
591 def _real_extract(self, url):
592 playlist_id = self._match_id(url)
594 webpage = self._download_webpage(url, playlist_id)
596 timestamp = parse_iso8601(self._search_regex(
597 [r'"datePublished":\s*"([^"]+)',
598 r'<meta[^>]+property="article:published_time"[^>]+content="([^"]+)"',
599 r'itemprop="datePublished"[^>]+datetime="([^"]+)"'],
600 webpage, 'date', default=None))
602 # single video with playlist.sxml URL (e.g. http://www.bbc.com/sport/0/football/3365340ng)
603 playlist = self._search_regex(
604 r'<param[^>]+name="playlist"[^>]+value="([^"]+)"',
605 webpage, 'playlist', default=None)
607 programme_id, title, description, duration, formats, subtitles = \
608 self._process_legacy_playlist_url(playlist, playlist_id)
609 self._sort_formats(formats)
613 'description': description,
614 'duration': duration,
615 'timestamp': timestamp,
617 'subtitles': subtitles,
620 # single video story (e.g. http://www.bbc.com/travel/story/20150625-sri-lankas-spicy-secret)
621 programme_id = self._search_regex(
622 [r'data-video-player-vpid="([\da-z]{8})"',
623 r'<param[^>]+name="externalIdentifier"[^>]+value="([\da-z]{8})"'],
624 webpage, 'vpid', default=None)
626 formats, subtitles = self._download_media_selector(programme_id)
627 self._sort_formats(formats)
628 # digitalData may be missing (e.g. http://www.bbc.com/autos/story/20130513-hyundais-rock-star)
629 digital_data = self._parse_json(
631 r'var\s+digitalData\s*=\s*({.+?});?\n', webpage, 'digital data', default='{}'),
632 programme_id, fatal=False)
633 page_info = digital_data.get('page', {}).get('pageInfo', {})
634 title = page_info.get('pageName') or self._og_search_title(webpage)
635 description = page_info.get('description') or self._og_search_description(webpage)
636 timestamp = parse_iso8601(page_info.get('publicationDate')) or timestamp
640 'description': description,
641 'timestamp': timestamp,
643 'subtitles': subtitles,
646 playlist_title = self._html_search_regex(
647 r'<title>(.*?)(?:\s*-\s*BBC [^ ]+)?</title>', webpage, 'playlist title')
648 playlist_description = self._og_search_description(webpage, default=None)
650 def extract_all(pattern):
651 return list(filter(None, map(
652 lambda s: self._parse_json(s, playlist_id, fatal=False),
653 re.findall(pattern, webpage))))
655 # Multiple video article (e.g.
656 # http://www.bbc.co.uk/blogs/adamcurtis/entries/3662a707-0af9-3149-963f-47bea720b460)
657 EMBED_URL = r'https?://(?:www\.)?bbc\.co\.uk/(?:[^/]+/)+[\da-z]{8}(?:\b[^"]+)?'
659 for match in extract_all(r'new\s+SMP\(({.+?})\)'):
660 embed_url = match.get('playerSettings', {}).get('externalEmbedUrl')
661 if embed_url and re.match(EMBED_URL, embed_url):
662 entries.append(embed_url)
663 entries.extend(re.findall(
664 r'setPlaylist\("(%s)"\)' % EMBED_URL, webpage))
666 return self.playlist_result(
667 [self.url_result(entry, 'BBCCoUk') for entry in entries],
668 playlist_id, playlist_title, playlist_description)
670 # Multiple video article (e.g. http://www.bbc.com/news/world-europe-32668511)
671 medias = extract_all(r"data-media-meta='({[^']+})'")
674 # Single video article (e.g. http://www.bbc.com/news/video_and_audio/international)
675 media_asset_page = self._parse_json(
677 r'mediaAssetPage\.init\(\s*({.+?}), "/', webpage, 'media asset'),
680 for video in media_asset_page.get('videos', {}).values():
681 medias.extend(video.values())
684 for num, media_meta in enumerate(medias, start=1):
685 formats, subtitles = self._extract_from_media_meta(media_meta, playlist_id)
688 self._sort_formats(formats)
690 video_id = media_meta.get('externalId')
692 video_id = playlist_id if len(medias) == 1 else '%s-%s' % (playlist_id, num)
694 title = media_meta.get('caption')
696 title = playlist_title if len(medias) == 1 else '%s - Video %s' % (playlist_title, num)
698 duration = int_or_none(media_meta.get('durationInSeconds')) or parse_duration(media_meta.get('duration'))
701 for image in media_meta.get('images', {}).values():
702 images.extend(image.values())
703 if 'image' in media_meta:
704 images.append(media_meta['image'])
707 'url': image.get('href'),
708 'width': int_or_none(image.get('width')),
709 'height': int_or_none(image.get('height')),
710 } for image in images]
715 'thumbnails': thumbnails,
716 'duration': duration,
717 'timestamp': timestamp,
719 'subtitles': subtitles,
722 return self.playlist_result(entries, playlist_id, playlist_title, playlist_description)