[bbccouk] Fix description (closes #6006)
[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/episode/b054fn09/ad/natural-world-20152016-2-super-powered-owls',
120             'info_dict': {
121                 'id': 'p02n76xf',
122                 'ext': 'flv',
123                 'title': 'Natural World, 2015-2016: 2. Super Powered Owls',
124                 'description': 'md5:e4db5c937d0e95a7c6b5e654d429183d',
125                 'duration': 3540,
126             },
127             'params': {
128                 # rtmp download
129                 'skip_download': True,
130             },
131             'skip': 'geolocation',
132         }, {
133             'url': 'http://www.bbc.co.uk/iplayer/episode/b05zmgwn/royal-academy-summer-exhibition',
134             'info_dict': {
135                 'id': 'b05zmgw1',
136                 'ext': 'flv',
137                 '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.',
138                 'title': 'Royal Academy Summer Exhibition',
139                 'duration': 3540,
140             },
141             'params': {
142                 # rtmp download
143                 'skip_download': True,
144             },
145             'skip': 'geolocation',
146         }, {
147             'url': 'http://www.bbc.co.uk/iplayer/playlist/p01dvks4',
148             'only_matching': True,
149         }, {
150             'url': 'http://www.bbc.co.uk/music/clips#p02frcc3',
151             'only_matching': True,
152         }, {
153             'url': 'http://www.bbc.co.uk/iplayer/cbeebies/episode/b0480276/bing-14-atchoo',
154             'only_matching': True,
155         }
156     ]
157
158     def _extract_asx_playlist(self, connection, programme_id):
159         asx = self._download_xml(connection.get('href'), programme_id, 'Downloading ASX playlist')
160         return [ref.get('href') for ref in asx.findall('./Entry/ref')]
161
162     def _extract_connection(self, connection, programme_id):
163         formats = []
164         protocol = connection.get('protocol')
165         supplier = connection.get('supplier')
166         if protocol == 'http':
167             href = connection.get('href')
168             # ASX playlist
169             if supplier == 'asx':
170                 for i, ref in enumerate(self._extract_asx_playlist(connection, programme_id)):
171                     formats.append({
172                         'url': ref,
173                         'format_id': 'ref%s_%s' % (i, supplier),
174                     })
175             # Direct link
176             else:
177                 formats.append({
178                     'url': href,
179                     'format_id': supplier,
180                 })
181         elif protocol == 'rtmp':
182             application = connection.get('application', 'ondemand')
183             auth_string = connection.get('authString')
184             identifier = connection.get('identifier')
185             server = connection.get('server')
186             formats.append({
187                 'url': '%s://%s/%s?%s' % (protocol, server, application, auth_string),
188                 'play_path': identifier,
189                 'app': '%s?%s' % (application, auth_string),
190                 'page_url': 'http://www.bbc.co.uk',
191                 'player_url': 'http://www.bbc.co.uk/emp/releases/iplayer/revisions/617463_618125_4/617463_618125_4_emp.swf',
192                 'rtmp_live': False,
193                 'ext': 'flv',
194                 'format_id': supplier,
195             })
196         return formats
197
198     def _extract_items(self, playlist):
199         return playlist.findall('./{http://bbc.co.uk/2008/emp/playlist}item')
200
201     def _extract_medias(self, media_selection):
202         error = media_selection.find('./{http://bbc.co.uk/2008/mp/mediaselection}error')
203         if error is not None:
204             raise ExtractorError(
205                 '%s returned error: %s' % (self.IE_NAME, error.get('id')), expected=True)
206         return media_selection.findall('./{http://bbc.co.uk/2008/mp/mediaselection}media')
207
208     def _extract_connections(self, media):
209         return media.findall('./{http://bbc.co.uk/2008/mp/mediaselection}connection')
210
211     def _extract_video(self, media, programme_id):
212         formats = []
213         vbr = int(media.get('bitrate'))
214         vcodec = media.get('encoding')
215         service = media.get('service')
216         width = int(media.get('width'))
217         height = int(media.get('height'))
218         file_size = int(media.get('media_file_size'))
219         for connection in self._extract_connections(media):
220             conn_formats = self._extract_connection(connection, programme_id)
221             for format in conn_formats:
222                 format.update({
223                     'format_id': '%s_%s' % (service, format['format_id']),
224                     'width': width,
225                     'height': height,
226                     'vbr': vbr,
227                     'vcodec': vcodec,
228                     'filesize': file_size,
229                 })
230             formats.extend(conn_formats)
231         return formats
232
233     def _extract_audio(self, media, programme_id):
234         formats = []
235         abr = int(media.get('bitrate'))
236         acodec = media.get('encoding')
237         service = media.get('service')
238         for connection in self._extract_connections(media):
239             conn_formats = self._extract_connection(connection, programme_id)
240             for format in conn_formats:
241                 format.update({
242                     'format_id': '%s_%s' % (service, format['format_id']),
243                     'abr': abr,
244                     'acodec': acodec,
245                 })
246             formats.extend(conn_formats)
247         return formats
248
249     def _get_subtitles(self, media, programme_id):
250         subtitles = {}
251         for connection in self._extract_connections(media):
252             captions = self._download_xml(connection.get('href'), programme_id, 'Downloading captions')
253             lang = captions.get('{http://www.w3.org/XML/1998/namespace}lang', 'en')
254             ps = captions.findall('./{0}body/{0}div/{0}p'.format('{http://www.w3.org/2006/10/ttaf1}'))
255             srt = ''
256
257             def _extract_text(p):
258                 if p.text is not None:
259                     stripped_text = p.text.strip()
260                     if stripped_text:
261                         return stripped_text
262                 return ' '.join(span.text.strip() for span in p.findall('{http://www.w3.org/2006/10/ttaf1}span'))
263             for pos, p in enumerate(ps):
264                 srt += '%s\r\n%s --> %s\r\n%s\r\n\r\n' % (str(pos), p.get('begin'), p.get('end'), _extract_text(p))
265             subtitles[lang] = [
266                 {
267                     'url': connection.get('href'),
268                     'ext': 'ttml',
269                 },
270                 {
271                     'data': srt,
272                     'ext': 'srt',
273                 },
274             ]
275         return subtitles
276
277     def _download_media_selector(self, programme_id):
278         try:
279             media_selection = self._download_xml(
280                 'http://open.live.bbc.co.uk/mediaselector/5/select/version/2.0/mediaset/pc/vpid/%s' % programme_id,
281                 programme_id, 'Downloading media selection XML')
282         except ExtractorError as ee:
283             if isinstance(ee.cause, compat_HTTPError) and ee.cause.code == 403:
284                 media_selection = xml.etree.ElementTree.fromstring(ee.cause.read().decode('utf-8'))
285             else:
286                 raise
287
288         formats = []
289         subtitles = None
290
291         for media in self._extract_medias(media_selection):
292             kind = media.get('kind')
293             if kind == 'audio':
294                 formats.extend(self._extract_audio(media, programme_id))
295             elif kind == 'video':
296                 formats.extend(self._extract_video(media, programme_id))
297             elif kind == 'captions':
298                 subtitles = self.extract_subtitles(media, programme_id)
299
300         return formats, subtitles
301
302     def _download_playlist(self, playlist_id):
303         try:
304             playlist = self._download_json(
305                 'http://www.bbc.co.uk/programmes/%s/playlist.json' % playlist_id,
306                 playlist_id, 'Downloading playlist JSON')
307
308             version = playlist.get('defaultAvailableVersion')
309             if version:
310                 smp_config = version['smpConfig']
311                 title = smp_config['title']
312                 description = smp_config['summary']
313                 for item in smp_config['items']:
314                     kind = item['kind']
315                     if kind != 'programme' and kind != 'radioProgramme':
316                         continue
317                     programme_id = item.get('vpid')
318                     duration = int(item.get('duration'))
319                     formats, subtitles = self._download_media_selector(programme_id)
320                 return programme_id, title, description, duration, formats, subtitles
321         except ExtractorError as ee:
322             if not (isinstance(ee.cause, compat_HTTPError) and ee.cause.code == 404):
323                 raise
324
325         # fallback to legacy playlist
326         playlist = self._download_xml(
327             'http://www.bbc.co.uk/iplayer/playlist/%s' % playlist_id,
328             playlist_id, 'Downloading legacy playlist XML')
329
330         no_items = playlist.find('./{http://bbc.co.uk/2008/emp/playlist}noItems')
331         if no_items is not None:
332             reason = no_items.get('reason')
333             if reason == 'preAvailability':
334                 msg = 'Episode %s is not yet available' % playlist_id
335             elif reason == 'postAvailability':
336                 msg = 'Episode %s is no longer available' % playlist_id
337             elif reason == 'noMedia':
338                 msg = 'Episode %s is not currently available' % playlist_id
339             else:
340                 msg = 'Episode %s is not available: %s' % (playlist_id, reason)
341             raise ExtractorError(msg, expected=True)
342
343         for item in self._extract_items(playlist):
344             kind = item.get('kind')
345             if kind != 'programme' and kind != 'radioProgramme':
346                 continue
347             title = playlist.find('./{http://bbc.co.uk/2008/emp/playlist}title').text
348             description = playlist.find('./{http://bbc.co.uk/2008/emp/playlist}summary').text
349             programme_id = item.get('identifier')
350             duration = int(item.get('duration'))
351             formats, subtitles = self._download_media_selector(programme_id)
352
353         return programme_id, title, description, duration, formats, subtitles
354
355     def _real_extract(self, url):
356         group_id = self._match_id(url)
357
358         webpage = self._download_webpage(url, group_id, 'Downloading video page')
359
360         programme_id = None
361
362         tviplayer = self._search_regex(
363             r'mediator\.bind\(({.+?})\s*,\s*document\.getElementById',
364             webpage, 'player', default=None)
365
366         if tviplayer:
367             player = self._parse_json(tviplayer, group_id).get('player', {})
368             duration = int_or_none(player.get('duration'))
369             programme_id = player.get('vpid')
370
371         if not programme_id:
372             programme_id = self._search_regex(
373                 r'"vpid"\s*:\s*"([\da-z]{8})"', webpage, 'vpid', fatal=False, default=None)
374
375         if programme_id:
376             formats, subtitles = self._download_media_selector(programme_id)
377             title = self._og_search_title(webpage)
378             description = self._search_regex(
379                 r'<p class="[^"]*medium-description[^"]*">([^<]+)</p>',
380                 webpage, 'description', fatal=False)
381         else:
382             programme_id, title, description, duration, formats, subtitles = self._download_playlist(group_id)
383
384         self._sort_formats(formats)
385
386         return {
387             'id': programme_id,
388             'title': title,
389             'description': description,
390             'thumbnail': self._og_search_thumbnail(webpage, default=None),
391             'duration': duration,
392             'formats': formats,
393             'subtitles': subtitles,
394         }