2 from __future__ import unicode_literals
6 from .common import InfoExtractor
15 from ..compat import (
16 compat_etree_fromstring,
21 class BBCCoUkIE(InfoExtractor):
23 IE_DESC = 'BBC iPlayer'
24 _ID_REGEX = r'[pb][\da-z]{7}'
27 (?:www\.)?bbc\.co\.uk/
29 programmes/(?!articles/)|
30 iplayer(?:/[^/]+)?/(?:episode/|playlist/)|
34 (?P<id>%s)(?!/(?:episodes|broadcasts|clips))
37 _MEDIASELECTOR_URLS = [
38 # Provides HQ HLS streams with even better quality that pc mediaset but fails
39 # with geolocation in some cases when it's even not geo restricted at all (e.g.
40 # http://www.bbc.co.uk/programmes/b06bp7lf). Also may fail with selectionunavailable.
41 'http://open.live.bbc.co.uk/mediaselector/5/select/version/2.0/mediaset/iptv-all/vpid/%s',
42 'http://open.live.bbc.co.uk/mediaselector/5/select/version/2.0/mediaset/pc/vpid/%s',
45 _MEDIASELECTION_NS = 'http://bbc.co.uk/2008/mp/mediaselection'
46 _EMP_PLAYLIST_NS = 'http://bbc.co.uk/2008/emp/playlist'
47 # Unified Streaming Platform
48 _USP_RE = r'/([^/]+)\.ism(?:\.hlsv2\.ism)?/[^/]+\.m3u8'
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.',
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': 'this episode is not currently available',
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': 'this episode is not currently available',
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.",
137 'skip_download': True,
140 'url': 'http://www.bbc.co.uk/music/clips/p025c0zz',
145 'title': 'Reading and Leeds Festival, 2014, Rae Morris - Closer (Live on BBC Three)',
146 'description': 'Rae Morris performs Closer for BBC Three at Reading 2014',
150 'skip_download': True,
153 'url': 'http://www.bbc.co.uk/iplayer/episode/b054fn09/ad/natural-world-20152016-2-super-powered-owls',
157 'title': 'Natural World, 2015-2016: 2. Super Powered Owls',
158 'description': 'md5:e4db5c937d0e95a7c6b5e654d429183d',
163 'skip_download': True,
165 'skip': 'this episode is not currently available',
167 'url': 'http://www.bbc.co.uk/iplayer/episode/b05zmgwn/royal-academy-summer-exhibition',
171 '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.',
172 'title': 'Royal Academy Summer Exhibition',
177 'skip_download': True,
179 'skip': 'this episode is not currently available',
181 # iptv-all mediaset fails with geolocation however there is no geo restriction
182 # for this programme at all
183 'url': 'http://www.bbc.co.uk/programmes/b06rkn85',
187 'title': "Best of the Mini-Mixes 2015: Part 3, Annie Mac's Friday Night - BBC Radio 1",
188 'description': "Annie has part three in the Best of the Mini-Mixes 2015, plus the year's Most Played!",
192 'skip_download': True,
194 'skip': 'this episode is not currently available on BBC iPlayer Radio',
196 # compact player (https://github.com/rg3/youtube-dl/issues/8147)
197 'url': 'http://www.bbc.co.uk/programmes/p028bfkf/player',
201 'title': 'Extract from BBC documentary Look Stranger - Giant Leeks and Magic Brews',
202 'description': 'Extract from BBC documentary Look Stranger - Giant Leeks and Magic Brews',
205 'skip_download': True,
208 'url': 'http://www.bbc.co.uk/iplayer/playlist/p01dvks4',
209 'only_matching': True,
211 'url': 'http://www.bbc.co.uk/music/clips#p02frcc3',
212 'only_matching': True,
214 'url': 'http://www.bbc.co.uk/iplayer/cbeebies/episode/b0480276/bing-14-atchoo',
215 'only_matching': True,
217 'url': 'http://www.bbc.co.uk/radio/player/p03cchwf',
218 'only_matching': True,
222 class MediaSelectionError(Exception):
223 def __init__(self, id):
226 def _extract_asx_playlist(self, connection, programme_id):
227 asx = self._download_xml(connection.get('href'), programme_id, 'Downloading ASX playlist')
228 return [ref.get('href') for ref in asx.findall('./Entry/ref')]
230 def _extract_connection(self, connection, programme_id):
232 kind = connection.get('kind')
233 protocol = connection.get('protocol')
234 supplier = connection.get('supplier')
235 if protocol == 'http':
236 href = connection.get('href')
237 transfer_format = connection.get('transferFormat')
239 if supplier == 'asx':
240 for i, ref in enumerate(self._extract_asx_playlist(connection, programme_id)):
243 'format_id': 'ref%s_%s' % (i, supplier),
245 # Skip DASH until supported
246 elif transfer_format == 'dash':
248 elif transfer_format == 'hls':
249 is_unified_streaming = re.search(self._USP_RE, href)
250 if is_unified_streaming:
251 href = re.sub(self._USP_RE, r'/\1.ism/\1.m3u8', href)
252 m3u8_formats = self._extract_m3u8_formats(
253 href, programme_id, ext='mp4', entry_protocol='m3u8_native',
254 m3u8_id=supplier, fatal=False)
255 if is_unified_streaming:
256 self._check_formats(m3u8_formats, programme_id)
257 formats.extend(m3u8_formats)
262 'format_id': supplier or kind or protocol,
264 elif protocol == 'rtmp':
265 application = connection.get('application', 'ondemand')
266 auth_string = connection.get('authString')
267 identifier = connection.get('identifier')
268 server = connection.get('server')
270 'url': '%s://%s/%s?%s' % (protocol, server, application, auth_string),
271 'play_path': identifier,
272 'app': '%s?%s' % (application, auth_string),
273 'page_url': 'http://www.bbc.co.uk',
274 'player_url': 'http://www.bbc.co.uk/emp/releases/iplayer/revisions/617463_618125_4/617463_618125_4_emp.swf',
277 'format_id': supplier,
281 def _extract_items(self, playlist):
282 return playlist.findall('./{%s}item' % self._EMP_PLAYLIST_NS)
284 def _findall_ns(self, element, xpath):
286 for ns in self._NAMESPACES:
287 elements.extend(element.findall(xpath % ns))
290 def _extract_medias(self, media_selection):
291 error = media_selection.find('./{%s}error' % self._MEDIASELECTION_NS)
293 media_selection.find('./{%s}error' % self._EMP_PLAYLIST_NS)
294 if error is not None:
295 raise BBCCoUkIE.MediaSelectionError(error.get('id'))
296 return self._findall_ns(media_selection, './{%s}media')
298 def _extract_connections(self, media):
299 return self._findall_ns(media, './{%s}connection')
301 def _extract_video(self, media, programme_id):
303 vbr = int_or_none(media.get('bitrate'))
304 vcodec = media.get('encoding')
305 service = media.get('service')
306 width = int_or_none(media.get('width'))
307 height = int_or_none(media.get('height'))
308 file_size = int_or_none(media.get('media_file_size'))
309 for connection in self._extract_connections(media):
310 conn_formats = self._extract_connection(connection, programme_id)
311 for format in conn_formats:
312 if format.get('protocol') != 'm3u8_native':
318 'filesize': file_size,
321 format['format_id'] = '%s_%s' % (service, format['format_id'])
322 formats.extend(conn_formats)
325 def _extract_audio(self, media, programme_id):
327 abr = int_or_none(media.get('bitrate'))
328 acodec = media.get('encoding')
329 service = media.get('service')
330 for connection in self._extract_connections(media):
331 conn_formats = self._extract_connection(connection, programme_id)
332 for format in conn_formats:
334 'format_id': '%s_%s' % (service, format['format_id']),
339 formats.extend(conn_formats)
342 def _get_subtitles(self, media, programme_id):
344 for connection in self._extract_connections(media):
345 captions = self._download_xml(connection.get('href'), programme_id, 'Downloading captions')
346 lang = captions.get('{http://www.w3.org/XML/1998/namespace}lang', 'en')
349 'url': connection.get('href'),
355 def _raise_extractor_error(self, media_selection_error):
356 raise ExtractorError(
357 '%s returned error: %s' % (self.IE_NAME, media_selection_error.id),
360 def _download_media_selector(self, programme_id):
361 last_exception = None
362 for mediaselector_url in self._MEDIASELECTOR_URLS:
364 return self._download_media_selector_url(
365 mediaselector_url % programme_id, programme_id)
366 except BBCCoUkIE.MediaSelectionError as e:
367 if e.id in ('notukerror', 'geolocation', 'selectionunavailable'):
370 self._raise_extractor_error(e)
371 self._raise_extractor_error(last_exception)
373 def _download_media_selector_url(self, url, programme_id=None):
375 media_selection = self._download_xml(
376 url, programme_id, 'Downloading media selection XML')
377 except ExtractorError as ee:
378 if isinstance(ee.cause, compat_HTTPError) and ee.cause.code in (403, 404):
379 media_selection = compat_etree_fromstring(ee.cause.read().decode('utf-8'))
382 return self._process_media_selector(media_selection, programme_id)
384 def _process_media_selector(self, media_selection, programme_id):
388 for media in self._extract_medias(media_selection):
389 kind = media.get('kind')
391 formats.extend(self._extract_audio(media, programme_id))
392 elif kind == 'video':
393 formats.extend(self._extract_video(media, programme_id))
394 elif kind == 'captions':
395 subtitles = self.extract_subtitles(media, programme_id)
396 return formats, subtitles
398 def _download_playlist(self, playlist_id):
400 playlist = self._download_json(
401 'http://www.bbc.co.uk/programmes/%s/playlist.json' % playlist_id,
402 playlist_id, 'Downloading playlist JSON')
404 version = playlist.get('defaultAvailableVersion')
406 smp_config = version['smpConfig']
407 title = smp_config['title']
408 description = smp_config['summary']
409 for item in smp_config['items']:
411 if kind != 'programme' and kind != 'radioProgramme':
413 programme_id = item.get('vpid')
414 duration = int_or_none(item.get('duration'))
415 formats, subtitles = self._download_media_selector(programme_id)
416 return programme_id, title, description, duration, formats, subtitles
417 except ExtractorError as ee:
418 if not (isinstance(ee.cause, compat_HTTPError) and ee.cause.code == 404):
421 # fallback to legacy playlist
422 return self._process_legacy_playlist(playlist_id)
424 def _process_legacy_playlist_url(self, url, display_id):
425 playlist = self._download_legacy_playlist_url(url, display_id)
426 return self._extract_from_legacy_playlist(playlist, display_id)
428 def _process_legacy_playlist(self, playlist_id):
429 return self._process_legacy_playlist_url(
430 'http://www.bbc.co.uk/iplayer/playlist/%s' % playlist_id, playlist_id)
432 def _download_legacy_playlist_url(self, url, playlist_id=None):
433 return self._download_xml(
434 url, playlist_id, 'Downloading legacy playlist XML')
436 def _extract_from_legacy_playlist(self, playlist, playlist_id):
437 no_items = playlist.find('./{%s}noItems' % self._EMP_PLAYLIST_NS)
438 if no_items is not None:
439 reason = no_items.get('reason')
440 if reason == 'preAvailability':
441 msg = 'Episode %s is not yet available' % playlist_id
442 elif reason == 'postAvailability':
443 msg = 'Episode %s is no longer available' % playlist_id
444 elif reason == 'noMedia':
445 msg = 'Episode %s is not currently available' % playlist_id
447 msg = 'Episode %s is not available: %s' % (playlist_id, reason)
448 raise ExtractorError(msg, expected=True)
450 for item in self._extract_items(playlist):
451 kind = item.get('kind')
452 if kind != 'programme' and kind != 'radioProgramme':
454 title = playlist.find('./{%s}title' % self._EMP_PLAYLIST_NS).text
455 description_el = playlist.find('./{%s}summary' % self._EMP_PLAYLIST_NS)
456 description = description_el.text if description_el is not None else None
458 def get_programme_id(item):
459 def get_from_attributes(item):
460 for p in('identifier', 'group'):
462 if value and re.match(r'^[pb][\da-z]{7}$', value):
464 get_from_attributes(item)
465 mediator = item.find('./{%s}mediator' % self._EMP_PLAYLIST_NS)
466 if mediator is not None:
467 return get_from_attributes(mediator)
469 programme_id = get_programme_id(item)
470 duration = int_or_none(item.get('duration'))
473 formats, subtitles = self._download_media_selector(programme_id)
475 formats, subtitles = self._process_media_selector(item, playlist_id)
476 programme_id = playlist_id
478 return programme_id, title, description, duration, formats, subtitles
480 def _real_extract(self, url):
481 group_id = self._match_id(url)
483 webpage = self._download_webpage(url, group_id, 'Downloading video page')
488 tviplayer = self._search_regex(
489 r'mediator\.bind\(({.+?})\s*,\s*document\.getElementById',
490 webpage, 'player', default=None)
493 player = self._parse_json(tviplayer, group_id).get('player', {})
494 duration = int_or_none(player.get('duration'))
495 programme_id = player.get('vpid')
498 programme_id = self._search_regex(
499 r'"vpid"\s*:\s*"(%s)"' % self._ID_REGEX, webpage, 'vpid', fatal=False, default=None)
502 formats, subtitles = self._download_media_selector(programme_id)
503 title = self._og_search_title(webpage, default=None) or self._html_search_regex(
504 (r'<h2[^>]+id="parent-title"[^>]*>(.+?)</h2>',
505 r'<div[^>]+class="info"[^>]*>\s*<h1>(.+?)</h1>'), webpage, 'title')
506 description = self._search_regex(
507 (r'<p class="[^"]*medium-description[^"]*">([^<]+)</p>',
508 r'<div[^>]+class="info_+synopsis"[^>]*>([^<]+)</div>'),
509 webpage, 'description', default=None)
511 description = self._html_search_meta('description', webpage)
513 programme_id, title, description, duration, formats, subtitles = self._download_playlist(group_id)
515 self._sort_formats(formats)
520 'description': description,
521 'thumbnail': self._og_search_thumbnail(webpage, default=None),
522 'duration': duration,
524 'subtitles': subtitles,
528 class BBCIE(BBCCoUkIE):
531 _VALID_URL = r'https?://(?:www\.)?bbc\.(?:com|co\.uk)/(?:[^/]+/)+(?P<id>[^/#?]+)'
533 _MEDIASELECTOR_URLS = [
534 # Provides HQ HLS streams but fails with geolocation in some cases when it's
535 # even not geo restricted at all
536 'http://open.live.bbc.co.uk/mediaselector/5/select/version/2.0/mediaset/iptv-all/vpid/%s',
537 # Provides more formats, namely direct mp4 links, but fails on some videos with
538 # notukerror for non UK (?) users (e.g.
539 # http://www.bbc.com/travel/story/20150625-sri-lankas-spicy-secret)
540 'http://open.live.bbc.co.uk/mediaselector/4/mtis/stream/%s',
541 # Provides fewer formats, but works everywhere for everybody (hopefully)
542 'http://open.live.bbc.co.uk/mediaselector/5/select/version/2.0/mediaset/journalism-pc/vpid/%s',
546 # article with multiple videos embedded with data-playable containing vpids
547 'url': 'http://www.bbc.com/news/world-europe-32668511',
549 'id': 'world-europe-32668511',
550 'title': 'Russia stages massive WW2 parade despite Western boycott',
551 'description': 'md5:00ff61976f6081841f759a08bf78cc9c',
555 # article with multiple videos embedded with data-playable (more videos)
556 'url': 'http://www.bbc.com/news/business-28299555',
558 'id': 'business-28299555',
559 'title': 'Farnborough Airshow: Video highlights',
560 'description': 'BBC reports and video highlights at the Farnborough Airshow.',
565 # article with multiple videos embedded with `new SMP()`
567 'url': 'http://www.bbc.co.uk/blogs/adamcurtis/entries/3662a707-0af9-3149-963f-47bea720b460',
569 'id': '3662a707-0af9-3149-963f-47bea720b460',
572 'playlist_count': 18,
574 # single video embedded with data-playable containing vpid
575 'url': 'http://www.bbc.com/news/world-europe-32041533',
579 'title': 'Aerial footage showed the site of the crash in the Alps - courtesy BFM TV',
580 'description': 'md5:2868290467291b37feda7863f7a83f54',
582 'timestamp': 1427219242,
583 'upload_date': '20150324',
587 'skip_download': True,
590 # article with single video embedded with data-playable containing XML playlist
591 # with direct video links as progressiveDownloadUrl (for now these are extracted)
592 # and playlist with f4m and m3u8 as streamingUrl
593 'url': 'http://www.bbc.com/turkce/haberler/2015/06/150615_telabyad_kentin_cogu',
595 'id': '150615_telabyad_kentin_cogu',
597 'title': "YPG: Tel Abyad'ın tamamı kontrolümüzde",
598 'timestamp': 1434397334,
599 'upload_date': '20150615',
602 'skip_download': True,
605 # single video embedded with data-playable containing XML playlists (regional section)
606 'url': 'http://www.bbc.com/mundo/video_fotos/2015/06/150619_video_honduras_militares_hospitales_corrupcion_aw',
608 'id': '150619_video_honduras_militares_hospitales_corrupcion_aw',
610 'title': 'Honduras militariza sus hospitales por nuevo escándalo de corrupción',
611 'timestamp': 1434713142,
612 'upload_date': '20150619',
615 'skip_download': True,
618 # single video from video playlist embedded with vxp-playlist-data JSON
619 'url': 'http://www.bbc.com/news/video_and_audio/must_see/33376376',
623 'title': '''Judge Mindy Glazer: "I'm sorry to see you here... I always wondered what happened to you"''',
625 'description': '''Judge Mindy Glazer: "I'm sorry to see you here... I always wondered what happened to you"''',
628 'skip_download': True,
631 # single video story with digitalData
632 'url': 'http://www.bbc.com/travel/story/20150625-sri-lankas-spicy-secret',
636 'title': 'Sri Lanka’s spicy secret',
637 'description': 'As a new train line to Jaffna opens up the country’s north, travellers can experience a truly distinct slice of Tamil culture.',
638 'timestamp': 1437674293,
639 'upload_date': '20150723',
643 'skip_download': True,
646 # single video story without digitalData
647 'url': 'http://www.bbc.com/autos/story/20130513-hyundais-rock-star',
651 'title': 'Hyundai Santa Fe Sport: Rock star',
652 'description': 'md5:b042a26142c4154a6e472933cf20793d',
653 'timestamp': 1415867444,
654 'upload_date': '20141113',
658 'skip_download': True,
661 # single video with playlist.sxml URL in playlist param
662 'url': 'http://www.bbc.com/sport/0/football/33653409',
666 'title': 'Transfers: Cristiano Ronaldo to Man Utd, Arsenal to spend?',
667 'description': 'BBC Sport\'s David Ornstein has the latest transfer gossip, including rumours of a Manchester United return for Cristiano Ronaldo.',
672 'skip_download': True,
675 # article with multiple videos embedded with playlist.sxml in playlist param
676 'url': 'http://www.bbc.com/sport/0/football/34475836',
679 'title': 'Jurgen Klopp: Furious football from a witty and winning coach',
680 'description': 'Fast-paced football, wit, wisdom and a ready smile - why Liverpool fans should come to love new boss Jurgen Klopp.',
684 # school report article with single video
685 'url': 'http://www.bbc.co.uk/schoolreport/35744779',
688 'title': 'School which breaks down barriers in Jerusalem',
692 # single video with playlist URL from weather section
693 'url': 'http://www.bbc.com/weather/features/33601775',
694 'only_matching': True,
696 # custom redirection to www.bbc.com
697 'url': 'http://www.bbc.co.uk/news/science-environment-33661876',
698 'only_matching': True,
700 # single video article embedded with data-media-vpid
701 'url': 'http://www.bbc.co.uk/sport/rowing/35908187',
702 'only_matching': True,
706 def suitable(cls, url):
707 EXCLUDE_IE = (BBCCoUkIE, BBCCoUkArticleIE, BBCCoUkIPlayerPlaylistIE, BBCCoUkPlaylistIE)
708 return (False if any(ie.suitable(url) for ie in EXCLUDE_IE)
709 else super(BBCIE, cls).suitable(url))
711 def _extract_from_media_meta(self, media_meta, video_id):
712 # Direct links to media in media metadata (e.g.
713 # http://www.bbc.com/turkce/haberler/2015/06/150615_telabyad_kentin_cogu)
714 # TODO: there are also f4m and m3u8 streams incorporated in playlist.sxml
715 source_files = media_meta.get('sourceFiles')
719 'format_id': format_id,
720 'ext': f.get('encoding'),
721 'tbr': float_or_none(f.get('bitrate'), 1000),
722 'filesize': int_or_none(f.get('filesize')),
723 } for format_id, f in source_files.items() if f.get('url')], []
725 programme_id = media_meta.get('externalId')
727 return self._download_media_selector(programme_id)
729 # Process playlist.sxml as legacy playlist
730 href = media_meta.get('href')
732 playlist = self._download_legacy_playlist_url(href)
733 _, _, _, _, formats, subtitles = self._extract_from_legacy_playlist(playlist, video_id)
734 return formats, subtitles
738 def _extract_from_playlist_sxml(self, url, playlist_id, timestamp):
739 programme_id, title, description, duration, formats, subtitles = \
740 self._process_legacy_playlist_url(url, playlist_id)
741 self._sort_formats(formats)
745 'description': description,
746 'duration': duration,
747 'timestamp': timestamp,
749 'subtitles': subtitles,
752 def _real_extract(self, url):
753 playlist_id = self._match_id(url)
755 webpage = self._download_webpage(url, playlist_id)
757 json_ld_info = self._search_json_ld(webpage, playlist_id, default=None)
758 timestamp = json_ld_info.get('timestamp')
760 playlist_title = json_ld_info.get('title')
761 if not playlist_title:
762 playlist_title = self._og_search_title(
763 webpage, default=None) or self._html_search_regex(
764 r'<title>(.+?)</title>', webpage, 'playlist title', default=None)
766 playlist_title = re.sub(r'(.+)\s*-\s*BBC.*?$', r'\1', playlist_title).strip()
768 playlist_description = json_ld_info.get(
769 'description') or self._og_search_description(webpage, default=None)
772 timestamp = parse_iso8601(self._search_regex(
773 [r'<meta[^>]+property="article:published_time"[^>]+content="([^"]+)"',
774 r'itemprop="datePublished"[^>]+datetime="([^"]+)"',
775 r'"datePublished":\s*"([^"]+)'],
776 webpage, 'date', default=None))
780 # article with multiple videos embedded with playlist.sxml (e.g.
781 # http://www.bbc.com/sport/0/football/34475836)
782 playlists = re.findall(r'<param[^>]+name="playlist"[^>]+value="([^"]+)"', webpage)
783 playlists.extend(re.findall(r'data-media-id="([^"]+/playlist\.sxml)"', webpage))
786 self._extract_from_playlist_sxml(playlist_url, playlist_id, timestamp)
787 for playlist_url in playlists]
789 # news article with multiple videos embedded with data-playable
790 data_playables = re.findall(r'data-playable=(["\'])({.+?})\1', webpage)
792 for _, data_playable_json in data_playables:
793 data_playable = self._parse_json(
794 unescapeHTML(data_playable_json), playlist_id, fatal=False)
795 if not data_playable:
797 settings = data_playable.get('settings', {})
799 # data-playable with video vpid in settings.playlistObject.items (e.g.
800 # http://www.bbc.com/news/world-us-canada-34473351)
801 playlist_object = settings.get('playlistObject', {})
803 items = playlist_object.get('items')
804 if items and isinstance(items, list):
805 title = playlist_object['title']
806 description = playlist_object.get('summary')
807 duration = int_or_none(items[0].get('duration'))
808 programme_id = items[0].get('vpid')
809 formats, subtitles = self._download_media_selector(programme_id)
810 self._sort_formats(formats)
814 'description': description,
815 'timestamp': timestamp,
816 'duration': duration,
818 'subtitles': subtitles,
821 # data-playable without vpid but with a playlist.sxml URLs
822 # in otherSettings.playlist (e.g.
823 # http://www.bbc.com/turkce/multimedya/2015/10/151010_vid_ankara_patlama_ani)
824 playlist = data_playable.get('otherSettings', {}).get('playlist', {})
826 entries.append(self._extract_from_playlist_sxml(
827 playlist.get('progressiveDownloadUrl'), playlist_id, timestamp))
830 return self.playlist_result(entries, playlist_id, playlist_title, playlist_description)
832 # single video story (e.g. http://www.bbc.com/travel/story/20150625-sri-lankas-spicy-secret)
833 programme_id = self._search_regex(
834 [r'data-(?:video-player|media)-vpid="(%s)"' % self._ID_REGEX,
835 r'<param[^>]+name="externalIdentifier"[^>]+value="(%s)"' % self._ID_REGEX,
836 r'videoId\s*:\s*["\'](%s)["\']' % self._ID_REGEX],
837 webpage, 'vpid', default=None)
840 formats, subtitles = self._download_media_selector(programme_id)
841 self._sort_formats(formats)
842 # digitalData may be missing (e.g. http://www.bbc.com/autos/story/20130513-hyundais-rock-star)
843 digital_data = self._parse_json(
845 r'var\s+digitalData\s*=\s*({.+?});?\n', webpage, 'digital data', default='{}'),
846 programme_id, fatal=False)
847 page_info = digital_data.get('page', {}).get('pageInfo', {})
848 title = page_info.get('pageName') or self._og_search_title(webpage)
849 description = page_info.get('description') or self._og_search_description(webpage)
850 timestamp = parse_iso8601(page_info.get('publicationDate')) or timestamp
854 'description': description,
855 'timestamp': timestamp,
857 'subtitles': subtitles,
860 def extract_all(pattern):
861 return list(filter(None, map(
862 lambda s: self._parse_json(s, playlist_id, fatal=False),
863 re.findall(pattern, webpage))))
865 # Multiple video article (e.g.
866 # http://www.bbc.co.uk/blogs/adamcurtis/entries/3662a707-0af9-3149-963f-47bea720b460)
867 EMBED_URL = r'https?://(?:www\.)?bbc\.co\.uk/(?:[^/]+/)+%s(?:\b[^"]+)?' % self._ID_REGEX
869 for match in extract_all(r'new\s+SMP\(({.+?})\)'):
870 embed_url = match.get('playerSettings', {}).get('externalEmbedUrl')
871 if embed_url and re.match(EMBED_URL, embed_url):
872 entries.append(embed_url)
873 entries.extend(re.findall(
874 r'setPlaylist\("(%s)"\)' % EMBED_URL, webpage))
876 return self.playlist_result(
877 [self.url_result(entry, 'BBCCoUk') for entry in entries],
878 playlist_id, playlist_title, playlist_description)
880 # Multiple video article (e.g. http://www.bbc.com/news/world-europe-32668511)
881 medias = extract_all(r"data-media-meta='({[^']+})'")
884 # Single video article (e.g. http://www.bbc.com/news/video_and_audio/international)
885 media_asset = self._search_regex(
886 r'mediaAssetPage\.init\(\s*({.+?}), "/',
887 webpage, 'media asset', default=None)
889 media_asset_page = self._parse_json(media_asset, playlist_id, fatal=False)
891 for video in media_asset_page.get('videos', {}).values():
892 medias.extend(video.values())
895 # Multiple video playlist with single `now playing` entry (e.g.
896 # http://www.bbc.com/news/video_and_audio/must_see/33767813)
897 vxp_playlist = self._parse_json(
899 r'<script[^>]+class="vxp-playlist-data"[^>]+type="application/json"[^>]*>([^<]+)</script>',
900 webpage, 'playlist data'),
903 for item in vxp_playlist:
904 media = item.get('media')
907 playlist_medias.append(media)
908 # Download single video if found media with asset id matching the video id from URL
909 if item.get('advert', {}).get('assetId') == playlist_id:
912 # Fallback to the whole playlist
914 medias = playlist_medias
917 for num, media_meta in enumerate(medias, start=1):
918 formats, subtitles = self._extract_from_media_meta(media_meta, playlist_id)
921 self._sort_formats(formats)
923 video_id = media_meta.get('externalId')
925 video_id = playlist_id if len(medias) == 1 else '%s-%s' % (playlist_id, num)
927 title = media_meta.get('caption')
929 title = playlist_title if len(medias) == 1 else '%s - Video %s' % (playlist_title, num)
931 duration = int_or_none(media_meta.get('durationInSeconds')) or parse_duration(media_meta.get('duration'))
934 for image in media_meta.get('images', {}).values():
935 images.extend(image.values())
936 if 'image' in media_meta:
937 images.append(media_meta['image'])
940 'url': image.get('href'),
941 'width': int_or_none(image.get('width')),
942 'height': int_or_none(image.get('height')),
943 } for image in images]
948 'thumbnails': thumbnails,
949 'duration': duration,
950 'timestamp': timestamp,
952 'subtitles': subtitles,
955 return self.playlist_result(entries, playlist_id, playlist_title, playlist_description)
958 class BBCCoUkArticleIE(InfoExtractor):
959 _VALID_URL = r'https?://www.bbc.co.uk/programmes/articles/(?P<id>[a-zA-Z0-9]+)'
960 IE_NAME = 'bbc.co.uk:article'
961 IE_DESC = 'BBC articles'
964 'url': 'http://www.bbc.co.uk/programmes/articles/3jNQLTMrPlYGTBn0WV6M2MS/not-your-typical-role-model-ada-lovelace-the-19th-century-programmer',
966 'id': '3jNQLTMrPlYGTBn0WV6M2MS',
967 'title': 'Calculating Ada: The Countess of Computing - Not your typical role model: Ada Lovelace the 19th century programmer - BBC Four',
968 'description': 'Hannah Fry reveals some of her surprising discoveries about Ada Lovelace during filming.',
971 'add_ie': ['BBCCoUk'],
974 def _real_extract(self, url):
975 playlist_id = self._match_id(url)
977 webpage = self._download_webpage(url, playlist_id)
979 title = self._og_search_title(webpage)
980 description = self._og_search_description(webpage).strip()
982 entries = [self.url_result(programme_url) for programme_url in re.findall(
983 r'<div[^>]+typeof="Clip"[^>]+resource="([^"]+)"', webpage)]
985 return self.playlist_result(entries, playlist_id, title, description)
988 class BBCCoUkPlaylistBaseIE(InfoExtractor):
989 def _real_extract(self, url):
990 playlist_id = self._match_id(url)
992 webpage = self._download_webpage(url, playlist_id)
995 self.url_result(self._URL_TEMPLATE % video_id, BBCCoUkIE.ie_key())
996 for video_id in re.findall(
997 self._VIDEO_ID_TEMPLATE % BBCCoUkIE._ID_REGEX, webpage)]
999 title, description = self._extract_title_and_description(webpage)
1001 return self.playlist_result(entries, playlist_id, title, description)
1004 class BBCCoUkIPlayerPlaylistIE(BBCCoUkPlaylistBaseIE):
1005 IE_NAME = 'bbc.co.uk:iplayer:playlist'
1006 _VALID_URL = r'https?://(?:www\.)?bbc\.co\.uk/iplayer/episodes/(?P<id>%s)' % BBCCoUkIE._ID_REGEX
1007 _URL_TEMPLATE = 'http://www.bbc.co.uk/iplayer/episode/%s'
1008 _VIDEO_ID_TEMPLATE = r'data-ip-id=["\'](%s)'
1010 'url': 'http://www.bbc.co.uk/iplayer/episodes/b05rcz9v',
1013 'title': 'The Disappearance',
1014 'description': 'French thriller serial about a missing teenager.',
1016 'playlist_mincount': 6,
1019 def _extract_title_and_description(self, webpage):
1020 title = self._search_regex(r'<h1>([^<]+)</h1>', webpage, 'title', fatal=False)
1021 description = self._search_regex(
1022 r'<p[^>]+class=(["\'])subtitle\1[^>]*>(?P<value>[^<]+)</p>',
1023 webpage, 'description', fatal=False, group='value')
1024 return title, description
1027 class BBCCoUkPlaylistIE(BBCCoUkPlaylistBaseIE):
1028 IE_NAME = 'bbc.co.uk:playlist'
1029 _VALID_URL = r'https?://(?:www\.)?bbc\.co\.uk/programmes/(?P<id>%s)/(?:episodes|broadcasts|clips)' % BBCCoUkIE._ID_REGEX
1030 _URL_TEMPLATE = 'http://www.bbc.co.uk/programmes/%s'
1031 _VIDEO_ID_TEMPLATE = r'data-pid=["\'](%s)'
1033 'url': 'http://www.bbc.co.uk/programmes/b05rcz9v/clips',
1036 'title': 'The Disappearance - Clips - BBC Four',
1037 'description': 'French thriller serial about a missing teenager.',
1039 'playlist_mincount': 7,
1041 'url': 'http://www.bbc.co.uk/programmes/b05rcz9v/broadcasts/2016/06',
1042 'only_matching': True,
1044 'url': 'http://www.bbc.co.uk/programmes/b05rcz9v/clips',
1045 'only_matching': True,
1047 'url': 'http://www.bbc.co.uk/programmes/b055jkys/episodes/player',
1048 'only_matching': True,
1051 def _extract_title_and_description(self, webpage):
1052 title = self._og_search_title(webpage, fatal=False)
1053 description = self._og_search_description(webpage)
1054 return title, description