]> jfr.im git - yt-dlp.git/blame - youtube_dl/extractor/bbccouk.py
bbcnews: Switch to parse_duration, revert change to docs/supportedsites.md
[yt-dlp.git] / youtube_dl / extractor / bbccouk.py
CommitLineData
082c6c86
S
1from __future__ import unicode_literals
2
c056efa2 3import xml.etree.ElementTree
082c6c86 4
f13b1e7d 5from .common import InfoExtractor
8683b4d8
S
6from ..utils import (
7 ExtractorError,
8 int_or_none,
9)
c056efa2 10from ..compat import compat_HTTPError
082c6c86
S
11
12
f13b1e7d 13class BBCCoUkIE(InfoExtractor):
082c6c86 14 IE_NAME = 'bbc.co.uk'
2e3fd9ec 15 IE_DESC = 'BBC iPlayer'
0692ef86 16 _VALID_URL = r'https?://(?:www\.)?bbc\.co\.uk/(?:(?:(?:programmes|iplayer(?:/[^/]+)?/(?:episode|playlist))/)|music/clips[/#])(?P<id>[\da-z]{8})'
082c6c86 17
a8b081a0 18 mediaselector_url = 'http://open.live.bbc.co.uk/mediaselector/5/select/version/2.0/mediaset/pc/vpid/%s'
19
2e3fd9ec
S
20 _TESTS = [
21 {
f2d0fc68 22 'url': 'http://www.bbc.co.uk/programmes/b039g8p7',
2e3fd9ec 23 'info_dict': {
f2d0fc68 24 'id': 'b039d07m',
2e3fd9ec 25 'ext': 'flv',
c4914185
S
26 'title': 'Kaleidoscope, Leonard Cohen',
27 'description': 'The Canadian poet and songwriter reflects on his musical career.',
f2d0fc68 28 'duration': 1740,
2e3fd9ec
S
29 },
30 'params': {
31 # rtmp download
32 'skip_download': True,
33 }
082c6c86 34 },
2e3fd9ec
S
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,
c7f0177f
S
47 },
48 'skip': 'Episode is no longer available on BBC iPlayer Radio',
2e3fd9ec
S
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',
17968e44
S
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,
2e3fd9ec
S
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',
c056efa2
S
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',
ae6986fb
S
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 }
c7e67594
S
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 }
e68ae99a
S
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',
25fa8d66
YCH
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',
31763975
S
148 }, {
149 'url': 'http://www.bbc.co.uk/iplayer/playlist/p01dvks4',
150 'only_matching': True,
c7e67594
S
151 }, {
152 'url': 'http://www.bbc.co.uk/music/clips#p02frcc3',
153 'only_matching': True,
0692ef86
S
154 }, {
155 'url': 'http://www.bbc.co.uk/iplayer/cbeebies/episode/b0480276/bing-14-atchoo',
156 'only_matching': True,
ae6986fb 157 }
2e3fd9ec
S
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):
c056efa2
S
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)
2e3fd9ec
S
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
f13b1e7d 251 def _get_subtitles(self, media, programme_id):
2e3fd9ec
S
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 = ''
f13b1e7d
JMF
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'))
2e3fd9ec 265 for pos, p in enumerate(ps):
f13b1e7d
JMF
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 ]
2e3fd9ec 277 return subtitles
082c6c86 278
c056efa2
S
279 def _download_media_selector(self, programme_id):
280 try:
281 media_selection = self._download_xml(
a8b081a0 282 self.mediaselector_url % programme_id,
c056efa2
S
283 programme_id, 'Downloading media selection XML')
284 except ExtractorError as ee:
285 if isinstance(ee.cause, compat_HTTPError) and ee.cause.code == 403:
974a6146 286 media_selection = xml.etree.ElementTree.fromstring(ee.cause.read().decode('utf-8'))
2e3fd9ec 287 else:
c056efa2 288 raise
082c6c86
S
289
290 formats = []
2e3fd9ec
S
291 subtitles = None
292
c056efa2
S
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':
f13b1e7d 300 subtitles = self.extract_subtitles(media, programme_id)
2e3fd9ec 301
c056efa2 302 return formats, subtitles
2e3fd9ec 303
ae6986fb
S
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:
f813928e 324 if not (isinstance(ee.cause, compat_HTTPError) and ee.cause.code == 404):
ae6986fb
S
325 raise
326
327 # fallback to legacy playlist
328 playlist = self._download_xml(
931e2d1d
PH
329 'http://www.bbc.co.uk/iplayer/playlist/%s' % playlist_id,
330 playlist_id, 'Downloading legacy playlist XML')
ae6986fb
S
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
c056efa2
S
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
8683b4d8
S
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
c056efa2 377 if programme_id:
c056efa2 378 formats, subtitles = self._download_media_selector(programme_id)
8683b4d8
S
379 title = self._og_search_title(webpage)
380 description = self._search_regex(
25fa8d66 381 r'<p class="[^"]*medium-description[^"]*">([^<]+)</p>',
8683b4d8 382 webpage, 'description', fatal=False)
c056efa2 383 else:
ae6986fb 384 programme_id, title, description, duration, formats, subtitles = self._download_playlist(group_id)
2e3fd9ec 385
082c6c86
S
386 self._sort_formats(formats)
387
388 return {
2e3fd9ec 389 'id': programme_id,
082c6c86
S
390 'title': title,
391 'description': description,
650cfd0c 392 'thumbnail': self._og_search_thumbnail(webpage, default=None),
082c6c86
S
393 'duration': duration,
394 'formats': formats,
2e3fd9ec 395 'subtitles': subtitles,
5f6a1245 396 }