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