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