2 from __future__ import unicode_literals
7 from .common import InfoExtractor
23 from ..compat import (
29 class BBCCoUkIE(InfoExtractor):
31 IE_DESC = 'BBC iPlayer'
32 _ID_REGEX = r'[pbw][\da-z]{7}'
35 (?:www\.)?bbc\.co\.uk/
37 programmes/(?!articles/)|
38 iplayer(?:/[^/]+)?/(?:episode/|playlist/)|
39 music/(?:clips|audiovideo/popular)[/#]|
41 events/[^/]+/play/[^/]+/
43 (?P<id>%s)(?!/(?:episodes|broadcasts|clips))
46 _LOGIN_URL = 'https://account.bbc.com/signin'
47 _NETRC_MACHINE = 'bbc'
49 _MEDIASELECTOR_URLS = [
50 # Provides HQ HLS streams with even better quality that pc mediaset but fails
51 # with geolocation in some cases when it's even not geo restricted at all (e.g.
52 # http://www.bbc.co.uk/programmes/b06bp7lf). Also may fail with selectionunavailable.
53 'http://open.live.bbc.co.uk/mediaselector/5/select/version/2.0/mediaset/iptv-all/vpid/%s',
54 'http://open.live.bbc.co.uk/mediaselector/5/select/version/2.0/mediaset/pc/vpid/%s',
57 _MEDIASELECTION_NS = 'http://bbc.co.uk/2008/mp/mediaselection'
58 _EMP_PLAYLIST_NS = 'http://bbc.co.uk/2008/emp/playlist'
67 'url': 'http://www.bbc.co.uk/programmes/b039g8p7',
71 'title': 'Leonard Cohen, Kaleidoscope - BBC Radio 4',
72 'description': 'The Canadian poet and songwriter reflects on his musical career.',
76 'skip_download': True,
80 'url': 'http://www.bbc.co.uk/iplayer/episode/b00yng5w/The_Man_in_Black_Series_3_The_Printed_Name/',
84 'title': 'The Man in Black: Series 3: The Printed Name',
85 'description': "Mark Gatiss introduces Nicholas Pierpan's chilling tale of a writer's devilish pact with a mysterious man. Stars Ewan Bailey.",
90 'skip_download': True,
92 'skip': 'Episode is no longer available on BBC iPlayer Radio',
95 'url': 'http://www.bbc.co.uk/iplayer/episode/b03vhd1f/The_Voice_UK_Series_3_Blind_Auditions_5/',
99 'title': 'The Voice UK: Series 3: Blind Auditions 5',
100 '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.',
105 'skip_download': True,
107 'skip': 'Currently BBC iPlayer TV programmes are available to play in the UK only',
110 'url': 'http://www.bbc.co.uk/iplayer/episode/p026c7jt/tomorrows-worlds-the-unearthly-history-of-science-fiction-2-invasion',
114 'title': "Tomorrow's Worlds: The Unearthly History of Science Fiction",
115 'description': '2. Invasion',
120 'skip_download': True,
122 'skip': 'Currently BBC iPlayer TV programmes are available to play in the UK only',
124 'url': 'http://www.bbc.co.uk/programmes/b04v20dw',
128 'title': 'Pete Tong, The Essential New Tune Special',
129 'description': "Pete has a very special mix - all of 2014's Essential New Tunes!",
134 'skip_download': True,
136 'skip': 'Episode is no longer available on BBC iPlayer Radio',
138 'url': 'http://www.bbc.co.uk/music/clips/p022h44b',
143 'title': 'BBC Proms Music Guides, Rachmaninov: Symphonic Dances',
144 'description': "In this Proms Music Guide, Andrew McGregor looks at Rachmaninov's Symphonic Dances.",
149 'skip_download': True,
152 'url': 'http://www.bbc.co.uk/music/clips/p025c0zz',
157 'title': 'Reading and Leeds Festival, 2014, Rae Morris - Closer (Live on BBC Three)',
158 'description': 'Rae Morris performs Closer for BBC Three at Reading 2014',
163 'skip_download': True,
166 'url': 'http://www.bbc.co.uk/iplayer/episode/b054fn09/ad/natural-world-20152016-2-super-powered-owls',
170 'title': 'Natural World, 2015-2016: 2. Super Powered Owls',
171 'description': 'md5:e4db5c937d0e95a7c6b5e654d429183d',
176 'skip_download': True,
178 'skip': 'geolocation',
180 'url': 'http://www.bbc.co.uk/iplayer/episode/b05zmgwn/royal-academy-summer-exhibition',
184 '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.',
185 'title': 'Royal Academy Summer Exhibition',
190 'skip_download': True,
192 'skip': 'geolocation',
194 # iptv-all mediaset fails with geolocation however there is no geo restriction
195 # for this programme at all
196 'url': 'http://www.bbc.co.uk/programmes/b06rkn85',
200 'title': "Best of the Mini-Mixes 2015: Part 3, Annie Mac's Friday Night - BBC Radio 1",
201 'description': "Annie has part three in the Best of the Mini-Mixes 2015, plus the year's Most Played!",
205 'skip_download': True,
207 'skip': 'Now it\'s really geo-restricted',
209 # compact player (https://github.com/rg3/youtube-dl/issues/8147)
210 'url': 'http://www.bbc.co.uk/programmes/p028bfkf/player',
214 'title': 'Extract from BBC documentary Look Stranger - Giant Leeks and Magic Brews',
215 'description': 'Extract from BBC documentary Look Stranger - Giant Leeks and Magic Brews',
219 'skip_download': True,
222 'url': 'http://www.bbc.co.uk/iplayer/playlist/p01dvks4',
223 'only_matching': True,
225 'url': 'http://www.bbc.co.uk/music/clips#p02frcc3',
226 'only_matching': True,
228 'url': 'http://www.bbc.co.uk/iplayer/cbeebies/episode/b0480276/bing-14-atchoo',
229 'only_matching': True,
231 'url': 'http://www.bbc.co.uk/radio/player/p03cchwf',
232 'only_matching': True,
234 'url': 'https://www.bbc.co.uk/music/audiovideo/popular#p055bc55',
235 'only_matching': True,
237 'url': 'http://www.bbc.co.uk/programmes/w3csv1y9',
238 'only_matching': True,
241 _USP_RE = r'/([^/]+?)\.ism(?:\.hlsv2\.ism)?/[^/]+\.m3u8'
244 username, password = self._get_login_info()
248 login_page = self._download_webpage(
249 self._LOGIN_URL, None, 'Downloading signin page')
251 login_form = self._hidden_inputs(login_page)
254 'username': username,
255 'password': password,
258 post_url = urljoin(self._LOGIN_URL, self._search_regex(
259 r'<form[^>]+action=(["\'])(?P<url>.+?)\1', login_page,
260 'post url', default=self._LOGIN_URL, group='url'))
262 response, urlh = self._download_webpage_handle(
263 post_url, None, 'Logging in', data=urlencode_postdata(login_form),
264 headers={'Referer': self._LOGIN_URL})
266 if self._LOGIN_URL in urlh.geturl():
267 error = clean_html(get_element_by_class('form-message', response))
269 raise ExtractorError(
270 'Unable to login: %s' % error, expected=True)
271 raise ExtractorError('Unable to log in')
273 def _real_initialize(self):
276 class MediaSelectionError(Exception):
277 def __init__(self, id):
280 def _extract_asx_playlist(self, connection, programme_id):
281 asx = self._download_xml(connection.get('href'), programme_id, 'Downloading ASX playlist')
282 return [ref.get('href') for ref in asx.findall('./Entry/ref')]
284 def _extract_items(self, playlist):
285 return playlist.findall('./{%s}item' % self._EMP_PLAYLIST_NS)
287 def _findall_ns(self, element, xpath):
289 for ns in self._NAMESPACES:
290 elements.extend(element.findall(xpath % ns))
293 def _extract_medias(self, media_selection):
294 error = media_selection.find('./{%s}error' % self._MEDIASELECTION_NS)
296 media_selection.find('./{%s}error' % self._EMP_PLAYLIST_NS)
297 if error is not None:
298 raise BBCCoUkIE.MediaSelectionError(error.get('id'))
299 return self._findall_ns(media_selection, './{%s}media')
301 def _extract_connections(self, media):
302 return self._findall_ns(media, './{%s}connection')
304 def _get_subtitles(self, media, programme_id):
306 for connection in self._extract_connections(media):
307 captions = self._download_xml(connection.get('href'), programme_id, 'Downloading captions')
308 lang = captions.get('{http://www.w3.org/XML/1998/namespace}lang', 'en')
311 'url': connection.get('href'),
317 def _raise_extractor_error(self, media_selection_error):
318 raise ExtractorError(
319 '%s returned error: %s' % (self.IE_NAME, media_selection_error.id),
322 def _download_media_selector(self, programme_id):
323 last_exception = None
324 for mediaselector_url in self._MEDIASELECTOR_URLS:
326 return self._download_media_selector_url(
327 mediaselector_url % programme_id, programme_id)
328 except BBCCoUkIE.MediaSelectionError as e:
329 if e.id in ('notukerror', 'geolocation', 'selectionunavailable'):
332 self._raise_extractor_error(e)
333 self._raise_extractor_error(last_exception)
335 def _download_media_selector_url(self, url, programme_id=None):
336 media_selection = self._download_xml(
337 url, programme_id, 'Downloading media selection XML',
338 expected_status=(403, 404))
339 return self._process_media_selector(media_selection, programme_id)
341 def _process_media_selector(self, media_selection, programme_id):
346 for media in self._extract_medias(media_selection):
347 kind = media.get('kind')
348 if kind in ('video', 'audio'):
349 bitrate = int_or_none(media.get('bitrate'))
350 encoding = media.get('encoding')
351 service = media.get('service')
352 width = int_or_none(media.get('width'))
353 height = int_or_none(media.get('height'))
354 file_size = int_or_none(media.get('media_file_size'))
355 for connection in self._extract_connections(media):
356 href = connection.get('href')
361 conn_kind = connection.get('kind')
362 protocol = connection.get('protocol')
363 supplier = connection.get('supplier')
364 transfer_format = connection.get('transferFormat')
365 format_id = supplier or conn_kind or protocol
367 format_id = '%s_%s' % (service, format_id)
369 if supplier == 'asx':
370 for i, ref in enumerate(self._extract_asx_playlist(connection, programme_id)):
373 'format_id': 'ref%s_%s' % (i, format_id),
375 elif transfer_format == 'dash':
376 formats.extend(self._extract_mpd_formats(
377 href, programme_id, mpd_id=format_id, fatal=False))
378 elif transfer_format == 'hls':
379 formats.extend(self._extract_m3u8_formats(
380 href, programme_id, ext='mp4', entry_protocol='m3u8_native',
381 m3u8_id=format_id, fatal=False))
382 if re.search(self._USP_RE, href):
383 usp_formats = self._extract_m3u8_formats(
384 re.sub(self._USP_RE, r'/\1.ism/\1.m3u8', href),
385 programme_id, ext='mp4', entry_protocol='m3u8_native',
386 m3u8_id=format_id, fatal=False)
387 for f in usp_formats:
388 if f.get('height') and f['height'] > 720:
391 elif transfer_format == 'hds':
392 formats.extend(self._extract_f4m_formats(
393 href, programme_id, f4m_id=format_id, fatal=False))
395 if not service and not supplier and bitrate:
396 format_id += '-%d' % bitrate
398 'format_id': format_id,
399 'filesize': file_size,
414 if protocol in ('http', 'https'):
419 elif protocol == 'rtmp':
420 application = connection.get('application', 'ondemand')
421 auth_string = connection.get('authString')
422 identifier = connection.get('identifier')
423 server = connection.get('server')
425 'url': '%s://%s/%s?%s' % (protocol, server, application, auth_string),
426 'play_path': identifier,
427 'app': '%s?%s' % (application, auth_string),
428 'page_url': 'http://www.bbc.co.uk',
429 'player_url': 'http://www.bbc.co.uk/emp/releases/iplayer/revisions/617463_618125_4/617463_618125_4_emp.swf',
436 elif kind == 'captions':
437 subtitles = self.extract_subtitles(media, programme_id)
438 return formats, subtitles
440 def _download_playlist(self, playlist_id):
442 playlist = self._download_json(
443 'http://www.bbc.co.uk/programmes/%s/playlist.json' % playlist_id,
444 playlist_id, 'Downloading playlist JSON')
446 version = playlist.get('defaultAvailableVersion')
448 smp_config = version['smpConfig']
449 title = smp_config['title']
450 description = smp_config['summary']
451 for item in smp_config['items']:
453 if kind not in ('programme', 'radioProgramme'):
455 programme_id = item.get('vpid')
456 duration = int_or_none(item.get('duration'))
457 formats, subtitles = self._download_media_selector(programme_id)
458 return programme_id, title, description, duration, formats, subtitles
459 except ExtractorError as ee:
460 if not (isinstance(ee.cause, compat_HTTPError) and ee.cause.code == 404):
463 # fallback to legacy playlist
464 return self._process_legacy_playlist(playlist_id)
466 def _process_legacy_playlist_url(self, url, display_id):
467 playlist = self._download_legacy_playlist_url(url, display_id)
468 return self._extract_from_legacy_playlist(playlist, display_id)
470 def _process_legacy_playlist(self, playlist_id):
471 return self._process_legacy_playlist_url(
472 'http://www.bbc.co.uk/iplayer/playlist/%s' % playlist_id, playlist_id)
474 def _download_legacy_playlist_url(self, url, playlist_id=None):
475 return self._download_xml(
476 url, playlist_id, 'Downloading legacy playlist XML')
478 def _extract_from_legacy_playlist(self, playlist, playlist_id):
479 no_items = playlist.find('./{%s}noItems' % self._EMP_PLAYLIST_NS)
480 if no_items is not None:
481 reason = no_items.get('reason')
482 if reason == 'preAvailability':
483 msg = 'Episode %s is not yet available' % playlist_id
484 elif reason == 'postAvailability':
485 msg = 'Episode %s is no longer available' % playlist_id
486 elif reason == 'noMedia':
487 msg = 'Episode %s is not currently available' % playlist_id
489 msg = 'Episode %s is not available: %s' % (playlist_id, reason)
490 raise ExtractorError(msg, expected=True)
492 for item in self._extract_items(playlist):
493 kind = item.get('kind')
494 if kind not in ('programme', 'radioProgramme'):
496 title = playlist.find('./{%s}title' % self._EMP_PLAYLIST_NS).text
497 description_el = playlist.find('./{%s}summary' % self._EMP_PLAYLIST_NS)
498 description = description_el.text if description_el is not None else None
500 def get_programme_id(item):
501 def get_from_attributes(item):
502 for p in('identifier', 'group'):
504 if value and re.match(r'^[pb][\da-z]{7}$', value):
506 get_from_attributes(item)
507 mediator = item.find('./{%s}mediator' % self._EMP_PLAYLIST_NS)
508 if mediator is not None:
509 return get_from_attributes(mediator)
511 programme_id = get_programme_id(item)
512 duration = int_or_none(item.get('duration'))
515 formats, subtitles = self._download_media_selector(programme_id)
517 formats, subtitles = self._process_media_selector(item, playlist_id)
518 programme_id = playlist_id
520 return programme_id, title, description, duration, formats, subtitles
522 def _real_extract(self, url):
523 group_id = self._match_id(url)
525 webpage = self._download_webpage(url, group_id, 'Downloading video page')
527 error = self._search_regex(
528 r'<div\b[^>]+\bclass=["\']smp__message delta["\'][^>]*>([^<]+)<',
529 webpage, 'error', default=None)
531 raise ExtractorError(error, expected=True)
536 tviplayer = self._search_regex(
537 r'mediator\.bind\(({.+?})\s*,\s*document\.getElementById',
538 webpage, 'player', default=None)
541 player = self._parse_json(tviplayer, group_id).get('player', {})
542 duration = int_or_none(player.get('duration'))
543 programme_id = player.get('vpid')
546 programme_id = self._search_regex(
547 r'"vpid"\s*:\s*"(%s)"' % self._ID_REGEX, webpage, 'vpid', fatal=False, default=None)
550 formats, subtitles = self._download_media_selector(programme_id)
551 title = self._og_search_title(webpage, default=None) or self._html_search_regex(
552 (r'<h2[^>]+id="parent-title"[^>]*>(.+?)</h2>',
553 r'<div[^>]+class="info"[^>]*>\s*<h1>(.+?)</h1>'), webpage, 'title')
554 description = self._search_regex(
555 (r'<p class="[^"]*medium-description[^"]*">([^<]+)</p>',
556 r'<div[^>]+class="info_+synopsis"[^>]*>([^<]+)</div>'),
557 webpage, 'description', default=None)
559 description = self._html_search_meta('description', webpage)
561 programme_id, title, description, duration, formats, subtitles = self._download_playlist(group_id)
563 self._sort_formats(formats)
568 'description': description,
569 'thumbnail': self._og_search_thumbnail(webpage, default=None),
570 'duration': duration,
572 'subtitles': subtitles,
576 class BBCIE(BBCCoUkIE):
579 _VALID_URL = r'https?://(?:www\.)?bbc\.(?:com|co\.uk)/(?:[^/]+/)+(?P<id>[^/#?]+)'
581 _MEDIASELECTOR_URLS = [
582 # Provides HQ HLS streams but fails with geolocation in some cases when it's
583 # even not geo restricted at all
584 'http://open.live.bbc.co.uk/mediaselector/5/select/version/2.0/mediaset/iptv-all/vpid/%s',
585 # Provides more formats, namely direct mp4 links, but fails on some videos with
586 # notukerror for non UK (?) users (e.g.
587 # http://www.bbc.com/travel/story/20150625-sri-lankas-spicy-secret)
588 'http://open.live.bbc.co.uk/mediaselector/4/mtis/stream/%s',
589 # Provides fewer formats, but works everywhere for everybody (hopefully)
590 'http://open.live.bbc.co.uk/mediaselector/5/select/version/2.0/mediaset/journalism-pc/vpid/%s',
594 # article with multiple videos embedded with data-playable containing vpids
595 'url': 'http://www.bbc.com/news/world-europe-32668511',
597 'id': 'world-europe-32668511',
598 'title': 'Russia stages massive WW2 parade despite Western boycott',
599 'description': 'md5:00ff61976f6081841f759a08bf78cc9c',
603 # article with multiple videos embedded with data-playable (more videos)
604 'url': 'http://www.bbc.com/news/business-28299555',
606 'id': 'business-28299555',
607 'title': 'Farnborough Airshow: Video highlights',
608 'description': 'BBC reports and video highlights at the Farnborough Airshow.',
613 # article with multiple videos embedded with `new SMP()`
615 'url': 'http://www.bbc.co.uk/blogs/adamcurtis/entries/3662a707-0af9-3149-963f-47bea720b460',
617 'id': '3662a707-0af9-3149-963f-47bea720b460',
620 'playlist_count': 18,
622 # single video embedded with data-playable containing vpid
623 'url': 'http://www.bbc.com/news/world-europe-32041533',
627 'title': 'Aerial footage showed the site of the crash in the Alps - courtesy BFM TV',
628 'description': 'md5:2868290467291b37feda7863f7a83f54',
630 'timestamp': 1427219242,
631 'upload_date': '20150324',
635 'skip_download': True,
638 # article with single video embedded with data-playable containing XML playlist
639 # with direct video links as progressiveDownloadUrl (for now these are extracted)
640 # and playlist with f4m and m3u8 as streamingUrl
641 'url': 'http://www.bbc.com/turkce/haberler/2015/06/150615_telabyad_kentin_cogu',
643 'id': '150615_telabyad_kentin_cogu',
645 'title': "YPG: Tel Abyad'ın tamamı kontrolümüzde",
646 'description': 'md5:33a4805a855c9baf7115fcbde57e7025',
647 'timestamp': 1434397334,
648 'upload_date': '20150615',
651 'skip_download': True,
654 # single video embedded with data-playable containing XML playlists (regional section)
655 'url': 'http://www.bbc.com/mundo/video_fotos/2015/06/150619_video_honduras_militares_hospitales_corrupcion_aw',
657 'id': '150619_video_honduras_militares_hospitales_corrupcion_aw',
659 'title': 'Honduras militariza sus hospitales por nuevo escándalo de corrupción',
660 'description': 'md5:1525f17448c4ee262b64b8f0c9ce66c8',
661 'timestamp': 1434713142,
662 'upload_date': '20150619',
665 'skip_download': True,
668 # single video from video playlist embedded with vxp-playlist-data JSON
669 'url': 'http://www.bbc.com/news/video_and_audio/must_see/33376376',
673 'title': '''Judge Mindy Glazer: "I'm sorry to see you here... I always wondered what happened to you"''',
675 'description': '''Judge Mindy Glazer: "I'm sorry to see you here... I always wondered what happened to you"''',
678 'skip_download': True,
681 # single video story with digitalData
682 'url': 'http://www.bbc.com/travel/story/20150625-sri-lankas-spicy-secret',
686 'title': 'Sri Lanka’s spicy secret',
687 'description': 'As a new train line to Jaffna opens up the country’s north, travellers can experience a truly distinct slice of Tamil culture.',
688 'timestamp': 1437674293,
689 'upload_date': '20150723',
693 'skip_download': True,
696 # single video story without digitalData
697 'url': 'http://www.bbc.com/autos/story/20130513-hyundais-rock-star',
701 'title': 'Hyundai Santa Fe Sport: Rock star',
702 'description': 'md5:b042a26142c4154a6e472933cf20793d',
703 'timestamp': 1415867444,
704 'upload_date': '20141113',
708 'skip_download': True,
711 # single video embedded with Morph
712 'url': 'http://www.bbc.co.uk/sport/live/olympics/36895975',
716 'title': "Nigeria v Japan - Men's First Round",
717 'description': 'Live coverage of the first round from Group B at the Amazonia Arena.',
719 'uploader': 'BBC Sport',
720 'uploader_id': 'bbc_sport',
724 'skip_download': True,
726 'skip': 'Georestricted to UK',
728 # single video with playlist.sxml URL in playlist param
729 'url': 'http://www.bbc.com/sport/0/football/33653409',
733 'title': 'Transfers: Cristiano Ronaldo to Man Utd, Arsenal to spend?',
734 'description': 'BBC Sport\'s David Ornstein has the latest transfer gossip, including rumours of a Manchester United return for Cristiano Ronaldo.',
739 'skip_download': True,
742 # article with multiple videos embedded with playlist.sxml in playlist param
743 'url': 'http://www.bbc.com/sport/0/football/34475836',
746 'title': 'Jurgen Klopp: Furious football from a witty and winning coach',
747 'description': 'Fast-paced football, wit, wisdom and a ready smile - why Liverpool fans should come to love new boss Jurgen Klopp.',
751 # school report article with single video
752 'url': 'http://www.bbc.co.uk/schoolreport/35744779',
755 'title': 'School which breaks down barriers in Jerusalem',
759 # single video with playlist URL from weather section
760 'url': 'http://www.bbc.com/weather/features/33601775',
761 'only_matching': True,
763 # custom redirection to www.bbc.com
764 'url': 'http://www.bbc.co.uk/news/science-environment-33661876',
765 'only_matching': True,
767 # single video article embedded with data-media-vpid
768 'url': 'http://www.bbc.co.uk/sport/rowing/35908187',
769 'only_matching': True,
771 'url': 'https://www.bbc.co.uk/bbcthree/clip/73d0bbd0-abc3-4cea-b3c0-cdae21905eb1',
775 'title': 'Transfers: Cristiano Ronaldo to Man Utd, Arsenal to spend?',
776 'description': 'md5:4b7dfd063d5a789a1512e99662be3ddd',
779 'skip_download': True,
782 # window.__PRELOADED_STATE__
783 'url': 'https://www.bbc.co.uk/radio/play/b0b9z4yl',
787 'title': 'Prom 6: An American in Paris and Turangalila',
788 'description': 'md5:51cf7d6f5c8553f197e58203bc78dff8',
789 'uploader': 'Radio 3',
790 'uploader_id': 'bbc_radio_three',
795 def suitable(cls, url):
796 EXCLUDE_IE = (BBCCoUkIE, BBCCoUkArticleIE, BBCCoUkIPlayerPlaylistIE, BBCCoUkPlaylistIE)
797 return (False if any(ie.suitable(url) for ie in EXCLUDE_IE)
798 else super(BBCIE, cls).suitable(url))
800 def _extract_from_media_meta(self, media_meta, video_id):
801 # Direct links to media in media metadata (e.g.
802 # http://www.bbc.com/turkce/haberler/2015/06/150615_telabyad_kentin_cogu)
803 # TODO: there are also f4m and m3u8 streams incorporated in playlist.sxml
804 source_files = media_meta.get('sourceFiles')
808 'format_id': format_id,
809 'ext': f.get('encoding'),
810 'tbr': float_or_none(f.get('bitrate'), 1000),
811 'filesize': int_or_none(f.get('filesize')),
812 } for format_id, f in source_files.items() if f.get('url')], []
814 programme_id = media_meta.get('externalId')
816 return self._download_media_selector(programme_id)
818 # Process playlist.sxml as legacy playlist
819 href = media_meta.get('href')
821 playlist = self._download_legacy_playlist_url(href)
822 _, _, _, _, formats, subtitles = self._extract_from_legacy_playlist(playlist, video_id)
823 return formats, subtitles
827 def _extract_from_playlist_sxml(self, url, playlist_id, timestamp):
828 programme_id, title, description, duration, formats, subtitles = \
829 self._process_legacy_playlist_url(url, playlist_id)
830 self._sort_formats(formats)
834 'description': description,
835 'duration': duration,
836 'timestamp': timestamp,
838 'subtitles': subtitles,
841 def _real_extract(self, url):
842 playlist_id = self._match_id(url)
844 webpage = self._download_webpage(url, playlist_id)
846 json_ld_info = self._search_json_ld(webpage, playlist_id, default={})
847 timestamp = json_ld_info.get('timestamp')
849 playlist_title = json_ld_info.get('title')
850 if not playlist_title:
851 playlist_title = self._og_search_title(
852 webpage, default=None) or self._html_search_regex(
853 r'<title>(.+?)</title>', webpage, 'playlist title', default=None)
855 playlist_title = re.sub(r'(.+)\s*-\s*BBC.*?$', r'\1', playlist_title).strip()
857 playlist_description = json_ld_info.get(
858 'description') or self._og_search_description(webpage, default=None)
861 timestamp = parse_iso8601(self._search_regex(
862 [r'<meta[^>]+property="article:published_time"[^>]+content="([^"]+)"',
863 r'itemprop="datePublished"[^>]+datetime="([^"]+)"',
864 r'"datePublished":\s*"([^"]+)'],
865 webpage, 'date', default=None))
869 # article with multiple videos embedded with playlist.sxml (e.g.
870 # http://www.bbc.com/sport/0/football/34475836)
871 playlists = re.findall(r'<param[^>]+name="playlist"[^>]+value="([^"]+)"', webpage)
872 playlists.extend(re.findall(r'data-media-id="([^"]+/playlist\.sxml)"', webpage))
875 self._extract_from_playlist_sxml(playlist_url, playlist_id, timestamp)
876 for playlist_url in playlists]
878 # news article with multiple videos embedded with data-playable
879 data_playables = re.findall(r'data-playable=(["\'])({.+?})\1', webpage)
881 for _, data_playable_json in data_playables:
882 data_playable = self._parse_json(
883 unescapeHTML(data_playable_json), playlist_id, fatal=False)
884 if not data_playable:
886 settings = data_playable.get('settings', {})
888 # data-playable with video vpid in settings.playlistObject.items (e.g.
889 # http://www.bbc.com/news/world-us-canada-34473351)
890 playlist_object = settings.get('playlistObject', {})
892 items = playlist_object.get('items')
893 if items and isinstance(items, list):
894 title = playlist_object['title']
895 description = playlist_object.get('summary')
896 duration = int_or_none(items[0].get('duration'))
897 programme_id = items[0].get('vpid')
898 formats, subtitles = self._download_media_selector(programme_id)
899 self._sort_formats(formats)
903 'description': description,
904 'timestamp': timestamp,
905 'duration': duration,
907 'subtitles': subtitles,
910 # data-playable without vpid but with a playlist.sxml URLs
911 # in otherSettings.playlist (e.g.
912 # http://www.bbc.com/turkce/multimedya/2015/10/151010_vid_ankara_patlama_ani)
913 playlist = data_playable.get('otherSettings', {}).get('playlist', {})
916 for key in ('streaming', 'progressiveDownload'):
917 playlist_url = playlist.get('%sUrl' % key)
921 info = self._extract_from_playlist_sxml(
922 playlist_url, playlist_id, timestamp)
926 entry['title'] = info['title']
927 entry['formats'].extend(info['formats'])
928 except Exception as e:
929 # Some playlist URL may fail with 500, at the same time
930 # the other one may work fine (e.g.
931 # http://www.bbc.com/turkce/haberler/2015/06/150615_telabyad_kentin_cogu)
932 if isinstance(e.cause, compat_HTTPError) and e.cause.code == 500:
936 self._sort_formats(entry['formats'])
937 entries.append(entry)
940 return self.playlist_result(entries, playlist_id, playlist_title, playlist_description)
942 # single video story (e.g. http://www.bbc.com/travel/story/20150625-sri-lankas-spicy-secret)
943 programme_id = self._search_regex(
944 [r'data-(?:video-player|media)-vpid="(%s)"' % self._ID_REGEX,
945 r'<param[^>]+name="externalIdentifier"[^>]+value="(%s)"' % self._ID_REGEX,
946 r'videoId\s*:\s*["\'](%s)["\']' % self._ID_REGEX],
947 webpage, 'vpid', default=None)
950 formats, subtitles = self._download_media_selector(programme_id)
951 self._sort_formats(formats)
952 # digitalData may be missing (e.g. http://www.bbc.com/autos/story/20130513-hyundais-rock-star)
953 digital_data = self._parse_json(
955 r'var\s+digitalData\s*=\s*({.+?});?\n', webpage, 'digital data', default='{}'),
956 programme_id, fatal=False)
957 page_info = digital_data.get('page', {}).get('pageInfo', {})
958 title = page_info.get('pageName') or self._og_search_title(webpage)
959 description = page_info.get('description') or self._og_search_description(webpage)
960 timestamp = parse_iso8601(page_info.get('publicationDate')) or timestamp
964 'description': description,
965 'timestamp': timestamp,
967 'subtitles': subtitles,
970 # Morph based embed (e.g. http://www.bbc.co.uk/sport/live/olympics/36895975)
971 # There are several setPayload calls may be present but the video
972 # seems to be always related to the first one
973 morph_payload = self._parse_json(
975 r'Morph\.setPayload\([^,]+,\s*({.+?})\);',
976 webpage, 'morph payload', default='{}'),
977 playlist_id, fatal=False)
979 components = try_get(morph_payload, lambda x: x['body']['components'], list) or []
980 for component in components:
981 if not isinstance(component, dict):
983 lead_media = try_get(component, lambda x: x['props']['leadMedia'], dict)
986 identifiers = lead_media.get('identifiers')
987 if not identifiers or not isinstance(identifiers, dict):
989 programme_id = identifiers.get('vpid') or identifiers.get('playablePid')
992 title = lead_media.get('title') or self._og_search_title(webpage)
993 formats, subtitles = self._download_media_selector(programme_id)
994 self._sort_formats(formats)
995 description = lead_media.get('summary')
996 uploader = lead_media.get('masterBrand')
997 uploader_id = lead_media.get('mid')
999 duration_d = lead_media.get('duration')
1000 if isinstance(duration_d, dict):
1001 duration = parse_duration(dict_get(
1002 duration_d, ('rawDuration', 'formattedDuration', 'spokenDuration')))
1006 'description': description,
1007 'duration': duration,
1008 'uploader': uploader,
1009 'uploader_id': uploader_id,
1011 'subtitles': subtitles,
1014 preload_state = self._parse_json(self._search_regex(
1015 r'window\.__PRELOADED_STATE__\s*=\s*({.+?});', webpage,
1016 'preload state', default='{}'), playlist_id, fatal=False)
1018 current_programme = preload_state.get('programmes', {}).get('current') or {}
1019 programme_id = current_programme.get('id')
1020 if current_programme and programme_id and current_programme.get('type') == 'playable_item':
1021 title = current_programme.get('titles', {}).get('tertiary') or playlist_title
1022 formats, subtitles = self._download_media_selector(programme_id)
1023 self._sort_formats(formats)
1024 synopses = current_programme.get('synopses') or {}
1025 network = current_programme.get('network') or {}
1026 duration = int_or_none(
1027 current_programme.get('duration', {}).get('value'))
1029 image_url = current_programme.get('image_url')
1031 thumbnail = image_url.replace('{recipe}', '1920x1920')
1035 'description': dict_get(synopses, ('long', 'medium', 'short')),
1036 'thumbnail': thumbnail,
1037 'duration': duration,
1038 'uploader': network.get('short_title'),
1039 'uploader_id': network.get('id'),
1041 'subtitles': subtitles,
1044 bbc3_config = self._parse_json(
1046 r'(?s)bbcthreeConfig\s*=\s*({.+?})\s*;\s*<', webpage,
1047 'bbcthree config', default='{}'),
1048 playlist_id, transform_source=js_to_json, fatal=False)
1050 bbc3_playlist = try_get(
1051 bbc3_config, lambda x: x['payload']['content']['bbcMedia']['playlist'],
1054 playlist_title = bbc3_playlist.get('title') or playlist_title
1055 thumbnail = bbc3_playlist.get('holdingImageURL')
1057 for bbc3_item in bbc3_playlist['items']:
1058 programme_id = bbc3_item.get('versionID')
1059 if not programme_id:
1061 formats, subtitles = self._download_media_selector(programme_id)
1062 self._sort_formats(formats)
1065 'title': playlist_title,
1066 'thumbnail': thumbnail,
1067 'timestamp': timestamp,
1069 'subtitles': subtitles,
1071 return self.playlist_result(
1072 entries, playlist_id, playlist_title, playlist_description)
1074 def extract_all(pattern):
1075 return list(filter(None, map(
1076 lambda s: self._parse_json(s, playlist_id, fatal=False),
1077 re.findall(pattern, webpage))))
1079 # Multiple video article (e.g.
1080 # http://www.bbc.co.uk/blogs/adamcurtis/entries/3662a707-0af9-3149-963f-47bea720b460)
1081 EMBED_URL = r'https?://(?:www\.)?bbc\.co\.uk/(?:[^/]+/)+%s(?:\b[^"]+)?' % self._ID_REGEX
1083 for match in extract_all(r'new\s+SMP\(({.+?})\)'):
1084 embed_url = match.get('playerSettings', {}).get('externalEmbedUrl')
1085 if embed_url and re.match(EMBED_URL, embed_url):
1086 entries.append(embed_url)
1087 entries.extend(re.findall(
1088 r'setPlaylist\("(%s)"\)' % EMBED_URL, webpage))
1090 return self.playlist_result(
1091 [self.url_result(entry_, 'BBCCoUk') for entry_ in entries],
1092 playlist_id, playlist_title, playlist_description)
1094 # Multiple video article (e.g. http://www.bbc.com/news/world-europe-32668511)
1095 medias = extract_all(r"data-media-meta='({[^']+})'")
1098 # Single video article (e.g. http://www.bbc.com/news/video_and_audio/international)
1099 media_asset = self._search_regex(
1100 r'mediaAssetPage\.init\(\s*({.+?}), "/',
1101 webpage, 'media asset', default=None)
1103 media_asset_page = self._parse_json(media_asset, playlist_id, fatal=False)
1105 for video in media_asset_page.get('videos', {}).values():
1106 medias.extend(video.values())
1109 # Multiple video playlist with single `now playing` entry (e.g.
1110 # http://www.bbc.com/news/video_and_audio/must_see/33767813)
1111 vxp_playlist = self._parse_json(
1113 r'<script[^>]+class="vxp-playlist-data"[^>]+type="application/json"[^>]*>([^<]+)</script>',
1114 webpage, 'playlist data'),
1116 playlist_medias = []
1117 for item in vxp_playlist:
1118 media = item.get('media')
1121 playlist_medias.append(media)
1122 # Download single video if found media with asset id matching the video id from URL
1123 if item.get('advert', {}).get('assetId') == playlist_id:
1126 # Fallback to the whole playlist
1128 medias = playlist_medias
1131 for num, media_meta in enumerate(medias, start=1):
1132 formats, subtitles = self._extract_from_media_meta(media_meta, playlist_id)
1135 self._sort_formats(formats)
1137 video_id = media_meta.get('externalId')
1139 video_id = playlist_id if len(medias) == 1 else '%s-%s' % (playlist_id, num)
1141 title = media_meta.get('caption')
1143 title = playlist_title if len(medias) == 1 else '%s - Video %s' % (playlist_title, num)
1145 duration = int_or_none(media_meta.get('durationInSeconds')) or parse_duration(media_meta.get('duration'))
1148 for image in media_meta.get('images', {}).values():
1149 images.extend(image.values())
1150 if 'image' in media_meta:
1151 images.append(media_meta['image'])
1154 'url': image.get('href'),
1155 'width': int_or_none(image.get('width')),
1156 'height': int_or_none(image.get('height')),
1157 } for image in images]
1162 'thumbnails': thumbnails,
1163 'duration': duration,
1164 'timestamp': timestamp,
1166 'subtitles': subtitles,
1169 return self.playlist_result(entries, playlist_id, playlist_title, playlist_description)
1172 class BBCCoUkArticleIE(InfoExtractor):
1173 _VALID_URL = r'https?://(?:www\.)?bbc\.co\.uk/programmes/articles/(?P<id>[a-zA-Z0-9]+)'
1174 IE_NAME = 'bbc.co.uk:article'
1175 IE_DESC = 'BBC articles'
1178 'url': 'http://www.bbc.co.uk/programmes/articles/3jNQLTMrPlYGTBn0WV6M2MS/not-your-typical-role-model-ada-lovelace-the-19th-century-programmer',
1180 'id': '3jNQLTMrPlYGTBn0WV6M2MS',
1181 'title': 'Calculating Ada: The Countess of Computing - Not your typical role model: Ada Lovelace the 19th century programmer - BBC Four',
1182 'description': 'Hannah Fry reveals some of her surprising discoveries about Ada Lovelace during filming.',
1184 'playlist_count': 4,
1185 'add_ie': ['BBCCoUk'],
1188 def _real_extract(self, url):
1189 playlist_id = self._match_id(url)
1191 webpage = self._download_webpage(url, playlist_id)
1193 title = self._og_search_title(webpage)
1194 description = self._og_search_description(webpage).strip()
1196 entries = [self.url_result(programme_url) for programme_url in re.findall(
1197 r'<div[^>]+typeof="Clip"[^>]+resource="([^"]+)"', webpage)]
1199 return self.playlist_result(entries, playlist_id, title, description)
1202 class BBCCoUkPlaylistBaseIE(InfoExtractor):
1203 def _entries(self, webpage, url, playlist_id):
1204 single_page = 'page' in compat_urlparse.parse_qs(
1205 compat_urlparse.urlparse(url).query)
1206 for page_num in itertools.count(2):
1207 for video_id in re.findall(
1208 self._VIDEO_ID_TEMPLATE % BBCCoUkIE._ID_REGEX, webpage):
1209 yield self.url_result(
1210 self._URL_TEMPLATE % video_id, BBCCoUkIE.ie_key())
1213 next_page = self._search_regex(
1214 r'<li[^>]+class=(["\'])pagination_+next\1[^>]*><a[^>]+href=(["\'])(?P<url>(?:(?!\2).)+)\2',
1215 webpage, 'next page url', default=None, group='url')
1218 webpage = self._download_webpage(
1219 compat_urlparse.urljoin(url, next_page), playlist_id,
1220 'Downloading page %d' % page_num, page_num)
1222 def _real_extract(self, url):
1223 playlist_id = self._match_id(url)
1225 webpage = self._download_webpage(url, playlist_id)
1227 title, description = self._extract_title_and_description(webpage)
1229 return self.playlist_result(
1230 self._entries(webpage, url, playlist_id),
1231 playlist_id, title, description)
1234 class BBCCoUkIPlayerPlaylistIE(BBCCoUkPlaylistBaseIE):
1235 IE_NAME = 'bbc.co.uk:iplayer:playlist'
1236 _VALID_URL = r'https?://(?:www\.)?bbc\.co\.uk/iplayer/(?:episodes|group)/(?P<id>%s)' % BBCCoUkIE._ID_REGEX
1237 _URL_TEMPLATE = 'http://www.bbc.co.uk/iplayer/episode/%s'
1238 _VIDEO_ID_TEMPLATE = r'data-ip-id=["\'](%s)'
1240 'url': 'http://www.bbc.co.uk/iplayer/episodes/b05rcz9v',
1243 'title': 'The Disappearance',
1244 'description': 'French thriller serial about a missing teenager.',
1246 'playlist_mincount': 6,
1247 'skip': 'This programme is not currently available on BBC iPlayer',
1249 # Available for over a year unlike 30 days for most other programmes
1250 'url': 'http://www.bbc.co.uk/iplayer/group/p02tcc32',
1253 'title': 'Bohemian Icons',
1254 'description': 'md5:683e901041b2fe9ba596f2ab04c4dbe7',
1256 'playlist_mincount': 10,
1259 def _extract_title_and_description(self, webpage):
1260 title = self._search_regex(r'<h1>([^<]+)</h1>', webpage, 'title', fatal=False)
1261 description = self._search_regex(
1262 r'<p[^>]+class=(["\'])subtitle\1[^>]*>(?P<value>[^<]+)</p>',
1263 webpage, 'description', fatal=False, group='value')
1264 return title, description
1267 class BBCCoUkPlaylistIE(BBCCoUkPlaylistBaseIE):
1268 IE_NAME = 'bbc.co.uk:playlist'
1269 _VALID_URL = r'https?://(?:www\.)?bbc\.co\.uk/programmes/(?P<id>%s)/(?:episodes|broadcasts|clips)' % BBCCoUkIE._ID_REGEX
1270 _URL_TEMPLATE = 'http://www.bbc.co.uk/programmes/%s'
1271 _VIDEO_ID_TEMPLATE = r'data-pid=["\'](%s)'
1273 'url': 'http://www.bbc.co.uk/programmes/b05rcz9v/clips',
1276 'title': 'The Disappearance - Clips - BBC Four',
1277 'description': 'French thriller serial about a missing teenager.',
1279 'playlist_mincount': 7,
1281 # multipage playlist, explicit page
1282 'url': 'http://www.bbc.co.uk/programmes/b00mfl7n/clips?page=1',
1285 'title': 'Frozen Planet - Clips - BBC One',
1286 'description': 'md5:65dcbf591ae628dafe32aa6c4a4a0d8c',
1288 'playlist_mincount': 24,
1290 # multipage playlist, all pages
1291 'url': 'http://www.bbc.co.uk/programmes/b00mfl7n/clips',
1294 'title': 'Frozen Planet - Clips - BBC One',
1295 'description': 'md5:65dcbf591ae628dafe32aa6c4a4a0d8c',
1297 'playlist_mincount': 142,
1299 'url': 'http://www.bbc.co.uk/programmes/b05rcz9v/broadcasts/2016/06',
1300 'only_matching': True,
1302 'url': 'http://www.bbc.co.uk/programmes/b05rcz9v/clips',
1303 'only_matching': True,
1305 'url': 'http://www.bbc.co.uk/programmes/b055jkys/episodes/player',
1306 'only_matching': True,
1309 def _extract_title_and_description(self, webpage):
1310 title = self._og_search_title(webpage, fatal=False)
1311 description = self._og_search_description(webpage)
1312 return title, description