2 from __future__ import unicode_literals
6 from .common import InfoExtractor
16 from ..compat import (
17 compat_etree_fromstring,
22 class BBCCoUkIE(InfoExtractor):
24 IE_DESC = 'BBC iPlayer'
25 _ID_REGEX = r'[pb][\da-z]{7}'
28 (?:www\.)?bbc\.co\.uk/
30 programmes/(?!articles/)|
31 iplayer(?:/[^/]+)?/(?:episode/|playlist/)|
38 _MEDIASELECTOR_URLS = [
39 # Provides HQ HLS streams with even better quality that pc mediaset but fails
40 # with geolocation in some cases when it's even not geo restricted at all (e.g.
41 # http://www.bbc.co.uk/programmes/b06bp7lf). Also may fail with selectionunavailable.
42 'http://open.live.bbc.co.uk/mediaselector/5/select/version/2.0/mediaset/iptv-all/vpid/%s',
43 'http://open.live.bbc.co.uk/mediaselector/5/select/version/2.0/mediaset/pc/vpid/%s',
46 _MEDIASELECTION_NS = 'http://bbc.co.uk/2008/mp/mediaselection'
47 _EMP_PLAYLIST_NS = 'http://bbc.co.uk/2008/emp/playlist'
56 'url': 'http://www.bbc.co.uk/programmes/b039g8p7',
60 'title': 'Leonard Cohen, Kaleidoscope - BBC Radio 4',
61 'description': 'The Canadian poet and songwriter reflects on his musical career.',
65 'skip_download': True,
69 'url': 'http://www.bbc.co.uk/iplayer/episode/b00yng5w/The_Man_in_Black_Series_3_The_Printed_Name/',
73 'title': 'The Man in Black: Series 3: The Printed Name',
74 'description': "Mark Gatiss introduces Nicholas Pierpan's chilling tale of a writer's devilish pact with a mysterious man. Stars Ewan Bailey.",
79 'skip_download': True,
81 'skip': 'Episode is no longer available on BBC iPlayer Radio',
84 'url': 'http://www.bbc.co.uk/iplayer/episode/b03vhd1f/The_Voice_UK_Series_3_Blind_Auditions_5/',
88 'title': 'The Voice UK: Series 3: Blind Auditions 5',
89 '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.",
94 'skip_download': True,
96 'skip': 'Currently BBC iPlayer TV programmes are available to play in the UK only',
99 'url': 'http://www.bbc.co.uk/iplayer/episode/p026c7jt/tomorrows-worlds-the-unearthly-history-of-science-fiction-2-invasion',
103 'title': "Tomorrow's Worlds: The Unearthly History of Science Fiction",
104 'description': '2. Invasion',
109 'skip_download': True,
111 'skip': 'Currently BBC iPlayer TV programmes are available to play in the UK only',
113 'url': 'http://www.bbc.co.uk/programmes/b04v20dw',
117 'title': 'Pete Tong, The Essential New Tune Special',
118 'description': "Pete has a very special mix - all of 2014's Essential New Tunes!",
123 'skip_download': True,
125 'skip': 'Episode is no longer available on BBC iPlayer Radio',
127 'url': 'http://www.bbc.co.uk/music/clips/p022h44b',
132 'title': 'BBC Proms Music Guides, Rachmaninov: Symphonic Dances',
133 'description': "In this Proms Music Guide, Andrew McGregor looks at Rachmaninov's Symphonic Dances.",
138 'skip_download': True,
141 'url': 'http://www.bbc.co.uk/music/clips/p025c0zz',
146 'title': 'Reading and Leeds Festival, 2014, Rae Morris - Closer (Live on BBC Three)',
147 'description': 'Rae Morris performs Closer for BBC Three at Reading 2014',
152 'skip_download': True,
155 'url': 'http://www.bbc.co.uk/iplayer/episode/b054fn09/ad/natural-world-20152016-2-super-powered-owls',
159 'title': 'Natural World, 2015-2016: 2. Super Powered Owls',
160 'description': 'md5:e4db5c937d0e95a7c6b5e654d429183d',
165 'skip_download': True,
167 'skip': 'geolocation',
169 'url': 'http://www.bbc.co.uk/iplayer/episode/b05zmgwn/royal-academy-summer-exhibition',
173 '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.',
174 'title': 'Royal Academy Summer Exhibition',
179 'skip_download': True,
181 'skip': 'geolocation',
183 # iptv-all mediaset fails with geolocation however there is no geo restriction
184 # for this programme at all
185 'url': 'http://www.bbc.co.uk/programmes/b06rkn85',
189 'title': "Best of the Mini-Mixes 2015: Part 3, Annie Mac's Friday Night - BBC Radio 1",
190 'description': "Annie has part three in the Best of the Mini-Mixes 2015, plus the year's Most Played!",
194 'skip_download': True,
197 'url': 'http://www.bbc.co.uk/iplayer/playlist/p01dvks4',
198 'only_matching': True,
200 'url': 'http://www.bbc.co.uk/music/clips#p02frcc3',
201 'only_matching': True,
203 'url': 'http://www.bbc.co.uk/iplayer/cbeebies/episode/b0480276/bing-14-atchoo',
204 'only_matching': True,
206 'url': 'http://www.bbc.co.uk/radio/player/p03cchwf',
207 'only_matching': True,
211 class MediaSelectionError(Exception):
212 def __init__(self, id):
215 def _extract_asx_playlist(self, connection, programme_id):
216 asx = self._download_xml(connection.get('href'), programme_id, 'Downloading ASX playlist')
217 return [ref.get('href') for ref in asx.findall('./Entry/ref')]
219 def _extract_connection(self, connection, programme_id):
221 kind = connection.get('kind')
222 protocol = connection.get('protocol')
223 supplier = connection.get('supplier')
224 if protocol == 'http':
225 href = connection.get('href')
226 transfer_format = connection.get('transferFormat')
228 if supplier == 'asx':
229 for i, ref in enumerate(self._extract_asx_playlist(connection, programme_id)):
232 'format_id': 'ref%s_%s' % (i, supplier),
234 # Skip DASH until supported
235 elif transfer_format == 'dash':
237 elif transfer_format == 'hls':
238 formats.extend(self._extract_m3u8_formats(
239 href, programme_id, ext='mp4', entry_protocol='m3u8_native',
240 m3u8_id=supplier, fatal=False))
245 'format_id': supplier or kind or protocol,
247 elif protocol == 'rtmp':
248 application = connection.get('application', 'ondemand')
249 auth_string = connection.get('authString')
250 identifier = connection.get('identifier')
251 server = connection.get('server')
253 'url': '%s://%s/%s?%s' % (protocol, server, application, auth_string),
254 'play_path': identifier,
255 'app': '%s?%s' % (application, auth_string),
256 'page_url': 'http://www.bbc.co.uk',
257 'player_url': 'http://www.bbc.co.uk/emp/releases/iplayer/revisions/617463_618125_4/617463_618125_4_emp.swf',
260 'format_id': supplier,
264 def _extract_items(self, playlist):
265 return playlist.findall('./{%s}item' % self._EMP_PLAYLIST_NS)
267 def _findall_ns(self, element, xpath):
269 for ns in self._NAMESPACES:
270 elements.extend(element.findall(xpath % ns))
273 def _extract_medias(self, media_selection):
274 error = media_selection.find('./{%s}error' % self._MEDIASELECTION_NS)
276 media_selection.find('./{%s}error' % self._EMP_PLAYLIST_NS)
277 if error is not None:
278 raise BBCCoUkIE.MediaSelectionError(error.get('id'))
279 return self._findall_ns(media_selection, './{%s}media')
281 def _extract_connections(self, media):
282 return self._findall_ns(media, './{%s}connection')
284 def _extract_video(self, media, programme_id):
286 vbr = int_or_none(media.get('bitrate'))
287 vcodec = media.get('encoding')
288 service = media.get('service')
289 width = int_or_none(media.get('width'))
290 height = int_or_none(media.get('height'))
291 file_size = int_or_none(media.get('media_file_size'))
292 for connection in self._extract_connections(media):
293 conn_formats = self._extract_connection(connection, programme_id)
294 for format in conn_formats:
300 'filesize': file_size,
303 format['format_id'] = '%s_%s' % (service, format['format_id'])
304 formats.extend(conn_formats)
307 def _extract_audio(self, media, programme_id):
309 abr = int_or_none(media.get('bitrate'))
310 acodec = media.get('encoding')
311 service = media.get('service')
312 for connection in self._extract_connections(media):
313 conn_formats = self._extract_connection(connection, programme_id)
314 for format in conn_formats:
316 'format_id': '%s_%s' % (service, format['format_id']),
320 formats.extend(conn_formats)
323 def _get_subtitles(self, media, programme_id):
325 for connection in self._extract_connections(media):
326 captions = self._download_xml(connection.get('href'), programme_id, 'Downloading captions')
327 lang = captions.get('{http://www.w3.org/XML/1998/namespace}lang', 'en')
330 'url': connection.get('href'),
336 def _raise_extractor_error(self, media_selection_error):
337 raise ExtractorError(
338 '%s returned error: %s' % (self.IE_NAME, media_selection_error.id),
341 def _download_media_selector(self, programme_id):
342 last_exception = None
343 for mediaselector_url in self._MEDIASELECTOR_URLS:
345 return self._download_media_selector_url(
346 mediaselector_url % programme_id, programme_id)
347 except BBCCoUkIE.MediaSelectionError as e:
348 if e.id in ('notukerror', 'geolocation', 'selectionunavailable'):
351 self._raise_extractor_error(e)
352 self._raise_extractor_error(last_exception)
354 def _download_media_selector_url(self, url, programme_id=None):
356 media_selection = self._download_xml(
357 url, programme_id, 'Downloading media selection XML')
358 except ExtractorError as ee:
359 if isinstance(ee.cause, compat_HTTPError) and ee.cause.code in (403, 404):
360 media_selection = compat_etree_fromstring(ee.cause.read().decode('utf-8'))
363 return self._process_media_selector(media_selection, programme_id)
365 def _process_media_selector(self, media_selection, programme_id):
369 for media in self._extract_medias(media_selection):
370 kind = media.get('kind')
372 formats.extend(self._extract_audio(media, programme_id))
373 elif kind == 'video':
374 formats.extend(self._extract_video(media, programme_id))
375 elif kind == 'captions':
376 subtitles = self.extract_subtitles(media, programme_id)
377 return formats, subtitles
379 def _download_playlist(self, playlist_id):
381 playlist = self._download_json(
382 'http://www.bbc.co.uk/programmes/%s/playlist.json' % playlist_id,
383 playlist_id, 'Downloading playlist JSON')
385 version = playlist.get('defaultAvailableVersion')
387 smp_config = version['smpConfig']
388 title = smp_config['title']
389 description = smp_config['summary']
390 for item in smp_config['items']:
392 if kind != 'programme' and kind != 'radioProgramme':
394 programme_id = item.get('vpid')
395 duration = int_or_none(item.get('duration'))
396 formats, subtitles = self._download_media_selector(programme_id)
397 return programme_id, title, description, duration, formats, subtitles
398 except ExtractorError as ee:
399 if not (isinstance(ee.cause, compat_HTTPError) and ee.cause.code == 404):
402 # fallback to legacy playlist
403 return self._process_legacy_playlist(playlist_id)
405 def _process_legacy_playlist_url(self, url, display_id):
406 playlist = self._download_legacy_playlist_url(url, display_id)
407 return self._extract_from_legacy_playlist(playlist, display_id)
409 def _process_legacy_playlist(self, playlist_id):
410 return self._process_legacy_playlist_url(
411 'http://www.bbc.co.uk/iplayer/playlist/%s' % playlist_id, playlist_id)
413 def _download_legacy_playlist_url(self, url, playlist_id=None):
414 return self._download_xml(
415 url, playlist_id, 'Downloading legacy playlist XML')
417 def _extract_from_legacy_playlist(self, playlist, playlist_id):
418 no_items = playlist.find('./{%s}noItems' % self._EMP_PLAYLIST_NS)
419 if no_items is not None:
420 reason = no_items.get('reason')
421 if reason == 'preAvailability':
422 msg = 'Episode %s is not yet available' % playlist_id
423 elif reason == 'postAvailability':
424 msg = 'Episode %s is no longer available' % playlist_id
425 elif reason == 'noMedia':
426 msg = 'Episode %s is not currently available' % playlist_id
428 msg = 'Episode %s is not available: %s' % (playlist_id, reason)
429 raise ExtractorError(msg, expected=True)
431 for item in self._extract_items(playlist):
432 kind = item.get('kind')
433 if kind != 'programme' and kind != 'radioProgramme':
435 title = playlist.find('./{%s}title' % self._EMP_PLAYLIST_NS).text
436 description_el = playlist.find('./{%s}summary' % self._EMP_PLAYLIST_NS)
437 description = description_el.text if description_el is not None else None
439 def get_programme_id(item):
440 def get_from_attributes(item):
441 for p in('identifier', 'group'):
443 if value and re.match(r'^[pb][\da-z]{7}$', value):
445 get_from_attributes(item)
446 mediator = item.find('./{%s}mediator' % self._EMP_PLAYLIST_NS)
447 if mediator is not None:
448 return get_from_attributes(mediator)
450 programme_id = get_programme_id(item)
451 duration = int_or_none(item.get('duration'))
454 formats, subtitles = self._download_media_selector(programme_id)
456 formats, subtitles = self._process_media_selector(item, playlist_id)
457 programme_id = playlist_id
459 return programme_id, title, description, duration, formats, subtitles
461 def _real_extract(self, url):
462 group_id = self._match_id(url)
464 webpage = self._download_webpage(url, group_id, 'Downloading video page')
469 tviplayer = self._search_regex(
470 r'mediator\.bind\(({.+?})\s*,\s*document\.getElementById',
471 webpage, 'player', default=None)
474 player = self._parse_json(tviplayer, group_id).get('player', {})
475 duration = int_or_none(player.get('duration'))
476 programme_id = player.get('vpid')
479 programme_id = self._search_regex(
480 r'"vpid"\s*:\s*"(%s)"' % self._ID_REGEX, webpage, 'vpid', fatal=False, default=None)
483 formats, subtitles = self._download_media_selector(programme_id)
484 title = self._og_search_title(webpage, default=None) or self._html_search_regex(
485 (r'<h2[^>]+id="parent-title"[^>]*>(.+?)</h2>',
486 r'<div[^>]+class="info"[^>]*>\s*<h1>(.+?)</h1>'), webpage, 'title')
487 description = self._search_regex(
488 (r'<p class="[^"]*medium-description[^"]*">([^<]+)</p>',
489 r'<div[^>]+class="info_+synopsis"[^>]*>([^<]+)</div>'),
490 webpage, 'description', default=None)
492 description = self._html_search_meta('description', webpage)
494 programme_id, title, description, duration, formats, subtitles = self._download_playlist(group_id)
496 self._sort_formats(formats)
501 'description': description,
502 'thumbnail': self._og_search_thumbnail(webpage, default=None),
503 'duration': duration,
505 'subtitles': subtitles,
509 class BBCIE(BBCCoUkIE):
512 _VALID_URL = r'https?://(?:www\.)?bbc\.(?:com|co\.uk)/(?:[^/]+/)+(?P<id>[^/#?]+)'
514 _MEDIASELECTOR_URLS = [
515 # Provides HQ HLS streams but fails with geolocation in some cases when it's
516 # even not geo restricted at all
517 'http://open.live.bbc.co.uk/mediaselector/5/select/version/2.0/mediaset/iptv-all/vpid/%s',
518 # Provides more formats, namely direct mp4 links, but fails on some videos with
519 # notukerror for non UK (?) users (e.g.
520 # http://www.bbc.com/travel/story/20150625-sri-lankas-spicy-secret)
521 'http://open.live.bbc.co.uk/mediaselector/4/mtis/stream/%s',
522 # Provides fewer formats, but works everywhere for everybody (hopefully)
523 'http://open.live.bbc.co.uk/mediaselector/5/select/version/2.0/mediaset/journalism-pc/vpid/%s',
527 # article with multiple videos embedded with data-playable containing vpids
528 'url': 'http://www.bbc.com/news/world-europe-32668511',
530 'id': 'world-europe-32668511',
531 'title': 'Russia stages massive WW2 parade despite Western boycott',
532 'description': 'md5:00ff61976f6081841f759a08bf78cc9c',
536 # article with multiple videos embedded with data-playable (more videos)
537 'url': 'http://www.bbc.com/news/business-28299555',
539 'id': 'business-28299555',
540 'title': 'Farnborough Airshow: Video highlights',
541 'description': 'BBC reports and video highlights at the Farnborough Airshow.',
546 # article with multiple videos embedded with `new SMP()`
548 'url': 'http://www.bbc.co.uk/blogs/adamcurtis/entries/3662a707-0af9-3149-963f-47bea720b460',
550 'id': '3662a707-0af9-3149-963f-47bea720b460',
551 'title': 'BBC Blogs - Adam Curtis - BUGGER',
553 'playlist_count': 18,
555 # single video embedded with data-playable containing vpid
556 'url': 'http://www.bbc.com/news/world-europe-32041533',
560 'title': 'Aerial footage showed the site of the crash in the Alps - courtesy BFM TV',
561 'description': 'md5:2868290467291b37feda7863f7a83f54',
563 'timestamp': 1427219242,
564 'upload_date': '20150324',
568 'skip_download': True,
571 # article with single video embedded with data-playable containing XML playlist
572 # with direct video links as progressiveDownloadUrl (for now these are extracted)
573 # and playlist with f4m and m3u8 as streamingUrl
574 'url': 'http://www.bbc.com/turkce/haberler/2015/06/150615_telabyad_kentin_cogu',
576 'id': '150615_telabyad_kentin_cogu',
578 'title': "YPG: Tel Abyad'ın tamamı kontrolümüzde",
579 'timestamp': 1434397334,
580 'upload_date': '20150615',
583 'skip_download': True,
586 # single video embedded with data-playable containing XML playlists (regional section)
587 'url': 'http://www.bbc.com/mundo/video_fotos/2015/06/150619_video_honduras_militares_hospitales_corrupcion_aw',
589 'id': '150619_video_honduras_militares_hospitales_corrupcion_aw',
591 'title': 'Honduras militariza sus hospitales por nuevo escándalo de corrupción',
592 'timestamp': 1434713142,
593 'upload_date': '20150619',
596 'skip_download': True,
599 # single video from video playlist embedded with vxp-playlist-data JSON
600 'url': 'http://www.bbc.com/news/video_and_audio/must_see/33376376',
604 'title': '''Judge Mindy Glazer: "I'm sorry to see you here... I always wondered what happened to you"''',
606 'description': '''Judge Mindy Glazer: "I'm sorry to see you here... I always wondered what happened to you"''',
609 'skip_download': True,
612 # single video story with digitalData
613 'url': 'http://www.bbc.com/travel/story/20150625-sri-lankas-spicy-secret',
617 'title': 'Sri Lanka’s spicy secret',
618 'description': 'As a new train line to Jaffna opens up the country’s north, travellers can experience a truly distinct slice of Tamil culture.',
619 'timestamp': 1437674293,
620 'upload_date': '20150723',
624 'skip_download': True,
627 # single video story without digitalData
628 'url': 'http://www.bbc.com/autos/story/20130513-hyundais-rock-star',
632 'title': 'Hyundai Santa Fe Sport: Rock star',
633 'description': 'md5:b042a26142c4154a6e472933cf20793d',
634 'timestamp': 1415867444,
635 'upload_date': '20141113',
639 'skip_download': True,
642 # single video with playlist.sxml URL in playlist param
643 'url': 'http://www.bbc.com/sport/0/football/33653409',
647 'title': 'Transfers: Cristiano Ronaldo to Man Utd, Arsenal to spend?',
648 'description': 'BBC Sport\'s David Ornstein has the latest transfer gossip, including rumours of a Manchester United return for Cristiano Ronaldo.',
653 'skip_download': True,
656 # article with multiple videos embedded with playlist.sxml in playlist param
657 'url': 'http://www.bbc.com/sport/0/football/34475836',
660 'title': 'What Liverpool can expect from Klopp',
664 # single video with playlist URL from weather section
665 'url': 'http://www.bbc.com/weather/features/33601775',
666 'only_matching': True,
668 # custom redirection to www.bbc.com
669 'url': 'http://www.bbc.co.uk/news/science-environment-33661876',
670 'only_matching': True,
674 def suitable(cls, url):
675 return False if BBCCoUkIE.suitable(url) or BBCCoUkArticleIE.suitable(url) else super(BBCIE, cls).suitable(url)
677 def _extract_from_media_meta(self, media_meta, video_id):
678 # Direct links to media in media metadata (e.g.
679 # http://www.bbc.com/turkce/haberler/2015/06/150615_telabyad_kentin_cogu)
680 # TODO: there are also f4m and m3u8 streams incorporated in playlist.sxml
681 source_files = media_meta.get('sourceFiles')
685 'format_id': format_id,
686 'ext': f.get('encoding'),
687 'tbr': float_or_none(f.get('bitrate'), 1000),
688 'filesize': int_or_none(f.get('filesize')),
689 } for format_id, f in source_files.items() if f.get('url')], []
691 programme_id = media_meta.get('externalId')
693 return self._download_media_selector(programme_id)
695 # Process playlist.sxml as legacy playlist
696 href = media_meta.get('href')
698 playlist = self._download_legacy_playlist_url(href)
699 _, _, _, _, formats, subtitles = self._extract_from_legacy_playlist(playlist, video_id)
700 return formats, subtitles
704 def _extract_from_playlist_sxml(self, url, playlist_id, timestamp):
705 programme_id, title, description, duration, formats, subtitles = \
706 self._process_legacy_playlist_url(url, playlist_id)
707 self._sort_formats(formats)
711 'description': description,
712 'duration': duration,
713 'timestamp': timestamp,
715 'subtitles': subtitles,
718 def _real_extract(self, url):
719 playlist_id = self._match_id(url)
721 webpage = self._download_webpage(url, playlist_id)
723 json_ld_info = self._search_json_ld(webpage, playlist_id, default=None)
724 timestamp = json_ld_info.get('timestamp')
725 playlist_title = json_ld_info.get('title')
726 playlist_description = json_ld_info.get('description')
729 timestamp = parse_iso8601(self._search_regex(
730 [r'<meta[^>]+property="article:published_time"[^>]+content="([^"]+)"',
731 r'itemprop="datePublished"[^>]+datetime="([^"]+)"',
732 r'"datePublished":\s*"([^"]+)'],
733 webpage, 'date', default=None))
737 # article with multiple videos embedded with playlist.sxml (e.g.
738 # http://www.bbc.com/sport/0/football/34475836)
739 playlists = re.findall(r'<param[^>]+name="playlist"[^>]+value="([^"]+)"', webpage)
740 playlists.extend(re.findall(r'data-media-id="([^"]+/playlist\.sxml)"', webpage))
743 self._extract_from_playlist_sxml(playlist_url, playlist_id, timestamp)
744 for playlist_url in playlists]
746 # news article with multiple videos embedded with data-playable
747 data_playables = re.findall(r'data-playable=(["\'])({.+?})\1', webpage)
749 for _, data_playable_json in data_playables:
750 data_playable = self._parse_json(
751 unescapeHTML(data_playable_json), playlist_id, fatal=False)
752 if not data_playable:
754 settings = data_playable.get('settings', {})
756 # data-playable with video vpid in settings.playlistObject.items (e.g.
757 # http://www.bbc.com/news/world-us-canada-34473351)
758 playlist_object = settings.get('playlistObject', {})
760 items = playlist_object.get('items')
761 if items and isinstance(items, list):
762 title = playlist_object['title']
763 description = playlist_object.get('summary')
764 duration = int_or_none(items[0].get('duration'))
765 programme_id = items[0].get('vpid')
766 formats, subtitles = self._download_media_selector(programme_id)
767 self._sort_formats(formats)
771 'description': description,
772 'timestamp': timestamp,
773 'duration': duration,
775 'subtitles': subtitles,
778 # data-playable without vpid but with a playlist.sxml URLs
779 # in otherSettings.playlist (e.g.
780 # http://www.bbc.com/turkce/multimedya/2015/10/151010_vid_ankara_patlama_ani)
781 playlist = data_playable.get('otherSettings', {}).get('playlist', {})
783 entries.append(self._extract_from_playlist_sxml(
784 playlist.get('progressiveDownloadUrl'), playlist_id, timestamp))
787 playlist_title = playlist_title or remove_end(self._og_search_title(webpage), ' - BBC News')
788 playlist_description = playlist_description or self._og_search_description(webpage, default=None)
789 return self.playlist_result(entries, playlist_id, playlist_title, playlist_description)
791 # single video story (e.g. http://www.bbc.com/travel/story/20150625-sri-lankas-spicy-secret)
792 programme_id = self._search_regex(
793 [r'data-video-player-vpid="(%s)"' % self._ID_REGEX,
794 r'<param[^>]+name="externalIdentifier"[^>]+value="(%s)"' % self._ID_REGEX,
795 r'videoId\s*:\s*["\'](%s)["\']' % self._ID_REGEX],
796 webpage, 'vpid', default=None)
799 formats, subtitles = self._download_media_selector(programme_id)
800 self._sort_formats(formats)
801 # digitalData may be missing (e.g. http://www.bbc.com/autos/story/20130513-hyundais-rock-star)
802 digital_data = self._parse_json(
804 r'var\s+digitalData\s*=\s*({.+?});?\n', webpage, 'digital data', default='{}'),
805 programme_id, fatal=False)
806 page_info = digital_data.get('page', {}).get('pageInfo', {})
807 title = page_info.get('pageName') or self._og_search_title(webpage)
808 description = page_info.get('description') or self._og_search_description(webpage)
809 timestamp = parse_iso8601(page_info.get('publicationDate')) or timestamp
813 'description': description,
814 'timestamp': timestamp,
816 'subtitles': subtitles,
819 playlist_title = self._html_search_regex(
820 r'<title>(.*?)(?:\s*-\s*BBC [^ ]+)?</title>', webpage, 'playlist title')
821 playlist_description = self._og_search_description(webpage, default=None)
823 def extract_all(pattern):
824 return list(filter(None, map(
825 lambda s: self._parse_json(s, playlist_id, fatal=False),
826 re.findall(pattern, webpage))))
828 # Multiple video article (e.g.
829 # http://www.bbc.co.uk/blogs/adamcurtis/entries/3662a707-0af9-3149-963f-47bea720b460)
830 EMBED_URL = r'https?://(?:www\.)?bbc\.co\.uk/(?:[^/]+/)+%s(?:\b[^"]+)?' % self._ID_REGEX
832 for match in extract_all(r'new\s+SMP\(({.+?})\)'):
833 embed_url = match.get('playerSettings', {}).get('externalEmbedUrl')
834 if embed_url and re.match(EMBED_URL, embed_url):
835 entries.append(embed_url)
836 entries.extend(re.findall(
837 r'setPlaylist\("(%s)"\)' % EMBED_URL, webpage))
839 return self.playlist_result(
840 [self.url_result(entry, 'BBCCoUk') for entry in entries],
841 playlist_id, playlist_title, playlist_description)
843 # Multiple video article (e.g. http://www.bbc.com/news/world-europe-32668511)
844 medias = extract_all(r"data-media-meta='({[^']+})'")
847 # Single video article (e.g. http://www.bbc.com/news/video_and_audio/international)
848 media_asset = self._search_regex(
849 r'mediaAssetPage\.init\(\s*({.+?}), "/',
850 webpage, 'media asset', default=None)
852 media_asset_page = self._parse_json(media_asset, playlist_id, fatal=False)
854 for video in media_asset_page.get('videos', {}).values():
855 medias.extend(video.values())
858 # Multiple video playlist with single `now playing` entry (e.g.
859 # http://www.bbc.com/news/video_and_audio/must_see/33767813)
860 vxp_playlist = self._parse_json(
862 r'<script[^>]+class="vxp-playlist-data"[^>]+type="application/json"[^>]*>([^<]+)</script>',
863 webpage, 'playlist data'),
866 for item in vxp_playlist:
867 media = item.get('media')
870 playlist_medias.append(media)
871 # Download single video if found media with asset id matching the video id from URL
872 if item.get('advert', {}).get('assetId') == playlist_id:
875 # Fallback to the whole playlist
877 medias = playlist_medias
880 for num, media_meta in enumerate(medias, start=1):
881 formats, subtitles = self._extract_from_media_meta(media_meta, playlist_id)
884 self._sort_formats(formats)
886 video_id = media_meta.get('externalId')
888 video_id = playlist_id if len(medias) == 1 else '%s-%s' % (playlist_id, num)
890 title = media_meta.get('caption')
892 title = playlist_title if len(medias) == 1 else '%s - Video %s' % (playlist_title, num)
894 duration = int_or_none(media_meta.get('durationInSeconds')) or parse_duration(media_meta.get('duration'))
897 for image in media_meta.get('images', {}).values():
898 images.extend(image.values())
899 if 'image' in media_meta:
900 images.append(media_meta['image'])
903 'url': image.get('href'),
904 'width': int_or_none(image.get('width')),
905 'height': int_or_none(image.get('height')),
906 } for image in images]
911 'thumbnails': thumbnails,
912 'duration': duration,
913 'timestamp': timestamp,
915 'subtitles': subtitles,
918 return self.playlist_result(entries, playlist_id, playlist_title, playlist_description)
921 class BBCCoUkArticleIE(InfoExtractor):
922 _VALID_URL = 'http://www.bbc.co.uk/programmes/articles/(?P<id>[a-zA-Z0-9]+)'
923 IE_NAME = 'bbc.co.uk:article'
924 IE_DESC = 'BBC articles'
927 'url': 'http://www.bbc.co.uk/programmes/articles/3jNQLTMrPlYGTBn0WV6M2MS/not-your-typical-role-model-ada-lovelace-the-19th-century-programmer',
929 'id': '3jNQLTMrPlYGTBn0WV6M2MS',
930 'title': 'Calculating Ada: The Countess of Computing - Not your typical role model: Ada Lovelace the 19th century programmer - BBC Four',
931 'description': 'Hannah Fry reveals some of her surprising discoveries about Ada Lovelace during filming.',
934 'add_ie': ['BBCCoUk'],
937 def _real_extract(self, url):
938 playlist_id = self._match_id(url)
940 webpage = self._download_webpage(url, playlist_id)
942 title = self._og_search_title(webpage)
943 description = self._og_search_description(webpage).strip()
945 entries = [self.url_result(programme_url) for programme_url in re.findall(
946 r'<div[^>]+typeof="Clip"[^>]+resource="([^"]+)"', webpage)]
948 return self.playlist_result(entries, playlist_id, title, description)