2 from __future__ import unicode_literals
7 from .common import InfoExtractor
22 from ..compat import (
23 compat_etree_fromstring,
29 class BBCCoUkIE(InfoExtractor):
31 IE_DESC = 'BBC iPlayer'
32 _ID_REGEX = r'[pb][\da-z]{7}'
35 (?:www\.)?bbc\.co\.uk/
37 programmes/(?!articles/)|
38 iplayer(?:/[^/]+)?/(?:episode/|playlist/)|
39 music/(?:clips|audiovideo/popular)[/#]|
42 (?P<id>%s)(?!/(?:episodes|broadcasts|clips))
45 _LOGIN_URL = 'https://account.bbc.com/signin'
46 _NETRC_MACHINE = 'bbc'
48 _MEDIASELECTOR_URLS = [
49 # Provides HQ HLS streams with even better quality that pc mediaset but fails
50 # with geolocation in some cases when it's even not geo restricted at all (e.g.
51 # http://www.bbc.co.uk/programmes/b06bp7lf). Also may fail with selectionunavailable.
52 'http://open.live.bbc.co.uk/mediaselector/5/select/version/2.0/mediaset/iptv-all/vpid/%s',
53 'http://open.live.bbc.co.uk/mediaselector/5/select/version/2.0/mediaset/pc/vpid/%s',
56 _MEDIASELECTION_NS = 'http://bbc.co.uk/2008/mp/mediaselection'
57 _EMP_PLAYLIST_NS = 'http://bbc.co.uk/2008/emp/playlist'
66 'url': 'http://www.bbc.co.uk/programmes/b039g8p7',
70 'title': 'Leonard Cohen, Kaleidoscope - BBC Radio 4',
71 'description': 'The Canadian poet and songwriter reflects on his musical career.',
75 'skip_download': True,
79 'url': 'http://www.bbc.co.uk/iplayer/episode/b00yng5w/The_Man_in_Black_Series_3_The_Printed_Name/',
83 'title': 'The Man in Black: Series 3: The Printed Name',
84 'description': "Mark Gatiss introduces Nicholas Pierpan's chilling tale of a writer's devilish pact with a mysterious man. Stars Ewan Bailey.",
89 'skip_download': True,
91 'skip': 'Episode is no longer available on BBC iPlayer Radio',
94 'url': 'http://www.bbc.co.uk/iplayer/episode/b03vhd1f/The_Voice_UK_Series_3_Blind_Auditions_5/',
98 'title': 'The Voice UK: Series 3: Blind Auditions 5',
99 '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.',
104 'skip_download': True,
106 'skip': 'Currently BBC iPlayer TV programmes are available to play in the UK only',
109 'url': 'http://www.bbc.co.uk/iplayer/episode/p026c7jt/tomorrows-worlds-the-unearthly-history-of-science-fiction-2-invasion',
113 'title': "Tomorrow's Worlds: The Unearthly History of Science Fiction",
114 'description': '2. Invasion',
119 'skip_download': True,
121 'skip': 'Currently BBC iPlayer TV programmes are available to play in the UK only',
123 'url': 'http://www.bbc.co.uk/programmes/b04v20dw',
127 'title': 'Pete Tong, The Essential New Tune Special',
128 'description': "Pete has a very special mix - all of 2014's Essential New Tunes!",
133 'skip_download': True,
135 'skip': 'Episode is no longer available on BBC iPlayer Radio',
137 'url': 'http://www.bbc.co.uk/music/clips/p022h44b',
142 'title': 'BBC Proms Music Guides, Rachmaninov: Symphonic Dances',
143 'description': "In this Proms Music Guide, Andrew McGregor looks at Rachmaninov's Symphonic Dances.",
148 'skip_download': True,
151 'url': 'http://www.bbc.co.uk/music/clips/p025c0zz',
156 'title': 'Reading and Leeds Festival, 2014, Rae Morris - Closer (Live on BBC Three)',
157 'description': 'Rae Morris performs Closer for BBC Three at Reading 2014',
162 'skip_download': True,
165 'url': 'http://www.bbc.co.uk/iplayer/episode/b054fn09/ad/natural-world-20152016-2-super-powered-owls',
169 'title': 'Natural World, 2015-2016: 2. Super Powered Owls',
170 'description': 'md5:e4db5c937d0e95a7c6b5e654d429183d',
175 'skip_download': True,
177 'skip': 'geolocation',
179 'url': 'http://www.bbc.co.uk/iplayer/episode/b05zmgwn/royal-academy-summer-exhibition',
183 '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.',
184 'title': 'Royal Academy Summer Exhibition',
189 'skip_download': True,
191 'skip': 'geolocation',
193 # iptv-all mediaset fails with geolocation however there is no geo restriction
194 # for this programme at all
195 'url': 'http://www.bbc.co.uk/programmes/b06rkn85',
199 'title': "Best of the Mini-Mixes 2015: Part 3, Annie Mac's Friday Night - BBC Radio 1",
200 'description': "Annie has part three in the Best of the Mini-Mixes 2015, plus the year's Most Played!",
204 'skip_download': True,
206 'skip': 'Now it\'s really geo-restricted',
208 # compact player (https://github.com/rg3/youtube-dl/issues/8147)
209 'url': 'http://www.bbc.co.uk/programmes/p028bfkf/player',
213 'title': 'Extract from BBC documentary Look Stranger - Giant Leeks and Magic Brews',
214 'description': 'Extract from BBC documentary Look Stranger - Giant Leeks and Magic Brews',
218 'skip_download': True,
221 'url': 'http://www.bbc.co.uk/iplayer/playlist/p01dvks4',
222 'only_matching': True,
224 'url': 'http://www.bbc.co.uk/music/clips#p02frcc3',
225 'only_matching': True,
227 'url': 'http://www.bbc.co.uk/iplayer/cbeebies/episode/b0480276/bing-14-atchoo',
228 'only_matching': True,
230 'url': 'http://www.bbc.co.uk/radio/player/p03cchwf',
231 'only_matching': True,
233 'url': 'https://www.bbc.co.uk/music/audiovideo/popular#p055bc55',
234 'only_matching': True,
237 _USP_RE = r'/([^/]+?)\.ism(?:\.hlsv2\.ism)?/[^/]+\.m3u8'
240 username, password = self._get_login_info()
244 login_page = self._download_webpage(
245 self._LOGIN_URL, None, 'Downloading signin page')
247 login_form = self._hidden_inputs(login_page)
250 'username': username,
251 'password': password,
254 post_url = urljoin(self._LOGIN_URL, self._search_regex(
255 r'<form[^>]+action=(["\'])(?P<url>.+?)\1', login_page,
256 'post url', default=self._LOGIN_URL, group='url'))
258 response, urlh = self._download_webpage_handle(
259 post_url, None, 'Logging in', data=urlencode_postdata(login_form),
260 headers={'Referer': self._LOGIN_URL})
262 if self._LOGIN_URL in urlh.geturl():
263 error = clean_html(get_element_by_class('form-message', response))
265 raise ExtractorError(
266 'Unable to login: %s' % error, expected=True)
267 raise ExtractorError('Unable to log in')
269 def _real_initialize(self):
272 class MediaSelectionError(Exception):
273 def __init__(self, id):
276 def _extract_asx_playlist(self, connection, programme_id):
277 asx = self._download_xml(connection.get('href'), programme_id, 'Downloading ASX playlist')
278 return [ref.get('href') for ref in asx.findall('./Entry/ref')]
280 def _extract_items(self, playlist):
281 return playlist.findall('./{%s}item' % self._EMP_PLAYLIST_NS)
283 def _findall_ns(self, element, xpath):
285 for ns in self._NAMESPACES:
286 elements.extend(element.findall(xpath % ns))
289 def _extract_medias(self, media_selection):
290 error = media_selection.find('./{%s}error' % self._MEDIASELECTION_NS)
292 media_selection.find('./{%s}error' % self._EMP_PLAYLIST_NS)
293 if error is not None:
294 raise BBCCoUkIE.MediaSelectionError(error.get('id'))
295 return self._findall_ns(media_selection, './{%s}media')
297 def _extract_connections(self, media):
298 return self._findall_ns(media, './{%s}connection')
300 def _get_subtitles(self, media, programme_id):
302 for connection in self._extract_connections(media):
303 captions = self._download_xml(connection.get('href'), programme_id, 'Downloading captions')
304 lang = captions.get('{http://www.w3.org/XML/1998/namespace}lang', 'en')
307 'url': connection.get('href'),
313 def _raise_extractor_error(self, media_selection_error):
314 raise ExtractorError(
315 '%s returned error: %s' % (self.IE_NAME, media_selection_error.id),
318 def _download_media_selector(self, programme_id):
319 last_exception = None
320 for mediaselector_url in self._MEDIASELECTOR_URLS:
322 return self._download_media_selector_url(
323 mediaselector_url % programme_id, programme_id)
324 except BBCCoUkIE.MediaSelectionError as e:
325 if e.id in ('notukerror', 'geolocation', 'selectionunavailable'):
328 self._raise_extractor_error(e)
329 self._raise_extractor_error(last_exception)
331 def _download_media_selector_url(self, url, programme_id=None):
333 media_selection = self._download_xml(
334 url, programme_id, 'Downloading media selection XML')
335 except ExtractorError as ee:
336 if isinstance(ee.cause, compat_HTTPError) and ee.cause.code in (403, 404):
337 media_selection = compat_etree_fromstring(ee.cause.read().decode('utf-8'))
340 return self._process_media_selector(media_selection, programme_id)
342 def _process_media_selector(self, media_selection, programme_id):
347 for media in self._extract_medias(media_selection):
348 kind = media.get('kind')
349 if kind in ('video', 'audio'):
350 bitrate = int_or_none(media.get('bitrate'))
351 encoding = media.get('encoding')
352 service = media.get('service')
353 width = int_or_none(media.get('width'))
354 height = int_or_none(media.get('height'))
355 file_size = int_or_none(media.get('media_file_size'))
356 for connection in self._extract_connections(media):
357 href = connection.get('href')
362 conn_kind = connection.get('kind')
363 protocol = connection.get('protocol')
364 supplier = connection.get('supplier')
365 transfer_format = connection.get('transferFormat')
366 format_id = supplier or conn_kind or protocol
368 format_id = '%s_%s' % (service, format_id)
370 if supplier == 'asx':
371 for i, ref in enumerate(self._extract_asx_playlist(connection, programme_id)):
374 'format_id': 'ref%s_%s' % (i, format_id),
376 elif transfer_format == 'dash':
377 formats.extend(self._extract_mpd_formats(
378 href, programme_id, mpd_id=format_id, fatal=False))
379 elif transfer_format == 'hls':
380 formats.extend(self._extract_m3u8_formats(
381 href, programme_id, ext='mp4', entry_protocol='m3u8_native',
382 m3u8_id=format_id, fatal=False))
383 if re.search(self._USP_RE, href):
384 usp_formats = self._extract_m3u8_formats(
385 re.sub(self._USP_RE, r'/\1.ism/\1.m3u8', href),
386 programme_id, ext='mp4', entry_protocol='m3u8_native',
387 m3u8_id=format_id, fatal=False)
388 for f in usp_formats:
389 if f.get('height') and f['height'] > 720:
392 elif transfer_format == 'hds':
393 formats.extend(self._extract_f4m_formats(
394 href, programme_id, f4m_id=format_id, fatal=False))
396 if not service and not supplier and bitrate:
397 format_id += '-%d' % bitrate
399 'format_id': format_id,
400 'filesize': file_size,
415 if protocol in ('http', 'https'):
420 elif protocol == 'rtmp':
421 application = connection.get('application', 'ondemand')
422 auth_string = connection.get('authString')
423 identifier = connection.get('identifier')
424 server = connection.get('server')
426 'url': '%s://%s/%s?%s' % (protocol, server, application, auth_string),
427 'play_path': identifier,
428 'app': '%s?%s' % (application, auth_string),
429 'page_url': 'http://www.bbc.co.uk',
430 'player_url': 'http://www.bbc.co.uk/emp/releases/iplayer/revisions/617463_618125_4/617463_618125_4_emp.swf',
437 elif kind == 'captions':
438 subtitles = self.extract_subtitles(media, programme_id)
439 return formats, subtitles
441 def _download_playlist(self, playlist_id):
443 playlist = self._download_json(
444 'http://www.bbc.co.uk/programmes/%s/playlist.json' % playlist_id,
445 playlist_id, 'Downloading playlist JSON')
447 version = playlist.get('defaultAvailableVersion')
449 smp_config = version['smpConfig']
450 title = smp_config['title']
451 description = smp_config['summary']
452 for item in smp_config['items']:
454 if kind not in ('programme', 'radioProgramme'):
456 programme_id = item.get('vpid')
457 duration = int_or_none(item.get('duration'))
458 formats, subtitles = self._download_media_selector(programme_id)
459 return programme_id, title, description, duration, formats, subtitles
460 except ExtractorError as ee:
461 if not (isinstance(ee.cause, compat_HTTPError) and ee.cause.code == 404):
464 # fallback to legacy playlist
465 return self._process_legacy_playlist(playlist_id)
467 def _process_legacy_playlist_url(self, url, display_id):
468 playlist = self._download_legacy_playlist_url(url, display_id)
469 return self._extract_from_legacy_playlist(playlist, display_id)
471 def _process_legacy_playlist(self, playlist_id):
472 return self._process_legacy_playlist_url(
473 'http://www.bbc.co.uk/iplayer/playlist/%s' % playlist_id, playlist_id)
475 def _download_legacy_playlist_url(self, url, playlist_id=None):
476 return self._download_xml(
477 url, playlist_id, 'Downloading legacy playlist XML')
479 def _extract_from_legacy_playlist(self, playlist, playlist_id):
480 no_items = playlist.find('./{%s}noItems' % self._EMP_PLAYLIST_NS)
481 if no_items is not None:
482 reason = no_items.get('reason')
483 if reason == 'preAvailability':
484 msg = 'Episode %s is not yet available' % playlist_id
485 elif reason == 'postAvailability':
486 msg = 'Episode %s is no longer available' % playlist_id
487 elif reason == 'noMedia':
488 msg = 'Episode %s is not currently available' % playlist_id
490 msg = 'Episode %s is not available: %s' % (playlist_id, reason)
491 raise ExtractorError(msg, expected=True)
493 for item in self._extract_items(playlist):
494 kind = item.get('kind')
495 if kind not in ('programme', 'radioProgramme'):
497 title = playlist.find('./{%s}title' % self._EMP_PLAYLIST_NS).text
498 description_el = playlist.find('./{%s}summary' % self._EMP_PLAYLIST_NS)
499 description = description_el.text if description_el is not None else None
501 def get_programme_id(item):
502 def get_from_attributes(item):
503 for p in('identifier', 'group'):
505 if value and re.match(r'^[pb][\da-z]{7}$', value):
507 get_from_attributes(item)
508 mediator = item.find('./{%s}mediator' % self._EMP_PLAYLIST_NS)
509 if mediator is not None:
510 return get_from_attributes(mediator)
512 programme_id = get_programme_id(item)
513 duration = int_or_none(item.get('duration'))
516 formats, subtitles = self._download_media_selector(programme_id)
518 formats, subtitles = self._process_media_selector(item, playlist_id)
519 programme_id = playlist_id
521 return programme_id, title, description, duration, formats, subtitles
523 def _real_extract(self, url):
524 group_id = self._match_id(url)
526 webpage = self._download_webpage(url, group_id, 'Downloading video page')
528 error = self._search_regex(
529 r'<div\b[^>]+\bclass=["\']smp__message delta["\'][^>]*>([^<]+)<',
530 webpage, 'error', default=None)
532 raise ExtractorError(error, expected=True)
537 tviplayer = self._search_regex(
538 r'mediator\.bind\(({.+?})\s*,\s*document\.getElementById',
539 webpage, 'player', default=None)
542 player = self._parse_json(tviplayer, group_id).get('player', {})
543 duration = int_or_none(player.get('duration'))
544 programme_id = player.get('vpid')
547 programme_id = self._search_regex(
548 r'"vpid"\s*:\s*"(%s)"' % self._ID_REGEX, webpage, 'vpid', fatal=False, default=None)
551 formats, subtitles = self._download_media_selector(programme_id)
552 title = self._og_search_title(webpage, default=None) or self._html_search_regex(
553 (r'<h2[^>]+id="parent-title"[^>]*>(.+?)</h2>',
554 r'<div[^>]+class="info"[^>]*>\s*<h1>(.+?)</h1>'), webpage, 'title')
555 description = self._search_regex(
556 (r'<p class="[^"]*medium-description[^"]*">([^<]+)</p>',
557 r'<div[^>]+class="info_+synopsis"[^>]*>([^<]+)</div>'),
558 webpage, 'description', default=None)
560 description = self._html_search_meta('description', webpage)
562 programme_id, title, description, duration, formats, subtitles = self._download_playlist(group_id)
564 self._sort_formats(formats)
569 'description': description,
570 'thumbnail': self._og_search_thumbnail(webpage, default=None),
571 'duration': duration,
573 'subtitles': subtitles,
577 class BBCIE(BBCCoUkIE):
580 _VALID_URL = r'https?://(?:www\.)?bbc\.(?:com|co\.uk)/(?:[^/]+/)+(?P<id>[^/#?]+)'
582 _MEDIASELECTOR_URLS = [
583 # Provides HQ HLS streams but fails with geolocation in some cases when it's
584 # even not geo restricted at all
585 'http://open.live.bbc.co.uk/mediaselector/5/select/version/2.0/mediaset/iptv-all/vpid/%s',
586 # Provides more formats, namely direct mp4 links, but fails on some videos with
587 # notukerror for non UK (?) users (e.g.
588 # http://www.bbc.com/travel/story/20150625-sri-lankas-spicy-secret)
589 'http://open.live.bbc.co.uk/mediaselector/4/mtis/stream/%s',
590 # Provides fewer formats, but works everywhere for everybody (hopefully)
591 'http://open.live.bbc.co.uk/mediaselector/5/select/version/2.0/mediaset/journalism-pc/vpid/%s',
595 # article with multiple videos embedded with data-playable containing vpids
596 'url': 'http://www.bbc.com/news/world-europe-32668511',
598 'id': 'world-europe-32668511',
599 'title': 'Russia stages massive WW2 parade despite Western boycott',
600 'description': 'md5:00ff61976f6081841f759a08bf78cc9c',
604 # article with multiple videos embedded with data-playable (more videos)
605 'url': 'http://www.bbc.com/news/business-28299555',
607 'id': 'business-28299555',
608 'title': 'Farnborough Airshow: Video highlights',
609 'description': 'BBC reports and video highlights at the Farnborough Airshow.',
614 # article with multiple videos embedded with `new SMP()`
616 'url': 'http://www.bbc.co.uk/blogs/adamcurtis/entries/3662a707-0af9-3149-963f-47bea720b460',
618 'id': '3662a707-0af9-3149-963f-47bea720b460',
621 'playlist_count': 18,
623 # single video embedded with data-playable containing vpid
624 'url': 'http://www.bbc.com/news/world-europe-32041533',
628 'title': 'Aerial footage showed the site of the crash in the Alps - courtesy BFM TV',
629 'description': 'md5:2868290467291b37feda7863f7a83f54',
631 'timestamp': 1427219242,
632 'upload_date': '20150324',
636 'skip_download': True,
639 # article with single video embedded with data-playable containing XML playlist
640 # with direct video links as progressiveDownloadUrl (for now these are extracted)
641 # and playlist with f4m and m3u8 as streamingUrl
642 'url': 'http://www.bbc.com/turkce/haberler/2015/06/150615_telabyad_kentin_cogu',
644 'id': '150615_telabyad_kentin_cogu',
646 'title': "YPG: Tel Abyad'ın tamamı kontrolümüzde",
647 'description': 'md5:33a4805a855c9baf7115fcbde57e7025',
648 'timestamp': 1434397334,
649 'upload_date': '20150615',
652 'skip_download': True,
655 # single video embedded with data-playable containing XML playlists (regional section)
656 'url': 'http://www.bbc.com/mundo/video_fotos/2015/06/150619_video_honduras_militares_hospitales_corrupcion_aw',
658 'id': '150619_video_honduras_militares_hospitales_corrupcion_aw',
660 'title': 'Honduras militariza sus hospitales por nuevo escándalo de corrupción',
661 'description': 'md5:1525f17448c4ee262b64b8f0c9ce66c8',
662 'timestamp': 1434713142,
663 'upload_date': '20150619',
666 'skip_download': True,
669 # single video from video playlist embedded with vxp-playlist-data JSON
670 'url': 'http://www.bbc.com/news/video_and_audio/must_see/33376376',
674 'title': '''Judge Mindy Glazer: "I'm sorry to see you here... I always wondered what happened to you"''',
676 'description': '''Judge Mindy Glazer: "I'm sorry to see you here... I always wondered what happened to you"''',
679 'skip_download': True,
682 # single video story with digitalData
683 'url': 'http://www.bbc.com/travel/story/20150625-sri-lankas-spicy-secret',
687 'title': 'Sri Lanka’s spicy secret',
688 'description': 'As a new train line to Jaffna opens up the country’s north, travellers can experience a truly distinct slice of Tamil culture.',
689 'timestamp': 1437674293,
690 'upload_date': '20150723',
694 'skip_download': True,
697 # single video story without digitalData
698 'url': 'http://www.bbc.com/autos/story/20130513-hyundais-rock-star',
702 'title': 'Hyundai Santa Fe Sport: Rock star',
703 'description': 'md5:b042a26142c4154a6e472933cf20793d',
704 'timestamp': 1415867444,
705 'upload_date': '20141113',
709 'skip_download': True,
712 # single video embedded with Morph
713 'url': 'http://www.bbc.co.uk/sport/live/olympics/36895975',
717 'title': "Nigeria v Japan - Men's First Round",
718 'description': 'Live coverage of the first round from Group B at the Amazonia Arena.',
720 'uploader': 'BBC Sport',
721 'uploader_id': 'bbc_sport',
725 'skip_download': True,
727 'skip': 'Georestricted to UK',
729 # single video with playlist.sxml URL in playlist param
730 'url': 'http://www.bbc.com/sport/0/football/33653409',
734 'title': 'Transfers: Cristiano Ronaldo to Man Utd, Arsenal to spend?',
735 'description': 'BBC Sport\'s David Ornstein has the latest transfer gossip, including rumours of a Manchester United return for Cristiano Ronaldo.',
740 'skip_download': True,
743 # article with multiple videos embedded with playlist.sxml in playlist param
744 'url': 'http://www.bbc.com/sport/0/football/34475836',
747 'title': 'Jurgen Klopp: Furious football from a witty and winning coach',
748 'description': 'Fast-paced football, wit, wisdom and a ready smile - why Liverpool fans should come to love new boss Jurgen Klopp.',
752 # school report article with single video
753 'url': 'http://www.bbc.co.uk/schoolreport/35744779',
756 'title': 'School which breaks down barriers in Jerusalem',
760 # single video with playlist URL from weather section
761 'url': 'http://www.bbc.com/weather/features/33601775',
762 'only_matching': True,
764 # custom redirection to www.bbc.com
765 'url': 'http://www.bbc.co.uk/news/science-environment-33661876',
766 'only_matching': True,
768 # single video article embedded with data-media-vpid
769 'url': 'http://www.bbc.co.uk/sport/rowing/35908187',
770 'only_matching': True,
774 def suitable(cls, url):
775 EXCLUDE_IE = (BBCCoUkIE, BBCCoUkArticleIE, BBCCoUkIPlayerPlaylistIE, BBCCoUkPlaylistIE)
776 return (False if any(ie.suitable(url) for ie in EXCLUDE_IE)
777 else super(BBCIE, cls).suitable(url))
779 def _extract_from_media_meta(self, media_meta, video_id):
780 # Direct links to media in media metadata (e.g.
781 # http://www.bbc.com/turkce/haberler/2015/06/150615_telabyad_kentin_cogu)
782 # TODO: there are also f4m and m3u8 streams incorporated in playlist.sxml
783 source_files = media_meta.get('sourceFiles')
787 'format_id': format_id,
788 'ext': f.get('encoding'),
789 'tbr': float_or_none(f.get('bitrate'), 1000),
790 'filesize': int_or_none(f.get('filesize')),
791 } for format_id, f in source_files.items() if f.get('url')], []
793 programme_id = media_meta.get('externalId')
795 return self._download_media_selector(programme_id)
797 # Process playlist.sxml as legacy playlist
798 href = media_meta.get('href')
800 playlist = self._download_legacy_playlist_url(href)
801 _, _, _, _, formats, subtitles = self._extract_from_legacy_playlist(playlist, video_id)
802 return formats, subtitles
806 def _extract_from_playlist_sxml(self, url, playlist_id, timestamp):
807 programme_id, title, description, duration, formats, subtitles = \
808 self._process_legacy_playlist_url(url, playlist_id)
809 self._sort_formats(formats)
813 'description': description,
814 'duration': duration,
815 'timestamp': timestamp,
817 'subtitles': subtitles,
820 def _real_extract(self, url):
821 playlist_id = self._match_id(url)
823 webpage = self._download_webpage(url, playlist_id)
825 json_ld_info = self._search_json_ld(webpage, playlist_id, default={})
826 timestamp = json_ld_info.get('timestamp')
828 playlist_title = json_ld_info.get('title')
829 if not playlist_title:
830 playlist_title = self._og_search_title(
831 webpage, default=None) or self._html_search_regex(
832 r'<title>(.+?)</title>', webpage, 'playlist title', default=None)
834 playlist_title = re.sub(r'(.+)\s*-\s*BBC.*?$', r'\1', playlist_title).strip()
836 playlist_description = json_ld_info.get(
837 'description') or self._og_search_description(webpage, default=None)
840 timestamp = parse_iso8601(self._search_regex(
841 [r'<meta[^>]+property="article:published_time"[^>]+content="([^"]+)"',
842 r'itemprop="datePublished"[^>]+datetime="([^"]+)"',
843 r'"datePublished":\s*"([^"]+)'],
844 webpage, 'date', default=None))
848 # article with multiple videos embedded with playlist.sxml (e.g.
849 # http://www.bbc.com/sport/0/football/34475836)
850 playlists = re.findall(r'<param[^>]+name="playlist"[^>]+value="([^"]+)"', webpage)
851 playlists.extend(re.findall(r'data-media-id="([^"]+/playlist\.sxml)"', webpage))
854 self._extract_from_playlist_sxml(playlist_url, playlist_id, timestamp)
855 for playlist_url in playlists]
857 # news article with multiple videos embedded with data-playable
858 data_playables = re.findall(r'data-playable=(["\'])({.+?})\1', webpage)
860 for _, data_playable_json in data_playables:
861 data_playable = self._parse_json(
862 unescapeHTML(data_playable_json), playlist_id, fatal=False)
863 if not data_playable:
865 settings = data_playable.get('settings', {})
867 # data-playable with video vpid in settings.playlistObject.items (e.g.
868 # http://www.bbc.com/news/world-us-canada-34473351)
869 playlist_object = settings.get('playlistObject', {})
871 items = playlist_object.get('items')
872 if items and isinstance(items, list):
873 title = playlist_object['title']
874 description = playlist_object.get('summary')
875 duration = int_or_none(items[0].get('duration'))
876 programme_id = items[0].get('vpid')
877 formats, subtitles = self._download_media_selector(programme_id)
878 self._sort_formats(formats)
882 'description': description,
883 'timestamp': timestamp,
884 'duration': duration,
886 'subtitles': subtitles,
889 # data-playable without vpid but with a playlist.sxml URLs
890 # in otherSettings.playlist (e.g.
891 # http://www.bbc.com/turkce/multimedya/2015/10/151010_vid_ankara_patlama_ani)
892 playlist = data_playable.get('otherSettings', {}).get('playlist', {})
895 for key in ('streaming', 'progressiveDownload'):
896 playlist_url = playlist.get('%sUrl' % key)
900 info = self._extract_from_playlist_sxml(
901 playlist_url, playlist_id, timestamp)
905 entry['title'] = info['title']
906 entry['formats'].extend(info['formats'])
907 except Exception as e:
908 # Some playlist URL may fail with 500, at the same time
909 # the other one may work fine (e.g.
910 # http://www.bbc.com/turkce/haberler/2015/06/150615_telabyad_kentin_cogu)
911 if isinstance(e.cause, compat_HTTPError) and e.cause.code == 500:
915 self._sort_formats(entry['formats'])
916 entries.append(entry)
919 return self.playlist_result(entries, playlist_id, playlist_title, playlist_description)
921 # single video story (e.g. http://www.bbc.com/travel/story/20150625-sri-lankas-spicy-secret)
922 programme_id = self._search_regex(
923 [r'data-(?:video-player|media)-vpid="(%s)"' % self._ID_REGEX,
924 r'<param[^>]+name="externalIdentifier"[^>]+value="(%s)"' % self._ID_REGEX,
925 r'videoId\s*:\s*["\'](%s)["\']' % self._ID_REGEX],
926 webpage, 'vpid', default=None)
929 formats, subtitles = self._download_media_selector(programme_id)
930 self._sort_formats(formats)
931 # digitalData may be missing (e.g. http://www.bbc.com/autos/story/20130513-hyundais-rock-star)
932 digital_data = self._parse_json(
934 r'var\s+digitalData\s*=\s*({.+?});?\n', webpage, 'digital data', default='{}'),
935 programme_id, fatal=False)
936 page_info = digital_data.get('page', {}).get('pageInfo', {})
937 title = page_info.get('pageName') or self._og_search_title(webpage)
938 description = page_info.get('description') or self._og_search_description(webpage)
939 timestamp = parse_iso8601(page_info.get('publicationDate')) or timestamp
943 'description': description,
944 'timestamp': timestamp,
946 'subtitles': subtitles,
949 # Morph based embed (e.g. http://www.bbc.co.uk/sport/live/olympics/36895975)
950 # There are several setPayload calls may be present but the video
951 # seems to be always related to the first one
952 morph_payload = self._parse_json(
954 r'Morph\.setPayload\([^,]+,\s*({.+?})\);',
955 webpage, 'morph payload', default='{}'),
956 playlist_id, fatal=False)
958 components = try_get(morph_payload, lambda x: x['body']['components'], list) or []
959 for component in components:
960 if not isinstance(component, dict):
962 lead_media = try_get(component, lambda x: x['props']['leadMedia'], dict)
965 identifiers = lead_media.get('identifiers')
966 if not identifiers or not isinstance(identifiers, dict):
968 programme_id = identifiers.get('vpid') or identifiers.get('playablePid')
971 title = lead_media.get('title') or self._og_search_title(webpage)
972 formats, subtitles = self._download_media_selector(programme_id)
973 self._sort_formats(formats)
974 description = lead_media.get('summary')
975 uploader = lead_media.get('masterBrand')
976 uploader_id = lead_media.get('mid')
978 duration_d = lead_media.get('duration')
979 if isinstance(duration_d, dict):
980 duration = parse_duration(dict_get(
981 duration_d, ('rawDuration', 'formattedDuration', 'spokenDuration')))
985 'description': description,
986 'duration': duration,
987 'uploader': uploader,
988 'uploader_id': uploader_id,
990 'subtitles': subtitles,
993 def extract_all(pattern):
994 return list(filter(None, map(
995 lambda s: self._parse_json(s, playlist_id, fatal=False),
996 re.findall(pattern, webpage))))
998 # Multiple video article (e.g.
999 # http://www.bbc.co.uk/blogs/adamcurtis/entries/3662a707-0af9-3149-963f-47bea720b460)
1000 EMBED_URL = r'https?://(?:www\.)?bbc\.co\.uk/(?:[^/]+/)+%s(?:\b[^"]+)?' % self._ID_REGEX
1002 for match in extract_all(r'new\s+SMP\(({.+?})\)'):
1003 embed_url = match.get('playerSettings', {}).get('externalEmbedUrl')
1004 if embed_url and re.match(EMBED_URL, embed_url):
1005 entries.append(embed_url)
1006 entries.extend(re.findall(
1007 r'setPlaylist\("(%s)"\)' % EMBED_URL, webpage))
1009 return self.playlist_result(
1010 [self.url_result(entry_, 'BBCCoUk') for entry_ in entries],
1011 playlist_id, playlist_title, playlist_description)
1013 # Multiple video article (e.g. http://www.bbc.com/news/world-europe-32668511)
1014 medias = extract_all(r"data-media-meta='({[^']+})'")
1017 # Single video article (e.g. http://www.bbc.com/news/video_and_audio/international)
1018 media_asset = self._search_regex(
1019 r'mediaAssetPage\.init\(\s*({.+?}), "/',
1020 webpage, 'media asset', default=None)
1022 media_asset_page = self._parse_json(media_asset, playlist_id, fatal=False)
1024 for video in media_asset_page.get('videos', {}).values():
1025 medias.extend(video.values())
1028 # Multiple video playlist with single `now playing` entry (e.g.
1029 # http://www.bbc.com/news/video_and_audio/must_see/33767813)
1030 vxp_playlist = self._parse_json(
1032 r'<script[^>]+class="vxp-playlist-data"[^>]+type="application/json"[^>]*>([^<]+)</script>',
1033 webpage, 'playlist data'),
1035 playlist_medias = []
1036 for item in vxp_playlist:
1037 media = item.get('media')
1040 playlist_medias.append(media)
1041 # Download single video if found media with asset id matching the video id from URL
1042 if item.get('advert', {}).get('assetId') == playlist_id:
1045 # Fallback to the whole playlist
1047 medias = playlist_medias
1050 for num, media_meta in enumerate(medias, start=1):
1051 formats, subtitles = self._extract_from_media_meta(media_meta, playlist_id)
1054 self._sort_formats(formats)
1056 video_id = media_meta.get('externalId')
1058 video_id = playlist_id if len(medias) == 1 else '%s-%s' % (playlist_id, num)
1060 title = media_meta.get('caption')
1062 title = playlist_title if len(medias) == 1 else '%s - Video %s' % (playlist_title, num)
1064 duration = int_or_none(media_meta.get('durationInSeconds')) or parse_duration(media_meta.get('duration'))
1067 for image in media_meta.get('images', {}).values():
1068 images.extend(image.values())
1069 if 'image' in media_meta:
1070 images.append(media_meta['image'])
1073 'url': image.get('href'),
1074 'width': int_or_none(image.get('width')),
1075 'height': int_or_none(image.get('height')),
1076 } for image in images]
1081 'thumbnails': thumbnails,
1082 'duration': duration,
1083 'timestamp': timestamp,
1085 'subtitles': subtitles,
1088 return self.playlist_result(entries, playlist_id, playlist_title, playlist_description)
1091 class BBCCoUkArticleIE(InfoExtractor):
1092 _VALID_URL = r'https?://(?:www\.)?bbc\.co\.uk/programmes/articles/(?P<id>[a-zA-Z0-9]+)'
1093 IE_NAME = 'bbc.co.uk:article'
1094 IE_DESC = 'BBC articles'
1097 'url': 'http://www.bbc.co.uk/programmes/articles/3jNQLTMrPlYGTBn0WV6M2MS/not-your-typical-role-model-ada-lovelace-the-19th-century-programmer',
1099 'id': '3jNQLTMrPlYGTBn0WV6M2MS',
1100 'title': 'Calculating Ada: The Countess of Computing - Not your typical role model: Ada Lovelace the 19th century programmer - BBC Four',
1101 'description': 'Hannah Fry reveals some of her surprising discoveries about Ada Lovelace during filming.',
1103 'playlist_count': 4,
1104 'add_ie': ['BBCCoUk'],
1107 def _real_extract(self, url):
1108 playlist_id = self._match_id(url)
1110 webpage = self._download_webpage(url, playlist_id)
1112 title = self._og_search_title(webpage)
1113 description = self._og_search_description(webpage).strip()
1115 entries = [self.url_result(programme_url) for programme_url in re.findall(
1116 r'<div[^>]+typeof="Clip"[^>]+resource="([^"]+)"', webpage)]
1118 return self.playlist_result(entries, playlist_id, title, description)
1121 class BBCCoUkPlaylistBaseIE(InfoExtractor):
1122 def _entries(self, webpage, url, playlist_id):
1123 single_page = 'page' in compat_urlparse.parse_qs(
1124 compat_urlparse.urlparse(url).query)
1125 for page_num in itertools.count(2):
1126 for video_id in re.findall(
1127 self._VIDEO_ID_TEMPLATE % BBCCoUkIE._ID_REGEX, webpage):
1128 yield self.url_result(
1129 self._URL_TEMPLATE % video_id, BBCCoUkIE.ie_key())
1132 next_page = self._search_regex(
1133 r'<li[^>]+class=(["\'])pagination_+next\1[^>]*><a[^>]+href=(["\'])(?P<url>(?:(?!\2).)+)\2',
1134 webpage, 'next page url', default=None, group='url')
1137 webpage = self._download_webpage(
1138 compat_urlparse.urljoin(url, next_page), playlist_id,
1139 'Downloading page %d' % page_num, page_num)
1141 def _real_extract(self, url):
1142 playlist_id = self._match_id(url)
1144 webpage = self._download_webpage(url, playlist_id)
1146 title, description = self._extract_title_and_description(webpage)
1148 return self.playlist_result(
1149 self._entries(webpage, url, playlist_id),
1150 playlist_id, title, description)
1153 class BBCCoUkIPlayerPlaylistIE(BBCCoUkPlaylistBaseIE):
1154 IE_NAME = 'bbc.co.uk:iplayer:playlist'
1155 _VALID_URL = r'https?://(?:www\.)?bbc\.co\.uk/iplayer/(?:episodes|group)/(?P<id>%s)' % BBCCoUkIE._ID_REGEX
1156 _URL_TEMPLATE = 'http://www.bbc.co.uk/iplayer/episode/%s'
1157 _VIDEO_ID_TEMPLATE = r'data-ip-id=["\'](%s)'
1159 'url': 'http://www.bbc.co.uk/iplayer/episodes/b05rcz9v',
1162 'title': 'The Disappearance',
1163 'description': 'French thriller serial about a missing teenager.',
1165 'playlist_mincount': 6,
1166 'skip': 'This programme is not currently available on BBC iPlayer',
1168 # Available for over a year unlike 30 days for most other programmes
1169 'url': 'http://www.bbc.co.uk/iplayer/group/p02tcc32',
1172 'title': 'Bohemian Icons',
1173 'description': 'md5:683e901041b2fe9ba596f2ab04c4dbe7',
1175 'playlist_mincount': 10,
1178 def _extract_title_and_description(self, webpage):
1179 title = self._search_regex(r'<h1>([^<]+)</h1>', webpage, 'title', fatal=False)
1180 description = self._search_regex(
1181 r'<p[^>]+class=(["\'])subtitle\1[^>]*>(?P<value>[^<]+)</p>',
1182 webpage, 'description', fatal=False, group='value')
1183 return title, description
1186 class BBCCoUkPlaylistIE(BBCCoUkPlaylistBaseIE):
1187 IE_NAME = 'bbc.co.uk:playlist'
1188 _VALID_URL = r'https?://(?:www\.)?bbc\.co\.uk/programmes/(?P<id>%s)/(?:episodes|broadcasts|clips)' % BBCCoUkIE._ID_REGEX
1189 _URL_TEMPLATE = 'http://www.bbc.co.uk/programmes/%s'
1190 _VIDEO_ID_TEMPLATE = r'data-pid=["\'](%s)'
1192 'url': 'http://www.bbc.co.uk/programmes/b05rcz9v/clips',
1195 'title': 'The Disappearance - Clips - BBC Four',
1196 'description': 'French thriller serial about a missing teenager.',
1198 'playlist_mincount': 7,
1200 # multipage playlist, explicit page
1201 'url': 'http://www.bbc.co.uk/programmes/b00mfl7n/clips?page=1',
1204 'title': 'Frozen Planet - Clips - BBC One',
1205 'description': 'md5:65dcbf591ae628dafe32aa6c4a4a0d8c',
1207 'playlist_mincount': 24,
1209 # multipage playlist, all pages
1210 'url': 'http://www.bbc.co.uk/programmes/b00mfl7n/clips',
1213 'title': 'Frozen Planet - Clips - BBC One',
1214 'description': 'md5:65dcbf591ae628dafe32aa6c4a4a0d8c',
1216 'playlist_mincount': 142,
1218 'url': 'http://www.bbc.co.uk/programmes/b05rcz9v/broadcasts/2016/06',
1219 'only_matching': True,
1221 'url': 'http://www.bbc.co.uk/programmes/b05rcz9v/clips',
1222 'only_matching': True,
1224 'url': 'http://www.bbc.co.uk/programmes/b055jkys/episodes/player',
1225 'only_matching': True,
1228 def _extract_title_and_description(self, webpage):
1229 title = self._og_search_title(webpage, fatal=False)
1230 description = self._og_search_description(webpage)
1231 return title, description