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