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