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