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