2 from __future__ import unicode_literals
7 from .common import InfoExtractor
24 from ..compat import (
31 class BBCCoUkIE(InfoExtractor):
33 IE_DESC = 'BBC iPlayer'
34 _ID_REGEX = r'(?:[pbm][\da-z]{7}|w[\da-z]{7,14})'
37 (?:www\.)?bbc\.co\.uk/
39 programmes/(?!articles/)|
40 iplayer(?:/[^/]+)?/(?:episode/|playlist/)|
41 music/(?:clips|audiovideo/popular)[/#]|
43 events/[^/]+/play/[^/]+/
45 (?P<id>%s)(?!/(?:episodes|broadcasts|clips))
48 _LOGIN_URL = 'https://account.bbc.com/signin'
49 _NETRC_MACHINE = 'bbc'
51 _MEDIASELECTOR_URLS = [
52 # Provides HQ HLS streams with even better quality that pc mediaset but fails
53 # with geolocation in some cases when it's even not geo restricted at all (e.g.
54 # http://www.bbc.co.uk/programmes/b06bp7lf). Also may fail with selectionunavailable.
55 'http://open.live.bbc.co.uk/mediaselector/5/select/version/2.0/mediaset/iptv-all/vpid/%s',
56 'http://open.live.bbc.co.uk/mediaselector/5/select/version/2.0/mediaset/pc/vpid/%s',
59 _MEDIASELECTION_NS = 'http://bbc.co.uk/2008/mp/mediaselection'
60 _EMP_PLAYLIST_NS = 'http://bbc.co.uk/2008/emp/playlist'
69 'url': 'http://www.bbc.co.uk/programmes/b039g8p7',
73 'title': 'Leonard Cohen, Kaleidoscope - BBC Radio 4',
74 'description': 'The Canadian poet and songwriter reflects on his musical career.',
78 'skip_download': True,
82 'url': 'http://www.bbc.co.uk/iplayer/episode/b00yng5w/The_Man_in_Black_Series_3_The_Printed_Name/',
86 'title': 'The Man in Black: Series 3: The Printed Name',
87 'description': "Mark Gatiss introduces Nicholas Pierpan's chilling tale of a writer's devilish pact with a mysterious man. Stars Ewan Bailey.",
92 'skip_download': True,
94 'skip': 'Episode is no longer available on BBC iPlayer Radio',
97 'url': 'http://www.bbc.co.uk/iplayer/episode/b03vhd1f/The_Voice_UK_Series_3_Blind_Auditions_5/',
101 'title': 'The Voice UK: Series 3: Blind Auditions 5',
102 '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.',
107 'skip_download': True,
109 'skip': 'Currently BBC iPlayer TV programmes are available to play in the UK only',
112 'url': 'http://www.bbc.co.uk/iplayer/episode/p026c7jt/tomorrows-worlds-the-unearthly-history-of-science-fiction-2-invasion',
116 'title': "Tomorrow's Worlds: The Unearthly History of Science Fiction",
117 'description': '2. Invasion',
122 'skip_download': True,
124 'skip': 'Currently BBC iPlayer TV programmes are available to play in the UK only',
126 'url': 'http://www.bbc.co.uk/programmes/b04v20dw',
130 'title': 'Pete Tong, The Essential New Tune Special',
131 'description': "Pete has a very special mix - all of 2014's Essential New Tunes!",
136 'skip_download': True,
138 'skip': 'Episode is no longer available on BBC iPlayer Radio',
140 'url': 'http://www.bbc.co.uk/music/clips/p022h44b',
145 'title': 'BBC Proms Music Guides, Rachmaninov: Symphonic Dances',
146 'description': "In this Proms Music Guide, Andrew McGregor looks at Rachmaninov's Symphonic Dances.",
151 'skip_download': True,
154 'url': 'http://www.bbc.co.uk/music/clips/p025c0zz',
159 'title': 'Reading and Leeds Festival, 2014, Rae Morris - Closer (Live on BBC Three)',
160 'description': 'Rae Morris performs Closer for BBC Three at Reading 2014',
165 'skip_download': True,
168 'url': 'http://www.bbc.co.uk/iplayer/episode/b054fn09/ad/natural-world-20152016-2-super-powered-owls',
172 'title': 'Natural World, 2015-2016: 2. Super Powered Owls',
173 'description': 'md5:e4db5c937d0e95a7c6b5e654d429183d',
178 'skip_download': True,
180 'skip': 'geolocation',
182 'url': 'http://www.bbc.co.uk/iplayer/episode/b05zmgwn/royal-academy-summer-exhibition',
186 '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.',
187 'title': 'Royal Academy Summer Exhibition',
192 'skip_download': True,
194 'skip': 'geolocation',
196 # iptv-all mediaset fails with geolocation however there is no geo restriction
197 # for this programme at all
198 'url': 'http://www.bbc.co.uk/programmes/b06rkn85',
202 'title': "Best of the Mini-Mixes 2015: Part 3, Annie Mac's Friday Night - BBC Radio 1",
203 'description': "Annie has part three in the Best of the Mini-Mixes 2015, plus the year's Most Played!",
207 'skip_download': True,
209 'skip': 'Now it\'s really geo-restricted',
211 # compact player (https://github.com/ytdl-org/youtube-dl/issues/8147)
212 'url': 'http://www.bbc.co.uk/programmes/p028bfkf/player',
216 'title': 'Extract from BBC documentary Look Stranger - Giant Leeks and Magic Brews',
217 'description': 'Extract from BBC documentary Look Stranger - Giant Leeks and Magic Brews',
221 'skip_download': True,
224 'url': 'http://www.bbc.co.uk/iplayer/playlist/p01dvks4',
225 'only_matching': True,
227 'url': 'http://www.bbc.co.uk/music/clips#p02frcc3',
228 'only_matching': True,
230 'url': 'http://www.bbc.co.uk/iplayer/cbeebies/episode/b0480276/bing-14-atchoo',
231 'only_matching': True,
233 'url': 'http://www.bbc.co.uk/radio/player/p03cchwf',
234 'only_matching': True,
236 'url': 'https://www.bbc.co.uk/music/audiovideo/popular#p055bc55',
237 'only_matching': True,
239 'url': 'http://www.bbc.co.uk/programmes/w3csv1y9',
240 'only_matching': True,
242 'url': 'https://www.bbc.co.uk/programmes/m00005xn',
243 'only_matching': True,
245 'url': 'https://www.bbc.co.uk/programmes/w172w4dww1jqt5s',
246 'only_matching': True,
249 _USP_RE = r'/([^/]+?)\.ism(?:\.hlsv2\.ism)?/[^/]+\.m3u8'
252 username, password = self._get_login_info()
256 login_page = self._download_webpage(
257 self._LOGIN_URL, None, 'Downloading signin page')
259 login_form = self._hidden_inputs(login_page)
262 'username': username,
263 'password': password,
266 post_url = urljoin(self._LOGIN_URL, self._search_regex(
267 r'<form[^>]+action=(["\'])(?P<url>.+?)\1', login_page,
268 'post url', default=self._LOGIN_URL, group='url'))
270 response, urlh = self._download_webpage_handle(
271 post_url, None, 'Logging in', data=urlencode_postdata(login_form),
272 headers={'Referer': self._LOGIN_URL})
274 if self._LOGIN_URL in urlh.geturl():
275 error = clean_html(get_element_by_class('form-message', response))
277 raise ExtractorError(
278 'Unable to login: %s' % error, expected=True)
279 raise ExtractorError('Unable to log in')
281 def _real_initialize(self):
284 class MediaSelectionError(Exception):
285 def __init__(self, id):
288 def _extract_asx_playlist(self, connection, programme_id):
289 asx = self._download_xml(connection.get('href'), programme_id, 'Downloading ASX playlist')
290 return [ref.get('href') for ref in asx.findall('./Entry/ref')]
292 def _extract_items(self, playlist):
293 return playlist.findall('./{%s}item' % self._EMP_PLAYLIST_NS)
295 def _findall_ns(self, element, xpath):
297 for ns in self._NAMESPACES:
298 elements.extend(element.findall(xpath % ns))
301 def _extract_medias(self, media_selection):
302 error = media_selection.find('./{%s}error' % self._MEDIASELECTION_NS)
304 media_selection.find('./{%s}error' % self._EMP_PLAYLIST_NS)
305 if error is not None:
306 raise BBCCoUkIE.MediaSelectionError(error.get('id'))
307 return self._findall_ns(media_selection, './{%s}media')
309 def _extract_connections(self, media):
310 return self._findall_ns(media, './{%s}connection')
312 def _get_subtitles(self, media, programme_id):
314 for connection in self._extract_connections(media):
315 cc_url = url_or_none(connection.get('href'))
318 captions = self._download_xml(
319 cc_url, programme_id, 'Downloading captions', fatal=False)
320 if not isinstance(captions, compat_etree_Element):
322 lang = captions.get('{http://www.w3.org/XML/1998/namespace}lang', 'en')
325 'url': connection.get('href'),
331 def _raise_extractor_error(self, media_selection_error):
332 raise ExtractorError(
333 '%s returned error: %s' % (self.IE_NAME, media_selection_error.id),
336 def _download_media_selector(self, programme_id):
337 last_exception = None
338 for mediaselector_url in self._MEDIASELECTOR_URLS:
340 return self._download_media_selector_url(
341 mediaselector_url % programme_id, programme_id)
342 except BBCCoUkIE.MediaSelectionError as e:
343 if e.id in ('notukerror', 'geolocation', 'selectionunavailable'):
346 self._raise_extractor_error(e)
347 self._raise_extractor_error(last_exception)
349 def _download_media_selector_url(self, url, programme_id=None):
350 media_selection = self._download_xml(
351 url, programme_id, 'Downloading media selection XML',
352 expected_status=(403, 404))
353 return self._process_media_selector(media_selection, programme_id)
355 def _process_media_selector(self, media_selection, programme_id):
360 for media in self._extract_medias(media_selection):
361 kind = media.get('kind')
362 if kind in ('video', 'audio'):
363 bitrate = int_or_none(media.get('bitrate'))
364 encoding = media.get('encoding')
365 service = media.get('service')
366 width = int_or_none(media.get('width'))
367 height = int_or_none(media.get('height'))
368 file_size = int_or_none(media.get('media_file_size'))
369 for connection in self._extract_connections(media):
370 href = connection.get('href')
375 conn_kind = connection.get('kind')
376 protocol = connection.get('protocol')
377 supplier = connection.get('supplier')
378 transfer_format = connection.get('transferFormat')
379 format_id = supplier or conn_kind or protocol
381 format_id = '%s_%s' % (service, format_id)
383 if supplier == 'asx':
384 for i, ref in enumerate(self._extract_asx_playlist(connection, programme_id)):
387 'format_id': 'ref%s_%s' % (i, format_id),
389 elif transfer_format == 'dash':
390 formats.extend(self._extract_mpd_formats(
391 href, programme_id, mpd_id=format_id, fatal=False))
392 elif transfer_format == 'hls':
393 formats.extend(self._extract_m3u8_formats(
394 href, programme_id, ext='mp4', entry_protocol='m3u8_native',
395 m3u8_id=format_id, fatal=False))
396 if re.search(self._USP_RE, href):
397 usp_formats = self._extract_m3u8_formats(
398 re.sub(self._USP_RE, r'/\1.ism/\1.m3u8', href),
399 programme_id, ext='mp4', entry_protocol='m3u8_native',
400 m3u8_id=format_id, fatal=False)
401 for f in usp_formats:
402 if f.get('height') and f['height'] > 720:
405 elif transfer_format == 'hds':
406 formats.extend(self._extract_f4m_formats(
407 href, programme_id, f4m_id=format_id, fatal=False))
409 if not service and not supplier and bitrate:
410 format_id += '-%d' % bitrate
412 'format_id': format_id,
413 'filesize': file_size,
428 if protocol in ('http', 'https'):
433 elif protocol == 'rtmp':
434 application = connection.get('application', 'ondemand')
435 auth_string = connection.get('authString')
436 identifier = connection.get('identifier')
437 server = connection.get('server')
439 'url': '%s://%s/%s?%s' % (protocol, server, application, auth_string),
440 'play_path': identifier,
441 'app': '%s?%s' % (application, auth_string),
442 'page_url': 'http://www.bbc.co.uk',
443 'player_url': 'http://www.bbc.co.uk/emp/releases/iplayer/revisions/617463_618125_4/617463_618125_4_emp.swf',
450 elif kind == 'captions':
451 subtitles = self.extract_subtitles(media, programme_id)
452 return formats, subtitles
454 def _download_playlist(self, playlist_id):
456 playlist = self._download_json(
457 'http://www.bbc.co.uk/programmes/%s/playlist.json' % playlist_id,
458 playlist_id, 'Downloading playlist JSON')
460 version = playlist.get('defaultAvailableVersion')
462 smp_config = version['smpConfig']
463 title = smp_config['title']
464 description = smp_config['summary']
465 for item in smp_config['items']:
467 if kind not in ('programme', 'radioProgramme'):
469 programme_id = item.get('vpid')
470 duration = int_or_none(item.get('duration'))
471 formats, subtitles = self._download_media_selector(programme_id)
472 return programme_id, title, description, duration, formats, subtitles
473 except ExtractorError as ee:
474 if not (isinstance(ee.cause, compat_HTTPError) and ee.cause.code == 404):
477 # fallback to legacy playlist
478 return self._process_legacy_playlist(playlist_id)
480 def _process_legacy_playlist_url(self, url, display_id):
481 playlist = self._download_legacy_playlist_url(url, display_id)
482 return self._extract_from_legacy_playlist(playlist, display_id)
484 def _process_legacy_playlist(self, playlist_id):
485 return self._process_legacy_playlist_url(
486 'http://www.bbc.co.uk/iplayer/playlist/%s' % playlist_id, playlist_id)
488 def _download_legacy_playlist_url(self, url, playlist_id=None):
489 return self._download_xml(
490 url, playlist_id, 'Downloading legacy playlist XML')
492 def _extract_from_legacy_playlist(self, playlist, playlist_id):
493 no_items = playlist.find('./{%s}noItems' % self._EMP_PLAYLIST_NS)
494 if no_items is not None:
495 reason = no_items.get('reason')
496 if reason == 'preAvailability':
497 msg = 'Episode %s is not yet available' % playlist_id
498 elif reason == 'postAvailability':
499 msg = 'Episode %s is no longer available' % playlist_id
500 elif reason == 'noMedia':
501 msg = 'Episode %s is not currently available' % playlist_id
503 msg = 'Episode %s is not available: %s' % (playlist_id, reason)
504 raise ExtractorError(msg, expected=True)
506 for item in self._extract_items(playlist):
507 kind = item.get('kind')
508 if kind not in ('programme', 'radioProgramme'):
510 title = playlist.find('./{%s}title' % self._EMP_PLAYLIST_NS).text
511 description_el = playlist.find('./{%s}summary' % self._EMP_PLAYLIST_NS)
512 description = description_el.text if description_el is not None else None
514 def get_programme_id(item):
515 def get_from_attributes(item):
516 for p in('identifier', 'group'):
518 if value and re.match(r'^[pb][\da-z]{7}$', value):
520 get_from_attributes(item)
521 mediator = item.find('./{%s}mediator' % self._EMP_PLAYLIST_NS)
522 if mediator is not None:
523 return get_from_attributes(mediator)
525 programme_id = get_programme_id(item)
526 duration = int_or_none(item.get('duration'))
529 formats, subtitles = self._download_media_selector(programme_id)
531 formats, subtitles = self._process_media_selector(item, playlist_id)
532 programme_id = playlist_id
534 return programme_id, title, description, duration, formats, subtitles
536 def _real_extract(self, url):
537 group_id = self._match_id(url)
539 webpage = self._download_webpage(url, group_id, 'Downloading video page')
541 error = self._search_regex(
542 r'<div\b[^>]+\bclass=["\']smp__message delta["\'][^>]*>([^<]+)<',
543 webpage, 'error', default=None)
545 raise ExtractorError(error, expected=True)
550 tviplayer = self._search_regex(
551 r'mediator\.bind\(({.+?})\s*,\s*document\.getElementById',
552 webpage, 'player', default=None)
555 player = self._parse_json(tviplayer, group_id).get('player', {})
556 duration = int_or_none(player.get('duration'))
557 programme_id = player.get('vpid')
560 programme_id = self._search_regex(
561 r'"vpid"\s*:\s*"(%s)"' % self._ID_REGEX, webpage, 'vpid', fatal=False, default=None)
564 formats, subtitles = self._download_media_selector(programme_id)
565 title = self._og_search_title(webpage, default=None) or self._html_search_regex(
566 (r'<h2[^>]+id="parent-title"[^>]*>(.+?)</h2>',
567 r'<div[^>]+class="info"[^>]*>\s*<h1>(.+?)</h1>'), webpage, 'title')
568 description = self._search_regex(
569 (r'<p class="[^"]*medium-description[^"]*">([^<]+)</p>',
570 r'<div[^>]+class="info_+synopsis"[^>]*>([^<]+)</div>'),
571 webpage, 'description', default=None)
573 description = self._html_search_meta('description', webpage)
575 programme_id, title, description, duration, formats, subtitles = self._download_playlist(group_id)
577 self._sort_formats(formats)
582 'description': description,
583 'thumbnail': self._og_search_thumbnail(webpage, default=None),
584 'duration': duration,
586 'subtitles': subtitles,
590 class BBCIE(BBCCoUkIE):
593 _VALID_URL = r'https?://(?:www\.)?bbc\.(?:com|co\.uk)/(?:[^/]+/)+(?P<id>[^/#?]+)'
595 _MEDIASELECTOR_URLS = [
596 # Provides HQ HLS streams but fails with geolocation in some cases when it's
597 # even not geo restricted at all
598 'http://open.live.bbc.co.uk/mediaselector/5/select/version/2.0/mediaset/iptv-all/vpid/%s',
599 # Provides more formats, namely direct mp4 links, but fails on some videos with
600 # notukerror for non UK (?) users (e.g.
601 # http://www.bbc.com/travel/story/20150625-sri-lankas-spicy-secret)
602 'http://open.live.bbc.co.uk/mediaselector/4/mtis/stream/%s',
603 # Provides fewer formats, but works everywhere for everybody (hopefully)
604 'http://open.live.bbc.co.uk/mediaselector/5/select/version/2.0/mediaset/journalism-pc/vpid/%s',
608 # article with multiple videos embedded with data-playable containing vpids
609 'url': 'http://www.bbc.com/news/world-europe-32668511',
611 'id': 'world-europe-32668511',
612 'title': 'Russia stages massive WW2 parade despite Western boycott',
613 'description': 'md5:00ff61976f6081841f759a08bf78cc9c',
617 # article with multiple videos embedded with data-playable (more videos)
618 'url': 'http://www.bbc.com/news/business-28299555',
620 'id': 'business-28299555',
621 'title': 'Farnborough Airshow: Video highlights',
622 'description': 'BBC reports and video highlights at the Farnborough Airshow.',
627 # article with multiple videos embedded with `new SMP()`
629 'url': 'http://www.bbc.co.uk/blogs/adamcurtis/entries/3662a707-0af9-3149-963f-47bea720b460',
631 'id': '3662a707-0af9-3149-963f-47bea720b460',
634 'playlist_count': 18,
636 # single video embedded with data-playable containing vpid
637 'url': 'http://www.bbc.com/news/world-europe-32041533',
641 'title': 'Aerial footage showed the site of the crash in the Alps - courtesy BFM TV',
642 'description': 'md5:2868290467291b37feda7863f7a83f54',
644 'timestamp': 1427219242,
645 'upload_date': '20150324',
649 'skip_download': True,
652 # article with single video embedded with data-playable containing XML playlist
653 # with direct video links as progressiveDownloadUrl (for now these are extracted)
654 # and playlist with f4m and m3u8 as streamingUrl
655 'url': 'http://www.bbc.com/turkce/haberler/2015/06/150615_telabyad_kentin_cogu',
657 'id': '150615_telabyad_kentin_cogu',
659 'title': "YPG: Tel Abyad'ın tamamı kontrolümüzde",
660 'description': 'md5:33a4805a855c9baf7115fcbde57e7025',
661 'timestamp': 1434397334,
662 'upload_date': '20150615',
665 'skip_download': True,
668 # single video embedded with data-playable containing XML playlists (regional section)
669 'url': 'http://www.bbc.com/mundo/video_fotos/2015/06/150619_video_honduras_militares_hospitales_corrupcion_aw',
671 'id': '150619_video_honduras_militares_hospitales_corrupcion_aw',
673 'title': 'Honduras militariza sus hospitales por nuevo escándalo de corrupción',
674 'description': 'md5:1525f17448c4ee262b64b8f0c9ce66c8',
675 'timestamp': 1434713142,
676 'upload_date': '20150619',
679 'skip_download': True,
682 # single video from video playlist embedded with vxp-playlist-data JSON
683 'url': 'http://www.bbc.com/news/video_and_audio/must_see/33376376',
687 'title': '''Judge Mindy Glazer: "I'm sorry to see you here... I always wondered what happened to you"''',
689 'description': '''Judge Mindy Glazer: "I'm sorry to see you here... I always wondered what happened to you"''',
692 'skip_download': True,
695 # single video story with digitalData
696 'url': 'http://www.bbc.com/travel/story/20150625-sri-lankas-spicy-secret',
700 'title': 'Sri Lanka’s spicy secret',
701 'description': 'As a new train line to Jaffna opens up the country’s north, travellers can experience a truly distinct slice of Tamil culture.',
702 'timestamp': 1437674293,
703 'upload_date': '20150723',
707 'skip_download': True,
710 # single video story without digitalData
711 'url': 'http://www.bbc.com/autos/story/20130513-hyundais-rock-star',
715 'title': 'Hyundai Santa Fe Sport: Rock star',
716 'description': 'md5:b042a26142c4154a6e472933cf20793d',
717 'timestamp': 1415867444,
718 'upload_date': '20141113',
722 'skip_download': True,
725 # single video embedded with Morph
726 'url': 'http://www.bbc.co.uk/sport/live/olympics/36895975',
730 'title': "Nigeria v Japan - Men's First Round",
731 'description': 'Live coverage of the first round from Group B at the Amazonia Arena.',
733 'uploader': 'BBC Sport',
734 'uploader_id': 'bbc_sport',
738 'skip_download': True,
740 'skip': 'Georestricted to UK',
742 # single video with playlist.sxml URL in playlist param
743 'url': 'http://www.bbc.com/sport/0/football/33653409',
747 'title': 'Transfers: Cristiano Ronaldo to Man Utd, Arsenal to spend?',
748 'description': 'BBC Sport\'s David Ornstein has the latest transfer gossip, including rumours of a Manchester United return for Cristiano Ronaldo.',
753 'skip_download': True,
756 # article with multiple videos embedded with playlist.sxml in playlist param
757 'url': 'http://www.bbc.com/sport/0/football/34475836',
760 'title': 'Jurgen Klopp: Furious football from a witty and winning coach',
761 'description': 'Fast-paced football, wit, wisdom and a ready smile - why Liverpool fans should come to love new boss Jurgen Klopp.',
765 # school report article with single video
766 'url': 'http://www.bbc.co.uk/schoolreport/35744779',
769 'title': 'School which breaks down barriers in Jerusalem',
773 # single video with playlist URL from weather section
774 'url': 'http://www.bbc.com/weather/features/33601775',
775 'only_matching': True,
777 # custom redirection to www.bbc.com
778 'url': 'http://www.bbc.co.uk/news/science-environment-33661876',
779 'only_matching': True,
781 # single video article embedded with data-media-vpid
782 'url': 'http://www.bbc.co.uk/sport/rowing/35908187',
783 'only_matching': True,
785 'url': 'https://www.bbc.co.uk/bbcthree/clip/73d0bbd0-abc3-4cea-b3c0-cdae21905eb1',
789 'title': 'Transfers: Cristiano Ronaldo to Man Utd, Arsenal to spend?',
790 'description': 'md5:4b7dfd063d5a789a1512e99662be3ddd',
793 'skip_download': True,
796 # window.__PRELOADED_STATE__
797 'url': 'https://www.bbc.co.uk/radio/play/b0b9z4yl',
801 'title': 'Prom 6: An American in Paris and Turangalila',
802 'description': 'md5:51cf7d6f5c8553f197e58203bc78dff8',
803 'uploader': 'Radio 3',
804 'uploader_id': 'bbc_radio_three',
807 'url': 'http://www.bbc.co.uk/learningenglish/chinese/features/lingohack/ep-181227',
811 'title': 'md5:2fabf12a726603193a2879a055f72514',
812 'description': 'Learn English words and phrases from this story',
814 'add_ie': [BBCCoUkIE.ie_key()],
818 def suitable(cls, url):
819 EXCLUDE_IE = (BBCCoUkIE, BBCCoUkArticleIE, BBCCoUkIPlayerPlaylistIE, BBCCoUkPlaylistIE)
820 return (False if any(ie.suitable(url) for ie in EXCLUDE_IE)
821 else super(BBCIE, cls).suitable(url))
823 def _extract_from_media_meta(self, media_meta, video_id):
824 # Direct links to media in media metadata (e.g.
825 # http://www.bbc.com/turkce/haberler/2015/06/150615_telabyad_kentin_cogu)
826 # TODO: there are also f4m and m3u8 streams incorporated in playlist.sxml
827 source_files = media_meta.get('sourceFiles')
831 'format_id': format_id,
832 'ext': f.get('encoding'),
833 'tbr': float_or_none(f.get('bitrate'), 1000),
834 'filesize': int_or_none(f.get('filesize')),
835 } for format_id, f in source_files.items() if f.get('url')], []
837 programme_id = media_meta.get('externalId')
839 return self._download_media_selector(programme_id)
841 # Process playlist.sxml as legacy playlist
842 href = media_meta.get('href')
844 playlist = self._download_legacy_playlist_url(href)
845 _, _, _, _, formats, subtitles = self._extract_from_legacy_playlist(playlist, video_id)
846 return formats, subtitles
850 def _extract_from_playlist_sxml(self, url, playlist_id, timestamp):
851 programme_id, title, description, duration, formats, subtitles = \
852 self._process_legacy_playlist_url(url, playlist_id)
853 self._sort_formats(formats)
857 'description': description,
858 'duration': duration,
859 'timestamp': timestamp,
861 'subtitles': subtitles,
864 def _real_extract(self, url):
865 playlist_id = self._match_id(url)
867 webpage = self._download_webpage(url, playlist_id)
869 json_ld_info = self._search_json_ld(webpage, playlist_id, default={})
870 timestamp = json_ld_info.get('timestamp')
872 playlist_title = json_ld_info.get('title')
873 if not playlist_title:
874 playlist_title = self._og_search_title(
875 webpage, default=None) or self._html_search_regex(
876 r'<title>(.+?)</title>', webpage, 'playlist title', default=None)
878 playlist_title = re.sub(r'(.+)\s*-\s*BBC.*?$', r'\1', playlist_title).strip()
880 playlist_description = json_ld_info.get(
881 'description') or self._og_search_description(webpage, default=None)
884 timestamp = parse_iso8601(self._search_regex(
885 [r'<meta[^>]+property="article:published_time"[^>]+content="([^"]+)"',
886 r'itemprop="datePublished"[^>]+datetime="([^"]+)"',
887 r'"datePublished":\s*"([^"]+)'],
888 webpage, 'date', default=None))
892 # article with multiple videos embedded with playlist.sxml (e.g.
893 # http://www.bbc.com/sport/0/football/34475836)
894 playlists = re.findall(r'<param[^>]+name="playlist"[^>]+value="([^"]+)"', webpage)
895 playlists.extend(re.findall(r'data-media-id="([^"]+/playlist\.sxml)"', webpage))
898 self._extract_from_playlist_sxml(playlist_url, playlist_id, timestamp)
899 for playlist_url in playlists]
901 # news article with multiple videos embedded with data-playable
902 data_playables = re.findall(r'data-playable=(["\'])({.+?})\1', webpage)
904 for _, data_playable_json in data_playables:
905 data_playable = self._parse_json(
906 unescapeHTML(data_playable_json), playlist_id, fatal=False)
907 if not data_playable:
909 settings = data_playable.get('settings', {})
911 # data-playable with video vpid in settings.playlistObject.items (e.g.
912 # http://www.bbc.com/news/world-us-canada-34473351)
913 playlist_object = settings.get('playlistObject', {})
915 items = playlist_object.get('items')
916 if items and isinstance(items, list):
917 title = playlist_object['title']
918 description = playlist_object.get('summary')
919 duration = int_or_none(items[0].get('duration'))
920 programme_id = items[0].get('vpid')
921 formats, subtitles = self._download_media_selector(programme_id)
922 self._sort_formats(formats)
926 'description': description,
927 'timestamp': timestamp,
928 'duration': duration,
930 'subtitles': subtitles,
933 # data-playable without vpid but with a playlist.sxml URLs
934 # in otherSettings.playlist (e.g.
935 # http://www.bbc.com/turkce/multimedya/2015/10/151010_vid_ankara_patlama_ani)
936 playlist = data_playable.get('otherSettings', {}).get('playlist', {})
939 for key in ('streaming', 'progressiveDownload'):
940 playlist_url = playlist.get('%sUrl' % key)
944 info = self._extract_from_playlist_sxml(
945 playlist_url, playlist_id, timestamp)
949 entry['title'] = info['title']
950 entry['formats'].extend(info['formats'])
951 except Exception as e:
952 # Some playlist URL may fail with 500, at the same time
953 # the other one may work fine (e.g.
954 # http://www.bbc.com/turkce/haberler/2015/06/150615_telabyad_kentin_cogu)
955 if isinstance(e.cause, compat_HTTPError) and e.cause.code == 500:
959 self._sort_formats(entry['formats'])
960 entries.append(entry)
963 return self.playlist_result(entries, playlist_id, playlist_title, playlist_description)
965 # http://www.bbc.co.uk/learningenglish/chinese/features/lingohack/ep-181227
966 group_id = self._search_regex(
967 r'<div[^>]+\bclass=["\']video["\'][^>]+\bdata-pid=["\'](%s)' % self._ID_REGEX,
968 webpage, 'group id', default=None)
970 return self.url_result(
971 'https://www.bbc.co.uk/programmes/%s' % group_id,
972 ie=BBCCoUkIE.ie_key())
974 # single video story (e.g. http://www.bbc.com/travel/story/20150625-sri-lankas-spicy-secret)
975 programme_id = self._search_regex(
976 [r'data-(?:video-player|media)-vpid="(%s)"' % self._ID_REGEX,
977 r'<param[^>]+name="externalIdentifier"[^>]+value="(%s)"' % self._ID_REGEX,
978 r'videoId\s*:\s*["\'](%s)["\']' % self._ID_REGEX],
979 webpage, 'vpid', default=None)
982 formats, subtitles = self._download_media_selector(programme_id)
983 self._sort_formats(formats)
984 # digitalData may be missing (e.g. http://www.bbc.com/autos/story/20130513-hyundais-rock-star)
985 digital_data = self._parse_json(
987 r'var\s+digitalData\s*=\s*({.+?});?\n', webpage, 'digital data', default='{}'),
988 programme_id, fatal=False)
989 page_info = digital_data.get('page', {}).get('pageInfo', {})
990 title = page_info.get('pageName') or self._og_search_title(webpage)
991 description = page_info.get('description') or self._og_search_description(webpage)
992 timestamp = parse_iso8601(page_info.get('publicationDate')) or timestamp
996 'description': description,
997 'timestamp': timestamp,
999 'subtitles': subtitles,
1002 # Morph based embed (e.g. http://www.bbc.co.uk/sport/live/olympics/36895975)
1003 # There are several setPayload calls may be present but the video
1004 # seems to be always related to the first one
1005 morph_payload = self._parse_json(
1007 r'Morph\.setPayload\([^,]+,\s*({.+?})\);',
1008 webpage, 'morph payload', default='{}'),
1009 playlist_id, fatal=False)
1011 components = try_get(morph_payload, lambda x: x['body']['components'], list) or []
1012 for component in components:
1013 if not isinstance(component, dict):
1015 lead_media = try_get(component, lambda x: x['props']['leadMedia'], dict)
1018 identifiers = lead_media.get('identifiers')
1019 if not identifiers or not isinstance(identifiers, dict):
1021 programme_id = identifiers.get('vpid') or identifiers.get('playablePid')
1022 if not programme_id:
1024 title = lead_media.get('title') or self._og_search_title(webpage)
1025 formats, subtitles = self._download_media_selector(programme_id)
1026 self._sort_formats(formats)
1027 description = lead_media.get('summary')
1028 uploader = lead_media.get('masterBrand')
1029 uploader_id = lead_media.get('mid')
1031 duration_d = lead_media.get('duration')
1032 if isinstance(duration_d, dict):
1033 duration = parse_duration(dict_get(
1034 duration_d, ('rawDuration', 'formattedDuration', 'spokenDuration')))
1038 'description': description,
1039 'duration': duration,
1040 'uploader': uploader,
1041 'uploader_id': uploader_id,
1043 'subtitles': subtitles,
1046 preload_state = self._parse_json(self._search_regex(
1047 r'window\.__PRELOADED_STATE__\s*=\s*({.+?});', webpage,
1048 'preload state', default='{}'), playlist_id, fatal=False)
1050 current_programme = preload_state.get('programmes', {}).get('current') or {}
1051 programme_id = current_programme.get('id')
1052 if current_programme and programme_id and current_programme.get('type') == 'playable_item':
1053 title = current_programme.get('titles', {}).get('tertiary') or playlist_title
1054 formats, subtitles = self._download_media_selector(programme_id)
1055 self._sort_formats(formats)
1056 synopses = current_programme.get('synopses') or {}
1057 network = current_programme.get('network') or {}
1058 duration = int_or_none(
1059 current_programme.get('duration', {}).get('value'))
1061 image_url = current_programme.get('image_url')
1063 thumbnail = image_url.replace('{recipe}', '1920x1920')
1067 'description': dict_get(synopses, ('long', 'medium', 'short')),
1068 'thumbnail': thumbnail,
1069 'duration': duration,
1070 'uploader': network.get('short_title'),
1071 'uploader_id': network.get('id'),
1073 'subtitles': subtitles,
1076 bbc3_config = self._parse_json(
1078 r'(?s)bbcthreeConfig\s*=\s*({.+?})\s*;\s*<', webpage,
1079 'bbcthree config', default='{}'),
1080 playlist_id, transform_source=js_to_json, fatal=False)
1082 bbc3_playlist = try_get(
1083 bbc3_config, lambda x: x['payload']['content']['bbcMedia']['playlist'],
1086 playlist_title = bbc3_playlist.get('title') or playlist_title
1087 thumbnail = bbc3_playlist.get('holdingImageURL')
1089 for bbc3_item in bbc3_playlist['items']:
1090 programme_id = bbc3_item.get('versionID')
1091 if not programme_id:
1093 formats, subtitles = self._download_media_selector(programme_id)
1094 self._sort_formats(formats)
1097 'title': playlist_title,
1098 'thumbnail': thumbnail,
1099 'timestamp': timestamp,
1101 'subtitles': subtitles,
1103 return self.playlist_result(
1104 entries, playlist_id, playlist_title, playlist_description)
1106 def extract_all(pattern):
1107 return list(filter(None, map(
1108 lambda s: self._parse_json(s, playlist_id, fatal=False),
1109 re.findall(pattern, webpage))))
1111 # Multiple video article (e.g.
1112 # http://www.bbc.co.uk/blogs/adamcurtis/entries/3662a707-0af9-3149-963f-47bea720b460)
1113 EMBED_URL = r'https?://(?:www\.)?bbc\.co\.uk/(?:[^/]+/)+%s(?:\b[^"]+)?' % self._ID_REGEX
1115 for match in extract_all(r'new\s+SMP\(({.+?})\)'):
1116 embed_url = match.get('playerSettings', {}).get('externalEmbedUrl')
1117 if embed_url and re.match(EMBED_URL, embed_url):
1118 entries.append(embed_url)
1119 entries.extend(re.findall(
1120 r'setPlaylist\("(%s)"\)' % EMBED_URL, webpage))
1122 return self.playlist_result(
1123 [self.url_result(entry_, 'BBCCoUk') for entry_ in entries],
1124 playlist_id, playlist_title, playlist_description)
1126 # Multiple video article (e.g. http://www.bbc.com/news/world-europe-32668511)
1127 medias = extract_all(r"data-media-meta='({[^']+})'")
1130 # Single video article (e.g. http://www.bbc.com/news/video_and_audio/international)
1131 media_asset = self._search_regex(
1132 r'mediaAssetPage\.init\(\s*({.+?}), "/',
1133 webpage, 'media asset', default=None)
1135 media_asset_page = self._parse_json(media_asset, playlist_id, fatal=False)
1137 for video in media_asset_page.get('videos', {}).values():
1138 medias.extend(video.values())
1141 # Multiple video playlist with single `now playing` entry (e.g.
1142 # http://www.bbc.com/news/video_and_audio/must_see/33767813)
1143 vxp_playlist = self._parse_json(
1145 r'<script[^>]+class="vxp-playlist-data"[^>]+type="application/json"[^>]*>([^<]+)</script>',
1146 webpage, 'playlist data'),
1148 playlist_medias = []
1149 for item in vxp_playlist:
1150 media = item.get('media')
1153 playlist_medias.append(media)
1154 # Download single video if found media with asset id matching the video id from URL
1155 if item.get('advert', {}).get('assetId') == playlist_id:
1158 # Fallback to the whole playlist
1160 medias = playlist_medias
1163 for num, media_meta in enumerate(medias, start=1):
1164 formats, subtitles = self._extract_from_media_meta(media_meta, playlist_id)
1167 self._sort_formats(formats)
1169 video_id = media_meta.get('externalId')
1171 video_id = playlist_id if len(medias) == 1 else '%s-%s' % (playlist_id, num)
1173 title = media_meta.get('caption')
1175 title = playlist_title if len(medias) == 1 else '%s - Video %s' % (playlist_title, num)
1177 duration = int_or_none(media_meta.get('durationInSeconds')) or parse_duration(media_meta.get('duration'))
1180 for image in media_meta.get('images', {}).values():
1181 images.extend(image.values())
1182 if 'image' in media_meta:
1183 images.append(media_meta['image'])
1186 'url': image.get('href'),
1187 'width': int_or_none(image.get('width')),
1188 'height': int_or_none(image.get('height')),
1189 } for image in images]
1194 'thumbnails': thumbnails,
1195 'duration': duration,
1196 'timestamp': timestamp,
1198 'subtitles': subtitles,
1201 return self.playlist_result(entries, playlist_id, playlist_title, playlist_description)
1204 class BBCCoUkArticleIE(InfoExtractor):
1205 _VALID_URL = r'https?://(?:www\.)?bbc\.co\.uk/programmes/articles/(?P<id>[a-zA-Z0-9]+)'
1206 IE_NAME = 'bbc.co.uk:article'
1207 IE_DESC = 'BBC articles'
1210 'url': 'http://www.bbc.co.uk/programmes/articles/3jNQLTMrPlYGTBn0WV6M2MS/not-your-typical-role-model-ada-lovelace-the-19th-century-programmer',
1212 'id': '3jNQLTMrPlYGTBn0WV6M2MS',
1213 'title': 'Calculating Ada: The Countess of Computing - Not your typical role model: Ada Lovelace the 19th century programmer - BBC Four',
1214 'description': 'Hannah Fry reveals some of her surprising discoveries about Ada Lovelace during filming.',
1216 'playlist_count': 4,
1217 'add_ie': ['BBCCoUk'],
1220 def _real_extract(self, url):
1221 playlist_id = self._match_id(url)
1223 webpage = self._download_webpage(url, playlist_id)
1225 title = self._og_search_title(webpage)
1226 description = self._og_search_description(webpage).strip()
1228 entries = [self.url_result(programme_url) for programme_url in re.findall(
1229 r'<div[^>]+typeof="Clip"[^>]+resource="([^"]+)"', webpage)]
1231 return self.playlist_result(entries, playlist_id, title, description)
1234 class BBCCoUkPlaylistBaseIE(InfoExtractor):
1235 def _entries(self, webpage, url, playlist_id):
1236 single_page = 'page' in compat_urlparse.parse_qs(
1237 compat_urlparse.urlparse(url).query)
1238 for page_num in itertools.count(2):
1239 for video_id in re.findall(
1240 self._VIDEO_ID_TEMPLATE % BBCCoUkIE._ID_REGEX, webpage):
1241 yield self.url_result(
1242 self._URL_TEMPLATE % video_id, BBCCoUkIE.ie_key())
1245 next_page = self._search_regex(
1246 r'<li[^>]+class=(["\'])pagination_+next\1[^>]*><a[^>]+href=(["\'])(?P<url>(?:(?!\2).)+)\2',
1247 webpage, 'next page url', default=None, group='url')
1250 webpage = self._download_webpage(
1251 compat_urlparse.urljoin(url, next_page), playlist_id,
1252 'Downloading page %d' % page_num, page_num)
1254 def _real_extract(self, url):
1255 playlist_id = self._match_id(url)
1257 webpage = self._download_webpage(url, playlist_id)
1259 title, description = self._extract_title_and_description(webpage)
1261 return self.playlist_result(
1262 self._entries(webpage, url, playlist_id),
1263 playlist_id, title, description)
1266 class BBCCoUkIPlayerPlaylistIE(BBCCoUkPlaylistBaseIE):
1267 IE_NAME = 'bbc.co.uk:iplayer:playlist'
1268 _VALID_URL = r'https?://(?:www\.)?bbc\.co\.uk/iplayer/(?:episodes|group)/(?P<id>%s)' % BBCCoUkIE._ID_REGEX
1269 _URL_TEMPLATE = 'http://www.bbc.co.uk/iplayer/episode/%s'
1270 _VIDEO_ID_TEMPLATE = r'data-ip-id=["\'](%s)'
1272 'url': 'http://www.bbc.co.uk/iplayer/episodes/b05rcz9v',
1275 'title': 'The Disappearance',
1276 'description': 'French thriller serial about a missing teenager.',
1278 'playlist_mincount': 6,
1279 'skip': 'This programme is not currently available on BBC iPlayer',
1281 # Available for over a year unlike 30 days for most other programmes
1282 'url': 'http://www.bbc.co.uk/iplayer/group/p02tcc32',
1285 'title': 'Bohemian Icons',
1286 'description': 'md5:683e901041b2fe9ba596f2ab04c4dbe7',
1288 'playlist_mincount': 10,
1291 def _extract_title_and_description(self, webpage):
1292 title = self._search_regex(r'<h1>([^<]+)</h1>', webpage, 'title', fatal=False)
1293 description = self._search_regex(
1294 r'<p[^>]+class=(["\'])subtitle\1[^>]*>(?P<value>[^<]+)</p>',
1295 webpage, 'description', fatal=False, group='value')
1296 return title, description
1299 class BBCCoUkPlaylistIE(BBCCoUkPlaylistBaseIE):
1300 IE_NAME = 'bbc.co.uk:playlist'
1301 _VALID_URL = r'https?://(?:www\.)?bbc\.co\.uk/programmes/(?P<id>%s)/(?:episodes|broadcasts|clips)' % BBCCoUkIE._ID_REGEX
1302 _URL_TEMPLATE = 'http://www.bbc.co.uk/programmes/%s'
1303 _VIDEO_ID_TEMPLATE = r'data-pid=["\'](%s)'
1305 'url': 'http://www.bbc.co.uk/programmes/b05rcz9v/clips',
1308 'title': 'The Disappearance - Clips - BBC Four',
1309 'description': 'French thriller serial about a missing teenager.',
1311 'playlist_mincount': 7,
1313 # multipage playlist, explicit page
1314 'url': 'http://www.bbc.co.uk/programmes/b00mfl7n/clips?page=1',
1317 'title': 'Frozen Planet - Clips - BBC One',
1318 'description': 'md5:65dcbf591ae628dafe32aa6c4a4a0d8c',
1320 'playlist_mincount': 24,
1322 # multipage playlist, all pages
1323 'url': 'http://www.bbc.co.uk/programmes/b00mfl7n/clips',
1326 'title': 'Frozen Planet - Clips - BBC One',
1327 'description': 'md5:65dcbf591ae628dafe32aa6c4a4a0d8c',
1329 'playlist_mincount': 142,
1331 'url': 'http://www.bbc.co.uk/programmes/b05rcz9v/broadcasts/2016/06',
1332 'only_matching': True,
1334 'url': 'http://www.bbc.co.uk/programmes/b05rcz9v/clips',
1335 'only_matching': True,
1337 'url': 'http://www.bbc.co.uk/programmes/b055jkys/episodes/player',
1338 'only_matching': True,
1341 def _extract_title_and_description(self, webpage):
1342 title = self._og_search_title(webpage, fatal=False)
1343 description = self._og_search_description(webpage)
1344 return title, description