2 from __future__
import unicode_literals
7 from .common
import InfoExtractor
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()],
798 'url': 'https://www.bbc.com/reel/video/p07c6sb6/how-positive-thinking-is-harming-your-happiness',
802 'title': 'How positive thinking is harming your happiness',
803 'alt_title': 'The downsides of positive thinking',
804 'description': 'md5:fad74b31da60d83b8265954ee42d85b4',
806 'thumbnail': r
're:https?://.+/p07c9dsr.jpg',
807 'upload_date': '20190604',
808 'categories': ['Psychology'],
813 def suitable(cls
, url
):
814 EXCLUDE_IE
= (BBCCoUkIE
, BBCCoUkArticleIE
, BBCCoUkIPlayerPlaylistIE
, BBCCoUkPlaylistIE
)
815 return (False if any(ie
.suitable(url
) for ie
in EXCLUDE_IE
)
816 else super(BBCIE
, cls
).suitable(url
))
818 def _extract_from_media_meta(self
, media_meta
, video_id
):
819 # Direct links to media in media metadata (e.g.
820 # http://www.bbc.com/turkce/haberler/2015/06/150615_telabyad_kentin_cogu)
821 # TODO: there are also f4m and m3u8 streams incorporated in playlist.sxml
822 source_files
= media_meta
.get('sourceFiles')
826 'format_id': format_id
,
827 'ext': f
.get('encoding'),
828 'tbr': float_or_none(f
.get('bitrate'), 1000),
829 'filesize': int_or_none(f
.get('filesize')),
830 } for format_id
, f
in source_files
.items() if f
.get('url')], []
832 programme_id
= media_meta
.get('externalId')
834 return self
._download
_media
_selector
(programme_id
)
836 # Process playlist.sxml as legacy playlist
837 href
= media_meta
.get('href')
839 playlist
= self
._download
_legacy
_playlist
_url
(href
)
840 _
, _
, _
, _
, formats
, subtitles
= self
._extract
_from
_legacy
_playlist
(playlist
, video_id
)
841 return formats
, subtitles
845 def _extract_from_playlist_sxml(self
, url
, playlist_id
, timestamp
):
846 programme_id
, title
, description
, duration
, formats
, subtitles
= \
847 self
._process
_legacy
_playlist
_url
(url
, playlist_id
)
848 self
._sort
_formats
(formats
)
852 'description': description
,
853 'duration': duration
,
854 'timestamp': timestamp
,
856 'subtitles': subtitles
,
859 def _real_extract(self
, url
):
860 playlist_id
= self
._match
_id
(url
)
862 webpage
= self
._download
_webpage
(url
, playlist_id
)
864 json_ld_info
= self
._search
_json
_ld
(webpage
, playlist_id
, default
={})
865 timestamp
= json_ld_info
.get('timestamp')
867 playlist_title
= json_ld_info
.get('title')
868 if not playlist_title
:
869 playlist_title
= self
._og
_search
_title
(
870 webpage
, default
=None) or self
._html
_search
_regex
(
871 r
'<title>(.+?)</title>', webpage
, 'playlist title', default
=None)
873 playlist_title
= re
.sub(r
'(.+)\s*-\s*BBC.*?$', r
'\1', playlist_title
).strip()
875 playlist_description
= json_ld_info
.get(
876 'description') or self
._og
_search
_description
(webpage
, default
=None)
879 timestamp
= parse_iso8601(self
._search
_regex
(
880 [r
'<meta[^>]+property="article:published_time"[^>]+content="([^"]+)"',
881 r
'itemprop="datePublished"[^>]+datetime="([^"]+)"',
882 r
'"datePublished":\s*"([^"]+)'],
883 webpage
, 'date', default
=None))
887 # article with multiple videos embedded with playlist.sxml (e.g.
888 # http://www.bbc.com/sport/0/football/34475836)
889 playlists
= re
.findall(r
'<param[^>]+name="playlist"[^>]+value="([^"]+)"', webpage
)
890 playlists
.extend(re
.findall(r
'data-media-id="([^"]+/playlist\.sxml)"', webpage
))
893 self
._extract
_from
_playlist
_sxml
(playlist_url
, playlist_id
, timestamp
)
894 for playlist_url
in playlists
]
896 # news article with multiple videos embedded with data-playable
897 data_playables
= re
.findall(r
'data-playable=(["\'])({.+?}
)\
1', webpage)
899 for _, data_playable_json in data_playables:
900 data_playable = self._parse_json(
901 unescapeHTML(data_playable_json), playlist_id, fatal=False)
902 if not data_playable:
904 settings = data_playable.get('settings
', {})
906 # data-playable with video vpid in settings.playlistObject.items (e.g.
907 # http://www.bbc.com/news/world-us-canada-34473351)
908 playlist_object = settings.get('playlistObject
', {})
910 items = playlist_object.get('items
')
911 if items and isinstance(items, list):
912 title = playlist_object['title
']
913 description = playlist_object.get('summary
')
914 duration = int_or_none(items[0].get('duration
'))
915 programme_id = items[0].get('vpid
')
916 formats, subtitles = self._download_media_selector(programme_id)
917 self._sort_formats(formats)
921 'description
': description,
922 'timestamp
': timestamp,
923 'duration
': duration,
925 'subtitles
': subtitles,
928 # data-playable without vpid but with a playlist.sxml URLs
929 # in otherSettings.playlist (e.g.
930 # http://www.bbc.com/turkce/multimedya/2015/10/151010_vid_ankara_patlama_ani)
931 playlist = data_playable.get('otherSettings
', {}).get('playlist', {})
934 for key in ('streaming
', 'progressiveDownload
'):
935 playlist_url = playlist.get('%sUrl
' % key)
939 info = self._extract_from_playlist_sxml(
940 playlist_url, playlist_id, timestamp)
944 entry['title
'] = info['title
']
945 entry['formats
'].extend(info['formats
'])
946 except ExtractorError as e:
947 # Some playlist URL may fail with 500, at the same time
948 # the other one may work fine (e.g.
949 # http://www.bbc.com/turkce/haberler/2015/06/150615_telabyad_kentin_cogu)
950 if isinstance(e.cause, compat_HTTPError) and e.cause.code == 500:
954 self._sort_formats(entry['formats
'])
955 entries.append(entry)
958 return self.playlist_result(entries, playlist_id, playlist_title, playlist_description)
960 # http://www.bbc.co.uk/learningenglish/chinese/features/lingohack/ep-181227
961 group_id = self._search_regex(
962 r'<div
[^
>]+\bclass
=["\']video["\'][^
>]+\bdata
-pid
=["\'](%s)' % self._ID_REGEX,
963 webpage, 'group id', default=None)
965 return self.url_result(
966 'https://www.bbc.co.uk/programmes/%s' % group_id,
967 ie=BBCCoUkIE.ie_key())
969 # single video story (e.g. http://www.bbc.com/travel/story/20150625-sri-lankas-spicy-secret)
970 programme_id = self._search_regex(
971 [r'data-(?:video-player|media)-vpid="(%s)"' % self._ID_REGEX,
972 r'<param[^>]+name="externalIdentifier
"[^>]+value="(%s)"' % self._ID_REGEX,
973 r'videoId\s*:\s*["\'](%s)["\']' % self._ID_REGEX],
974 webpage, 'vpid', default=None)
977 formats, subtitles = self._download_media_selector(programme_id)
978 self._sort_formats(formats)
979 # digitalData may be missing (e.g. http://www.bbc.com/autos/story/20130513-hyundais-rock-star)
980 digital_data = self._parse_json(
982 r'var\s+digitalData\s*=\s*({.+?});?\n', webpage, 'digital data', default='{}'),
983 programme_id, fatal=False)
984 page_info = digital_data.get('page', {}).get('pageInfo', {})
985 title = page_info.get('pageName') or self._og_search_title(webpage)
986 description = page_info.get('description') or self._og_search_description(webpage)
987 timestamp = parse_iso8601(page_info.get('publicationDate')) or timestamp
991 'description': description,
992 'timestamp': timestamp,
994 'subtitles': subtitles,
997 # bbc reel (e.g. https://www.bbc.com/reel/video/p07c6sb6/how-positive-thinking-is-harming-your-happiness)
998 initial_data = self._parse_json(self._html_search_regex(
999 r'<script[^>]+id=(["\'])initial
-data\
1[^
>]+data
-json
=(["\'])(?P<json>(?:(?!\2).)+)',
1000 webpage, 'initial data', default='{}', group='json'), playlist_id, fatal=False)
1002 init_data = try_get(
1003 initial_data, lambda x: x['initData']['items'][0], dict) or {}
1004 smp_data = init_data.get('smpData') or {}
1005 clip_data = try_get(smp_data, lambda x: x['items'][0], dict) or {}
1006 version_id = clip_data.get('versionID')
1008 title = smp_data['title']
1009 formats, subtitles = self._download_media_selector(version_id)
1010 self._sort_formats(formats)
1011 image_url = smp_data.get('holdingImageURL')
1012 display_date = init_data.get('displayDate')
1013 topic_title = init_data.get('topicTitle')
1019 'alt_title': init_data.get('shortTitle'),
1020 'thumbnail': image_url.replace('$recipe', 'raw') if image_url else None,
1021 'description': smp_data.get('summary') or init_data.get('shortSummary'),
1022 'upload_date': display_date.replace('-', '') if display_date else None,
1023 'subtitles': subtitles,
1024 'duration': int_or_none(clip_data.get('duration')),
1025 'categories': [topic_title] if topic_title else None,
1028 # Morph based embed (e.g. http://www.bbc.co.uk/sport/live/olympics/36895975)
1029 # There are several setPayload calls may be present but the video
1030 # seems to be always related to the first one
1031 morph_payload = self._parse_json(
1033 r'Morph\.setPayload\([^,]+,\s*({.+?})\);',
1034 webpage, 'morph payload', default='{}'),
1035 playlist_id, fatal=False)
1037 components = try_get(morph_payload, lambda x: x['body']['components'], list) or []
1038 for component in components:
1039 if not isinstance(component, dict):
1041 lead_media = try_get(component, lambda x: x['props']['leadMedia'], dict)
1044 identifiers = lead_media.get('identifiers')
1045 if not identifiers or not isinstance(identifiers, dict):
1047 programme_id = identifiers.get('vpid') or identifiers.get('playablePid')
1048 if not programme_id:
1050 title = lead_media.get('title') or self._og_search_title(webpage)
1051 formats, subtitles = self._download_media_selector(programme_id)
1052 self._sort_formats(formats)
1053 description = lead_media.get('summary')
1054 uploader = lead_media.get('masterBrand')
1055 uploader_id = lead_media.get('mid')
1057 duration_d = lead_media.get('duration')
1058 if isinstance(duration_d, dict):
1059 duration = parse_duration(dict_get(
1060 duration_d, ('rawDuration', 'formattedDuration', 'spokenDuration')))
1064 'description': description,
1065 'duration': duration,
1066 'uploader': uploader,
1067 'uploader_id': uploader_id,
1069 'subtitles': subtitles,
1072 preload_state = self._parse_json(self._search_regex(
1073 r'window\.__PRELOADED_STATE__\s*=\s*({.+?});', webpage,
1074 'preload state', default='{}'), playlist_id, fatal=False)
1076 current_programme = preload_state.get('programmes', {}).get('current') or {}
1077 programme_id = current_programme.get('id')
1078 if current_programme and programme_id and current_programme.get('type') == 'playable_item':
1079 title = current_programme.get('titles', {}).get('tertiary') or playlist_title
1080 formats, subtitles = self._download_media_selector(programme_id)
1081 self._sort_formats(formats)
1082 synopses = current_programme.get('synopses') or {}
1083 network = current_programme.get('network') or {}
1084 duration = int_or_none(
1085 current_programme.get('duration', {}).get('value'))
1087 image_url = current_programme.get('image_url')
1089 thumbnail = image_url.replace('{recipe}', 'raw')
1093 'description': dict_get(synopses, ('long', 'medium', 'short')),
1094 'thumbnail': thumbnail,
1095 'duration': duration,
1096 'uploader': network.get('short_title'),
1097 'uploader_id': network.get('id'),
1099 'subtitles': subtitles,
1102 bbc3_config = self._parse_json(
1104 r'(?s)bbcthreeConfig\s*=\s*({.+?})\s*;\s*<', webpage,
1105 'bbcthree config', default='{}'),
1106 playlist_id, transform_source=js_to_json, fatal=False) or {}
1107 payload = bbc3_config.get('payload') or {}
1109 clip = payload.get('currentClip') or {}
1110 clip_vpid = clip.get('vpid')
1111 clip_title = clip.get('title')
1112 if clip_vpid and clip_title:
1113 formats, subtitles = self._download_media_selector(clip_vpid)
1114 self._sort_formats(formats)
1117 'title': clip_title,
1118 'thumbnail': dict_get(clip, ('poster', 'imageUrl')),
1119 'description': clip.get('description'),
1120 'duration': parse_duration(clip.get('duration')),
1122 'subtitles': subtitles,
1124 bbc3_playlist = try_get(
1125 payload, lambda x: x['content']['bbcMedia']['playlist'],
1128 playlist_title = bbc3_playlist.get('title') or playlist_title
1129 thumbnail = bbc3_playlist.get('holdingImageURL')
1131 for bbc3_item in bbc3_playlist['items']:
1132 programme_id = bbc3_item.get('versionID')
1133 if not programme_id:
1135 formats, subtitles = self._download_media_selector(programme_id)
1136 self._sort_formats(formats)
1139 'title': playlist_title,
1140 'thumbnail': thumbnail,
1141 'timestamp': timestamp,
1143 'subtitles': subtitles,
1145 return self.playlist_result(
1146 entries, playlist_id, playlist_title, playlist_description)
1148 initial_data = self._parse_json(self._search_regex(
1149 r'window\.__INITIAL_DATA__\s*=\s*({.+?});', webpage,
1150 'preload state', default='{}'), playlist_id, fatal=False)
1152 def parse_media(media):
1155 for item in (try_get(media, lambda x: x['media']['items'], list) or []):
1156 item_id = item.get('id')
1157 item_title = item.get('title')
1158 if not (item_id and item_title):
1160 formats, subtitles = self._download_media_selector(item_id)
1161 self._sort_formats(formats)
1164 'title': item_title,
1165 'thumbnail': item.get('holdingImageUrl'),
1167 'subtitles': subtitles,
1169 for resp in (initial_data.get('data') or {}).values():
1170 name = resp.get('name')
1171 if name == 'media-experience':
1172 parse_media(try_get(resp, lambda x: x['data']['initialItem']['mediaItem'], dict))
1173 elif name == 'article':
1174 for block in (try_get(resp, lambda x: x['data']['blocks'], list) or []):
1175 if block.get('type') != 'media':
1177 parse_media(block.get('model'))
1178 return self.playlist_result(
1179 entries, playlist_id, playlist_title, playlist_description)
1181 def extract_all(pattern):
1182 return list(filter(None, map(
1183 lambda s: self._parse_json(s, playlist_id, fatal=False),
1184 re.findall(pattern, webpage))))
1186 # Multiple video article (e.g.
1187 # http://www.bbc.co.uk/blogs/adamcurtis/entries/3662a707-0af9-3149-963f-47bea720b460)
1188 EMBED_URL = r'https?://(?:www\.)?bbc\.co\.uk/(?:[^/]+/)+%s(?:\b[^"]+)?
' % self._ID_REGEX
1190 for match in extract_all(r'new\s
+SMP\
(({.+?}
)\
)'):
1191 embed_url = match.get('playerSettings
', {}).get('externalEmbedUrl
')
1192 if embed_url and re.match(EMBED_URL, embed_url):
1193 entries.append(embed_url)
1194 entries.extend(re.findall(
1195 r'setPlaylist\
("(%s)"\
)' % EMBED_URL, webpage))
1197 return self.playlist_result(
1198 [self.url_result(entry_, 'BBCCoUk
') for entry_ in entries],
1199 playlist_id, playlist_title, playlist_description)
1201 # Multiple video article (e.g. http://www.bbc.com/news/world-europe-32668511)
1202 medias = extract_all(r"data-media-meta='({[^']+}
)'")
1205 # Single video article (e.g. http://www.bbc.com/news/video_and_audio/international)
1206 media_asset = self._search_regex(
1207 r'mediaAssetPage\
.init\
(\s
*({.+?}
), "/',
1208 webpage, 'media asset', default=None)
1210 media_asset_page = self._parse_json(media_asset, playlist_id, fatal=False)
1212 for video in media_asset_page.get('videos', {}).values():
1213 medias.extend(video.values())
1216 # Multiple video playlist with single `now playing` entry (e.g.
1217 # http://www.bbc.com/news/video_and_audio/must_see/33767813)
1218 vxp_playlist = self._parse_json(
1220 r'<script[^>]+class="vxp
-playlist
-data
"[^>]+type="application
/json
"[^>]*>([^<]+)</script>',
1221 webpage, 'playlist data'),
1223 playlist_medias = []
1224 for item in vxp_playlist:
1225 media = item.get('media')
1228 playlist_medias.append(media)
1229 # Download single video if found media with asset id matching the video id from URL
1230 if item.get('advert', {}).get('assetId') == playlist_id:
1233 # Fallback to the whole playlist
1235 medias = playlist_medias
1238 for num, media_meta in enumerate(medias, start=1):
1239 formats, subtitles = self._extract_from_media_meta(media_meta, playlist_id)
1242 self._sort_formats(formats)
1244 video_id = media_meta.get('externalId')
1246 video_id = playlist_id if len(medias) == 1 else '%s-%s' % (playlist_id, num)
1248 title = media_meta.get('caption')
1250 title = playlist_title if len(medias) == 1 else '%s - Video %s' % (playlist_title, num)
1252 duration = int_or_none(media_meta.get('durationInSeconds')) or parse_duration(media_meta.get('duration'))
1255 for image in media_meta.get('images', {}).values():
1256 images.extend(image.values())
1257 if 'image' in media_meta:
1258 images.append(media_meta['image'])
1261 'url': image.get('href'),
1262 'width': int_or_none(image.get('width')),
1263 'height': int_or_none(image.get('height')),
1264 } for image in images]
1269 'thumbnails': thumbnails,
1270 'duration': duration,
1271 'timestamp': timestamp,
1273 'subtitles': subtitles,
1276 return self.playlist_result(entries, playlist_id, playlist_title, playlist_description)
1279 class BBCCoUkArticleIE(InfoExtractor):
1280 _VALID_URL = r'https?://(?:www\.)?bbc\.co\.uk/programmes/articles/(?P<id>[a-zA-Z0-9]+)'
1281 IE_NAME = 'bbc.co.uk:article'
1282 IE_DESC = 'BBC articles'
1285 'url': 'http://www.bbc.co.uk/programmes/articles/3jNQLTMrPlYGTBn0WV6M2MS/not-your-typical-role-model-ada-lovelace-the-19th-century-programmer',
1287 'id': '3jNQLTMrPlYGTBn0WV6M2MS',
1288 'title': 'Calculating Ada: The Countess of Computing - Not your typical role model: Ada Lovelace the 19th century programmer - BBC Four',
1289 'description': 'Hannah Fry reveals some of her surprising discoveries about Ada Lovelace during filming.',
1291 'playlist_count': 4,
1292 'add_ie': ['BBCCoUk'],
1295 def _real_extract(self, url):
1296 playlist_id = self._match_id(url)
1298 webpage = self._download_webpage(url, playlist_id)
1300 title = self._og_search_title(webpage)
1301 description = self._og_search_description(webpage).strip()
1303 entries = [self.url_result(programme_url) for programme_url in re.findall(
1304 r'<div[^>]+typeof="Clip
"[^>]+resource="([^
"]+)"', webpage)]
1306 return self.playlist_result(entries, playlist_id, title, description)
1309 class BBCCoUkPlaylistBaseIE(InfoExtractor):
1310 def _entries(self, webpage, url, playlist_id):
1311 single_page = 'page
' in compat_urlparse.parse_qs(
1312 compat_urlparse.urlparse(url).query)
1313 for page_num in itertools.count(2):
1314 for video_id in re.findall(
1315 self._VIDEO_ID_TEMPLATE % BBCCoUkIE._ID_REGEX, webpage):
1316 yield self.url_result(
1317 self._URL_TEMPLATE % video_id, BBCCoUkIE.ie_key())
1320 next_page = self._search_regex(
1321 r'<li
[^
>]+class=(["\'])pagination_+next\1[^>]*><a[^>]+href=(["\'])(?P
<url
>(?
:(?
!\
2).)+)\
2',
1322 webpage, 'next page url
', default=None, group='url
')
1325 webpage = self._download_webpage(
1326 compat_urlparse.urljoin(url, next_page), playlist_id,
1327 'Downloading page
%d' % page_num, page_num)
1329 def _real_extract(self, url):
1330 playlist_id = self._match_id(url)
1332 webpage = self._download_webpage(url, playlist_id)
1334 title, description = self._extract_title_and_description(webpage)
1336 return self.playlist_result(
1337 self._entries(webpage, url, playlist_id),
1338 playlist_id, title, description)
1341 class BBCCoUkIPlayerPlaylistIE(BBCCoUkPlaylistBaseIE):
1342 IE_NAME = 'bbc
.co
.uk
:iplayer
:playlist
'
1343 _VALID_URL = r'https?
://(?
:www\
.)?bbc\
.co\
.uk
/iplayer
/(?
:episodes|group
)/(?P
<id>%s)' % BBCCoUkIE._ID_REGEX
1344 _URL_TEMPLATE = 'http
://www
.bbc
.co
.uk
/iplayer
/episode
/%s'
1345 _VIDEO_ID_TEMPLATE = r'data
-ip
-id=["\'](%s)'
1347 'url': 'http://www.bbc.co.uk/iplayer/episodes/b05rcz9v',
1350 'title': 'The Disappearance',
1351 'description': 'French thriller serial about a missing teenager.',
1353 'playlist_mincount': 6,
1354 'skip': 'This programme is not currently available on BBC iPlayer',
1356 # Available for over a year unlike 30 days for most other programmes
1357 'url': 'http://www.bbc.co.uk/iplayer/group/p02tcc32',
1360 'title': 'Bohemian Icons',
1361 'description': 'md5:683e901041b2fe9ba596f2ab04c4dbe7',
1363 'playlist_mincount': 10,
1366 def _extract_title_and_description(self, webpage):
1367 title = self._search_regex(r'<h1>([^<]+)</h1>', webpage, 'title', fatal=False)
1368 description = self._search_regex(
1369 r'<p[^>]+class=(["\'])subtitle\
1[^
>]*>(?P
<value
>[^
<]+)</p
>',
1370 webpage, 'description
', fatal=False, group='value
')
1371 return title, description
1374 class BBCCoUkPlaylistIE(BBCCoUkPlaylistBaseIE):
1375 IE_NAME = 'bbc
.co
.uk
:playlist
'
1376 _VALID_URL = r'https?
://(?
:www\
.)?bbc\
.co\
.uk
/programmes
/(?P
<id>%s)/(?
:episodes|broadcasts|clips
)' % BBCCoUkIE._ID_REGEX
1377 _URL_TEMPLATE = 'http
://www
.bbc
.co
.uk
/programmes
/%s'
1378 _VIDEO_ID_TEMPLATE = r'data
-pid
=["\'](%s)'
1380 'url': 'http://www.bbc.co.uk/programmes/b05rcz9v/clips',
1383 'title': 'The Disappearance - Clips - BBC Four',
1384 'description': 'French thriller serial about a missing teenager.',
1386 'playlist_mincount': 7,
1388 # multipage playlist, explicit page
1389 'url': 'http://www.bbc.co.uk/programmes/b00mfl7n/clips?page=1',
1392 'title': 'Frozen Planet - Clips - BBC One',
1393 'description': 'md5:65dcbf591ae628dafe32aa6c4a4a0d8c',
1395 'playlist_mincount': 24,
1397 # multipage playlist, all pages
1398 'url': 'http://www.bbc.co.uk/programmes/b00mfl7n/clips',
1401 'title': 'Frozen Planet - Clips - BBC One',
1402 'description': 'md5:65dcbf591ae628dafe32aa6c4a4a0d8c',
1404 'playlist_mincount': 142,
1406 'url': 'http://www.bbc.co.uk/programmes/b05rcz9v/broadcasts/2016/06',
1407 'only_matching': True,
1409 'url': 'http://www.bbc.co.uk/programmes/b05rcz9v/clips',
1410 'only_matching': True,
1412 'url': 'http://www.bbc.co.uk/programmes/b055jkys/episodes/player',
1413 'only_matching': True,
1416 def _extract_title_and_description(self, webpage):
1417 title = self._og_search_title(webpage, fatal=False)
1418 description = self._og_search_description(webpage)
1419 return title, description