2 from __future__
import unicode_literals
7 from .common
import InfoExtractor
24 from ..compat
import (
31 class BBCCoUkIE(InfoExtractor
):
33 IE_DESC
= 'BBC iPlayer'
34 _ID_REGEX
= r
'(?:[pbm][\da-z]{7}|w[\da-z]{7,14})'
37 (?:www\.)?bbc\.co\.uk/
39 programmes/(?!articles/)|
40 iplayer(?:/[^/]+)?/(?:episode/|playlist/)|
41 music/(?:clips|audiovideo/popular)[/#]|
44 events/[^/]+/play/[^/]+/
46 (?P<id>%s)(?!/(?:episodes|broadcasts|clips))
49 _LOGIN_URL
= 'https://account.bbc.com/signin'
50 _NETRC_MACHINE
= 'bbc'
52 _MEDIA_SELECTOR_URL_TEMPL
= 'https://open.live.bbc.co.uk/mediaselector/6/select/version/2.0/mediaset/%s/vpid/%s'
54 # Provides HQ HLS streams with even better quality that pc mediaset but fails
55 # with geolocation in some cases when it's even not geo restricted at all (e.g.
56 # http://www.bbc.co.uk/programmes/b06bp7lf). Also may fail with selectionunavailable.
61 _EMP_PLAYLIST_NS
= 'http://bbc.co.uk/2008/emp/playlist'
65 'url': 'http://www.bbc.co.uk/programmes/b039g8p7',
69 'title': 'Kaleidoscope, Leonard Cohen',
70 'description': 'The Canadian poet and songwriter reflects on his musical career.',
74 'skip_download': True,
78 'url': 'http://www.bbc.co.uk/iplayer/episode/b00yng5w/The_Man_in_Black_Series_3_The_Printed_Name/',
82 'title': 'The Man in Black: Series 3: The Printed Name',
83 'description': "Mark Gatiss introduces Nicholas Pierpan's chilling tale of a writer's devilish pact with a mysterious man. Stars Ewan Bailey.",
88 'skip_download': True,
90 'skip': 'Episode is no longer available on BBC iPlayer Radio',
93 'url': 'http://www.bbc.co.uk/iplayer/episode/b03vhd1f/The_Voice_UK_Series_3_Blind_Auditions_5/',
97 'title': 'The Voice UK: Series 3: Blind Auditions 5',
98 '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.',
103 'skip_download': True,
105 'skip': 'Currently BBC iPlayer TV programmes are available to play in the UK only',
108 'url': 'http://www.bbc.co.uk/iplayer/episode/p026c7jt/tomorrows-worlds-the-unearthly-history-of-science-fiction-2-invasion',
112 'title': "Tomorrow's Worlds: The Unearthly History of Science Fiction",
113 'description': '2. Invasion',
118 'skip_download': True,
120 'skip': 'Currently BBC iPlayer TV programmes are available to play in the UK only',
122 'url': 'http://www.bbc.co.uk/programmes/b04v20dw',
126 'title': 'Pete Tong, The Essential New Tune Special',
127 'description': "Pete has a very special mix - all of 2014's Essential New Tunes!",
132 'skip_download': True,
134 'skip': 'Episode is no longer available on BBC iPlayer Radio',
136 'url': 'http://www.bbc.co.uk/music/clips/p022h44b',
141 'title': 'BBC Proms Music Guides, Rachmaninov: Symphonic Dances',
142 'description': "In this Proms Music Guide, Andrew McGregor looks at Rachmaninov's Symphonic Dances.",
147 'skip_download': True,
150 'url': 'http://www.bbc.co.uk/music/clips/p025c0zz',
155 'title': 'Reading and Leeds Festival, 2014, Rae Morris - Closer (Live on BBC Three)',
156 'description': 'Rae Morris performs Closer for BBC Three at Reading 2014',
161 'skip_download': True,
164 'url': 'http://www.bbc.co.uk/iplayer/episode/b054fn09/ad/natural-world-20152016-2-super-powered-owls',
168 'title': 'Natural World, 2015-2016: 2. Super Powered Owls',
169 'description': 'md5:e4db5c937d0e95a7c6b5e654d429183d',
174 'skip_download': True,
176 'skip': 'geolocation',
178 'url': 'http://www.bbc.co.uk/iplayer/episode/b05zmgwn/royal-academy-summer-exhibition',
182 '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.',
183 'title': 'Royal Academy Summer Exhibition',
188 'skip_download': True,
190 'skip': 'geolocation',
192 # iptv-all mediaset fails with geolocation however there is no geo restriction
193 # for this programme at all
194 'url': 'http://www.bbc.co.uk/programmes/b06rkn85',
198 'title': "Best of the Mini-Mixes 2015: Part 3, Annie Mac's Friday Night - BBC Radio 1",
199 'description': "Annie has part three in the Best of the Mini-Mixes 2015, plus the year's Most Played!",
203 'skip_download': True,
205 'skip': 'Now it\'s really geo-restricted',
207 # compact player (https://github.com/ytdl-org/youtube-dl/issues/8147)
208 'url': 'http://www.bbc.co.uk/programmes/p028bfkf/player',
212 'title': 'Extract from BBC documentary Look Stranger - Giant Leeks and Magic Brews',
213 'description': 'Extract from BBC documentary Look Stranger - Giant Leeks and Magic Brews',
217 'skip_download': True,
220 'url': 'https://www.bbc.co.uk/sounds/play/m0007jzb',
225 'title': 'BBC Proms, 2019, Prom 34: West–Eastern Divan Orchestra',
226 'description': "Live BBC Proms. West–Eastern Divan Orchestra with Daniel Barenboim and Martha Argerich.",
231 'skip_download': True,
234 'url': 'http://www.bbc.co.uk/iplayer/playlist/p01dvks4',
235 'only_matching': True,
237 'url': 'http://www.bbc.co.uk/music/clips#p02frcc3',
238 'only_matching': True,
240 'url': 'http://www.bbc.co.uk/iplayer/cbeebies/episode/b0480276/bing-14-atchoo',
241 'only_matching': True,
243 'url': 'http://www.bbc.co.uk/radio/player/p03cchwf',
244 'only_matching': True,
246 'url': 'https://www.bbc.co.uk/music/audiovideo/popular#p055bc55',
247 'only_matching': True,
249 'url': 'http://www.bbc.co.uk/programmes/w3csv1y9',
250 'only_matching': True,
252 'url': 'https://www.bbc.co.uk/programmes/m00005xn',
253 'only_matching': True,
255 'url': 'https://www.bbc.co.uk/programmes/w172w4dww1jqt5s',
256 'only_matching': True,
260 username
, password
= self
._get
_login
_info
()
264 login_page
= self
._download
_webpage
(
265 self
._LOGIN
_URL
, None, 'Downloading signin page')
267 login_form
= self
._hidden
_inputs
(login_page
)
270 'username': username
,
271 'password': password
,
274 post_url
= urljoin(self
._LOGIN
_URL
, self
._search
_regex
(
275 r
'<form[^>]+action=(["\'])(?P
<url
>.+?
)\
1', login_page,
276 'post url
', default=self._LOGIN_URL, group='url
'))
278 response, urlh = self._download_webpage_handle(
279 post_url, None, 'Logging
in', data=urlencode_postdata(login_form),
280 headers={'Referer': self._LOGIN_URL})
282 if self._LOGIN_URL in urlh.geturl():
283 error = clean_html(get_element_by_class('form
-message
', response))
285 raise ExtractorError(
286 'Unable to login
: %s' % error, expected=True)
287 raise ExtractorError('Unable to log
in')
289 def _real_initialize(self):
292 class MediaSelectionError(Exception):
293 def __init__(self, id):
296 def _extract_asx_playlist(self, connection, programme_id):
297 asx = self._download_xml(connection.get('href
'), programme_id, 'Downloading ASX playlist
')
298 return [ref.get('href
') for ref in asx.findall('./Entry
/ref
')]
300 def _extract_items(self, playlist):
301 return playlist.findall('./{%s}item
' % self._EMP_PLAYLIST_NS)
303 def _extract_medias(self, media_selection):
304 error = media_selection.get('result
')
306 raise BBCCoUkIE.MediaSelectionError(error)
307 return media_selection.get('media
') or []
309 def _extract_connections(self, media):
310 return media.get('connection
') or []
312 def _get_subtitles(self, media, programme_id):
314 for connection in self._extract_connections(media):
315 cc_url = url_or_none(connection.get('href
'))
318 captions = self._download_xml(
319 cc_url, programme_id, 'Downloading captions
', fatal=False)
320 if not isinstance(captions, compat_etree_Element):
324 'url
': connection.get('href
'),
331 def _raise_extractor_error(self, media_selection_error):
332 raise ExtractorError(
333 '%s returned error
: %s' % (self.IE_NAME, media_selection_error.id),
336 def _download_media_selector(self, programme_id):
337 last_exception = None
338 for media_set in self._MEDIA_SETS:
340 return self._download_media_selector_url(
341 self._MEDIA_SELECTOR_URL_TEMPL % (media_set, programme_id), programme_id)
342 except BBCCoUkIE.MediaSelectionError as e:
343 if e.id in ('notukerror
', 'geolocation
', 'selectionunavailable
'):
346 self._raise_extractor_error(e)
347 self._raise_extractor_error(last_exception)
349 def _download_media_selector_url(self, url, programme_id=None):
350 media_selection = self._download_json(
351 url, programme_id, 'Downloading media selection JSON
',
352 expected_status=(403, 404))
353 return self._process_media_selector(media_selection, programme_id)
355 def _process_media_selector(self, media_selection, programme_id):
360 for media in self._extract_medias(media_selection):
361 kind = media.get('kind
')
362 if kind in ('video
', 'audio
'):
363 bitrate = int_or_none(media.get('bitrate
'))
364 encoding = media.get('encoding
')
365 width = int_or_none(media.get('width
'))
366 height = int_or_none(media.get('height
'))
367 file_size = int_or_none(media.get('media_file_size
'))
368 for connection in self._extract_connections(media):
369 href = connection.get('href
')
374 conn_kind = connection.get('kind
')
375 protocol = connection.get('protocol
')
376 supplier = connection.get('supplier
')
377 transfer_format = connection.get('transferFormat
')
378 format_id = supplier or conn_kind or protocol
380 if supplier == 'asx
':
381 for i, ref in enumerate(self._extract_asx_playlist(connection, programme_id)):
384 'format_id
': 'ref
%s_%s' % (i, format_id),
386 elif transfer_format == 'dash
':
387 formats.extend(self._extract_mpd_formats(
388 href, programme_id, mpd_id=format_id, fatal=False))
389 elif transfer_format == 'hls
':
390 formats.extend(self._extract_m3u8_formats(
391 href, programme_id, ext='mp4
', entry_protocol='m3u8_native
',
392 m3u8_id=format_id, fatal=False))
393 elif transfer_format == 'hds
':
394 formats.extend(self._extract_f4m_formats(
395 href, programme_id, f4m_id=format_id, fatal=False))
397 if not supplier and bitrate:
398 format_id += '-%d' % bitrate
400 'format_id
': format_id,
401 'filesize
': file_size,
416 if protocol in ('http
', 'https
'):
421 elif protocol == 'rtmp
':
422 application = connection.get('application
', 'ondemand
')
423 auth_string = connection.get('authString
')
424 identifier = connection.get('identifier
')
425 server = connection.get('server
')
427 'url
': '%s://%s/%s?
%s' % (protocol, server, application, auth_string),
428 'play_path
': identifier,
429 'app
': '%s?
%s' % (application, auth_string),
430 'page_url
': 'http
://www
.bbc
.co
.uk
',
431 'player_url
': 'http
://www
.bbc
.co
.uk
/emp
/releases
/iplayer
/revisions
/617463_618125_4/617463_618125_4_emp
.swf
',
438 elif kind == 'captions
':
439 subtitles = self.extract_subtitles(media, programme_id)
440 return formats, subtitles
442 def _download_playlist(self, playlist_id):
444 playlist = self._download_json(
445 'http
://www
.bbc
.co
.uk
/programmes
/%s/playlist
.json
' % playlist_id,
446 playlist_id, 'Downloading playlist JSON
')
448 version = playlist.get('defaultAvailableVersion
')
450 smp_config = version['smpConfig
']
451 title = smp_config['title
']
452 description = smp_config['summary
']
453 for item in smp_config['items
']:
455 if kind not in ('programme
', 'radioProgramme
'):
457 programme_id = item.get('vpid
')
458 duration = int_or_none(item.get('duration
'))
459 formats, subtitles = self._download_media_selector(programme_id)
460 return programme_id, title, description, duration, formats, subtitles
461 except ExtractorError as ee:
462 if not (isinstance(ee.cause, compat_HTTPError) and ee.cause.code == 404):
465 # fallback to legacy playlist
466 return self._process_legacy_playlist(playlist_id)
468 def _process_legacy_playlist_url(self, url, display_id):
469 playlist = self._download_legacy_playlist_url(url, display_id)
470 return self._extract_from_legacy_playlist(playlist, display_id)
472 def _process_legacy_playlist(self, playlist_id):
473 return self._process_legacy_playlist_url(
474 'http
://www
.bbc
.co
.uk
/iplayer
/playlist
/%s' % playlist_id, playlist_id)
476 def _download_legacy_playlist_url(self, url, playlist_id=None):
477 return self._download_xml(
478 url, playlist_id, 'Downloading legacy playlist XML
')
480 def _extract_from_legacy_playlist(self, playlist, playlist_id):
481 no_items = playlist.find('./{%s}noItems
' % self._EMP_PLAYLIST_NS)
482 if no_items is not None:
483 reason = no_items.get('reason
')
484 if reason == 'preAvailability
':
485 msg = 'Episode
%s is not yet available
' % playlist_id
486 elif reason == 'postAvailability
':
487 msg = 'Episode
%s is no longer available
' % playlist_id
488 elif reason == 'noMedia
':
489 msg = 'Episode
%s is not currently available
' % playlist_id
491 msg = 'Episode
%s is not available
: %s' % (playlist_id, reason)
492 raise ExtractorError(msg, expected=True)
494 for item in self._extract_items(playlist):
495 kind = item.get('kind
')
496 if kind not in ('programme
', 'radioProgramme
'):
498 title = playlist.find('./{%s}title
' % self._EMP_PLAYLIST_NS).text
499 description_el = playlist.find('./{%s}summary
' % self._EMP_PLAYLIST_NS)
500 description = description_el.text if description_el is not None else None
502 def get_programme_id(item):
503 def get_from_attributes(item):
504 for p in ('identifier
', 'group
'):
506 if value and re.match(r'^
[pb
][\da
-z
]{7}$
', value):
508 get_from_attributes(item)
509 mediator = item.find('./{%s}mediator
' % self._EMP_PLAYLIST_NS)
510 if mediator is not None:
511 return get_from_attributes(mediator)
513 programme_id = get_programme_id(item)
514 duration = int_or_none(item.get('duration
'))
517 formats, subtitles = self._download_media_selector(programme_id)
519 formats, subtitles = self._process_media_selector(item, playlist_id)
520 programme_id = playlist_id
522 return programme_id, title, description, duration, formats, subtitles
524 def _real_extract(self, url):
525 group_id = self._match_id(url)
527 webpage = self._download_webpage(url, group_id, 'Downloading video page
')
529 error = self._search_regex(
530 r'<div
\b[^
>]+\bclass
=["\'](?:smp|playout)__message delta["\'][^
>]*>\s
*([^
<]+?
)\s
*<',
531 webpage, 'error
', default=None)
533 raise ExtractorError(error, expected=True)
538 tviplayer = self._search_regex(
539 r'mediator\
.bind\
(({.+?}
)\s
*,\s
*document\
.getElementById
',
540 webpage, 'player
', default=None)
543 player = self._parse_json(tviplayer, group_id).get('player
', {})
544 duration = int_or_none(player.get('duration
'))
545 programme_id = player.get('vpid
')
548 programme_id = self._search_regex(
549 r'"vpid"\s
*:\s
*"(%s)"' % self._ID_REGEX, webpage, 'vpid
', fatal=False, default=None)
552 formats, subtitles = self._download_media_selector(programme_id)
553 title = self._og_search_title(webpage, default=None) or self._html_search_regex(
554 (r'<h2
[^
>]+id="parent-title"[^
>]*>(.+?
)</h2
>',
555 r'<div
[^
>]+class="info"[^
>]*>\s
*<h1
>(.+?
)</h1
>'), webpage, 'title
')
556 description = self._search_regex(
557 (r'<p
class="[^"]*medium
-description
[^
"]*">([^
<]+)</p
>',
558 r'<div
[^
>]+class="info_+synopsis"[^
>]*>([^
<]+)</div
>'),
559 webpage, 'description
', default=None)
561 description = self._html_search_meta('description
', webpage)
563 programme_id, title, description, duration, formats, subtitles = self._download_playlist(group_id)
565 self._sort_formats(formats)
570 'description
': description,
571 'thumbnail
': self._og_search_thumbnail(webpage, default=None),
572 'duration
': duration,
574 'subtitles
': subtitles,
578 class BBCIE(BBCCoUkIE):
581 _VALID_URL = r'https?
://(?
:www\
.)?bbc\
.(?
:com|co\
.uk
)/(?
:[^
/]+/)+(?P
<id>[^
/#?]+)'
584 'mobile-tablet-main',
589 # article with multiple videos embedded with data-playable containing vpids
590 'url': 'http://www.bbc.com/news/world-europe-32668511',
592 'id': 'world-europe-32668511',
593 'title': 'Russia stages massive WW2 parade',
594 'description': 'md5:00ff61976f6081841f759a08bf78cc9c',
598 # article with multiple videos embedded with data-playable (more videos)
599 'url': 'http://www.bbc.com/news/business-28299555',
601 'id': 'business-28299555',
602 'title': 'Farnborough Airshow: Video highlights',
603 'description': 'BBC reports and video highlights at the Farnborough Airshow.',
608 # article with multiple videos embedded with `new SMP()`
610 'url': 'http://www.bbc.co.uk/blogs/adamcurtis/entries/3662a707-0af9-3149-963f-47bea720b460',
612 'id': '3662a707-0af9-3149-963f-47bea720b460',
615 'playlist_count': 18,
617 # single video embedded with data-playable containing vpid
618 'url': 'http://www.bbc.com/news/world-europe-32041533',
622 'title': 'Aerial footage showed the site of the crash in the Alps - courtesy BFM TV',
623 'description': 'md5:2868290467291b37feda7863f7a83f54',
625 'timestamp': 1427219242,
626 'upload_date': '20150324',
630 'skip_download': True,
633 # article with single video embedded with data-playable containing XML playlist
634 # with direct video links as progressiveDownloadUrl (for now these are extracted)
635 # and playlist with f4m and m3u8 as streamingUrl
636 'url': 'http://www.bbc.com/turkce/haberler/2015/06/150615_telabyad_kentin_cogu',
638 'id': '150615_telabyad_kentin_cogu',
640 'title': "YPG: Tel Abyad'ın tamamı kontrolümüzde",
641 'description': 'md5:33a4805a855c9baf7115fcbde57e7025',
642 'timestamp': 1434397334,
643 'upload_date': '20150615',
646 'skip_download': True,
649 # single video embedded with data-playable containing XML playlists (regional section)
650 'url': 'http://www.bbc.com/mundo/video_fotos/2015/06/150619_video_honduras_militares_hospitales_corrupcion_aw',
652 'id': '150619_video_honduras_militares_hospitales_corrupcion_aw',
654 'title': 'Honduras militariza sus hospitales por nuevo escándalo de corrupción',
655 'description': 'md5:1525f17448c4ee262b64b8f0c9ce66c8',
656 'timestamp': 1434713142,
657 'upload_date': '20150619',
660 'skip_download': True,
663 # single video from video playlist embedded with vxp-playlist-data JSON
664 'url': 'http://www.bbc.com/news/video_and_audio/must_see/33376376',
668 'title': '''Judge Mindy Glazer: "I'm sorry to see you here... I always wondered what happened to you"''',
670 'description': '''Judge Mindy Glazer: "I'm sorry to see you here... I always wondered what happened to you"''',
673 'skip_download': True,
676 # single video story with digitalData
677 'url': 'http://www.bbc.com/travel/story/20150625-sri-lankas-spicy-secret',
681 'title': 'Sri Lanka’s spicy secret',
682 'description': 'As a new train line to Jaffna opens up the country’s north, travellers can experience a truly distinct slice of Tamil culture.',
683 'timestamp': 1437674293,
684 'upload_date': '20150723',
688 'skip_download': True,
691 # single video story without digitalData
692 'url': 'http://www.bbc.com/autos/story/20130513-hyundais-rock-star',
696 'title': 'Hyundai Santa Fe Sport: Rock star',
697 'description': 'md5:b042a26142c4154a6e472933cf20793d',
698 'timestamp': 1415867444,
699 'upload_date': '20141113',
703 'skip_download': True,
706 # single video embedded with Morph
707 'url': 'http://www.bbc.co.uk/sport/live/olympics/36895975',
711 'title': "Nigeria v Japan - Men's First Round",
712 'description': 'Live coverage of the first round from Group B at the Amazonia Arena.',
714 'uploader': 'BBC Sport',
715 'uploader_id': 'bbc_sport',
719 'skip_download': True,
721 'skip': 'Georestricted to UK',
723 # single video with playlist.sxml URL in playlist param
724 'url': 'http://www.bbc.com/sport/0/football/33653409',
728 'title': 'Transfers: Cristiano Ronaldo to Man Utd, Arsenal to spend?',
729 'description': 'BBC Sport\'s David Ornstein has the latest transfer gossip, including rumours of a Manchester United return for Cristiano Ronaldo.',
734 'skip_download': True,
737 # article with multiple videos embedded with playlist.sxml in playlist param
738 'url': 'http://www.bbc.com/sport/0/football/34475836',
741 'title': 'Jurgen Klopp: Furious football from a witty and winning coach',
742 'description': 'Fast-paced football, wit, wisdom and a ready smile - why Liverpool fans should come to love new boss Jurgen Klopp.',
746 # school report article with single video
747 'url': 'http://www.bbc.co.uk/schoolreport/35744779',
750 'title': 'School which breaks down barriers in Jerusalem',
754 # single video with playlist URL from weather section
755 'url': 'http://www.bbc.com/weather/features/33601775',
756 'only_matching': True,
758 # custom redirection to www.bbc.com
759 'url': 'http://www.bbc.co.uk/news/science-environment-33661876',
760 'only_matching': True,
762 # single video article embedded with data-media-vpid
763 'url': 'http://www.bbc.co.uk/sport/rowing/35908187',
764 'only_matching': True,
766 'url': 'https://www.bbc.co.uk/bbcthree/clip/73d0bbd0-abc3-4cea-b3c0-cdae21905eb1',
770 'title': 'Transfers: Cristiano Ronaldo to Man Utd, Arsenal to spend?',
771 'description': 'md5:4b7dfd063d5a789a1512e99662be3ddd',
774 'skip_download': True,
777 # window.__PRELOADED_STATE__
778 'url': 'https://www.bbc.co.uk/radio/play/b0b9z4yl',
782 'title': 'Prom 6: An American in Paris and Turangalila',
783 'description': 'md5:51cf7d6f5c8553f197e58203bc78dff8',
784 'uploader': 'Radio 3',
785 'uploader_id': 'bbc_radio_three',
788 'url': 'http://www.bbc.co.uk/learningenglish/chinese/features/lingohack/ep-181227',
792 'title': 'md5:2fabf12a726603193a2879a055f72514',
793 'description': 'Learn English words and phrases from this story',
795 'add_ie': [BBCCoUkIE
.ie_key()],
799 def suitable(cls
, url
):
800 EXCLUDE_IE
= (BBCCoUkIE
, BBCCoUkArticleIE
, BBCCoUkIPlayerPlaylistIE
, BBCCoUkPlaylistIE
)
801 return (False if any(ie
.suitable(url
) for ie
in EXCLUDE_IE
)
802 else super(BBCIE
, cls
).suitable(url
))
804 def _extract_from_media_meta(self
, media_meta
, video_id
):
805 # Direct links to media in media metadata (e.g.
806 # http://www.bbc.com/turkce/haberler/2015/06/150615_telabyad_kentin_cogu)
807 # TODO: there are also f4m and m3u8 streams incorporated in playlist.sxml
808 source_files
= media_meta
.get('sourceFiles')
812 'format_id': format_id
,
813 'ext': f
.get('encoding'),
814 'tbr': float_or_none(f
.get('bitrate'), 1000),
815 'filesize': int_or_none(f
.get('filesize')),
816 } for format_id
, f
in source_files
.items() if f
.get('url')], []
818 programme_id
= media_meta
.get('externalId')
820 return self
._download
_media
_selector
(programme_id
)
822 # Process playlist.sxml as legacy playlist
823 href
= media_meta
.get('href')
825 playlist
= self
._download
_legacy
_playlist
_url
(href
)
826 _
, _
, _
, _
, formats
, subtitles
= self
._extract
_from
_legacy
_playlist
(playlist
, video_id
)
827 return formats
, subtitles
831 def _extract_from_playlist_sxml(self
, url
, playlist_id
, timestamp
):
832 programme_id
, title
, description
, duration
, formats
, subtitles
= \
833 self
._process
_legacy
_playlist
_url
(url
, playlist_id
)
834 self
._sort
_formats
(formats
)
838 'description': description
,
839 'duration': duration
,
840 'timestamp': timestamp
,
842 'subtitles': subtitles
,
845 def _real_extract(self
, url
):
846 playlist_id
= self
._match
_id
(url
)
848 webpage
= self
._download
_webpage
(url
, playlist_id
)
850 json_ld_info
= self
._search
_json
_ld
(webpage
, playlist_id
, default
={})
851 timestamp
= json_ld_info
.get('timestamp')
853 playlist_title
= json_ld_info
.get('title')
854 if not playlist_title
:
855 playlist_title
= self
._og
_search
_title
(
856 webpage
, default
=None) or self
._html
_search
_regex
(
857 r
'<title>(.+?)</title>', webpage
, 'playlist title', default
=None)
859 playlist_title
= re
.sub(r
'(.+)\s*-\s*BBC.*?$', r
'\1', playlist_title
).strip()
861 playlist_description
= json_ld_info
.get(
862 'description') or self
._og
_search
_description
(webpage
, default
=None)
865 timestamp
= parse_iso8601(self
._search
_regex
(
866 [r
'<meta[^>]+property="article:published_time"[^>]+content="([^"]+)"',
867 r
'itemprop="datePublished"[^>]+datetime="([^"]+)"',
868 r
'"datePublished":\s*"([^"]+)'],
869 webpage
, 'date', default
=None))
873 # article with multiple videos embedded with playlist.sxml (e.g.
874 # http://www.bbc.com/sport/0/football/34475836)
875 playlists
= re
.findall(r
'<param[^>]+name="playlist"[^>]+value="([^"]+)"', webpage
)
876 playlists
.extend(re
.findall(r
'data-media-id="([^"]+/playlist\.sxml)"', webpage
))
879 self
._extract
_from
_playlist
_sxml
(playlist_url
, playlist_id
, timestamp
)
880 for playlist_url
in playlists
]
882 # news article with multiple videos embedded with data-playable
883 data_playables
= re
.findall(r
'data-playable=(["\'])({.+?}
)\
1', webpage)
885 for _, data_playable_json in data_playables:
886 data_playable = self._parse_json(
887 unescapeHTML(data_playable_json), playlist_id, fatal=False)
888 if not data_playable:
890 settings = data_playable.get('settings
', {})
892 # data-playable with video vpid in settings.playlistObject.items (e.g.
893 # http://www.bbc.com/news/world-us-canada-34473351)
894 playlist_object = settings.get('playlistObject
', {})
896 items = playlist_object.get('items
')
897 if items and isinstance(items, list):
898 title = playlist_object['title
']
899 description = playlist_object.get('summary
')
900 duration = int_or_none(items[0].get('duration
'))
901 programme_id = items[0].get('vpid
')
902 formats, subtitles = self._download_media_selector(programme_id)
903 self._sort_formats(formats)
907 'description
': description,
908 'timestamp
': timestamp,
909 'duration
': duration,
911 'subtitles
': subtitles,
914 # data-playable without vpid but with a playlist.sxml URLs
915 # in otherSettings.playlist (e.g.
916 # http://www.bbc.com/turkce/multimedya/2015/10/151010_vid_ankara_patlama_ani)
917 playlist = data_playable.get('otherSettings
', {}).get('playlist', {})
920 for key in ('streaming
', 'progressiveDownload
'):
921 playlist_url = playlist.get('%sUrl
' % key)
925 info = self._extract_from_playlist_sxml(
926 playlist_url, playlist_id, timestamp)
930 entry['title
'] = info['title
']
931 entry['formats
'].extend(info['formats
'])
932 except Exception as e:
933 # Some playlist URL may fail with 500, at the same time
934 # the other one may work fine (e.g.
935 # http://www.bbc.com/turkce/haberler/2015/06/150615_telabyad_kentin_cogu)
936 if isinstance(e.cause, compat_HTTPError) and e.cause.code == 500:
940 self._sort_formats(entry['formats
'])
941 entries.append(entry)
944 return self.playlist_result(entries, playlist_id, playlist_title, playlist_description)
946 # http://www.bbc.co.uk/learningenglish/chinese/features/lingohack/ep-181227
947 group_id = self._search_regex(
948 r'<div
[^
>]+\bclass
=["\']video["\'][^
>]+\bdata
-pid
=["\'](%s)' % self._ID_REGEX,
949 webpage, 'group id', default=None)
951 return self.url_result(
952 'https://www.bbc.co.uk/programmes/%s' % group_id,
953 ie=BBCCoUkIE.ie_key())
955 # single video story (e.g. http://www.bbc.com/travel/story/20150625-sri-lankas-spicy-secret)
956 programme_id = self._search_regex(
957 [r'data-(?:video-player|media)-vpid="(%s)"' % self._ID_REGEX,
958 r'<param[^>]+name="externalIdentifier
"[^>]+value="(%s)"' % self._ID_REGEX,
959 r'videoId\s*:\s*["\'](%s)["\']' % self._ID_REGEX],
960 webpage, 'vpid', default=None)
963 formats, subtitles = self._download_media_selector(programme_id)
964 self._sort_formats(formats)
965 # digitalData may be missing (e.g. http://www.bbc.com/autos/story/20130513-hyundais-rock-star)
966 digital_data = self._parse_json(
968 r'var\s+digitalData\s*=\s*({.+?});?\n', webpage, 'digital data', default='{}'),
969 programme_id, fatal=False)
970 page_info = digital_data.get('page', {}).get('pageInfo', {})
971 title = page_info.get('pageName') or self._og_search_title(webpage)
972 description = page_info.get('description') or self._og_search_description(webpage)
973 timestamp = parse_iso8601(page_info.get('publicationDate')) or timestamp
977 'description': description,
978 'timestamp': timestamp,
980 'subtitles': subtitles,
983 # Morph based embed (e.g. http://www.bbc.co.uk/sport/live/olympics/36895975)
984 # There are several setPayload calls may be present but the video
985 # seems to be always related to the first one
986 morph_payload = self._parse_json(
988 r'Morph\.setPayload\([^,]+,\s*({.+?})\);',
989 webpage, 'morph payload', default='{}'),
990 playlist_id, fatal=False)
992 components = try_get(morph_payload, lambda x: x['body']['components'], list) or []
993 for component in components:
994 if not isinstance(component, dict):
996 lead_media = try_get(component, lambda x: x['props']['leadMedia'], dict)
999 identifiers = lead_media.get('identifiers')
1000 if not identifiers or not isinstance(identifiers, dict):
1002 programme_id = identifiers.get('vpid') or identifiers.get('playablePid')
1003 if not programme_id:
1005 title = lead_media.get('title') or self._og_search_title(webpage)
1006 formats, subtitles = self._download_media_selector(programme_id)
1007 self._sort_formats(formats)
1008 description = lead_media.get('summary')
1009 uploader = lead_media.get('masterBrand')
1010 uploader_id = lead_media.get('mid')
1012 duration_d = lead_media.get('duration')
1013 if isinstance(duration_d, dict):
1014 duration = parse_duration(dict_get(
1015 duration_d, ('rawDuration', 'formattedDuration', 'spokenDuration')))
1019 'description': description,
1020 'duration': duration,
1021 'uploader': uploader,
1022 'uploader_id': uploader_id,
1024 'subtitles': subtitles,
1027 preload_state = self._parse_json(self._search_regex(
1028 r'window\.__PRELOADED_STATE__\s*=\s*({.+?});', webpage,
1029 'preload state', default='{}'), playlist_id, fatal=False)
1031 current_programme = preload_state.get('programmes', {}).get('current') or {}
1032 programme_id = current_programme.get('id')
1033 if current_programme and programme_id and current_programme.get('type') == 'playable_item':
1034 title = current_programme.get('titles', {}).get('tertiary') or playlist_title
1035 formats, subtitles = self._download_media_selector(programme_id)
1036 self._sort_formats(formats)
1037 synopses = current_programme.get('synopses') or {}
1038 network = current_programme.get('network') or {}
1039 duration = int_or_none(
1040 current_programme.get('duration', {}).get('value'))
1042 image_url = current_programme.get('image_url')
1044 thumbnail = image_url.replace('{recipe}', '1920x1920')
1048 'description': dict_get(synopses, ('long', 'medium', 'short')),
1049 'thumbnail': thumbnail,
1050 'duration': duration,
1051 'uploader': network.get('short_title'),
1052 'uploader_id': network.get('id'),
1054 'subtitles': subtitles,
1057 bbc3_config = self._parse_json(
1059 r'(?s)bbcthreeConfig\s*=\s*({.+?})\s*;\s*<', webpage,
1060 'bbcthree config', default='{}'),
1061 playlist_id, transform_source=js_to_json, fatal=False) or {}
1062 payload = bbc3_config.get('payload') or {}
1064 clip = payload.get('currentClip') or {}
1065 clip_vpid = clip.get('vpid')
1066 clip_title = clip.get('title')
1067 if clip_vpid and clip_title:
1068 formats, subtitles = self._download_media_selector(clip_vpid)
1069 self._sort_formats(formats)
1072 'title': clip_title,
1073 'thumbnail': dict_get(clip, ('poster', 'imageUrl')),
1074 'description': clip.get('description'),
1075 'duration': parse_duration(clip.get('duration')),
1077 'subtitles': subtitles,
1079 bbc3_playlist = try_get(
1080 payload, lambda x: x['content']['bbcMedia']['playlist'],
1083 playlist_title = bbc3_playlist.get('title') or playlist_title
1084 thumbnail = bbc3_playlist.get('holdingImageURL')
1086 for bbc3_item in bbc3_playlist['items']:
1087 programme_id = bbc3_item.get('versionID')
1088 if not programme_id:
1090 formats, subtitles = self._download_media_selector(programme_id)
1091 self._sort_formats(formats)
1094 'title': playlist_title,
1095 'thumbnail': thumbnail,
1096 'timestamp': timestamp,
1098 'subtitles': subtitles,
1100 return self.playlist_result(
1101 entries, playlist_id, playlist_title, playlist_description)
1103 initial_data = self._parse_json(self._search_regex(
1104 r'window\.__INITIAL_DATA__\s*=\s*({.+?});', webpage,
1105 'preload state', default='{}'), playlist_id, fatal=False)
1107 def parse_media(media):
1110 for item in (try_get(media, lambda x: x['media']['items'], list) or []):
1111 item_id = item.get('id')
1112 item_title = item.get('title')
1113 if not (item_id and item_title):
1115 formats, subtitles = self._download_media_selector(item_id)
1116 self._sort_formats(formats)
1119 'title': item_title,
1120 'thumbnail': item.get('holdingImageUrl'),
1122 'subtitles': subtitles,
1124 for resp in (initial_data.get('data') or {}).values():
1125 name = resp.get('name')
1126 if name == 'media-experience':
1127 parse_media(try_get(resp, lambda x: x['data']['initialItem']['mediaItem'], dict))
1128 elif name == 'article':
1129 for block in (try_get(resp, lambda x: x['data']['blocks'], list) or []):
1130 if block.get('type') != 'media':
1132 parse_media(block.get('model'))
1133 return self.playlist_result(
1134 entries, playlist_id, playlist_title, playlist_description)
1136 def extract_all(pattern):
1137 return list(filter(None, map(
1138 lambda s: self._parse_json(s, playlist_id, fatal=False),
1139 re.findall(pattern, webpage))))
1141 # Multiple video article (e.g.
1142 # http://www.bbc.co.uk/blogs/adamcurtis/entries/3662a707-0af9-3149-963f-47bea720b460)
1143 EMBED_URL = r'https?://(?:www\.)?bbc\.co\.uk/(?:[^/]+/)+%s(?:\b[^"]+)?
' % self._ID_REGEX
1145 for match in extract_all(r'new\s
+SMP\
(({.+?}
)\
)'):
1146 embed_url = match.get('playerSettings
', {}).get('externalEmbedUrl
')
1147 if embed_url and re.match(EMBED_URL, embed_url):
1148 entries.append(embed_url)
1149 entries.extend(re.findall(
1150 r'setPlaylist\
("(%s)"\
)' % EMBED_URL, webpage))
1152 return self.playlist_result(
1153 [self.url_result(entry_, 'BBCCoUk
') for entry_ in entries],
1154 playlist_id, playlist_title, playlist_description)
1156 # Multiple video article (e.g. http://www.bbc.com/news/world-europe-32668511)
1157 medias = extract_all(r"data-media-meta='({[^']+}
)'")
1160 # Single video article (e.g. http://www.bbc.com/news/video_and_audio/international)
1161 media_asset = self._search_regex(
1162 r'mediaAssetPage\
.init\
(\s
*({.+?}
), "/',
1163 webpage, 'media asset', default=None)
1165 media_asset_page = self._parse_json(media_asset, playlist_id, fatal=False)
1167 for video in media_asset_page.get('videos', {}).values():
1168 medias.extend(video.values())
1171 # Multiple video playlist with single `now playing` entry (e.g.
1172 # http://www.bbc.com/news/video_and_audio/must_see/33767813)
1173 vxp_playlist = self._parse_json(
1175 r'<script[^>]+class="vxp
-playlist
-data
"[^>]+type="application
/json
"[^>]*>([^<]+)</script>',
1176 webpage, 'playlist data'),
1178 playlist_medias = []
1179 for item in vxp_playlist:
1180 media = item.get('media')
1183 playlist_medias.append(media)
1184 # Download single video if found media with asset id matching the video id from URL
1185 if item.get('advert', {}).get('assetId') == playlist_id:
1188 # Fallback to the whole playlist
1190 medias = playlist_medias
1193 for num, media_meta in enumerate(medias, start=1):
1194 formats, subtitles = self._extract_from_media_meta(media_meta, playlist_id)
1197 self._sort_formats(formats)
1199 video_id = media_meta.get('externalId')
1201 video_id = playlist_id if len(medias) == 1 else '%s-%s' % (playlist_id, num)
1203 title = media_meta.get('caption')
1205 title = playlist_title if len(medias) == 1 else '%s - Video %s' % (playlist_title, num)
1207 duration = int_or_none(media_meta.get('durationInSeconds')) or parse_duration(media_meta.get('duration'))
1210 for image in media_meta.get('images', {}).values():
1211 images.extend(image.values())
1212 if 'image' in media_meta:
1213 images.append(media_meta['image'])
1216 'url': image.get('href'),
1217 'width': int_or_none(image.get('width')),
1218 'height': int_or_none(image.get('height')),
1219 } for image in images]
1224 'thumbnails': thumbnails,
1225 'duration': duration,
1226 'timestamp': timestamp,
1228 'subtitles': subtitles,
1231 return self.playlist_result(entries, playlist_id, playlist_title, playlist_description)
1234 class BBCCoUkArticleIE(InfoExtractor):
1235 _VALID_URL = r'https?://(?:www\.)?bbc\.co\.uk/programmes/articles/(?P<id>[a-zA-Z0-9]+)'
1236 IE_NAME = 'bbc.co.uk:article'
1237 IE_DESC = 'BBC articles'
1240 'url': 'http://www.bbc.co.uk/programmes/articles/3jNQLTMrPlYGTBn0WV6M2MS/not-your-typical-role-model-ada-lovelace-the-19th-century-programmer',
1242 'id': '3jNQLTMrPlYGTBn0WV6M2MS',
1243 'title': 'Calculating Ada: The Countess of Computing - Not your typical role model: Ada Lovelace the 19th century programmer - BBC Four',
1244 'description': 'Hannah Fry reveals some of her surprising discoveries about Ada Lovelace during filming.',
1246 'playlist_count': 4,
1247 'add_ie': ['BBCCoUk'],
1250 def _real_extract(self, url):
1251 playlist_id = self._match_id(url)
1253 webpage = self._download_webpage(url, playlist_id)
1255 title = self._og_search_title(webpage)
1256 description = self._og_search_description(webpage).strip()
1258 entries = [self.url_result(programme_url) for programme_url in re.findall(
1259 r'<div[^>]+typeof="Clip
"[^>]+resource="([^
"]+)"', webpage)]
1261 return self.playlist_result(entries, playlist_id, title, description)
1264 class BBCCoUkPlaylistBaseIE(InfoExtractor):
1265 def _entries(self, webpage, url, playlist_id):
1266 single_page = 'page
' in compat_urlparse.parse_qs(
1267 compat_urlparse.urlparse(url).query)
1268 for page_num in itertools.count(2):
1269 for video_id in re.findall(
1270 self._VIDEO_ID_TEMPLATE % BBCCoUkIE._ID_REGEX, webpage):
1271 yield self.url_result(
1272 self._URL_TEMPLATE % video_id, BBCCoUkIE.ie_key())
1275 next_page = self._search_regex(
1276 r'<li
[^
>]+class=(["\'])pagination_+next\1[^>]*><a[^>]+href=(["\'])(?P
<url
>(?
:(?
!\
2).)+)\
2',
1277 webpage, 'next page url
', default=None, group='url
')
1280 webpage = self._download_webpage(
1281 compat_urlparse.urljoin(url, next_page), playlist_id,
1282 'Downloading page
%d' % page_num, page_num)
1284 def _real_extract(self, url):
1285 playlist_id = self._match_id(url)
1287 webpage = self._download_webpage(url, playlist_id)
1289 title, description = self._extract_title_and_description(webpage)
1291 return self.playlist_result(
1292 self._entries(webpage, url, playlist_id),
1293 playlist_id, title, description)
1296 class BBCCoUkIPlayerPlaylistIE(BBCCoUkPlaylistBaseIE):
1297 IE_NAME = 'bbc
.co
.uk
:iplayer
:playlist
'
1298 _VALID_URL = r'https?
://(?
:www\
.)?bbc\
.co\
.uk
/iplayer
/(?
:episodes|group
)/(?P
<id>%s)' % BBCCoUkIE._ID_REGEX
1299 _URL_TEMPLATE = 'http
://www
.bbc
.co
.uk
/iplayer
/episode
/%s'
1300 _VIDEO_ID_TEMPLATE = r'data
-ip
-id=["\'](%s)'
1302 'url': 'http://www.bbc.co.uk/iplayer/episodes/b05rcz9v',
1305 'title': 'The Disappearance',
1306 'description': 'French thriller serial about a missing teenager.',
1308 'playlist_mincount': 6,
1309 'skip': 'This programme is not currently available on BBC iPlayer',
1311 # Available for over a year unlike 30 days for most other programmes
1312 'url': 'http://www.bbc.co.uk/iplayer/group/p02tcc32',
1315 'title': 'Bohemian Icons',
1316 'description': 'md5:683e901041b2fe9ba596f2ab04c4dbe7',
1318 'playlist_mincount': 10,
1321 def _extract_title_and_description(self, webpage):
1322 title = self._search_regex(r'<h1>([^<]+)</h1>', webpage, 'title', fatal=False)
1323 description = self._search_regex(
1324 r'<p[^>]+class=(["\'])subtitle\
1[^
>]*>(?P
<value
>[^
<]+)</p
>',
1325 webpage, 'description
', fatal=False, group='value
')
1326 return title, description
1329 class BBCCoUkPlaylistIE(BBCCoUkPlaylistBaseIE):
1330 IE_NAME = 'bbc
.co
.uk
:playlist
'
1331 _VALID_URL = r'https?
://(?
:www\
.)?bbc\
.co\
.uk
/programmes
/(?P
<id>%s)/(?
:episodes|broadcasts|clips
)' % BBCCoUkIE._ID_REGEX
1332 _URL_TEMPLATE = 'http
://www
.bbc
.co
.uk
/programmes
/%s'
1333 _VIDEO_ID_TEMPLATE = r'data
-pid
=["\'](%s)'
1335 'url': 'http://www.bbc.co.uk/programmes/b05rcz9v/clips',
1338 'title': 'The Disappearance - Clips - BBC Four',
1339 'description': 'French thriller serial about a missing teenager.',
1341 'playlist_mincount': 7,
1343 # multipage playlist, explicit page
1344 'url': 'http://www.bbc.co.uk/programmes/b00mfl7n/clips?page=1',
1347 'title': 'Frozen Planet - Clips - BBC One',
1348 'description': 'md5:65dcbf591ae628dafe32aa6c4a4a0d8c',
1350 'playlist_mincount': 24,
1352 # multipage playlist, all pages
1353 'url': 'http://www.bbc.co.uk/programmes/b00mfl7n/clips',
1356 'title': 'Frozen Planet - Clips - BBC One',
1357 'description': 'md5:65dcbf591ae628dafe32aa6c4a4a0d8c',
1359 'playlist_mincount': 142,
1361 'url': 'http://www.bbc.co.uk/programmes/b05rcz9v/broadcasts/2016/06',
1362 'only_matching': True,
1364 'url': 'http://www.bbc.co.uk/programmes/b05rcz9v/clips',
1365 'only_matching': True,
1367 'url': 'http://www.bbc.co.uk/programmes/b055jkys/episodes/player',
1368 'only_matching': True,
1371 def _extract_title_and_description(self, webpage):
1372 title = self._og_search_title(webpage, fatal=False)
1373 description = self._og_search_description(webpage)
1374 return title, description