]> jfr.im git - yt-dlp.git/blame - youtube_dl/extractor/bbc.py
[bbc.co.uk] Fix test_BBCCoUk
[yt-dlp.git] / youtube_dl / extractor / bbc.py
CommitLineData
9afa1770 1# coding: utf-8
082c6c86
S
2from __future__ import unicode_literals
3
9afa1770 4import re
082c6c86 5
f13b1e7d 6from .common import InfoExtractor
8683b4d8
S
7from ..utils import (
8 ExtractorError,
9afa1770 9 float_or_none,
8683b4d8 10 int_or_none,
9afa1770
S
11 parse_duration,
12 parse_iso8601,
ae8bdfd1 13 remove_end,
dab062fb 14 unescapeHTML,
8683b4d8 15)
36e6f62c
JMF
16from ..compat import (
17 compat_etree_fromstring,
18 compat_HTTPError,
19)
082c6c86 20
d12a1a47 21
f13b1e7d 22class BBCCoUkIE(InfoExtractor):
082c6c86 23 IE_NAME = 'bbc.co.uk'
2e3fd9ec 24 IE_DESC = 'BBC iPlayer'
22d7368d 25 _ID_REGEX = r'[pb][\da-z]{7}'
49358274 26 _VALID_URL = r'https?://(?:www\.)?bbc\.co\.uk/(?:(?:programmes/(?!articles/)|iplayer(?:/[^/]+)?/(?:episode/|playlist/))|music/clips[/#])(?P<id>%s)' % _ID_REGEX
082c6c86 27
d12a1a47 28 _MEDIASELECTOR_URLS = [
26ccc68b
S
29 # Provides HQ HLS streams with even better quality that pc mediaset but fails
30 # with geolocation in some cases when it's even not geo restricted at all (e.g.
d781e293 31 # http://www.bbc.co.uk/programmes/b06bp7lf). Also may fail with selectionunavailable.
d1c694ea 32 'http://open.live.bbc.co.uk/mediaselector/5/select/version/2.0/mediaset/iptv-all/vpid/%s',
d12a1a47
S
33 'http://open.live.bbc.co.uk/mediaselector/5/select/version/2.0/mediaset/pc/vpid/%s',
34 ]
a8b081a0 35
e6174ee9
S
36 _MEDIASELECTION_NS = 'http://bbc.co.uk/2008/mp/mediaselection'
37 _EMP_PLAYLIST_NS = 'http://bbc.co.uk/2008/emp/playlist'
38
39 _NAMESPACES = (
40 _MEDIASELECTION_NS,
41 _EMP_PLAYLIST_NS,
42 )
43
2e3fd9ec
S
44 _TESTS = [
45 {
f2d0fc68 46 'url': 'http://www.bbc.co.uk/programmes/b039g8p7',
2e3fd9ec 47 'info_dict': {
f2d0fc68 48 'id': 'b039d07m',
2e3fd9ec 49 'ext': 'flv',
679bacf0 50 'title': 'Leonard Cohen, Kaleidoscope - BBC Radio 4',
c4914185 51 'description': 'The Canadian poet and songwriter reflects on his musical career.',
2e3fd9ec
S
52 },
53 'params': {
54 # rtmp download
55 'skip_download': True,
56 }
082c6c86 57 },
2e3fd9ec
S
58 {
59 'url': 'http://www.bbc.co.uk/iplayer/episode/b00yng5w/The_Man_in_Black_Series_3_The_Printed_Name/',
60 'info_dict': {
61 'id': 'b00yng1d',
62 'ext': 'flv',
63 'title': 'The Man in Black: Series 3: The Printed Name',
64 'description': "Mark Gatiss introduces Nicholas Pierpan's chilling tale of a writer's devilish pact with a mysterious man. Stars Ewan Bailey.",
65 'duration': 1800,
66 },
67 'params': {
68 # rtmp download
69 'skip_download': True,
c7f0177f
S
70 },
71 'skip': 'Episode is no longer available on BBC iPlayer Radio',
2e3fd9ec
S
72 },
73 {
74 'url': 'http://www.bbc.co.uk/iplayer/episode/b03vhd1f/The_Voice_UK_Series_3_Blind_Auditions_5/',
75 'info_dict': {
76 'id': 'b00yng1d',
77 'ext': 'flv',
17968e44
S
78 'title': 'The Voice UK: Series 3: Blind Auditions 5',
79 '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.",
80 'duration': 5100,
2e3fd9ec
S
81 },
82 'params': {
83 # rtmp download
84 'skip_download': True,
85 },
86 'skip': 'Currently BBC iPlayer TV programmes are available to play in the UK only',
c056efa2
S
87 },
88 {
89 'url': 'http://www.bbc.co.uk/iplayer/episode/p026c7jt/tomorrows-worlds-the-unearthly-history-of-science-fiction-2-invasion',
90 'info_dict': {
91 'id': 'b03k3pb7',
92 'ext': 'flv',
93 'title': "Tomorrow's Worlds: The Unearthly History of Science Fiction",
94 'description': '2. Invasion',
95 'duration': 3600,
96 },
97 'params': {
98 # rtmp download
99 'skip_download': True,
100 },
101 'skip': 'Currently BBC iPlayer TV programmes are available to play in the UK only',
ae6986fb
S
102 }, {
103 'url': 'http://www.bbc.co.uk/programmes/b04v20dw',
104 'info_dict': {
105 'id': 'b04v209v',
106 'ext': 'flv',
107 'title': 'Pete Tong, The Essential New Tune Special',
108 'description': "Pete has a very special mix - all of 2014's Essential New Tunes!",
109 'duration': 10800,
110 },
111 'params': {
112 # rtmp download
113 'skip_download': True,
114 }
c7e67594
S
115 }, {
116 'url': 'http://www.bbc.co.uk/music/clips/p02frcc3',
117 'note': 'Audio',
118 'info_dict': {
119 'id': 'p02frcch',
120 'ext': 'flv',
121 'title': 'Pete Tong, Past, Present and Future Special, Madeon - After Hours mix',
122 'description': 'French house superstar Madeon takes us out of the club and onto the after party.',
123 'duration': 3507,
124 },
125 'params': {
126 # rtmp download
127 'skip_download': True,
128 }
129 }, {
130 'url': 'http://www.bbc.co.uk/music/clips/p025c0zz',
131 'note': 'Video',
132 'info_dict': {
133 'id': 'p025c103',
134 'ext': 'flv',
135 'title': 'Reading and Leeds Festival, 2014, Rae Morris - Closer (Live on BBC Three)',
136 'description': 'Rae Morris performs Closer for BBC Three at Reading 2014',
137 'duration': 226,
138 },
139 'params': {
140 # rtmp download
141 'skip_download': True,
142 }
e68ae99a
S
143 }, {
144 'url': 'http://www.bbc.co.uk/iplayer/episode/b054fn09/ad/natural-world-20152016-2-super-powered-owls',
145 'info_dict': {
146 'id': 'p02n76xf',
147 'ext': 'flv',
148 'title': 'Natural World, 2015-2016: 2. Super Powered Owls',
149 'description': 'md5:e4db5c937d0e95a7c6b5e654d429183d',
150 'duration': 3540,
151 },
152 'params': {
153 # rtmp download
154 'skip_download': True,
155 },
156 'skip': 'geolocation',
25fa8d66
YCH
157 }, {
158 'url': 'http://www.bbc.co.uk/iplayer/episode/b05zmgwn/royal-academy-summer-exhibition',
159 'info_dict': {
160 'id': 'b05zmgw1',
161 'ext': 'flv',
162 '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.',
163 'title': 'Royal Academy Summer Exhibition',
164 'duration': 3540,
165 },
166 'params': {
167 # rtmp download
168 'skip_download': True,
169 },
170 'skip': 'geolocation',
54914380
S
171 }, {
172 # iptv-all mediaset fails with geolocation however there is no geo restriction
173 # for this programme at all
174 'url': 'http://www.bbc.co.uk/programmes/b06bp7lf',
175 'info_dict': {
176 'id': 'b06bp7kf',
177 'ext': 'flv',
178 'title': "Annie Mac's Friday Night, B.Traits sits in for Annie",
179 'description': 'B.Traits sits in for Annie Mac with a Mini-Mix from Disclosure.',
180 'duration': 10800,
181 },
182 'params': {
183 # rtmp download
184 'skip_download': True,
185 },
31763975
S
186 }, {
187 'url': 'http://www.bbc.co.uk/iplayer/playlist/p01dvks4',
188 'only_matching': True,
c7e67594
S
189 }, {
190 'url': 'http://www.bbc.co.uk/music/clips#p02frcc3',
191 'only_matching': True,
0692ef86
S
192 }, {
193 'url': 'http://www.bbc.co.uk/iplayer/cbeebies/episode/b0480276/bing-14-atchoo',
194 'only_matching': True,
ae6986fb 195 }
2e3fd9ec
S
196 ]
197
d12a1a47
S
198 class MediaSelectionError(Exception):
199 def __init__(self, id):
200 self.id = id
201
2e3fd9ec
S
202 def _extract_asx_playlist(self, connection, programme_id):
203 asx = self._download_xml(connection.get('href'), programme_id, 'Downloading ASX playlist')
204 return [ref.get('href') for ref in asx.findall('./Entry/ref')]
205
206 def _extract_connection(self, connection, programme_id):
207 formats = []
e6174ee9 208 kind = connection.get('kind')
2e3fd9ec
S
209 protocol = connection.get('protocol')
210 supplier = connection.get('supplier')
211 if protocol == 'http':
212 href = connection.get('href')
7a896817 213 transfer_format = connection.get('transferFormat')
2e3fd9ec
S
214 # ASX playlist
215 if supplier == 'asx':
216 for i, ref in enumerate(self._extract_asx_playlist(connection, programme_id)):
217 formats.append({
218 'url': ref,
219 'format_id': 'ref%s_%s' % (i, supplier),
220 })
7a896817
S
221 # Skip DASH until supported
222 elif transfer_format == 'dash':
223 pass
d1c694ea
S
224 elif transfer_format == 'hls':
225 m3u8_formats = self._extract_m3u8_formats(
226 href, programme_id, ext='mp4', entry_protocol='m3u8_native',
227 m3u8_id=supplier, fatal=False)
228 if m3u8_formats:
229 formats.extend(m3u8_formats)
2e3fd9ec
S
230 # Direct link
231 else:
232 formats.append({
233 'url': href,
e6174ee9 234 'format_id': supplier or kind or protocol,
2e3fd9ec
S
235 })
236 elif protocol == 'rtmp':
237 application = connection.get('application', 'ondemand')
238 auth_string = connection.get('authString')
239 identifier = connection.get('identifier')
240 server = connection.get('server')
241 formats.append({
242 'url': '%s://%s/%s?%s' % (protocol, server, application, auth_string),
243 'play_path': identifier,
244 'app': '%s?%s' % (application, auth_string),
245 'page_url': 'http://www.bbc.co.uk',
246 'player_url': 'http://www.bbc.co.uk/emp/releases/iplayer/revisions/617463_618125_4/617463_618125_4_emp.swf',
247 'rtmp_live': False,
248 'ext': 'flv',
249 'format_id': supplier,
250 })
251 return formats
252
253 def _extract_items(self, playlist):
e6174ee9
S
254 return playlist.findall('./{%s}item' % self._EMP_PLAYLIST_NS)
255
256 def _findall_ns(self, element, xpath):
257 elements = []
258 for ns in self._NAMESPACES:
259 elements.extend(element.findall(xpath % ns))
260 return elements
2e3fd9ec
S
261
262 def _extract_medias(self, media_selection):
e6174ee9
S
263 error = media_selection.find('./{%s}error' % self._MEDIASELECTION_NS)
264 if error is None:
265 media_selection.find('./{%s}error' % self._EMP_PLAYLIST_NS)
c056efa2 266 if error is not None:
d12a1a47 267 raise BBCCoUkIE.MediaSelectionError(error.get('id'))
e6174ee9 268 return self._findall_ns(media_selection, './{%s}media')
2e3fd9ec
S
269
270 def _extract_connections(self, media):
e6174ee9 271 return self._findall_ns(media, './{%s}connection')
2e3fd9ec
S
272
273 def _extract_video(self, media, programme_id):
274 formats = []
d97f5cd7 275 vbr = int_or_none(media.get('bitrate'))
2e3fd9ec
S
276 vcodec = media.get('encoding')
277 service = media.get('service')
d97f5cd7
S
278 width = int_or_none(media.get('width'))
279 height = int_or_none(media.get('height'))
280 file_size = int_or_none(media.get('media_file_size'))
2e3fd9ec
S
281 for connection in self._extract_connections(media):
282 conn_formats = self._extract_connection(connection, programme_id)
283 for format in conn_formats:
284 format.update({
2e3fd9ec
S
285 'width': width,
286 'height': height,
287 'vbr': vbr,
288 'vcodec': vcodec,
289 'filesize': file_size,
290 })
e6174ee9
S
291 if service:
292 format['format_id'] = '%s_%s' % (service, format['format_id'])
2e3fd9ec
S
293 formats.extend(conn_formats)
294 return formats
295
296 def _extract_audio(self, media, programme_id):
297 formats = []
d97f5cd7 298 abr = int_or_none(media.get('bitrate'))
2e3fd9ec
S
299 acodec = media.get('encoding')
300 service = media.get('service')
301 for connection in self._extract_connections(media):
302 conn_formats = self._extract_connection(connection, programme_id)
303 for format in conn_formats:
304 format.update({
305 'format_id': '%s_%s' % (service, format['format_id']),
306 'abr': abr,
307 'acodec': acodec,
308 })
309 formats.extend(conn_formats)
310 return formats
311
f13b1e7d 312 def _get_subtitles(self, media, programme_id):
2e3fd9ec
S
313 subtitles = {}
314 for connection in self._extract_connections(media):
315 captions = self._download_xml(connection.get('href'), programme_id, 'Downloading captions')
316 lang = captions.get('{http://www.w3.org/XML/1998/namespace}lang', 'en')
f13b1e7d
JMF
317 subtitles[lang] = [
318 {
319 'url': connection.get('href'),
320 'ext': 'ttml',
321 },
f13b1e7d 322 ]
2e3fd9ec 323 return subtitles
082c6c86 324
d12a1a47
S
325 def _raise_extractor_error(self, media_selection_error):
326 raise ExtractorError(
327 '%s returned error: %s' % (self.IE_NAME, media_selection_error.id),
328 expected=True)
329
c056efa2 330 def _download_media_selector(self, programme_id):
d12a1a47
S
331 last_exception = None
332 for mediaselector_url in self._MEDIASELECTOR_URLS:
333 try:
334 return self._download_media_selector_url(
335 mediaselector_url % programme_id, programme_id)
336 except BBCCoUkIE.MediaSelectionError as e:
d781e293 337 if e.id in ('notukerror', 'geolocation', 'selectionunavailable'):
d12a1a47
S
338 last_exception = e
339 continue
340 self._raise_extractor_error(e)
341 self._raise_extractor_error(last_exception)
9afa1770
S
342
343 def _download_media_selector_url(self, url, programme_id=None):
c056efa2
S
344 try:
345 media_selection = self._download_xml(
9afa1770 346 url, programme_id, 'Downloading media selection XML')
c056efa2 347 except ExtractorError as ee:
d781e293 348 if isinstance(ee.cause, compat_HTTPError) and ee.cause.code in (403, 404):
36e6f62c 349 media_selection = compat_etree_fromstring(ee.cause.read().decode('utf-8'))
2e3fd9ec 350 else:
c056efa2 351 raise
9afa1770 352 return self._process_media_selector(media_selection, programme_id)
082c6c86 353
9afa1770 354 def _process_media_selector(self, media_selection, programme_id):
082c6c86 355 formats = []
2e3fd9ec
S
356 subtitles = None
357
c056efa2
S
358 for media in self._extract_medias(media_selection):
359 kind = media.get('kind')
360 if kind == 'audio':
361 formats.extend(self._extract_audio(media, programme_id))
362 elif kind == 'video':
363 formats.extend(self._extract_video(media, programme_id))
364 elif kind == 'captions':
f13b1e7d 365 subtitles = self.extract_subtitles(media, programme_id)
c056efa2 366 return formats, subtitles
2e3fd9ec 367
ae6986fb
S
368 def _download_playlist(self, playlist_id):
369 try:
370 playlist = self._download_json(
371 'http://www.bbc.co.uk/programmes/%s/playlist.json' % playlist_id,
372 playlist_id, 'Downloading playlist JSON')
373
374 version = playlist.get('defaultAvailableVersion')
375 if version:
376 smp_config = version['smpConfig']
377 title = smp_config['title']
378 description = smp_config['summary']
379 for item in smp_config['items']:
380 kind = item['kind']
381 if kind != 'programme' and kind != 'radioProgramme':
382 continue
383 programme_id = item.get('vpid')
d97f5cd7 384 duration = int_or_none(item.get('duration'))
ae6986fb
S
385 formats, subtitles = self._download_media_selector(programme_id)
386 return programme_id, title, description, duration, formats, subtitles
387 except ExtractorError as ee:
f813928e 388 if not (isinstance(ee.cause, compat_HTTPError) and ee.cause.code == 404):
ae6986fb
S
389 raise
390
391 # fallback to legacy playlist
9afa1770
S
392 return self._process_legacy_playlist(playlist_id)
393
394 def _process_legacy_playlist_url(self, url, display_id):
395 playlist = self._download_legacy_playlist_url(url, display_id)
396 return self._extract_from_legacy_playlist(playlist, display_id)
397
398 def _process_legacy_playlist(self, playlist_id):
399 return self._process_legacy_playlist_url(
400 'http://www.bbc.co.uk/iplayer/playlist/%s' % playlist_id, playlist_id)
401
402 def _download_legacy_playlist_url(self, url, playlist_id=None):
403 return self._download_xml(
404 url, playlist_id, 'Downloading legacy playlist XML')
ae6986fb 405
9afa1770 406 def _extract_from_legacy_playlist(self, playlist, playlist_id):
e6174ee9 407 no_items = playlist.find('./{%s}noItems' % self._EMP_PLAYLIST_NS)
ae6986fb
S
408 if no_items is not None:
409 reason = no_items.get('reason')
410 if reason == 'preAvailability':
411 msg = 'Episode %s is not yet available' % playlist_id
412 elif reason == 'postAvailability':
413 msg = 'Episode %s is no longer available' % playlist_id
414 elif reason == 'noMedia':
415 msg = 'Episode %s is not currently available' % playlist_id
416 else:
417 msg = 'Episode %s is not available: %s' % (playlist_id, reason)
418 raise ExtractorError(msg, expected=True)
419
420 for item in self._extract_items(playlist):
421 kind = item.get('kind')
422 if kind != 'programme' and kind != 'radioProgramme':
423 continue
e6174ee9
S
424 title = playlist.find('./{%s}title' % self._EMP_PLAYLIST_NS).text
425 description_el = playlist.find('./{%s}summary' % self._EMP_PLAYLIST_NS)
8daeeedc 426 description = description_el.text if description_el is not None else None
9afa1770
S
427
428 def get_programme_id(item):
429 def get_from_attributes(item):
430 for p in('identifier', 'group'):
431 value = item.get(p)
432 if value and re.match(r'^[pb][\da-z]{7}$', value):
433 return value
434 get_from_attributes(item)
e6174ee9 435 mediator = item.find('./{%s}mediator' % self._EMP_PLAYLIST_NS)
9afa1770
S
436 if mediator is not None:
437 return get_from_attributes(mediator)
438
439 programme_id = get_programme_id(item)
d97f5cd7 440 duration = int_or_none(item.get('duration'))
e6174ee9
S
441
442 if programme_id:
443 formats, subtitles = self._download_media_selector(programme_id)
444 else:
445 formats, subtitles = self._process_media_selector(item, playlist_id)
446 programme_id = playlist_id
ae6986fb
S
447
448 return programme_id, title, description, duration, formats, subtitles
449
c056efa2
S
450 def _real_extract(self, url):
451 group_id = self._match_id(url)
452
453 webpage = self._download_webpage(url, group_id, 'Downloading video page')
454
8683b4d8 455 programme_id = None
679bacf0 456 duration = None
8683b4d8
S
457
458 tviplayer = self._search_regex(
459 r'mediator\.bind\(({.+?})\s*,\s*document\.getElementById',
460 webpage, 'player', default=None)
461
462 if tviplayer:
463 player = self._parse_json(tviplayer, group_id).get('player', {})
464 duration = int_or_none(player.get('duration'))
465 programme_id = player.get('vpid')
466
467 if not programme_id:
468 programme_id = self._search_regex(
22d7368d 469 r'"vpid"\s*:\s*"(%s)"' % self._ID_REGEX, webpage, 'vpid', fatal=False, default=None)
8683b4d8 470
c056efa2 471 if programme_id:
c056efa2 472 formats, subtitles = self._download_media_selector(programme_id)
8683b4d8
S
473 title = self._og_search_title(webpage)
474 description = self._search_regex(
25fa8d66 475 r'<p class="[^"]*medium-description[^"]*">([^<]+)</p>',
679bacf0
YCH
476 webpage, 'description', default=None)
477 if not description:
478 description = self._html_search_meta('description', webpage)
c056efa2 479 else:
ae6986fb 480 programme_id, title, description, duration, formats, subtitles = self._download_playlist(group_id)
2e3fd9ec 481
082c6c86
S
482 self._sort_formats(formats)
483
484 return {
2e3fd9ec 485 'id': programme_id,
082c6c86
S
486 'title': title,
487 'description': description,
650cfd0c 488 'thumbnail': self._og_search_thumbnail(webpage, default=None),
082c6c86
S
489 'duration': duration,
490 'formats': formats,
2e3fd9ec 491 'subtitles': subtitles,
5f6a1245 492 }
10273d6e 493
494
9afa1770
S
495class BBCIE(BBCCoUkIE):
496 IE_NAME = 'bbc'
497 IE_DESC = 'BBC'
498 _VALID_URL = r'https?://(?:www\.)?bbc\.(?:com|co\.uk)/(?:[^/]+/)+(?P<id>[^/#?]+)'
10273d6e 499
d12a1a47 500 _MEDIASELECTOR_URLS = [
55ebae26
S
501 # Provides HQ HLS streams but fails with geolocation in some cases when it's
502 # even not geo restricted at all
503 'http://open.live.bbc.co.uk/mediaselector/5/select/version/2.0/mediaset/iptv-all/vpid/%s',
d12a1a47
S
504 # Provides more formats, namely direct mp4 links, but fails on some videos with
505 # notukerror for non UK (?) users (e.g.
506 # http://www.bbc.com/travel/story/20150625-sri-lankas-spicy-secret)
507 'http://open.live.bbc.co.uk/mediaselector/4/mtis/stream/%s',
508 # Provides fewer formats, but works everywhere for everybody (hopefully)
509 'http://open.live.bbc.co.uk/mediaselector/5/select/version/2.0/mediaset/journalism-pc/vpid/%s',
510 ]
10273d6e 511
512 _TESTS = [{
6a747190 513 # article with multiple videos embedded with data-playable containing vpids
10273d6e 514 'url': 'http://www.bbc.com/news/world-europe-32668511',
515 'info_dict': {
516 'id': 'world-europe-32668511',
517 'title': 'Russia stages massive WW2 parade despite Western boycott',
9afa1770 518 'description': 'md5:00ff61976f6081841f759a08bf78cc9c',
10273d6e 519 },
520 'playlist_count': 2,
a3bfddfa 521 }, {
6a747190 522 # article with multiple videos embedded with data-playable (more videos)
10273d6e 523 'url': 'http://www.bbc.com/news/business-28299555',
524 'info_dict': {
525 'id': 'business-28299555',
526 'title': 'Farnborough Airshow: Video highlights',
9afa1770 527 'description': 'BBC reports and video highlights at the Farnborough Airshow.',
10273d6e 528 },
529 'playlist_count': 9,
9afa1770 530 'skip': 'Save time',
88ed52ae
S
531 }, {
532 # article with multiple videos embedded with `new SMP()`
6a747190 533 # broken
88ed52ae
S
534 'url': 'http://www.bbc.co.uk/blogs/adamcurtis/entries/3662a707-0af9-3149-963f-47bea720b460',
535 'info_dict': {
536 'id': '3662a707-0af9-3149-963f-47bea720b460',
537 'title': 'BBC Blogs - Adam Curtis - BUGGER',
538 },
539 'playlist_count': 18,
a3bfddfa 540 }, {
6a747190 541 # single video embedded with data-playable containing vpid
10273d6e 542 'url': 'http://www.bbc.com/news/world-europe-32041533',
10273d6e 543 'info_dict': {
544 'id': 'p02mprgb',
55ebae26 545 'ext': 'mp4',
10273d6e 546 'title': 'Aerial footage showed the site of the crash in the Alps - courtesy BFM TV',
55ebae26 547 'description': 'md5:2868290467291b37feda7863f7a83f54',
10273d6e 548 'duration': 47,
9afa1770 549 'timestamp': 1427219242,
da92eeae 550 'upload_date': '20150324',
10273d6e 551 },
552 'params': {
9afa1770 553 # rtmp download
10273d6e 554 'skip_download': True,
555 }
a3bfddfa 556 }, {
6a747190
S
557 # article with single video embedded with data-playable containing XML playlist
558 # with direct video links as progressiveDownloadUrl (for now these are extracted)
559 # and playlist with f4m and m3u8 as streamingUrl
de939d89 560 'url': 'http://www.bbc.com/turkce/haberler/2015/06/150615_telabyad_kentin_cogu',
de939d89 561 'info_dict': {
9afa1770 562 'id': '150615_telabyad_kentin_cogu',
de939d89 563 'ext': 'mp4',
9afa1770 564 'title': "YPG: Tel Abyad'ın tamamı kontrolümüzde",
9afa1770 565 'timestamp': 1434397334,
da92eeae 566 'upload_date': '20150615',
de939d89 567 },
568 'params': {
569 'skip_download': True,
570 }
c936d8cc 571 }, {
6a747190 572 # single video embedded with data-playable containing XML playlists (regional section)
de939d89 573 'url': 'http://www.bbc.com/mundo/video_fotos/2015/06/150619_video_honduras_militares_hospitales_corrupcion_aw',
de939d89 574 'info_dict': {
9afa1770 575 'id': '150619_video_honduras_militares_hospitales_corrupcion_aw',
de939d89 576 'ext': 'mp4',
9afa1770 577 'title': 'Honduras militariza sus hospitales por nuevo escándalo de corrupción',
9afa1770 578 'timestamp': 1434713142,
da92eeae 579 'upload_date': '20150619',
de939d89 580 },
581 'params': {
582 'skip_download': True,
583 }
a346b1ff
S
584 }, {
585 # single video from video playlist embedded with vxp-playlist-data JSON
586 'url': 'http://www.bbc.com/news/video_and_audio/must_see/33376376',
587 'info_dict': {
588 'id': 'p02w6qjc',
55ebae26 589 'ext': 'mp4',
a346b1ff
S
590 'title': '''Judge Mindy Glazer: "I'm sorry to see you here... I always wondered what happened to you"''',
591 'duration': 56,
592 },
593 'params': {
594 'skip_download': True,
595 }
9afa1770
S
596 }, {
597 # single video story with digitalData
598 'url': 'http://www.bbc.com/travel/story/20150625-sri-lankas-spicy-secret',
599 'info_dict': {
600 'id': 'p02q6gc4',
601 'ext': 'flv',
602 'title': 'Sri Lanka’s spicy secret',
603 'description': 'As a new train line to Jaffna opens up the country’s north, travellers can experience a truly distinct slice of Tamil culture.',
604 'timestamp': 1437674293,
605 'upload_date': '20150723',
606 },
607 'params': {
608 # rtmp download
609 'skip_download': True,
610 }
611 }, {
612 # single video story without digitalData
613 'url': 'http://www.bbc.com/autos/story/20130513-hyundais-rock-star',
614 'info_dict': {
615 'id': 'p018zqqg',
55ebae26 616 'ext': 'mp4',
9afa1770
S
617 'title': 'Hyundai Santa Fe Sport: Rock star',
618 'description': 'md5:b042a26142c4154a6e472933cf20793d',
ae8bdfd1
S
619 'timestamp': 1415867444,
620 'upload_date': '20141113',
9afa1770
S
621 },
622 'params': {
623 # rtmp download
624 'skip_download': True,
625 }
626 }, {
6a747190 627 # single video with playlist.sxml URL in playlist param
9afa1770
S
628 'url': 'http://www.bbc.com/sport/0/football/33653409',
629 'info_dict': {
630 'id': 'p02xycnp',
55ebae26 631 'ext': 'mp4',
9afa1770 632 'title': 'Transfers: Cristiano Ronaldo to Man Utd, Arsenal to spend?',
7033bc1a 633 'description': 'BBC Sport\'s David Ornstein has the latest transfer gossip, including rumours of a Manchester United return for Cristiano Ronaldo.',
9afa1770
S
634 'duration': 140,
635 },
636 'params': {
637 # rtmp download
638 'skip_download': True,
639 }
b5d48cb1 640 }, {
6a747190 641 # article with multiple videos embedded with playlist.sxml in playlist param
b5d48cb1
S
642 'url': 'http://www.bbc.com/sport/0/football/34475836',
643 'info_dict': {
644 'id': '34475836',
645 'title': 'What Liverpool can expect from Klopp',
646 },
647 'playlist_count': 3,
9afa1770
S
648 }, {
649 # single video with playlist URL from weather section
650 'url': 'http://www.bbc.com/weather/features/33601775',
651 'only_matching': True,
652 }, {
653 # custom redirection to www.bbc.com
654 'url': 'http://www.bbc.co.uk/news/science-environment-33661876',
655 'only_matching': True,
10273d6e 656 }]
657
9afa1770
S
658 @classmethod
659 def suitable(cls, url):
a65402ef 660 return False if BBCCoUkIE.suitable(url) or BBCCoUkArticleIE.suitable(url) else super(BBCIE, cls).suitable(url)
9afa1770
S
661
662 def _extract_from_media_meta(self, media_meta, video_id):
663 # Direct links to media in media metadata (e.g.
664 # http://www.bbc.com/turkce/haberler/2015/06/150615_telabyad_kentin_cogu)
665 # TODO: there are also f4m and m3u8 streams incorporated in playlist.sxml
666 source_files = media_meta.get('sourceFiles')
667 if source_files:
668 return [{
669 'url': f['url'],
670 'format_id': format_id,
671 'ext': f.get('encoding'),
672 'tbr': float_or_none(f.get('bitrate'), 1000),
673 'filesize': int_or_none(f.get('filesize')),
674 } for format_id, f in source_files.items() if f.get('url')], []
675
676 programme_id = media_meta.get('externalId')
677 if programme_id:
678 return self._download_media_selector(programme_id)
679
680 # Process playlist.sxml as legacy playlist
681 href = media_meta.get('href')
682 if href:
683 playlist = self._download_legacy_playlist_url(href)
684 _, _, _, _, formats, subtitles = self._extract_from_legacy_playlist(playlist, video_id)
685 return formats, subtitles
686
687 return [], []
688
baf39a1a
S
689 def _extract_from_playlist_sxml(self, url, playlist_id, timestamp):
690 programme_id, title, description, duration, formats, subtitles = \
691 self._process_legacy_playlist_url(url, playlist_id)
692 self._sort_formats(formats)
693 return {
694 'id': programme_id,
695 'title': title,
696 'description': description,
697 'duration': duration,
698 'timestamp': timestamp,
699 'formats': formats,
700 'subtitles': subtitles,
701 }
702
10273d6e 703 def _real_extract(self, url):
9afa1770
S
704 playlist_id = self._match_id(url)
705
706 webpage = self._download_webpage(url, playlist_id)
707
ae8bdfd1
S
708 timestamp = None
709 playlist_title = None
710 playlist_description = None
711
712 ld = self._parse_json(
713 self._search_regex(
714 r'(?s)<script type="application/ld\+json">(.+?)</script>',
715 webpage, 'ld json', default='{}'),
716 playlist_id, fatal=False)
717 if ld:
718 timestamp = parse_iso8601(ld.get('datePublished'))
719 playlist_title = ld.get('headline')
720 playlist_description = ld.get('articleBody')
721
722 if not timestamp:
723 timestamp = parse_iso8601(self._search_regex(
724 [r'<meta[^>]+property="article:published_time"[^>]+content="([^"]+)"',
725 r'itemprop="datePublished"[^>]+datetime="([^"]+)"',
6f789365 726 r'"datePublished":\s*"([^"]+)'],
ae8bdfd1 727 webpage, 'date', default=None))
9afa1770 728
78f9d843
S
729 entries = []
730
de665713
S
731 # article with multiple videos embedded with playlist.sxml (e.g.
732 # http://www.bbc.com/sport/0/football/34475836)
733 playlists = re.findall(r'<param[^>]+name="playlist"[^>]+value="([^"]+)"', webpage)
734 if playlists:
baf39a1a
S
735 entries = [
736 self._extract_from_playlist_sxml(playlist_url, playlist_id, timestamp)
737 for playlist_url in playlists]
de939d89 738
78f9d843
S
739 # news article with multiple videos embedded with data-playable
740 data_playables = re.findall(r'data-playable=(["\'])({.+?})\1', webpage)
741 if data_playables:
742 for _, data_playable_json in data_playables:
743 data_playable = self._parse_json(
744 unescapeHTML(data_playable_json), playlist_id, fatal=False)
745 if not data_playable:
746 continue
baf39a1a
S
747 settings = data_playable.get('settings', {})
748 if settings:
78f9d843
S
749 # data-playable with video vpid in settings.playlistObject.items (e.g.
750 # http://www.bbc.com/news/world-us-canada-34473351)
baf39a1a
S
751 playlist_object = settings.get('playlistObject', {})
752 if playlist_object:
753 items = playlist_object.get('items')
754 if items and isinstance(items, list):
78f9d843
S
755 title = playlist_object['title']
756 description = playlist_object.get('summary')
baf39a1a
S
757 duration = int_or_none(items[0].get('duration'))
758 programme_id = items[0].get('vpid')
78f9d843
S
759 formats, subtitles = self._download_media_selector(programme_id)
760 self._sort_formats(formats)
761 entries.append({
762 'id': programme_id,
763 'title': title,
764 'description': description,
765 'timestamp': timestamp,
766 'duration': duration,
767 'formats': formats,
768 'subtitles': subtitles,
769 })
770 else:
771 # data-playable without vpid but with a playlist.sxml URLs
772 # in otherSettings.playlist (e.g.
773 # http://www.bbc.com/turkce/multimedya/2015/10/151010_vid_ankara_patlama_ani)
774 playlist = data_playable.get('otherSettings', {}).get('playlist', {})
775 if playlist:
776 entries.append(self._extract_from_playlist_sxml(
777 playlist.get('progressiveDownloadUrl'), playlist_id, timestamp))
778
779 if entries:
ae8bdfd1
S
780 playlist_title = playlist_title or remove_end(self._og_search_title(webpage), ' - BBC News')
781 playlist_description = playlist_description or self._og_search_description(webpage, default=None)
78f9d843
S
782 return self.playlist_result(entries, playlist_id, playlist_title, playlist_description)
783
784 # single video story (e.g. http://www.bbc.com/travel/story/20150625-sri-lankas-spicy-secret)
785 programme_id = self._search_regex(
22d7368d
S
786 [r'data-video-player-vpid="(%s)"' % self._ID_REGEX,
787 r'<param[^>]+name="externalIdentifier"[^>]+value="(%s)"' % self._ID_REGEX,
788 r'videoId\s*:\s*["\'](%s)["\']' % self._ID_REGEX],
78f9d843 789 webpage, 'vpid', default=None)
dab062fb 790
9afa1770
S
791 if programme_id:
792 formats, subtitles = self._download_media_selector(programme_id)
793 self._sort_formats(formats)
794 # digitalData may be missing (e.g. http://www.bbc.com/autos/story/20130513-hyundais-rock-star)
795 digital_data = self._parse_json(
796 self._search_regex(
797 r'var\s+digitalData\s*=\s*({.+?});?\n', webpage, 'digital data', default='{}'),
798 programme_id, fatal=False)
799 page_info = digital_data.get('page', {}).get('pageInfo', {})
800 title = page_info.get('pageName') or self._og_search_title(webpage)
801 description = page_info.get('description') or self._og_search_description(webpage)
802 timestamp = parse_iso8601(page_info.get('publicationDate')) or timestamp
803 return {
804 'id': programme_id,
805 'title': title,
806 'description': description,
807 'timestamp': timestamp,
808 'formats': formats,
809 'subtitles': subtitles,
810 }
a3bfddfa 811
9afa1770
S
812 playlist_title = self._html_search_regex(
813 r'<title>(.*?)(?:\s*-\s*BBC [^ ]+)?</title>', webpage, 'playlist title')
88ed52ae
S
814 playlist_description = self._og_search_description(webpage, default=None)
815
816 def extract_all(pattern):
817 return list(filter(None, map(
818 lambda s: self._parse_json(s, playlist_id, fatal=False),
819 re.findall(pattern, webpage))))
820
821 # Multiple video article (e.g.
822 # http://www.bbc.co.uk/blogs/adamcurtis/entries/3662a707-0af9-3149-963f-47bea720b460)
22d7368d 823 EMBED_URL = r'https?://(?:www\.)?bbc\.co\.uk/(?:[^/]+/)+%s(?:\b[^"]+)?' % self._ID_REGEX
88ed52ae
S
824 entries = []
825 for match in extract_all(r'new\s+SMP\(({.+?})\)'):
826 embed_url = match.get('playerSettings', {}).get('externalEmbedUrl')
827 if embed_url and re.match(EMBED_URL, embed_url):
828 entries.append(embed_url)
829 entries.extend(re.findall(
830 r'setPlaylist\("(%s)"\)' % EMBED_URL, webpage))
831 if entries:
832 return self.playlist_result(
833 [self.url_result(entry, 'BBCCoUk') for entry in entries],
834 playlist_id, playlist_title, playlist_description)
9afa1770
S
835
836 # Multiple video article (e.g. http://www.bbc.com/news/world-europe-32668511)
88ed52ae 837 medias = extract_all(r"data-media-meta='({[^']+})'")
9afa1770
S
838
839 if not medias:
840 # Single video article (e.g. http://www.bbc.com/news/video_and_audio/international)
a346b1ff
S
841 media_asset = self._search_regex(
842 r'mediaAssetPage\.init\(\s*({.+?}), "/',
843 webpage, 'media asset', default=None)
844 if media_asset:
845 media_asset_page = self._parse_json(media_asset, playlist_id, fatal=False)
846 medias = []
847 for video in media_asset_page.get('videos', {}).values():
848 medias.extend(video.values())
849
850 if not medias:
851 # Multiple video playlist with single `now playing` entry (e.g.
852 # http://www.bbc.com/news/video_and_audio/must_see/33767813)
853 vxp_playlist = self._parse_json(
9afa1770 854 self._search_regex(
a346b1ff
S
855 r'<script[^>]+class="vxp-playlist-data"[^>]+type="application/json"[^>]*>([^<]+)</script>',
856 webpage, 'playlist data'),
9afa1770 857 playlist_id)
a346b1ff
S
858 playlist_medias = []
859 for item in vxp_playlist:
860 media = item.get('media')
861 if not media:
862 continue
863 playlist_medias.append(media)
864 # Download single video if found media with asset id matching the video id from URL
865 if item.get('advert', {}).get('assetId') == playlist_id:
866 medias = [media]
867 break
868 # Fallback to the whole playlist
869 if not medias:
870 medias = playlist_medias
9afa1770
S
871
872 entries = []
873 for num, media_meta in enumerate(medias, start=1):
874 formats, subtitles = self._extract_from_media_meta(media_meta, playlist_id)
875 if not formats:
876 continue
10273d6e 877 self._sort_formats(formats)
878
9afa1770
S
879 video_id = media_meta.get('externalId')
880 if not video_id:
881 video_id = playlist_id if len(medias) == 1 else '%s-%s' % (playlist_id, num)
882
883 title = media_meta.get('caption')
884 if not title:
885 title = playlist_title if len(medias) == 1 else '%s - Video %s' % (playlist_title, num)
886
887 duration = int_or_none(media_meta.get('durationInSeconds')) or parse_duration(media_meta.get('duration'))
da92eeae 888
9afa1770
S
889 images = []
890 for image in media_meta.get('images', {}).values():
891 images.extend(image.values())
892 if 'image' in media_meta:
893 images.append(media_meta['image'])
894
895 thumbnails = [{
896 'url': image.get('href'),
897 'width': int_or_none(image.get('width')),
898 'height': int_or_none(image.get('height')),
899 } for image in images]
900
901 entries.append({
902 'id': video_id,
10273d6e 903 'title': title,
9afa1770 904 'thumbnails': thumbnails,
10273d6e 905 'duration': duration,
9afa1770 906 'timestamp': timestamp,
10273d6e 907 'formats': formats,
908 'subtitles': subtitles,
a3bfddfa 909 })
10273d6e 910
9afa1770 911 return self.playlist_result(entries, playlist_id, playlist_title, playlist_description)
a65402ef
YCH
912
913
914class BBCCoUkArticleIE(InfoExtractor):
915 _VALID_URL = 'http://www.bbc.co.uk/programmes/articles/(?P<id>[a-zA-Z0-9]+)'
916 IE_NAME = 'bbc.co.uk:article'
917 IE_DESC = 'BBC articles'
918
919 _TEST = {
920 'url': 'http://www.bbc.co.uk/programmes/articles/3jNQLTMrPlYGTBn0WV6M2MS/not-your-typical-role-model-ada-lovelace-the-19th-century-programmer',
921 'info_dict': {
922 'id': '3jNQLTMrPlYGTBn0WV6M2MS',
923 'title': 'Calculating Ada: The Countess of Computing - Not your typical role model: Ada Lovelace the 19th century programmer - BBC Four',
924 'description': 'Hannah Fry reveals some of her surprising discoveries about Ada Lovelace during filming.',
925 },
926 'playlist_count': 4,
927 'add_ie': ['BBCCoUk'],
928 }
929
930 def _real_extract(self, url):
931 playlist_id = self._match_id(url)
932
933 webpage = self._download_webpage(url, playlist_id)
934
935 title = self._og_search_title(webpage)
936 description = self._og_search_description(webpage).strip()
937
938 entries = [self.url_result(programme_url) for programme_url in re.findall(
939 r'<div[^>]+typeof="Clip"[^>]+resource="([^"]+)"', webpage)]
940
941 return self.playlist_result(entries, playlist_id, title, description)