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