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