2 from __future__ import unicode_literals
5 import xml.etree.ElementTree
7 from .common import InfoExtractor
15 from ..compat import compat_HTTPError
17 class BBCCoUkIE(InfoExtractor):
19 IE_DESC = 'BBC iPlayer'
20 _VALID_URL = r'https?://(?:www\.)?bbc\.co\.uk/(?:(?:(?:programmes|iplayer(?:/[^/]+)?/(?:episode|playlist))/)|music/clips[/#])(?P<id>[\da-z]{8})'
22 _MEDIASELECTOR_URL = 'http://open.live.bbc.co.uk/mediaselector/5/select/version/2.0/mediaset/pc/vpid/%s'
26 'url': 'http://www.bbc.co.uk/programmes/b039g8p7',
30 'title': 'Kaleidoscope, Leonard Cohen',
31 'description': 'The Canadian poet and songwriter reflects on his musical career.',
36 'skip_download': True,
40 'url': 'http://www.bbc.co.uk/iplayer/episode/b00yng5w/The_Man_in_Black_Series_3_The_Printed_Name/',
44 'title': 'The Man in Black: Series 3: The Printed Name',
45 'description': "Mark Gatiss introduces Nicholas Pierpan's chilling tale of a writer's devilish pact with a mysterious man. Stars Ewan Bailey.",
50 'skip_download': True,
52 'skip': 'Episode is no longer available on BBC iPlayer Radio',
55 'url': 'http://www.bbc.co.uk/iplayer/episode/b03vhd1f/The_Voice_UK_Series_3_Blind_Auditions_5/',
59 'title': 'The Voice UK: Series 3: Blind Auditions 5',
60 '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.",
65 'skip_download': True,
67 'skip': 'Currently BBC iPlayer TV programmes are available to play in the UK only',
70 'url': 'http://www.bbc.co.uk/iplayer/episode/p026c7jt/tomorrows-worlds-the-unearthly-history-of-science-fiction-2-invasion',
74 'title': "Tomorrow's Worlds: The Unearthly History of Science Fiction",
75 'description': '2. Invasion',
80 'skip_download': True,
82 'skip': 'Currently BBC iPlayer TV programmes are available to play in the UK only',
84 'url': 'http://www.bbc.co.uk/programmes/b04v20dw',
88 'title': 'Pete Tong, The Essential New Tune Special',
89 'description': "Pete has a very special mix - all of 2014's Essential New Tunes!",
94 'skip_download': True,
97 'url': 'http://www.bbc.co.uk/music/clips/p02frcc3',
102 'title': 'Pete Tong, Past, Present and Future Special, Madeon - After Hours mix',
103 'description': 'French house superstar Madeon takes us out of the club and onto the after party.',
108 'skip_download': True,
111 'url': 'http://www.bbc.co.uk/music/clips/p025c0zz',
116 'title': 'Reading and Leeds Festival, 2014, Rae Morris - Closer (Live on BBC Three)',
117 'description': 'Rae Morris performs Closer for BBC Three at Reading 2014',
122 'skip_download': True,
125 'url': 'http://www.bbc.co.uk/iplayer/episode/b054fn09/ad/natural-world-20152016-2-super-powered-owls',
129 'title': 'Natural World, 2015-2016: 2. Super Powered Owls',
130 'description': 'md5:e4db5c937d0e95a7c6b5e654d429183d',
135 'skip_download': True,
137 'skip': 'geolocation',
139 'url': 'http://www.bbc.co.uk/iplayer/episode/b05zmgwn/royal-academy-summer-exhibition',
143 '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.',
144 'title': 'Royal Academy Summer Exhibition',
149 'skip_download': True,
151 'skip': 'geolocation',
153 'url': 'http://www.bbc.co.uk/iplayer/playlist/p01dvks4',
154 'only_matching': True,
156 'url': 'http://www.bbc.co.uk/music/clips#p02frcc3',
157 'only_matching': True,
159 'url': 'http://www.bbc.co.uk/iplayer/cbeebies/episode/b0480276/bing-14-atchoo',
160 'only_matching': True,
164 def _extract_asx_playlist(self, connection, programme_id):
165 asx = self._download_xml(connection.get('href'), programme_id, 'Downloading ASX playlist')
166 return [ref.get('href') for ref in asx.findall('./Entry/ref')]
168 def _extract_connection(self, connection, programme_id):
170 protocol = connection.get('protocol')
171 supplier = connection.get('supplier')
172 if protocol == 'http':
173 href = connection.get('href')
174 transfer_format = connection.get('transferFormat')
176 if supplier == 'asx':
177 for i, ref in enumerate(self._extract_asx_playlist(connection, programme_id)):
180 'format_id': 'ref%s_%s' % (i, supplier),
182 # Skip DASH until supported
183 elif transfer_format == 'dash':
189 'format_id': supplier,
191 elif protocol == 'rtmp':
192 application = connection.get('application', 'ondemand')
193 auth_string = connection.get('authString')
194 identifier = connection.get('identifier')
195 server = connection.get('server')
197 'url': '%s://%s/%s?%s' % (protocol, server, application, auth_string),
198 'play_path': identifier,
199 'app': '%s?%s' % (application, auth_string),
200 'page_url': 'http://www.bbc.co.uk',
201 'player_url': 'http://www.bbc.co.uk/emp/releases/iplayer/revisions/617463_618125_4/617463_618125_4_emp.swf',
204 'format_id': supplier,
208 def _extract_items(self, playlist):
209 return playlist.findall('./{http://bbc.co.uk/2008/emp/playlist}item')
211 def _extract_medias(self, media_selection):
212 error = media_selection.find('./{http://bbc.co.uk/2008/mp/mediaselection}error')
213 if error is not None:
214 raise ExtractorError(
215 '%s returned error: %s' % (self.IE_NAME, error.get('id')), expected=True)
216 return media_selection.findall('./{http://bbc.co.uk/2008/mp/mediaselection}media')
218 def _extract_connections(self, media):
219 return media.findall('./{http://bbc.co.uk/2008/mp/mediaselection}connection')
221 def _extract_video(self, media, programme_id):
223 vbr = int_or_none(media.get('bitrate'))
224 vcodec = media.get('encoding')
225 service = media.get('service')
226 width = int_or_none(media.get('width'))
227 height = int_or_none(media.get('height'))
228 file_size = int_or_none(media.get('media_file_size'))
229 for connection in self._extract_connections(media):
230 conn_formats = self._extract_connection(connection, programme_id)
231 for format in conn_formats:
233 'format_id': '%s_%s' % (service, format['format_id']),
238 'filesize': file_size,
240 formats.extend(conn_formats)
243 def _extract_audio(self, media, programme_id):
245 abr = int_or_none(media.get('bitrate'))
246 acodec = media.get('encoding')
247 service = media.get('service')
248 for connection in self._extract_connections(media):
249 conn_formats = self._extract_connection(connection, programme_id)
250 for format in conn_formats:
252 'format_id': '%s_%s' % (service, format['format_id']),
256 formats.extend(conn_formats)
259 def _get_subtitles(self, media, programme_id):
261 for connection in self._extract_connections(media):
262 captions = self._download_xml(connection.get('href'), programme_id, 'Downloading captions')
263 lang = captions.get('{http://www.w3.org/XML/1998/namespace}lang', 'en')
266 'url': connection.get('href'),
272 def _download_media_selector(self, programme_id):
274 return self._download_media_selector_url(
275 self._MEDIASELECTOR_URL % programme_id, programme_id)
276 except ExtractorError as e:
277 if hasattr(self, '_MEDIASELECTOR_ALT_URL') and str(e) == 'bbc returned error: notukerror':
278 # notukerror on bbc.com/travel using bbc news mediaselector: fallback to /mediaselector/5/
279 return self._download_media_selector_url(
280 self._MEDIASELECTOR_ALT_URL % programme_id, programme_id)
284 def _download_media_selector_url(self, url, programme_id=None):
286 media_selection = self._download_xml(
287 url, programme_id, 'Downloading media selection XML')
288 except ExtractorError as ee:
289 if isinstance(ee.cause, compat_HTTPError) and ee.cause.code == 403:
290 media_selection = xml.etree.ElementTree.fromstring(ee.cause.read().decode('utf-8'))
293 return self._process_media_selector(media_selection, programme_id)
295 def _process_media_selector(self, media_selection, programme_id):
299 for media in self._extract_medias(media_selection):
300 kind = media.get('kind')
302 formats.extend(self._extract_audio(media, programme_id))
303 elif kind == 'video':
304 formats.extend(self._extract_video(media, programme_id))
305 elif kind == 'captions':
306 subtitles = self.extract_subtitles(media, programme_id)
307 return formats, subtitles
309 def _download_playlist(self, playlist_id):
311 playlist = self._download_json(
312 'http://www.bbc.co.uk/programmes/%s/playlist.json' % playlist_id,
313 playlist_id, 'Downloading playlist JSON')
315 version = playlist.get('defaultAvailableVersion')
317 smp_config = version['smpConfig']
318 title = smp_config['title']
319 description = smp_config['summary']
320 for item in smp_config['items']:
322 if kind != 'programme' and kind != 'radioProgramme':
324 programme_id = item.get('vpid')
325 duration = int_or_none(item.get('duration'))
326 formats, subtitles = self._download_media_selector(programme_id)
327 return programme_id, title, description, duration, formats, subtitles
328 except ExtractorError as ee:
329 if not (isinstance(ee.cause, compat_HTTPError) and ee.cause.code == 404):
332 # fallback to legacy playlist
333 return self._process_legacy_playlist(playlist_id)
335 def _process_legacy_playlist_url(self, url, display_id):
336 playlist = self._download_legacy_playlist_url(url, display_id)
337 return self._extract_from_legacy_playlist(playlist, display_id)
339 def _process_legacy_playlist(self, playlist_id):
340 return self._process_legacy_playlist_url(
341 'http://www.bbc.co.uk/iplayer/playlist/%s' % playlist_id, playlist_id)
343 def _download_legacy_playlist_url(self, url, playlist_id=None):
344 return self._download_xml(
345 url, playlist_id, 'Downloading legacy playlist XML')
347 def _extract_from_legacy_playlist(self, playlist, playlist_id):
348 no_items = playlist.find('./{http://bbc.co.uk/2008/emp/playlist}noItems')
349 if no_items is not None:
350 reason = no_items.get('reason')
351 if reason == 'preAvailability':
352 msg = 'Episode %s is not yet available' % playlist_id
353 elif reason == 'postAvailability':
354 msg = 'Episode %s is no longer available' % playlist_id
355 elif reason == 'noMedia':
356 msg = 'Episode %s is not currently available' % playlist_id
358 msg = 'Episode %s is not available: %s' % (playlist_id, reason)
359 raise ExtractorError(msg, expected=True)
361 for item in self._extract_items(playlist):
362 kind = item.get('kind')
363 if kind != 'programme' and kind != 'radioProgramme':
365 title = playlist.find('./{http://bbc.co.uk/2008/emp/playlist}title').text
366 description = playlist.find('./{http://bbc.co.uk/2008/emp/playlist}summary').text
368 def get_programme_id(item):
369 def get_from_attributes(item):
370 for p in('identifier', 'group'):
372 if value and re.match(r'^[pb][\da-z]{7}$', value):
374 get_from_attributes(item)
375 mediator = item.find('./{http://bbc.co.uk/2008/emp/playlist}mediator')
376 if mediator is not None:
377 return get_from_attributes(mediator)
379 programme_id = get_programme_id(item)
380 duration = int_or_none(item.get('duration'))
381 # TODO: programme_id can be None and media items can be incorporated right inside
382 # playlist's item (e.g. http://www.bbc.com/turkce/haberler/2015/06/150615_telabyad_kentin_cogu)
384 formats, subtitles = self._download_media_selector(programme_id)
386 return programme_id, title, description, duration, formats, subtitles
388 def _real_extract(self, url):
389 group_id = self._match_id(url)
391 webpage = self._download_webpage(url, group_id, 'Downloading video page')
395 tviplayer = self._search_regex(
396 r'mediator\.bind\(({.+?})\s*,\s*document\.getElementById',
397 webpage, 'player', default=None)
400 player = self._parse_json(tviplayer, group_id).get('player', {})
401 duration = int_or_none(player.get('duration'))
402 programme_id = player.get('vpid')
405 programme_id = self._search_regex(
406 r'"vpid"\s*:\s*"([\da-z]{8})"', webpage, 'vpid', fatal=False, default=None)
409 formats, subtitles = self._download_media_selector(programme_id)
410 title = self._og_search_title(webpage)
411 description = self._search_regex(
412 r'<p class="[^"]*medium-description[^"]*">([^<]+)</p>',
413 webpage, 'description', fatal=False)
415 programme_id, title, description, duration, formats, subtitles = self._download_playlist(group_id)
417 self._sort_formats(formats)
422 'description': description,
423 'thumbnail': self._og_search_thumbnail(webpage, default=None),
424 'duration': duration,
426 'subtitles': subtitles,
430 class BBCIE(BBCCoUkIE):
433 _VALID_URL = r'https?://(?:www\.)?bbc\.(?:com|co\.uk)/(?:[^/]+/)+(?P<id>[^/#?]+)'
435 # fails with notukerror for some videos ( non news sites such as bbc.com/travel )
436 _MEDIASELECTOR_URL = 'http://open.live.bbc.co.uk/mediaselector/4/mtis/stream/%s'
437 # limited selection of formats but may work where the above does not
438 _MEDIASELECTOR_ALT_URL = 'http://open.live.bbc.co.uk/mediaselector/5/select/version/2.0/mediaset/journalism-pc/vpid/%s'
441 # article with multiple videos embedded with data-media-meta containing
442 # playlist.sxml, externalId and no direct video links
443 'url': 'http://www.bbc.com/news/world-europe-32668511',
445 'id': 'world-europe-32668511',
446 'title': 'Russia stages massive WW2 parade despite Western boycott',
447 'description': 'md5:00ff61976f6081841f759a08bf78cc9c',
451 # article with multiple videos embedded with data-media-meta (more videos)
452 'url': 'http://www.bbc.com/news/business-28299555',
454 'id': 'business-28299555',
455 'title': 'Farnborough Airshow: Video highlights',
456 'description': 'BBC reports and video highlights at the Farnborough Airshow.',
461 # single video embedded with mediaAssetPage.init()
462 'url': 'http://www.bbc.com/news/world-europe-32041533',
466 'title': 'Aerial footage showed the site of the crash in the Alps - courtesy BFM TV',
468 'timestamp': 1427219242,
469 'upload_date': '20150324',
473 'skip_download': True,
476 # article with single video embedded with data-media-meta containing
477 # direct video links (for now these are extracted) and playlist.xml (with
478 # media items as f4m and m3u8 - currently unsupported)
479 'url': 'http://www.bbc.com/turkce/haberler/2015/06/150615_telabyad_kentin_cogu',
481 'id': '150615_telabyad_kentin_cogu',
483 'title': "YPG: Tel Abyad'ın tamamı kontrolümüzde",
485 'timestamp': 1434397334,
486 'upload_date': '20150615',
489 'skip_download': True,
492 # single video embedded with mediaAssetPage.init() (regional section)
493 'url': 'http://www.bbc.com/mundo/video_fotos/2015/06/150619_video_honduras_militares_hospitales_corrupcion_aw',
495 'id': '150619_video_honduras_militares_hospitales_corrupcion_aw',
497 'title': 'Honduras militariza sus hospitales por nuevo escándalo de corrupción',
499 'timestamp': 1434713142,
500 'upload_date': '20150619',
503 'skip_download': True,
506 # single video story with digitalData
507 'url': 'http://www.bbc.com/travel/story/20150625-sri-lankas-spicy-secret',
511 'title': 'Sri Lanka’s spicy secret',
512 'description': 'As a new train line to Jaffna opens up the country’s north, travellers can experience a truly distinct slice of Tamil culture.',
513 'timestamp': 1437674293,
514 'upload_date': '20150723',
518 'skip_download': True,
521 # single video story without digitalData
522 'url': 'http://www.bbc.com/autos/story/20130513-hyundais-rock-star',
526 'title': 'Hyundai Santa Fe Sport: Rock star',
527 'description': 'md5:b042a26142c4154a6e472933cf20793d',
528 'timestamp': 1368473503,
529 'upload_date': '20130513',
533 'skip_download': True,
536 # single video with playlist.sxml URL
537 'url': 'http://www.bbc.com/sport/0/football/33653409',
541 'title': 'Transfers: Cristiano Ronaldo to Man Utd, Arsenal to spend?',
542 'description': 'md5:398fca0e2e701c609d726e034fa1fc89',
547 'skip_download': True,
550 # single video with playlist URL from weather section
551 'url': 'http://www.bbc.com/weather/features/33601775',
552 'only_matching': True,
554 # custom redirection to www.bbc.com
555 'url': 'http://www.bbc.co.uk/news/science-environment-33661876',
556 'only_matching': True,
560 def suitable(cls, url):
561 return False if BBCCoUkIE.suitable(url) else super(BBCIE, cls).suitable(url)
563 def _extract_from_media_meta(self, media_meta, video_id):
564 # Direct links to media in media metadata (e.g.
565 # http://www.bbc.com/turkce/haberler/2015/06/150615_telabyad_kentin_cogu)
566 # TODO: there are also f4m and m3u8 streams incorporated in playlist.sxml
567 source_files = media_meta.get('sourceFiles')
571 'format_id': format_id,
572 'ext': f.get('encoding'),
573 'tbr': float_or_none(f.get('bitrate'), 1000),
574 'filesize': int_or_none(f.get('filesize')),
575 } for format_id, f in source_files.items() if f.get('url')], []
577 programme_id = media_meta.get('externalId')
579 return self._download_media_selector(programme_id)
581 # Process playlist.sxml as legacy playlist
582 href = media_meta.get('href')
584 playlist = self._download_legacy_playlist_url(href)
585 _, _, _, _, formats, subtitles = self._extract_from_legacy_playlist(playlist, video_id)
586 return formats, subtitles
590 def _real_extract(self, url):
591 playlist_id = self._match_id(url)
593 webpage = self._download_webpage(url, playlist_id)
595 timestamp = parse_iso8601(self._search_regex(
596 [r'"datePublished":\s*"([^"]+)',
597 r'<meta[^>]+property="article:published_time"[^>]+content="([^"]+)"',
598 r'itemprop="datePublished"[^>]+datetime="([^"]+)"'],
599 webpage, 'date', default=None))
601 # single video with playlist.sxml URL (e.g. http://www.bbc.com/sport/0/football/3365340ng)
602 playlist = self._search_regex(
603 r'<param[^>]+name="playlist"[^>]+value="([^"]+)"',
604 webpage, 'playlist', default=None)
606 programme_id, title, description, duration, formats, subtitles = \
607 self._process_legacy_playlist_url(playlist, playlist_id)
608 self._sort_formats(formats)
612 'description': description,
613 'duration': duration,
614 'timestamp': timestamp,
616 'subtitles': subtitles,
619 # single video story (e.g. http://www.bbc.com/travel/story/20150625-sri-lankas-spicy-secret)
620 programme_id = self._search_regex(
621 [r'data-video-player-vpid="([\da-z]{8})"',
622 r'<param[^>]+name="externalIdentifier"[^>]+value="([\da-z]{8})"'],
623 webpage, 'vpid', default=None)
625 formats, subtitles = self._download_media_selector(programme_id)
626 self._sort_formats(formats)
627 # digitalData may be missing (e.g. http://www.bbc.com/autos/story/20130513-hyundais-rock-star)
628 digital_data = self._parse_json(
630 r'var\s+digitalData\s*=\s*({.+?});?\n', webpage, 'digital data', default='{}'),
631 programme_id, fatal=False)
632 page_info = digital_data.get('page', {}).get('pageInfo', {})
633 title = page_info.get('pageName') or self._og_search_title(webpage)
634 description = page_info.get('description') or self._og_search_description(webpage)
635 timestamp = parse_iso8601(page_info.get('publicationDate')) or timestamp
639 'description': description,
640 'timestamp': timestamp,
642 'subtitles': subtitles,
645 playlist_title = self._html_search_regex(
646 r'<title>(.*?)(?:\s*-\s*BBC [^ ]+)?</title>', webpage, 'playlist title')
647 playlist_description = self._og_search_description(webpage)
649 # Multiple video article (e.g. http://www.bbc.com/news/world-europe-32668511)
650 medias = list(filter(None, map(
651 lambda s: self._parse_json(s, playlist_id, fatal=False),
652 re.findall(r"data-media-meta='({[^']+})'", webpage))))
655 # Single video article (e.g. http://www.bbc.com/news/video_and_audio/international)
656 media_asset_page = self._parse_json(
658 r'mediaAssetPage\.init\(\s*({.+?}), "/', webpage, 'media asset'),
661 for video in media_asset_page.get('videos', {}).values():
662 medias.extend(video.values())
665 for num, media_meta in enumerate(medias, start=1):
666 formats, subtitles = self._extract_from_media_meta(media_meta, playlist_id)
669 self._sort_formats(formats)
671 video_id = media_meta.get('externalId')
673 video_id = playlist_id if len(medias) == 1 else '%s-%s' % (playlist_id, num)
675 title = media_meta.get('caption')
677 title = playlist_title if len(medias) == 1 else '%s - Video %s' % (playlist_title, num)
679 duration = int_or_none(media_meta.get('durationInSeconds')) or parse_duration(media_meta.get('duration'))
682 for image in media_meta.get('images', {}).values():
683 images.extend(image.values())
684 if 'image' in media_meta:
685 images.append(media_meta['image'])
688 'url': image.get('href'),
689 'width': int_or_none(image.get('width')),
690 'height': int_or_none(image.get('height')),
691 } for image in images]
696 'thumbnails': thumbnails,
697 'duration': duration,
698 'timestamp': timestamp,
700 'subtitles': subtitles,
703 return self.playlist_result(entries, playlist_id, playlist_title, playlist_description)