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