[bbc] Extract article JSON and actualize tests
[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     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 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 more formats, namely direct mp4 links, but fails on some videos with
497         # notukerror for non UK (?) users (e.g.
498         # http://www.bbc.com/travel/story/20150625-sri-lankas-spicy-secret)
499         'http://open.live.bbc.co.uk/mediaselector/4/mtis/stream/%s',
500         # Provides fewer formats, but works everywhere for everybody (hopefully)
501         'http://open.live.bbc.co.uk/mediaselector/5/select/version/2.0/mediaset/journalism-pc/vpid/%s',
502     ]
503
504     _TESTS = [{
505         # article with multiple videos embedded with data-playable containing vpids
506         'url': 'http://www.bbc.com/news/world-europe-32668511',
507         'info_dict': {
508             'id': 'world-europe-32668511',
509             'title': 'Russia stages massive WW2 parade despite Western boycott',
510             'description': 'md5:00ff61976f6081841f759a08bf78cc9c',
511         },
512         'playlist_count': 2,
513     }, {
514         # article with multiple videos embedded with data-playable (more videos)
515         'url': 'http://www.bbc.com/news/business-28299555',
516         'info_dict': {
517             'id': 'business-28299555',
518             'title': 'Farnborough Airshow: Video highlights',
519             'description': 'BBC reports and video highlights at the Farnborough Airshow.',
520         },
521         'playlist_count': 9,
522         'skip': 'Save time',
523     }, {
524         # article with multiple videos embedded with `new SMP()`
525         # broken
526         'url': 'http://www.bbc.co.uk/blogs/adamcurtis/entries/3662a707-0af9-3149-963f-47bea720b460',
527         'info_dict': {
528             'id': '3662a707-0af9-3149-963f-47bea720b460',
529             'title': 'BBC Blogs - Adam Curtis - BUGGER',
530         },
531         'playlist_count': 18,
532     }, {
533         # single video embedded with data-playable containing vpid
534         'url': 'http://www.bbc.com/news/world-europe-32041533',
535         'info_dict': {
536             'id': 'p02mprgb',
537             'ext': 'flv',
538             'title': 'Aerial footage showed the site of the crash in the Alps - courtesy BFM TV',
539             'duration': 47,
540             'timestamp': 1427219242,
541             'upload_date': '20150324',
542         },
543         'params': {
544             # rtmp download
545             'skip_download': True,
546         }
547     }, {
548         # article with single video embedded with data-playable containing XML playlist
549         # with direct video links as progressiveDownloadUrl (for now these are extracted)
550         # and playlist with f4m and m3u8 as streamingUrl
551         'url': 'http://www.bbc.com/turkce/haberler/2015/06/150615_telabyad_kentin_cogu',
552         'info_dict': {
553             'id': '150615_telabyad_kentin_cogu',
554             'ext': 'mp4',
555             'title': "YPG: Tel Abyad'ın tamamı kontrolümüzde",
556             'timestamp': 1434397334,
557             'upload_date': '20150615',
558         },
559         'params': {
560             'skip_download': True,
561         }
562     }, {
563         # single video embedded with data-playable containing XML playlists (regional section)
564         'url': 'http://www.bbc.com/mundo/video_fotos/2015/06/150619_video_honduras_militares_hospitales_corrupcion_aw',
565         'info_dict': {
566             'id': '150619_video_honduras_militares_hospitales_corrupcion_aw',
567             'ext': 'mp4',
568             'title': 'Honduras militariza sus hospitales por nuevo escándalo de corrupción',
569             'timestamp': 1434713142,
570             'upload_date': '20150619',
571         },
572         'params': {
573             'skip_download': True,
574         }
575     }, {
576         # single video from video playlist embedded with vxp-playlist-data JSON
577         'url': 'http://www.bbc.com/news/video_and_audio/must_see/33376376',
578         'info_dict': {
579             'id': 'p02w6qjc',
580             'ext': 'flv',
581             'title': '''Judge Mindy Glazer: "I'm sorry to see you here... I always wondered what happened to you"''',
582             'duration': 56,
583         },
584         'params': {
585             'skip_download': True,
586         }
587     }, {
588         # single video story with digitalData
589         'url': 'http://www.bbc.com/travel/story/20150625-sri-lankas-spicy-secret',
590         'info_dict': {
591             'id': 'p02q6gc4',
592             'ext': 'flv',
593             'title': 'Sri Lanka’s spicy secret',
594             'description': 'As a new train line to Jaffna opens up the country’s north, travellers can experience a truly distinct slice of Tamil culture.',
595             'timestamp': 1437674293,
596             'upload_date': '20150723',
597         },
598         'params': {
599             # rtmp download
600             'skip_download': True,
601         }
602     }, {
603         # single video story without digitalData
604         'url': 'http://www.bbc.com/autos/story/20130513-hyundais-rock-star',
605         'info_dict': {
606             'id': 'p018zqqg',
607             'ext': 'flv',
608             'title': 'Hyundai Santa Fe Sport: Rock star',
609             'description': 'md5:b042a26142c4154a6e472933cf20793d',
610             'timestamp': 1415867444,
611             'upload_date': '20141113',
612         },
613         'params': {
614             # rtmp download
615             'skip_download': True,
616         }
617     }, {
618         # single video with playlist.sxml URL in playlist param
619         'url': 'http://www.bbc.com/sport/0/football/33653409',
620         'info_dict': {
621             'id': 'p02xycnp',
622             'ext': 'flv',
623             'title': 'Transfers: Cristiano Ronaldo to Man Utd, Arsenal to spend?',
624             'duration': 140,
625         },
626         'params': {
627             # rtmp download
628             'skip_download': True,
629         }
630     }, {
631         # article with multiple videos embedded with playlist.sxml in playlist param
632         'url': 'http://www.bbc.com/sport/0/football/34475836',
633         'info_dict': {
634             'id': '34475836',
635             'title': 'What Liverpool can expect from Klopp',
636         },
637         'playlist_count': 3,
638     }, {
639         # single video with playlist URL from weather section
640         'url': 'http://www.bbc.com/weather/features/33601775',
641         'only_matching': True,
642     }, {
643         # custom redirection to www.bbc.com
644         'url': 'http://www.bbc.co.uk/news/science-environment-33661876',
645         'only_matching': True,
646     }]
647
648     @classmethod
649     def suitable(cls, url):
650         return False if BBCCoUkIE.suitable(url) else super(BBCIE, cls).suitable(url)
651
652     def _extract_from_media_meta(self, media_meta, video_id):
653         # Direct links to media in media metadata (e.g.
654         # http://www.bbc.com/turkce/haberler/2015/06/150615_telabyad_kentin_cogu)
655         # TODO: there are also f4m and m3u8 streams incorporated in playlist.sxml
656         source_files = media_meta.get('sourceFiles')
657         if source_files:
658             return [{
659                 'url': f['url'],
660                 'format_id': format_id,
661                 'ext': f.get('encoding'),
662                 'tbr': float_or_none(f.get('bitrate'), 1000),
663                 'filesize': int_or_none(f.get('filesize')),
664             } for format_id, f in source_files.items() if f.get('url')], []
665
666         programme_id = media_meta.get('externalId')
667         if programme_id:
668             return self._download_media_selector(programme_id)
669
670         # Process playlist.sxml as legacy playlist
671         href = media_meta.get('href')
672         if href:
673             playlist = self._download_legacy_playlist_url(href)
674             _, _, _, _, formats, subtitles = self._extract_from_legacy_playlist(playlist, video_id)
675             return formats, subtitles
676
677         return [], []
678
679     def _extract_from_playlist_sxml(self, url, playlist_id, timestamp):
680         programme_id, title, description, duration, formats, subtitles = \
681             self._process_legacy_playlist_url(url, playlist_id)
682         self._sort_formats(formats)
683         return {
684             'id': programme_id,
685             'title': title,
686             'description': description,
687             'duration': duration,
688             'timestamp': timestamp,
689             'formats': formats,
690             'subtitles': subtitles,
691         }
692
693     def _real_extract(self, url):
694         playlist_id = self._match_id(url)
695
696         webpage = self._download_webpage(url, playlist_id)
697
698         timestamp = None
699         playlist_title = None
700         playlist_description = None
701
702         ld = self._parse_json(
703             self._search_regex(
704                 r'(?s)<script type="application/ld\+json">(.+?)</script>',
705                 webpage, 'ld json', default='{}'),
706             playlist_id, fatal=False)
707         if ld:
708             timestamp = parse_iso8601(ld.get('datePublished'))
709             playlist_title = ld.get('headline')
710             playlist_description = ld.get('articleBody')
711
712         if not timestamp:
713             timestamp = parse_iso8601(self._search_regex(
714                 [r'<meta[^>]+property="article:published_time"[^>]+content="([^"]+)"',
715                  r'itemprop="datePublished"[^>]+datetime="([^"]+)"',
716                  r'"datePublished":\s*"([^"]+)',],
717                 webpage, 'date', default=None))
718
719         entries = []
720
721         # article with multiple videos embedded with playlist.sxml (e.g.
722         # http://www.bbc.com/sport/0/football/34475836)
723         playlists = re.findall(r'<param[^>]+name="playlist"[^>]+value="([^"]+)"', webpage)
724         if playlists:
725             entries = [
726                 self._extract_from_playlist_sxml(playlist_url, playlist_id, timestamp)
727                 for playlist_url in playlists]
728
729         # news article with multiple videos embedded with data-playable
730         data_playables = re.findall(r'data-playable=(["\'])({.+?})\1', webpage)
731         if data_playables:
732             for _, data_playable_json in data_playables:
733                 data_playable = self._parse_json(
734                     unescapeHTML(data_playable_json), playlist_id, fatal=False)
735                 if not data_playable:
736                     continue
737                 settings = data_playable.get('settings', {})
738                 if settings:
739                     # data-playable with video vpid in settings.playlistObject.items (e.g.
740                     # http://www.bbc.com/news/world-us-canada-34473351)
741                     playlist_object = settings.get('playlistObject', {})
742                     if playlist_object:
743                         items = playlist_object.get('items')
744                         if items and isinstance(items, list):
745                             title = playlist_object['title']
746                             description = playlist_object.get('summary')
747                             duration = int_or_none(items[0].get('duration'))
748                             programme_id = items[0].get('vpid')
749                             formats, subtitles = self._download_media_selector(programme_id)
750                             self._sort_formats(formats)
751                             entries.append({
752                                 'id': programme_id,
753                                 'title': title,
754                                 'description': description,
755                                 'timestamp': timestamp,
756                                 'duration': duration,
757                                 'formats': formats,
758                                 'subtitles': subtitles,
759                             })
760                     else:
761                         # data-playable without vpid but with a playlist.sxml URLs
762                         # in otherSettings.playlist (e.g.
763                         # http://www.bbc.com/turkce/multimedya/2015/10/151010_vid_ankara_patlama_ani)
764                         playlist = data_playable.get('otherSettings', {}).get('playlist', {})
765                         if playlist:
766                             entries.append(self._extract_from_playlist_sxml(
767                                 playlist.get('progressiveDownloadUrl'), playlist_id, timestamp))
768
769         if entries:
770             playlist_title = playlist_title or remove_end(self._og_search_title(webpage), ' - BBC News')
771             playlist_description = playlist_description or self._og_search_description(webpage, default=None)
772             return self.playlist_result(entries, playlist_id, playlist_title, playlist_description)
773
774         # single video story (e.g. http://www.bbc.com/travel/story/20150625-sri-lankas-spicy-secret)
775         programme_id = self._search_regex(
776             [r'data-video-player-vpid="([\da-z]{8})"',
777              r'<param[^>]+name="externalIdentifier"[^>]+value="([\da-z]{8})"'],
778             webpage, 'vpid', default=None)
779
780         if programme_id:
781             formats, subtitles = self._download_media_selector(programme_id)
782             self._sort_formats(formats)
783             # digitalData may be missing (e.g. http://www.bbc.com/autos/story/20130513-hyundais-rock-star)
784             digital_data = self._parse_json(
785                 self._search_regex(
786                     r'var\s+digitalData\s*=\s*({.+?});?\n', webpage, 'digital data', default='{}'),
787                 programme_id, fatal=False)
788             page_info = digital_data.get('page', {}).get('pageInfo', {})
789             title = page_info.get('pageName') or self._og_search_title(webpage)
790             description = page_info.get('description') or self._og_search_description(webpage)
791             timestamp = parse_iso8601(page_info.get('publicationDate')) or timestamp
792             return {
793                 'id': programme_id,
794                 'title': title,
795                 'description': description,
796                 'timestamp': timestamp,
797                 'formats': formats,
798                 'subtitles': subtitles,
799             }
800
801         playlist_title = self._html_search_regex(
802             r'<title>(.*?)(?:\s*-\s*BBC [^ ]+)?</title>', webpage, 'playlist title')
803         playlist_description = self._og_search_description(webpage, default=None)
804
805         def extract_all(pattern):
806             return list(filter(None, map(
807                 lambda s: self._parse_json(s, playlist_id, fatal=False),
808                 re.findall(pattern, webpage))))
809
810         # Multiple video article (e.g.
811         # http://www.bbc.co.uk/blogs/adamcurtis/entries/3662a707-0af9-3149-963f-47bea720b460)
812         EMBED_URL = r'https?://(?:www\.)?bbc\.co\.uk/(?:[^/]+/)+[\da-z]{8}(?:\b[^"]+)?'
813         entries = []
814         for match in extract_all(r'new\s+SMP\(({.+?})\)'):
815             embed_url = match.get('playerSettings', {}).get('externalEmbedUrl')
816             if embed_url and re.match(EMBED_URL, embed_url):
817                 entries.append(embed_url)
818         entries.extend(re.findall(
819             r'setPlaylist\("(%s)"\)' % EMBED_URL, webpage))
820         if entries:
821             return self.playlist_result(
822                 [self.url_result(entry, 'BBCCoUk') for entry in entries],
823                 playlist_id, playlist_title, playlist_description)
824
825         # Multiple video article (e.g. http://www.bbc.com/news/world-europe-32668511)
826         medias = extract_all(r"data-media-meta='({[^']+})'")
827
828         if not medias:
829             # Single video article (e.g. http://www.bbc.com/news/video_and_audio/international)
830             media_asset = self._search_regex(
831                 r'mediaAssetPage\.init\(\s*({.+?}), "/',
832                 webpage, 'media asset', default=None)
833             if media_asset:
834                 media_asset_page = self._parse_json(media_asset, playlist_id, fatal=False)
835                 medias = []
836                 for video in media_asset_page.get('videos', {}).values():
837                     medias.extend(video.values())
838
839         if not medias:
840             # Multiple video playlist with single `now playing` entry (e.g.
841             # http://www.bbc.com/news/video_and_audio/must_see/33767813)
842             vxp_playlist = self._parse_json(
843                 self._search_regex(
844                     r'<script[^>]+class="vxp-playlist-data"[^>]+type="application/json"[^>]*>([^<]+)</script>',
845                     webpage, 'playlist data'),
846                 playlist_id)
847             playlist_medias = []
848             for item in vxp_playlist:
849                 media = item.get('media')
850                 if not media:
851                     continue
852                 playlist_medias.append(media)
853                 # Download single video if found media with asset id matching the video id from URL
854                 if item.get('advert', {}).get('assetId') == playlist_id:
855                     medias = [media]
856                     break
857             # Fallback to the whole playlist
858             if not medias:
859                 medias = playlist_medias
860
861         entries = []
862         for num, media_meta in enumerate(medias, start=1):
863             formats, subtitles = self._extract_from_media_meta(media_meta, playlist_id)
864             if not formats:
865                 continue
866             self._sort_formats(formats)
867
868             video_id = media_meta.get('externalId')
869             if not video_id:
870                 video_id = playlist_id if len(medias) == 1 else '%s-%s' % (playlist_id, num)
871
872             title = media_meta.get('caption')
873             if not title:
874                 title = playlist_title if len(medias) == 1 else '%s - Video %s' % (playlist_title, num)
875
876             duration = int_or_none(media_meta.get('durationInSeconds')) or parse_duration(media_meta.get('duration'))
877
878             images = []
879             for image in media_meta.get('images', {}).values():
880                 images.extend(image.values())
881             if 'image' in media_meta:
882                 images.append(media_meta['image'])
883
884             thumbnails = [{
885                 'url': image.get('href'),
886                 'width': int_or_none(image.get('width')),
887                 'height': int_or_none(image.get('height')),
888             } for image in images]
889
890             entries.append({
891                 'id': video_id,
892                 'title': title,
893                 'thumbnails': thumbnails,
894                 'duration': duration,
895                 'timestamp': timestamp,
896                 'formats': formats,
897                 'subtitles': subtitles,
898             })
899
900         return self.playlist_result(entries, playlist_id, playlist_title, playlist_description)