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