2 from __future__ import unicode_literals
6 from .common import InfoExtractor
17 from ..compat import (
18 compat_etree_fromstring,
23 class BBCCoUkIE(InfoExtractor):
25 IE_DESC = 'BBC iPlayer'
26 _ID_REGEX = r'[pb][\da-z]{7}'
29 (?:www\.)?bbc\.co\.uk/
31 programmes/(?!articles/)|
32 iplayer(?:/[^/]+)?/(?:episode/|playlist/)|
36 (?P<id>%s)(?!/(?:episodes|broadcasts|clips))
39 _MEDIASELECTOR_URLS = [
40 # Provides HQ HLS streams with even better quality that pc mediaset but fails
41 # with geolocation in some cases when it's even not geo restricted at all (e.g.
42 # http://www.bbc.co.uk/programmes/b06bp7lf). Also may fail with selectionunavailable.
43 'http://open.live.bbc.co.uk/mediaselector/5/select/version/2.0/mediaset/iptv-all/vpid/%s',
44 'http://open.live.bbc.co.uk/mediaselector/5/select/version/2.0/mediaset/pc/vpid/%s',
47 _MEDIASELECTION_NS = 'http://bbc.co.uk/2008/mp/mediaselection'
48 _EMP_PLAYLIST_NS = 'http://bbc.co.uk/2008/emp/playlist'
57 'url': 'http://www.bbc.co.uk/programmes/b039g8p7',
61 'title': 'Leonard Cohen, Kaleidoscope - BBC Radio 4',
62 'description': 'The Canadian poet and songwriter reflects on his musical career.',
66 'skip_download': True,
70 'url': 'http://www.bbc.co.uk/iplayer/episode/b00yng5w/The_Man_in_Black_Series_3_The_Printed_Name/',
74 'title': 'The Man in Black: Series 3: The Printed Name',
75 'description': "Mark Gatiss introduces Nicholas Pierpan's chilling tale of a writer's devilish pact with a mysterious man. Stars Ewan Bailey.",
80 'skip_download': True,
82 'skip': 'Episode is no longer available on BBC iPlayer Radio',
85 'url': 'http://www.bbc.co.uk/iplayer/episode/b03vhd1f/The_Voice_UK_Series_3_Blind_Auditions_5/',
89 'title': 'The Voice UK: Series 3: Blind Auditions 5',
90 '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.',
95 'skip_download': True,
97 'skip': 'Currently BBC iPlayer TV programmes are available to play in the UK only',
100 'url': 'http://www.bbc.co.uk/iplayer/episode/p026c7jt/tomorrows-worlds-the-unearthly-history-of-science-fiction-2-invasion',
104 'title': "Tomorrow's Worlds: The Unearthly History of Science Fiction",
105 'description': '2. Invasion',
110 'skip_download': True,
112 'skip': 'Currently BBC iPlayer TV programmes are available to play in the UK only',
114 'url': 'http://www.bbc.co.uk/programmes/b04v20dw',
118 'title': 'Pete Tong, The Essential New Tune Special',
119 'description': "Pete has a very special mix - all of 2014's Essential New Tunes!",
124 'skip_download': True,
126 'skip': 'Episode is no longer available on BBC iPlayer Radio',
128 'url': 'http://www.bbc.co.uk/music/clips/p022h44b',
133 'title': 'BBC Proms Music Guides, Rachmaninov: Symphonic Dances',
134 'description': "In this Proms Music Guide, Andrew McGregor looks at Rachmaninov's Symphonic Dances.",
139 'skip_download': True,
142 'url': 'http://www.bbc.co.uk/music/clips/p025c0zz',
147 'title': 'Reading and Leeds Festival, 2014, Rae Morris - Closer (Live on BBC Three)',
148 'description': 'Rae Morris performs Closer for BBC Three at Reading 2014',
153 'skip_download': True,
156 'url': 'http://www.bbc.co.uk/iplayer/episode/b054fn09/ad/natural-world-20152016-2-super-powered-owls',
160 'title': 'Natural World, 2015-2016: 2. Super Powered Owls',
161 'description': 'md5:e4db5c937d0e95a7c6b5e654d429183d',
166 'skip_download': True,
168 'skip': 'geolocation',
170 'url': 'http://www.bbc.co.uk/iplayer/episode/b05zmgwn/royal-academy-summer-exhibition',
174 '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.',
175 'title': 'Royal Academy Summer Exhibition',
180 'skip_download': True,
182 'skip': 'geolocation',
184 # iptv-all mediaset fails with geolocation however there is no geo restriction
185 # for this programme at all
186 'url': 'http://www.bbc.co.uk/programmes/b06rkn85',
190 'title': "Best of the Mini-Mixes 2015: Part 3, Annie Mac's Friday Night - BBC Radio 1",
191 'description': "Annie has part three in the Best of the Mini-Mixes 2015, plus the year's Most Played!",
195 'skip_download': True,
197 'skip': 'Now it\'s really geo-restricted',
199 # compact player (https://github.com/rg3/youtube-dl/issues/8147)
200 'url': 'http://www.bbc.co.uk/programmes/p028bfkf/player',
204 'title': 'Extract from BBC documentary Look Stranger - Giant Leeks and Magic Brews',
205 'description': 'Extract from BBC documentary Look Stranger - Giant Leeks and Magic Brews',
209 'skip_download': True,
212 'url': 'http://www.bbc.co.uk/iplayer/playlist/p01dvks4',
213 'only_matching': True,
215 'url': 'http://www.bbc.co.uk/music/clips#p02frcc3',
216 'only_matching': True,
218 'url': 'http://www.bbc.co.uk/iplayer/cbeebies/episode/b0480276/bing-14-atchoo',
219 'only_matching': True,
221 'url': 'http://www.bbc.co.uk/radio/player/p03cchwf',
222 'only_matching': True,
226 class MediaSelectionError(Exception):
227 def __init__(self, id):
230 def _extract_asx_playlist(self, connection, programme_id):
231 asx = self._download_xml(connection.get('href'), programme_id, 'Downloading ASX playlist')
232 return [ref.get('href') for ref in asx.findall('./Entry/ref')]
234 def _extract_items(self, playlist):
235 return playlist.findall('./{%s}item' % self._EMP_PLAYLIST_NS)
237 def _findall_ns(self, element, xpath):
239 for ns in self._NAMESPACES:
240 elements.extend(element.findall(xpath % ns))
243 def _extract_medias(self, media_selection):
244 error = media_selection.find('./{%s}error' % self._MEDIASELECTION_NS)
246 media_selection.find('./{%s}error' % self._EMP_PLAYLIST_NS)
247 if error is not None:
248 raise BBCCoUkIE.MediaSelectionError(error.get('id'))
249 return self._findall_ns(media_selection, './{%s}media')
251 def _extract_connections(self, media):
252 return self._findall_ns(media, './{%s}connection')
254 def _get_subtitles(self, media, programme_id):
256 for connection in self._extract_connections(media):
257 captions = self._download_xml(connection.get('href'), programme_id, 'Downloading captions')
258 lang = captions.get('{http://www.w3.org/XML/1998/namespace}lang', 'en')
261 'url': connection.get('href'),
267 def _raise_extractor_error(self, media_selection_error):
268 raise ExtractorError(
269 '%s returned error: %s' % (self.IE_NAME, media_selection_error.id),
272 def _download_media_selector(self, programme_id):
273 last_exception = None
274 for mediaselector_url in self._MEDIASELECTOR_URLS:
276 return self._download_media_selector_url(
277 mediaselector_url % programme_id, programme_id)
278 except BBCCoUkIE.MediaSelectionError as e:
279 if e.id in ('notukerror', 'geolocation', 'selectionunavailable'):
282 self._raise_extractor_error(e)
283 self._raise_extractor_error(last_exception)
285 def _download_media_selector_url(self, url, programme_id=None):
287 media_selection = self._download_xml(
288 url, programme_id, 'Downloading media selection XML')
289 except ExtractorError as ee:
290 if isinstance(ee.cause, compat_HTTPError) and ee.cause.code in (403, 404):
291 media_selection = compat_etree_fromstring(ee.cause.read().decode('utf-8'))
294 return self._process_media_selector(media_selection, programme_id)
296 def _process_media_selector(self, media_selection, programme_id):
301 for media in self._extract_medias(media_selection):
302 kind = media.get('kind')
303 if kind in ('video', 'audio'):
304 bitrate = int_or_none(media.get('bitrate'))
305 encoding = media.get('encoding')
306 service = media.get('service')
307 width = int_or_none(media.get('width'))
308 height = int_or_none(media.get('height'))
309 file_size = int_or_none(media.get('media_file_size'))
310 for connection in self._extract_connections(media):
311 href = connection.get('href')
316 conn_kind = connection.get('kind')
317 protocol = connection.get('protocol')
318 supplier = connection.get('supplier')
319 transfer_format = connection.get('transferFormat')
320 format_id = supplier or conn_kind or protocol
322 format_id = '%s_%s' % (service, format_id)
324 if supplier == 'asx':
325 for i, ref in enumerate(self._extract_asx_playlist(connection, programme_id)):
328 'format_id': 'ref%s_%s' % (i, format_id),
330 elif transfer_format == 'dash':
331 formats.extend(self._extract_mpd_formats(
332 href, programme_id, mpd_id=format_id, fatal=False))
333 elif transfer_format == 'hls':
334 formats.extend(self._extract_m3u8_formats(
335 href, programme_id, ext='mp4', entry_protocol='m3u8_native',
336 m3u8_id=format_id, fatal=False))
337 elif transfer_format == 'hds':
338 formats.extend(self._extract_f4m_formats(
339 href, programme_id, f4m_id=format_id, fatal=False))
341 if not service and not supplier and bitrate:
342 format_id += '-%d' % bitrate
344 'format_id': format_id,
345 'filesize': file_size,
360 if protocol == 'http':
365 elif protocol == 'rtmp':
366 application = connection.get('application', 'ondemand')
367 auth_string = connection.get('authString')
368 identifier = connection.get('identifier')
369 server = connection.get('server')
371 'url': '%s://%s/%s?%s' % (protocol, server, application, auth_string),
372 'play_path': identifier,
373 'app': '%s?%s' % (application, auth_string),
374 'page_url': 'http://www.bbc.co.uk',
375 'player_url': 'http://www.bbc.co.uk/emp/releases/iplayer/revisions/617463_618125_4/617463_618125_4_emp.swf',
380 elif kind == 'captions':
381 subtitles = self.extract_subtitles(media, programme_id)
382 return formats, subtitles
384 def _download_playlist(self, playlist_id):
386 playlist = self._download_json(
387 'http://www.bbc.co.uk/programmes/%s/playlist.json' % playlist_id,
388 playlist_id, 'Downloading playlist JSON')
390 version = playlist.get('defaultAvailableVersion')
392 smp_config = version['smpConfig']
393 title = smp_config['title']
394 description = smp_config['summary']
395 for item in smp_config['items']:
397 if kind != 'programme' and kind != 'radioProgramme':
399 programme_id = item.get('vpid')
400 duration = int_or_none(item.get('duration'))
401 formats, subtitles = self._download_media_selector(programme_id)
402 return programme_id, title, description, duration, formats, subtitles
403 except ExtractorError as ee:
404 if not (isinstance(ee.cause, compat_HTTPError) and ee.cause.code == 404):
407 # fallback to legacy playlist
408 return self._process_legacy_playlist(playlist_id)
410 def _process_legacy_playlist_url(self, url, display_id):
411 playlist = self._download_legacy_playlist_url(url, display_id)
412 return self._extract_from_legacy_playlist(playlist, display_id)
414 def _process_legacy_playlist(self, playlist_id):
415 return self._process_legacy_playlist_url(
416 'http://www.bbc.co.uk/iplayer/playlist/%s' % playlist_id, playlist_id)
418 def _download_legacy_playlist_url(self, url, playlist_id=None):
419 return self._download_xml(
420 url, playlist_id, 'Downloading legacy playlist XML')
422 def _extract_from_legacy_playlist(self, playlist, playlist_id):
423 no_items = playlist.find('./{%s}noItems' % self._EMP_PLAYLIST_NS)
424 if no_items is not None:
425 reason = no_items.get('reason')
426 if reason == 'preAvailability':
427 msg = 'Episode %s is not yet available' % playlist_id
428 elif reason == 'postAvailability':
429 msg = 'Episode %s is no longer available' % playlist_id
430 elif reason == 'noMedia':
431 msg = 'Episode %s is not currently available' % playlist_id
433 msg = 'Episode %s is not available: %s' % (playlist_id, reason)
434 raise ExtractorError(msg, expected=True)
436 for item in self._extract_items(playlist):
437 kind = item.get('kind')
438 if kind != 'programme' and kind != 'radioProgramme':
440 title = playlist.find('./{%s}title' % self._EMP_PLAYLIST_NS).text
441 description_el = playlist.find('./{%s}summary' % self._EMP_PLAYLIST_NS)
442 description = description_el.text if description_el is not None else None
444 def get_programme_id(item):
445 def get_from_attributes(item):
446 for p in('identifier', 'group'):
448 if value and re.match(r'^[pb][\da-z]{7}$', value):
450 get_from_attributes(item)
451 mediator = item.find('./{%s}mediator' % self._EMP_PLAYLIST_NS)
452 if mediator is not None:
453 return get_from_attributes(mediator)
455 programme_id = get_programme_id(item)
456 duration = int_or_none(item.get('duration'))
459 formats, subtitles = self._download_media_selector(programme_id)
461 formats, subtitles = self._process_media_selector(item, playlist_id)
462 programme_id = playlist_id
464 return programme_id, title, description, duration, formats, subtitles
466 def _real_extract(self, url):
467 group_id = self._match_id(url)
469 webpage = self._download_webpage(url, group_id, 'Downloading video page')
474 tviplayer = self._search_regex(
475 r'mediator\.bind\(({.+?})\s*,\s*document\.getElementById',
476 webpage, 'player', default=None)
479 player = self._parse_json(tviplayer, group_id).get('player', {})
480 duration = int_or_none(player.get('duration'))
481 programme_id = player.get('vpid')
484 programme_id = self._search_regex(
485 r'"vpid"\s*:\s*"(%s)"' % self._ID_REGEX, webpage, 'vpid', fatal=False, default=None)
488 formats, subtitles = self._download_media_selector(programme_id)
489 title = self._og_search_title(webpage, default=None) or self._html_search_regex(
490 (r'<h2[^>]+id="parent-title"[^>]*>(.+?)</h2>',
491 r'<div[^>]+class="info"[^>]*>\s*<h1>(.+?)</h1>'), webpage, 'title')
492 description = self._search_regex(
493 (r'<p class="[^"]*medium-description[^"]*">([^<]+)</p>',
494 r'<div[^>]+class="info_+synopsis"[^>]*>([^<]+)</div>'),
495 webpage, 'description', default=None)
497 description = self._html_search_meta('description', webpage)
499 programme_id, title, description, duration, formats, subtitles = self._download_playlist(group_id)
501 self._sort_formats(formats)
506 'description': description,
507 'thumbnail': self._og_search_thumbnail(webpage, default=None),
508 'duration': duration,
510 'subtitles': subtitles,
514 class BBCIE(BBCCoUkIE):
517 _VALID_URL = r'https?://(?:www\.)?bbc\.(?:com|co\.uk)/(?:[^/]+/)+(?P<id>[^/#?]+)'
519 _MEDIASELECTOR_URLS = [
520 # Provides HQ HLS streams but fails with geolocation in some cases when it's
521 # even not geo restricted at all
522 'http://open.live.bbc.co.uk/mediaselector/5/select/version/2.0/mediaset/iptv-all/vpid/%s',
523 # Provides more formats, namely direct mp4 links, but fails on some videos with
524 # notukerror for non UK (?) users (e.g.
525 # http://www.bbc.com/travel/story/20150625-sri-lankas-spicy-secret)
526 'http://open.live.bbc.co.uk/mediaselector/4/mtis/stream/%s',
527 # Provides fewer formats, but works everywhere for everybody (hopefully)
528 'http://open.live.bbc.co.uk/mediaselector/5/select/version/2.0/mediaset/journalism-pc/vpid/%s',
532 # article with multiple videos embedded with data-playable containing vpids
533 'url': 'http://www.bbc.com/news/world-europe-32668511',
535 'id': 'world-europe-32668511',
536 'title': 'Russia stages massive WW2 parade despite Western boycott',
537 'description': 'md5:00ff61976f6081841f759a08bf78cc9c',
541 # article with multiple videos embedded with data-playable (more videos)
542 'url': 'http://www.bbc.com/news/business-28299555',
544 'id': 'business-28299555',
545 'title': 'Farnborough Airshow: Video highlights',
546 'description': 'BBC reports and video highlights at the Farnborough Airshow.',
551 # article with multiple videos embedded with `new SMP()`
553 'url': 'http://www.bbc.co.uk/blogs/adamcurtis/entries/3662a707-0af9-3149-963f-47bea720b460',
555 'id': '3662a707-0af9-3149-963f-47bea720b460',
558 'playlist_count': 18,
560 # single video embedded with data-playable containing vpid
561 'url': 'http://www.bbc.com/news/world-europe-32041533',
565 'title': 'Aerial footage showed the site of the crash in the Alps - courtesy BFM TV',
566 'description': 'md5:2868290467291b37feda7863f7a83f54',
568 'timestamp': 1427219242,
569 'upload_date': '20150324',
573 'skip_download': True,
576 # article with single video embedded with data-playable containing XML playlist
577 # with direct video links as progressiveDownloadUrl (for now these are extracted)
578 # and playlist with f4m and m3u8 as streamingUrl
579 'url': 'http://www.bbc.com/turkce/haberler/2015/06/150615_telabyad_kentin_cogu',
581 'id': '150615_telabyad_kentin_cogu',
583 'title': "YPG: Tel Abyad'ın tamamı kontrolümüzde",
584 'description': 'md5:33a4805a855c9baf7115fcbde57e7025',
585 'timestamp': 1434397334,
586 'upload_date': '20150615',
589 'skip_download': True,
592 # single video embedded with data-playable containing XML playlists (regional section)
593 'url': 'http://www.bbc.com/mundo/video_fotos/2015/06/150619_video_honduras_militares_hospitales_corrupcion_aw',
595 'id': '150619_video_honduras_militares_hospitales_corrupcion_aw',
597 'title': 'Honduras militariza sus hospitales por nuevo escándalo de corrupción',
598 'description': 'md5:1525f17448c4ee262b64b8f0c9ce66c8',
599 'timestamp': 1434713142,
600 'upload_date': '20150619',
603 'skip_download': True,
606 # single video from video playlist embedded with vxp-playlist-data JSON
607 'url': 'http://www.bbc.com/news/video_and_audio/must_see/33376376',
611 'title': '''Judge Mindy Glazer: "I'm sorry to see you here... I always wondered what happened to you"''',
613 'description': '''Judge Mindy Glazer: "I'm sorry to see you here... I always wondered what happened to you"''',
616 'skip_download': True,
619 # single video story with digitalData
620 'url': 'http://www.bbc.com/travel/story/20150625-sri-lankas-spicy-secret',
624 'title': 'Sri Lanka’s spicy secret',
625 'description': 'As a new train line to Jaffna opens up the country’s north, travellers can experience a truly distinct slice of Tamil culture.',
626 'timestamp': 1437674293,
627 'upload_date': '20150723',
631 'skip_download': True,
634 # single video story without digitalData
635 'url': 'http://www.bbc.com/autos/story/20130513-hyundais-rock-star',
639 'title': 'Hyundai Santa Fe Sport: Rock star',
640 'description': 'md5:b042a26142c4154a6e472933cf20793d',
641 'timestamp': 1415867444,
642 'upload_date': '20141113',
646 'skip_download': True,
649 # single video embedded with Morph
650 'url': 'http://www.bbc.co.uk/sport/live/olympics/36895975',
654 'title': "Nigeria v Japan - Men's First Round",
655 'description': 'Live coverage of the first round from Group B at the Amazonia Arena.',
657 'uploader': 'BBC Sport',
658 'uploader_id': 'bbc_sport',
662 'skip_download': True,
663 'proxy': '5.101.173.158:8080',
665 'skip': 'Georestricted to UK',
667 # single video with playlist.sxml URL in playlist param
668 'url': 'http://www.bbc.com/sport/0/football/33653409',
672 'title': 'Transfers: Cristiano Ronaldo to Man Utd, Arsenal to spend?',
673 'description': 'BBC Sport\'s David Ornstein has the latest transfer gossip, including rumours of a Manchester United return for Cristiano Ronaldo.',
678 'skip_download': True,
681 # article with multiple videos embedded with playlist.sxml in playlist param
682 'url': 'http://www.bbc.com/sport/0/football/34475836',
685 'title': 'Jurgen Klopp: Furious football from a witty and winning coach',
686 'description': 'Fast-paced football, wit, wisdom and a ready smile - why Liverpool fans should come to love new boss Jurgen Klopp.',
690 # school report article with single video
691 'url': 'http://www.bbc.co.uk/schoolreport/35744779',
694 'title': 'School which breaks down barriers in Jerusalem',
698 # single video with playlist URL from weather section
699 'url': 'http://www.bbc.com/weather/features/33601775',
700 'only_matching': True,
702 # custom redirection to www.bbc.com
703 'url': 'http://www.bbc.co.uk/news/science-environment-33661876',
704 'only_matching': True,
706 # single video article embedded with data-media-vpid
707 'url': 'http://www.bbc.co.uk/sport/rowing/35908187',
708 'only_matching': True,
712 def suitable(cls, url):
713 EXCLUDE_IE = (BBCCoUkIE, BBCCoUkArticleIE, BBCCoUkIPlayerPlaylistIE, BBCCoUkPlaylistIE)
714 return (False if any(ie.suitable(url) for ie in EXCLUDE_IE)
715 else super(BBCIE, cls).suitable(url))
717 def _extract_from_media_meta(self, media_meta, video_id):
718 # Direct links to media in media metadata (e.g.
719 # http://www.bbc.com/turkce/haberler/2015/06/150615_telabyad_kentin_cogu)
720 # TODO: there are also f4m and m3u8 streams incorporated in playlist.sxml
721 source_files = media_meta.get('sourceFiles')
725 'format_id': format_id,
726 'ext': f.get('encoding'),
727 'tbr': float_or_none(f.get('bitrate'), 1000),
728 'filesize': int_or_none(f.get('filesize')),
729 } for format_id, f in source_files.items() if f.get('url')], []
731 programme_id = media_meta.get('externalId')
733 return self._download_media_selector(programme_id)
735 # Process playlist.sxml as legacy playlist
736 href = media_meta.get('href')
738 playlist = self._download_legacy_playlist_url(href)
739 _, _, _, _, formats, subtitles = self._extract_from_legacy_playlist(playlist, video_id)
740 return formats, subtitles
744 def _extract_from_playlist_sxml(self, url, playlist_id, timestamp):
745 programme_id, title, description, duration, formats, subtitles = \
746 self._process_legacy_playlist_url(url, playlist_id)
747 self._sort_formats(formats)
751 'description': description,
752 'duration': duration,
753 'timestamp': timestamp,
755 'subtitles': subtitles,
758 def _real_extract(self, url):
759 playlist_id = self._match_id(url)
761 webpage = self._download_webpage(url, playlist_id)
763 json_ld_info = self._search_json_ld(webpage, playlist_id, default=None)
764 timestamp = json_ld_info.get('timestamp')
766 playlist_title = json_ld_info.get('title')
767 if not playlist_title:
768 playlist_title = self._og_search_title(
769 webpage, default=None) or self._html_search_regex(
770 r'<title>(.+?)</title>', webpage, 'playlist title', default=None)
772 playlist_title = re.sub(r'(.+)\s*-\s*BBC.*?$', r'\1', playlist_title).strip()
774 playlist_description = json_ld_info.get(
775 'description') or self._og_search_description(webpage, default=None)
778 timestamp = parse_iso8601(self._search_regex(
779 [r'<meta[^>]+property="article:published_time"[^>]+content="([^"]+)"',
780 r'itemprop="datePublished"[^>]+datetime="([^"]+)"',
781 r'"datePublished":\s*"([^"]+)'],
782 webpage, 'date', default=None))
786 # article with multiple videos embedded with playlist.sxml (e.g.
787 # http://www.bbc.com/sport/0/football/34475836)
788 playlists = re.findall(r'<param[^>]+name="playlist"[^>]+value="([^"]+)"', webpage)
789 playlists.extend(re.findall(r'data-media-id="([^"]+/playlist\.sxml)"', webpage))
792 self._extract_from_playlist_sxml(playlist_url, playlist_id, timestamp)
793 for playlist_url in playlists]
795 # news article with multiple videos embedded with data-playable
796 data_playables = re.findall(r'data-playable=(["\'])({.+?})\1', webpage)
798 for _, data_playable_json in data_playables:
799 data_playable = self._parse_json(
800 unescapeHTML(data_playable_json), playlist_id, fatal=False)
801 if not data_playable:
803 settings = data_playable.get('settings', {})
805 # data-playable with video vpid in settings.playlistObject.items (e.g.
806 # http://www.bbc.com/news/world-us-canada-34473351)
807 playlist_object = settings.get('playlistObject', {})
809 items = playlist_object.get('items')
810 if items and isinstance(items, list):
811 title = playlist_object['title']
812 description = playlist_object.get('summary')
813 duration = int_or_none(items[0].get('duration'))
814 programme_id = items[0].get('vpid')
815 formats, subtitles = self._download_media_selector(programme_id)
816 self._sort_formats(formats)
820 'description': description,
821 'timestamp': timestamp,
822 'duration': duration,
824 'subtitles': subtitles,
827 # data-playable without vpid but with a playlist.sxml URLs
828 # in otherSettings.playlist (e.g.
829 # http://www.bbc.com/turkce/multimedya/2015/10/151010_vid_ankara_patlama_ani)
830 playlist = data_playable.get('otherSettings', {}).get('playlist', {})
833 for key in ('streaming', 'progressiveDownload'):
834 playlist_url = playlist.get('%sUrl' % key)
838 info = self._extract_from_playlist_sxml(
839 playlist_url, playlist_id, timestamp)
843 entry['title'] = info['title']
844 entry['formats'].extend(info['formats'])
845 except Exception as e:
846 # Some playlist URL may fail with 500, at the same time
847 # the other one may work fine (e.g.
848 # http://www.bbc.com/turkce/haberler/2015/06/150615_telabyad_kentin_cogu)
849 if isinstance(e.cause, compat_HTTPError) and e.cause.code == 500:
853 self._sort_formats(entry['formats'])
854 entries.append(entry)
857 return self.playlist_result(entries, playlist_id, playlist_title, playlist_description)
859 # single video story (e.g. http://www.bbc.com/travel/story/20150625-sri-lankas-spicy-secret)
860 programme_id = self._search_regex(
861 [r'data-(?:video-player|media)-vpid="(%s)"' % self._ID_REGEX,
862 r'<param[^>]+name="externalIdentifier"[^>]+value="(%s)"' % self._ID_REGEX,
863 r'videoId\s*:\s*["\'](%s)["\']' % self._ID_REGEX],
864 webpage, 'vpid', default=None)
867 formats, subtitles = self._download_media_selector(programme_id)
868 self._sort_formats(formats)
869 # digitalData may be missing (e.g. http://www.bbc.com/autos/story/20130513-hyundais-rock-star)
870 digital_data = self._parse_json(
872 r'var\s+digitalData\s*=\s*({.+?});?\n', webpage, 'digital data', default='{}'),
873 programme_id, fatal=False)
874 page_info = digital_data.get('page', {}).get('pageInfo', {})
875 title = page_info.get('pageName') or self._og_search_title(webpage)
876 description = page_info.get('description') or self._og_search_description(webpage)
877 timestamp = parse_iso8601(page_info.get('publicationDate')) or timestamp
881 'description': description,
882 'timestamp': timestamp,
884 'subtitles': subtitles,
887 # Morph based embed (e.g. http://www.bbc.co.uk/sport/live/olympics/36895975)
888 # There are several setPayload calls may be present but the video
889 # seems to be always related to the first one
890 morph_payload = self._parse_json(
892 r'Morph\.setPayload\([^,]+,\s*({.+?})\);',
893 webpage, 'morph payload', default='{}'),
894 playlist_id, fatal=False)
896 components = try_get(morph_payload, lambda x: x['body']['components'], list) or []
897 for component in components:
898 if not isinstance(component, dict):
900 lead_media = try_get(component, lambda x: x['props']['leadMedia'], dict)
903 identifiers = lead_media.get('identifiers')
904 if not identifiers or not isinstance(identifiers, dict):
906 programme_id = identifiers.get('vpid') or identifiers.get('playablePid')
909 title = lead_media.get('title') or self._og_search_title(webpage)
910 formats, subtitles = self._download_media_selector(programme_id)
911 self._sort_formats(formats)
912 description = lead_media.get('summary')
913 uploader = lead_media.get('masterBrand')
914 uploader_id = lead_media.get('mid')
916 duration_d = lead_media.get('duration')
917 if isinstance(duration_d, dict):
918 duration = parse_duration(dict_get(
919 duration_d, ('rawDuration', 'formattedDuration', 'spokenDuration')))
923 'description': description,
924 'duration': duration,
925 'uploader': uploader,
926 'uploader_id': uploader_id,
928 'subtitles': subtitles,
931 def extract_all(pattern):
932 return list(filter(None, map(
933 lambda s: self._parse_json(s, playlist_id, fatal=False),
934 re.findall(pattern, webpage))))
936 # Multiple video article (e.g.
937 # http://www.bbc.co.uk/blogs/adamcurtis/entries/3662a707-0af9-3149-963f-47bea720b460)
938 EMBED_URL = r'https?://(?:www\.)?bbc\.co\.uk/(?:[^/]+/)+%s(?:\b[^"]+)?' % self._ID_REGEX
940 for match in extract_all(r'new\s+SMP\(({.+?})\)'):
941 embed_url = match.get('playerSettings', {}).get('externalEmbedUrl')
942 if embed_url and re.match(EMBED_URL, embed_url):
943 entries.append(embed_url)
944 entries.extend(re.findall(
945 r'setPlaylist\("(%s)"\)' % EMBED_URL, webpage))
947 return self.playlist_result(
948 [self.url_result(entry, 'BBCCoUk') for entry in entries],
949 playlist_id, playlist_title, playlist_description)
951 # Multiple video article (e.g. http://www.bbc.com/news/world-europe-32668511)
952 medias = extract_all(r"data-media-meta='({[^']+})'")
955 # Single video article (e.g. http://www.bbc.com/news/video_and_audio/international)
956 media_asset = self._search_regex(
957 r'mediaAssetPage\.init\(\s*({.+?}), "/',
958 webpage, 'media asset', default=None)
960 media_asset_page = self._parse_json(media_asset, playlist_id, fatal=False)
962 for video in media_asset_page.get('videos', {}).values():
963 medias.extend(video.values())
966 # Multiple video playlist with single `now playing` entry (e.g.
967 # http://www.bbc.com/news/video_and_audio/must_see/33767813)
968 vxp_playlist = self._parse_json(
970 r'<script[^>]+class="vxp-playlist-data"[^>]+type="application/json"[^>]*>([^<]+)</script>',
971 webpage, 'playlist data'),
974 for item in vxp_playlist:
975 media = item.get('media')
978 playlist_medias.append(media)
979 # Download single video if found media with asset id matching the video id from URL
980 if item.get('advert', {}).get('assetId') == playlist_id:
983 # Fallback to the whole playlist
985 medias = playlist_medias
988 for num, media_meta in enumerate(medias, start=1):
989 formats, subtitles = self._extract_from_media_meta(media_meta, playlist_id)
992 self._sort_formats(formats)
994 video_id = media_meta.get('externalId')
996 video_id = playlist_id if len(medias) == 1 else '%s-%s' % (playlist_id, num)
998 title = media_meta.get('caption')
1000 title = playlist_title if len(medias) == 1 else '%s - Video %s' % (playlist_title, num)
1002 duration = int_or_none(media_meta.get('durationInSeconds')) or parse_duration(media_meta.get('duration'))
1005 for image in media_meta.get('images', {}).values():
1006 images.extend(image.values())
1007 if 'image' in media_meta:
1008 images.append(media_meta['image'])
1011 'url': image.get('href'),
1012 'width': int_or_none(image.get('width')),
1013 'height': int_or_none(image.get('height')),
1014 } for image in images]
1019 'thumbnails': thumbnails,
1020 'duration': duration,
1021 'timestamp': timestamp,
1023 'subtitles': subtitles,
1026 return self.playlist_result(entries, playlist_id, playlist_title, playlist_description)
1029 class BBCCoUkArticleIE(InfoExtractor):
1030 _VALID_URL = r'https?://www.bbc.co.uk/programmes/articles/(?P<id>[a-zA-Z0-9]+)'
1031 IE_NAME = 'bbc.co.uk:article'
1032 IE_DESC = 'BBC articles'
1035 'url': 'http://www.bbc.co.uk/programmes/articles/3jNQLTMrPlYGTBn0WV6M2MS/not-your-typical-role-model-ada-lovelace-the-19th-century-programmer',
1037 'id': '3jNQLTMrPlYGTBn0WV6M2MS',
1038 'title': 'Calculating Ada: The Countess of Computing - Not your typical role model: Ada Lovelace the 19th century programmer - BBC Four',
1039 'description': 'Hannah Fry reveals some of her surprising discoveries about Ada Lovelace during filming.',
1041 'playlist_count': 4,
1042 'add_ie': ['BBCCoUk'],
1045 def _real_extract(self, url):
1046 playlist_id = self._match_id(url)
1048 webpage = self._download_webpage(url, playlist_id)
1050 title = self._og_search_title(webpage)
1051 description = self._og_search_description(webpage).strip()
1053 entries = [self.url_result(programme_url) for programme_url in re.findall(
1054 r'<div[^>]+typeof="Clip"[^>]+resource="([^"]+)"', webpage)]
1056 return self.playlist_result(entries, playlist_id, title, description)
1059 class BBCCoUkPlaylistBaseIE(InfoExtractor):
1060 def _real_extract(self, url):
1061 playlist_id = self._match_id(url)
1063 webpage = self._download_webpage(url, playlist_id)
1066 self.url_result(self._URL_TEMPLATE % video_id, BBCCoUkIE.ie_key())
1067 for video_id in re.findall(
1068 self._VIDEO_ID_TEMPLATE % BBCCoUkIE._ID_REGEX, webpage)]
1070 title, description = self._extract_title_and_description(webpage)
1072 return self.playlist_result(entries, playlist_id, title, description)
1075 class BBCCoUkIPlayerPlaylistIE(BBCCoUkPlaylistBaseIE):
1076 IE_NAME = 'bbc.co.uk:iplayer:playlist'
1077 _VALID_URL = r'https?://(?:www\.)?bbc\.co\.uk/iplayer/(?:episodes|group)/(?P<id>%s)' % BBCCoUkIE._ID_REGEX
1078 _URL_TEMPLATE = 'http://www.bbc.co.uk/iplayer/episode/%s'
1079 _VIDEO_ID_TEMPLATE = r'data-ip-id=["\'](%s)'
1081 'url': 'http://www.bbc.co.uk/iplayer/episodes/b05rcz9v',
1084 'title': 'The Disappearance',
1085 'description': 'French thriller serial about a missing teenager.',
1087 'playlist_mincount': 6,
1088 'skip': 'This programme is not currently available on BBC iPlayer',
1090 # Available for over a year unlike 30 days for most other programmes
1091 'url': 'http://www.bbc.co.uk/iplayer/group/p02tcc32',
1094 'title': 'Bohemian Icons',
1095 'description': 'md5:683e901041b2fe9ba596f2ab04c4dbe7',
1097 'playlist_mincount': 10,
1100 def _extract_title_and_description(self, webpage):
1101 title = self._search_regex(r'<h1>([^<]+)</h1>', webpage, 'title', fatal=False)
1102 description = self._search_regex(
1103 r'<p[^>]+class=(["\'])subtitle\1[^>]*>(?P<value>[^<]+)</p>',
1104 webpage, 'description', fatal=False, group='value')
1105 return title, description
1108 class BBCCoUkPlaylistIE(BBCCoUkPlaylistBaseIE):
1109 IE_NAME = 'bbc.co.uk:playlist'
1110 _VALID_URL = r'https?://(?:www\.)?bbc\.co\.uk/programmes/(?P<id>%s)/(?:episodes|broadcasts|clips)' % BBCCoUkIE._ID_REGEX
1111 _URL_TEMPLATE = 'http://www.bbc.co.uk/programmes/%s'
1112 _VIDEO_ID_TEMPLATE = r'data-pid=["\'](%s)'
1114 'url': 'http://www.bbc.co.uk/programmes/b05rcz9v/clips',
1117 'title': 'The Disappearance - Clips - BBC Four',
1118 'description': 'French thriller serial about a missing teenager.',
1120 'playlist_mincount': 7,
1122 'url': 'http://www.bbc.co.uk/programmes/b05rcz9v/broadcasts/2016/06',
1123 'only_matching': True,
1125 'url': 'http://www.bbc.co.uk/programmes/b05rcz9v/clips',
1126 'only_matching': True,
1128 'url': 'http://www.bbc.co.uk/programmes/b055jkys/episodes/player',
1129 'only_matching': True,
1132 def _extract_title_and_description(self, webpage):
1133 title = self._og_search_title(webpage, fatal=False)
1134 description = self._og_search_description(webpage)
1135 return title, description