dcc5fc2fadff772b58615c7beb9bc18084a6465f
[youtube-dl] / youtube_dl / extractor / bbccouk.py
1 from __future__ import unicode_literals
2
3 import xml.etree.ElementTree
4
5 from .common import InfoExtractor
6 from ..utils import (
7     ExtractorError,
8     int_or_none,
9 )
10 from ..compat import compat_HTTPError
11
12
13 class BBCCoUkIE(InfoExtractor):
14     IE_NAME = 'bbc.co.uk'
15     IE_DESC = 'BBC iPlayer'
16     _VALID_URL = r'https?://(?:www\.)?bbc\.co\.uk/(?:(?:(?:programmes|iplayer(?:/[^/]+)?/(?:episode|playlist))/)|music/clips[/#])(?P<id>[\da-z]{8})'
17
18     mediaselector_url = 'http://open.live.bbc.co.uk/mediaselector/5/select/version/2.0/mediaset/pc/vpid/%s'
19
20     _TESTS = [
21         {
22             'url': 'http://www.bbc.co.uk/programmes/b039g8p7',
23             'info_dict': {
24                 'id': 'b039d07m',
25                 'ext': 'flv',
26                 'title': 'Kaleidoscope, Leonard Cohen',
27                 'description': 'The Canadian poet and songwriter reflects on his musical career.',
28                 'duration': 1740,
29             },
30             'params': {
31                 # rtmp download
32                 'skip_download': True,
33             }
34         },
35         {
36             'url': 'http://www.bbc.co.uk/iplayer/episode/b00yng5w/The_Man_in_Black_Series_3_The_Printed_Name/',
37             'info_dict': {
38                 'id': 'b00yng1d',
39                 'ext': 'flv',
40                 'title': 'The Man in Black: Series 3: The Printed Name',
41                 'description': "Mark Gatiss introduces Nicholas Pierpan's chilling tale of a writer's devilish pact with a mysterious man. Stars Ewan Bailey.",
42                 'duration': 1800,
43             },
44             'params': {
45                 # rtmp download
46                 'skip_download': True,
47             },
48             'skip': 'Episode is no longer available on BBC iPlayer Radio',
49         },
50         {
51             'url': 'http://www.bbc.co.uk/iplayer/episode/b03vhd1f/The_Voice_UK_Series_3_Blind_Auditions_5/',
52             'info_dict': {
53                 'id': 'b00yng1d',
54                 'ext': 'flv',
55                 'title': 'The Voice UK: Series 3: Blind Auditions 5',
56                 '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.",
57                 'duration': 5100,
58             },
59             'params': {
60                 # rtmp download
61                 'skip_download': True,
62             },
63             'skip': 'Currently BBC iPlayer TV programmes are available to play in the UK only',
64         },
65         {
66             'url': 'http://www.bbc.co.uk/iplayer/episode/p026c7jt/tomorrows-worlds-the-unearthly-history-of-science-fiction-2-invasion',
67             'info_dict': {
68                 'id': 'b03k3pb7',
69                 'ext': 'flv',
70                 'title': "Tomorrow's Worlds: The Unearthly History of Science Fiction",
71                 'description': '2. Invasion',
72                 'duration': 3600,
73             },
74             'params': {
75                 # rtmp download
76                 'skip_download': True,
77             },
78             'skip': 'Currently BBC iPlayer TV programmes are available to play in the UK only',
79         }, {
80             'url': 'http://www.bbc.co.uk/programmes/b04v20dw',
81             'info_dict': {
82                 'id': 'b04v209v',
83                 'ext': 'flv',
84                 'title': 'Pete Tong, The Essential New Tune Special',
85                 'description': "Pete has a very special mix - all of 2014's Essential New Tunes!",
86                 'duration': 10800,
87             },
88             'params': {
89                 # rtmp download
90                 'skip_download': True,
91             }
92         }, {
93             'url': 'http://www.bbc.co.uk/music/clips/p02frcc3',
94             'note': 'Audio',
95             'info_dict': {
96                 'id': 'p02frcch',
97                 'ext': 'flv',
98                 'title': 'Pete Tong, Past, Present and Future Special, Madeon - After Hours mix',
99                 'description': 'French house superstar Madeon takes us out of the club and onto the after party.',
100                 'duration': 3507,
101             },
102             'params': {
103                 # rtmp download
104                 'skip_download': True,
105             }
106         }, {
107             'url': 'http://www.bbc.co.uk/music/clips/p025c0zz',
108             'note': 'Video',
109             'info_dict': {
110                 'id': 'p025c103',
111                 'ext': 'flv',
112                 'title': 'Reading and Leeds Festival, 2014, Rae Morris - Closer (Live on BBC Three)',
113                 'description': 'Rae Morris performs Closer for BBC Three at Reading 2014',
114                 'duration': 226,
115             },
116             'params': {
117                 # rtmp download
118                 'skip_download': True,
119             }
120         }, {
121             'url': 'http://www.bbc.co.uk/iplayer/episode/b054fn09/ad/natural-world-20152016-2-super-powered-owls',
122             'info_dict': {
123                 'id': 'p02n76xf',
124                 'ext': 'flv',
125                 'title': 'Natural World, 2015-2016: 2. Super Powered Owls',
126                 'description': 'md5:e4db5c937d0e95a7c6b5e654d429183d',
127                 'duration': 3540,
128             },
129             'params': {
130                 # rtmp download
131                 'skip_download': True,
132             },
133             'skip': 'geolocation',
134         }, {
135             'url': 'http://www.bbc.co.uk/iplayer/episode/b05zmgwn/royal-academy-summer-exhibition',
136             'info_dict': {
137                 'id': 'b05zmgw1',
138                 'ext': 'flv',
139                 '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.',
140                 'title': 'Royal Academy Summer Exhibition',
141                 'duration': 3540,
142             },
143             'params': {
144                 # rtmp download
145                 'skip_download': True,
146             },
147             'skip': 'geolocation',
148         }, {
149             'url': 'http://www.bbc.co.uk/iplayer/playlist/p01dvks4',
150             'only_matching': True,
151         }, {
152             'url': 'http://www.bbc.co.uk/music/clips#p02frcc3',
153             'only_matching': True,
154         }, {
155             'url': 'http://www.bbc.co.uk/iplayer/cbeebies/episode/b0480276/bing-14-atchoo',
156             'only_matching': True,
157         }
158     ]
159
160     def _extract_asx_playlist(self, connection, programme_id):
161         asx = self._download_xml(connection.get('href'), programme_id, 'Downloading ASX playlist')
162         return [ref.get('href') for ref in asx.findall('./Entry/ref')]
163
164     def _extract_connection(self, connection, programme_id):
165         formats = []
166         protocol = connection.get('protocol')
167         supplier = connection.get('supplier')
168         if protocol == 'http':
169             href = connection.get('href')
170             # ASX playlist
171             if supplier == 'asx':
172                 for i, ref in enumerate(self._extract_asx_playlist(connection, programme_id)):
173                     formats.append({
174                         'url': ref,
175                         'format_id': 'ref%s_%s' % (i, supplier),
176                     })
177             # Direct link
178             else:
179                 formats.append({
180                     'url': href,
181                     'format_id': supplier,
182                 })
183         elif protocol == 'rtmp':
184             application = connection.get('application', 'ondemand')
185             auth_string = connection.get('authString')
186             identifier = connection.get('identifier')
187             server = connection.get('server')
188             formats.append({
189                 'url': '%s://%s/%s?%s' % (protocol, server, application, auth_string),
190                 'play_path': identifier,
191                 'app': '%s?%s' % (application, auth_string),
192                 'page_url': 'http://www.bbc.co.uk',
193                 'player_url': 'http://www.bbc.co.uk/emp/releases/iplayer/revisions/617463_618125_4/617463_618125_4_emp.swf',
194                 'rtmp_live': False,
195                 'ext': 'flv',
196                 'format_id': supplier,
197             })
198         return formats
199
200     def _extract_items(self, playlist):
201         return playlist.findall('./{http://bbc.co.uk/2008/emp/playlist}item')
202
203     def _extract_medias(self, media_selection):
204         error = media_selection.find('./{http://bbc.co.uk/2008/mp/mediaselection}error')
205         if error is not None:
206             raise ExtractorError(
207                 '%s returned error: %s' % (self.IE_NAME, error.get('id')), expected=True)
208         return media_selection.findall('./{http://bbc.co.uk/2008/mp/mediaselection}media')
209
210     def _extract_connections(self, media):
211         return media.findall('./{http://bbc.co.uk/2008/mp/mediaselection}connection')
212
213     def _extract_video(self, media, programme_id):
214         formats = []
215         vbr = int(media.get('bitrate'))
216         vcodec = media.get('encoding')
217         service = media.get('service')
218         width = int(media.get('width'))
219         height = int(media.get('height'))
220         file_size = int(media.get('media_file_size'))
221         for connection in self._extract_connections(media):
222             conn_formats = self._extract_connection(connection, programme_id)
223             for format in conn_formats:
224                 format.update({
225                     'format_id': '%s_%s' % (service, format['format_id']),
226                     'width': width,
227                     'height': height,
228                     'vbr': vbr,
229                     'vcodec': vcodec,
230                     'filesize': file_size,
231                 })
232             formats.extend(conn_formats)
233         return formats
234
235     def _extract_audio(self, media, programme_id):
236         formats = []
237         abr = int(media.get('bitrate'))
238         acodec = media.get('encoding')
239         service = media.get('service')
240         for connection in self._extract_connections(media):
241             conn_formats = self._extract_connection(connection, programme_id)
242             for format in conn_formats:
243                 format.update({
244                     'format_id': '%s_%s' % (service, format['format_id']),
245                     'abr': abr,
246                     'acodec': acodec,
247                 })
248             formats.extend(conn_formats)
249         return formats
250
251     def _get_subtitles(self, media, programme_id):
252         subtitles = {}
253         for connection in self._extract_connections(media):
254             captions = self._download_xml(connection.get('href'), programme_id, 'Downloading captions')
255             lang = captions.get('{http://www.w3.org/XML/1998/namespace}lang', 'en')
256             ps = captions.findall('./{0}body/{0}div/{0}p'.format('{http://www.w3.org/2006/10/ttaf1}'))
257             srt = ''
258
259             def _extract_text(p):
260                 if p.text is not None:
261                     stripped_text = p.text.strip()
262                     if stripped_text:
263                         return stripped_text
264                 return ' '.join(span.text.strip() for span in p.findall('{http://www.w3.org/2006/10/ttaf1}span'))
265             for pos, p in enumerate(ps):
266                 srt += '%s\r\n%s --> %s\r\n%s\r\n\r\n' % (str(pos), p.get('begin'), p.get('end'), _extract_text(p))
267             subtitles[lang] = [
268                 {
269                     'url': connection.get('href'),
270                     'ext': 'ttml',
271                 },
272                 {
273                     'data': srt,
274                     'ext': 'srt',
275                 },
276             ]
277         return subtitles
278
279     def _download_media_selector(self, programme_id):
280         try:
281             media_selection = self._download_xml(
282                 self.mediaselector_url % programme_id,
283                 programme_id, 'Downloading media selection XML')
284         except ExtractorError as ee:
285             if isinstance(ee.cause, compat_HTTPError) and ee.cause.code == 403:
286                 media_selection = xml.etree.ElementTree.fromstring(ee.cause.read().decode('utf-8'))
287             else:
288                 raise
289
290         formats = []
291         subtitles = None
292
293         for media in self._extract_medias(media_selection):
294             kind = media.get('kind')
295             if kind == 'audio':
296                 formats.extend(self._extract_audio(media, programme_id))
297             elif kind == 'video':
298                 formats.extend(self._extract_video(media, programme_id))
299             elif kind == 'captions':
300                 subtitles = self.extract_subtitles(media, programme_id)
301
302         return formats, subtitles
303
304     def _download_playlist(self, playlist_id):
305         try:
306             playlist = self._download_json(
307                 'http://www.bbc.co.uk/programmes/%s/playlist.json' % playlist_id,
308                 playlist_id, 'Downloading playlist JSON')
309
310             version = playlist.get('defaultAvailableVersion')
311             if version:
312                 smp_config = version['smpConfig']
313                 title = smp_config['title']
314                 description = smp_config['summary']
315                 for item in smp_config['items']:
316                     kind = item['kind']
317                     if kind != 'programme' and kind != 'radioProgramme':
318                         continue
319                     programme_id = item.get('vpid')
320                     duration = int(item.get('duration'))
321                     formats, subtitles = self._download_media_selector(programme_id)
322                 return programme_id, title, description, duration, formats, subtitles
323         except ExtractorError as ee:
324             if not (isinstance(ee.cause, compat_HTTPError) and ee.cause.code == 404):
325                 raise
326
327         # fallback to legacy playlist
328         playlist = self._download_xml(
329             'http://www.bbc.co.uk/iplayer/playlist/%s' % playlist_id,
330             playlist_id, 'Downloading legacy playlist XML')
331
332         no_items = playlist.find('./{http://bbc.co.uk/2008/emp/playlist}noItems')
333         if no_items is not None:
334             reason = no_items.get('reason')
335             if reason == 'preAvailability':
336                 msg = 'Episode %s is not yet available' % playlist_id
337             elif reason == 'postAvailability':
338                 msg = 'Episode %s is no longer available' % playlist_id
339             elif reason == 'noMedia':
340                 msg = 'Episode %s is not currently available' % playlist_id
341             else:
342                 msg = 'Episode %s is not available: %s' % (playlist_id, reason)
343             raise ExtractorError(msg, expected=True)
344
345         for item in self._extract_items(playlist):
346             kind = item.get('kind')
347             if kind != 'programme' and kind != 'radioProgramme':
348                 continue
349             title = playlist.find('./{http://bbc.co.uk/2008/emp/playlist}title').text
350             description = playlist.find('./{http://bbc.co.uk/2008/emp/playlist}summary').text
351             programme_id = item.get('identifier')
352             duration = int(item.get('duration'))
353             formats, subtitles = self._download_media_selector(programme_id)
354
355         return programme_id, title, description, duration, formats, subtitles
356
357     def _real_extract(self, url):
358         group_id = self._match_id(url)
359
360         webpage = self._download_webpage(url, group_id, 'Downloading video page')
361
362         programme_id = None
363
364         tviplayer = self._search_regex(
365             r'mediator\.bind\(({.+?})\s*,\s*document\.getElementById',
366             webpage, 'player', default=None)
367
368         if tviplayer:
369             player = self._parse_json(tviplayer, group_id).get('player', {})
370             duration = int_or_none(player.get('duration'))
371             programme_id = player.get('vpid')
372
373         if not programme_id:
374             programme_id = self._search_regex(
375                 r'"vpid"\s*:\s*"([\da-z]{8})"', webpage, 'vpid', fatal=False, default=None)
376
377         if programme_id:
378             formats, subtitles = self._download_media_selector(programme_id)
379             title = self._og_search_title(webpage)
380             description = self._search_regex(
381                 r'<p class="[^"]*medium-description[^"]*">([^<]+)</p>',
382                 webpage, 'description', fatal=False)
383         else:
384             programme_id, title, description, duration, formats, subtitles = self._download_playlist(group_id)
385
386         self._sort_formats(formats)
387
388         return {
389             'id': programme_id,
390             'title': title,
391             'description': description,
392             'thumbnail': self._og_search_thumbnail(webpage, default=None),
393             'duration': duration,
394             'formats': formats,
395             'subtitles': subtitles,
396         }