]> jfr.im git - yt-dlp.git/blame - youtube_dl/extractor/bbc.py
Prefer externalId over non-mediaserver-specific hashkey for video id.
[yt-dlp.git] / youtube_dl / extractor / bbc.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,
10273d6e 8 parse_duration,
8683b4d8
S
9 int_or_none,
10)
c056efa2 11from ..compat import compat_HTTPError
10273d6e 12import re
082c6c86
S
13
14
f13b1e7d 15class BBCCoUkIE(InfoExtractor):
082c6c86 16 IE_NAME = 'bbc.co.uk'
2e3fd9ec 17 IE_DESC = 'BBC iPlayer'
0692ef86 18 _VALID_URL = r'https?://(?:www\.)?bbc\.co\.uk/(?:(?:(?:programmes|iplayer(?:/[^/]+)?/(?:episode|playlist))/)|music/clips[/#])(?P<id>[\da-z]{8})'
082c6c86 19
a8b081a0 20 mediaselector_url = 'http://open.live.bbc.co.uk/mediaselector/5/select/version/2.0/mediaset/pc/vpid/%s'
21
2e3fd9ec
S
22 _TESTS = [
23 {
f2d0fc68 24 'url': 'http://www.bbc.co.uk/programmes/b039g8p7',
2e3fd9ec 25 'info_dict': {
f2d0fc68 26 'id': 'b039d07m',
2e3fd9ec 27 'ext': 'flv',
c4914185
S
28 'title': 'Kaleidoscope, Leonard Cohen',
29 'description': 'The Canadian poet and songwriter reflects on his musical career.',
f2d0fc68 30 'duration': 1740,
2e3fd9ec
S
31 },
32 'params': {
33 # rtmp download
34 'skip_download': True,
35 }
082c6c86 36 },
2e3fd9ec
S
37 {
38 'url': 'http://www.bbc.co.uk/iplayer/episode/b00yng5w/The_Man_in_Black_Series_3_The_Printed_Name/',
39 'info_dict': {
40 'id': 'b00yng1d',
41 'ext': 'flv',
42 'title': 'The Man in Black: Series 3: The Printed Name',
43 'description': "Mark Gatiss introduces Nicholas Pierpan's chilling tale of a writer's devilish pact with a mysterious man. Stars Ewan Bailey.",
44 'duration': 1800,
45 },
46 'params': {
47 # rtmp download
48 'skip_download': True,
c7f0177f
S
49 },
50 'skip': 'Episode is no longer available on BBC iPlayer Radio',
2e3fd9ec
S
51 },
52 {
53 'url': 'http://www.bbc.co.uk/iplayer/episode/b03vhd1f/The_Voice_UK_Series_3_Blind_Auditions_5/',
54 'info_dict': {
55 'id': 'b00yng1d',
56 'ext': 'flv',
17968e44
S
57 'title': 'The Voice UK: Series 3: Blind Auditions 5',
58 '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.",
59 'duration': 5100,
2e3fd9ec
S
60 },
61 'params': {
62 # rtmp download
63 'skip_download': True,
64 },
65 'skip': 'Currently BBC iPlayer TV programmes are available to play in the UK only',
c056efa2
S
66 },
67 {
68 'url': 'http://www.bbc.co.uk/iplayer/episode/p026c7jt/tomorrows-worlds-the-unearthly-history-of-science-fiction-2-invasion',
69 'info_dict': {
70 'id': 'b03k3pb7',
71 'ext': 'flv',
72 'title': "Tomorrow's Worlds: The Unearthly History of Science Fiction",
73 'description': '2. Invasion',
74 'duration': 3600,
75 },
76 'params': {
77 # rtmp download
78 'skip_download': True,
79 },
80 'skip': 'Currently BBC iPlayer TV programmes are available to play in the UK only',
ae6986fb
S
81 }, {
82 'url': 'http://www.bbc.co.uk/programmes/b04v20dw',
83 'info_dict': {
84 'id': 'b04v209v',
85 'ext': 'flv',
86 'title': 'Pete Tong, The Essential New Tune Special',
87 'description': "Pete has a very special mix - all of 2014's Essential New Tunes!",
88 'duration': 10800,
89 },
90 'params': {
91 # rtmp download
92 'skip_download': True,
93 }
c7e67594
S
94 }, {
95 'url': 'http://www.bbc.co.uk/music/clips/p02frcc3',
96 'note': 'Audio',
97 'info_dict': {
98 'id': 'p02frcch',
99 'ext': 'flv',
100 'title': 'Pete Tong, Past, Present and Future Special, Madeon - After Hours mix',
101 'description': 'French house superstar Madeon takes us out of the club and onto the after party.',
102 'duration': 3507,
103 },
104 'params': {
105 # rtmp download
106 'skip_download': True,
107 }
108 }, {
109 'url': 'http://www.bbc.co.uk/music/clips/p025c0zz',
110 'note': 'Video',
111 'info_dict': {
112 'id': 'p025c103',
113 'ext': 'flv',
114 'title': 'Reading and Leeds Festival, 2014, Rae Morris - Closer (Live on BBC Three)',
115 'description': 'Rae Morris performs Closer for BBC Three at Reading 2014',
116 'duration': 226,
117 },
118 'params': {
119 # rtmp download
120 'skip_download': True,
121 }
e68ae99a
S
122 }, {
123 'url': 'http://www.bbc.co.uk/iplayer/episode/b054fn09/ad/natural-world-20152016-2-super-powered-owls',
124 'info_dict': {
125 'id': 'p02n76xf',
126 'ext': 'flv',
127 'title': 'Natural World, 2015-2016: 2. Super Powered Owls',
128 'description': 'md5:e4db5c937d0e95a7c6b5e654d429183d',
129 'duration': 3540,
130 },
131 'params': {
132 # rtmp download
133 'skip_download': True,
134 },
135 'skip': 'geolocation',
25fa8d66
YCH
136 }, {
137 'url': 'http://www.bbc.co.uk/iplayer/episode/b05zmgwn/royal-academy-summer-exhibition',
138 'info_dict': {
139 'id': 'b05zmgw1',
140 'ext': 'flv',
141 '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.',
142 'title': 'Royal Academy Summer Exhibition',
143 'duration': 3540,
144 },
145 'params': {
146 # rtmp download
147 'skip_download': True,
148 },
149 'skip': 'geolocation',
31763975
S
150 }, {
151 'url': 'http://www.bbc.co.uk/iplayer/playlist/p01dvks4',
152 'only_matching': True,
c7e67594
S
153 }, {
154 'url': 'http://www.bbc.co.uk/music/clips#p02frcc3',
155 'only_matching': True,
0692ef86
S
156 }, {
157 'url': 'http://www.bbc.co.uk/iplayer/cbeebies/episode/b0480276/bing-14-atchoo',
158 'only_matching': True,
ae6986fb 159 }
2e3fd9ec
S
160 ]
161
162 def _extract_asx_playlist(self, connection, programme_id):
163 asx = self._download_xml(connection.get('href'), programme_id, 'Downloading ASX playlist')
164 return [ref.get('href') for ref in asx.findall('./Entry/ref')]
165
166 def _extract_connection(self, connection, programme_id):
167 formats = []
168 protocol = connection.get('protocol')
169 supplier = connection.get('supplier')
170 if protocol == 'http':
171 href = connection.get('href')
172 # ASX playlist
173 if supplier == 'asx':
174 for i, ref in enumerate(self._extract_asx_playlist(connection, programme_id)):
175 formats.append({
176 'url': ref,
177 'format_id': 'ref%s_%s' % (i, supplier),
178 })
179 # Direct link
180 else:
181 formats.append({
182 'url': href,
183 'format_id': supplier,
184 })
185 elif protocol == 'rtmp':
186 application = connection.get('application', 'ondemand')
187 auth_string = connection.get('authString')
188 identifier = connection.get('identifier')
189 server = connection.get('server')
190 formats.append({
191 'url': '%s://%s/%s?%s' % (protocol, server, application, auth_string),
192 'play_path': identifier,
193 'app': '%s?%s' % (application, auth_string),
194 'page_url': 'http://www.bbc.co.uk',
195 'player_url': 'http://www.bbc.co.uk/emp/releases/iplayer/revisions/617463_618125_4/617463_618125_4_emp.swf',
196 'rtmp_live': False,
197 'ext': 'flv',
198 'format_id': supplier,
199 })
200 return formats
201
202 def _extract_items(self, playlist):
203 return playlist.findall('./{http://bbc.co.uk/2008/emp/playlist}item')
204
205 def _extract_medias(self, media_selection):
c056efa2
S
206 error = media_selection.find('./{http://bbc.co.uk/2008/mp/mediaselection}error')
207 if error is not None:
208 raise ExtractorError(
209 '%s returned error: %s' % (self.IE_NAME, error.get('id')), expected=True)
2e3fd9ec
S
210 return media_selection.findall('./{http://bbc.co.uk/2008/mp/mediaselection}media')
211
212 def _extract_connections(self, media):
213 return media.findall('./{http://bbc.co.uk/2008/mp/mediaselection}connection')
214
215 def _extract_video(self, media, programme_id):
216 formats = []
217 vbr = int(media.get('bitrate'))
218 vcodec = media.get('encoding')
219 service = media.get('service')
220 width = int(media.get('width'))
221 height = int(media.get('height'))
222 file_size = int(media.get('media_file_size'))
223 for connection in self._extract_connections(media):
224 conn_formats = self._extract_connection(connection, programme_id)
225 for format in conn_formats:
226 format.update({
227 'format_id': '%s_%s' % (service, format['format_id']),
228 'width': width,
229 'height': height,
230 'vbr': vbr,
231 'vcodec': vcodec,
232 'filesize': file_size,
233 })
234 formats.extend(conn_formats)
235 return formats
236
237 def _extract_audio(self, media, programme_id):
238 formats = []
239 abr = int(media.get('bitrate'))
240 acodec = media.get('encoding')
241 service = media.get('service')
242 for connection in self._extract_connections(media):
243 conn_formats = self._extract_connection(connection, programme_id)
244 for format in conn_formats:
245 format.update({
246 'format_id': '%s_%s' % (service, format['format_id']),
247 'abr': abr,
248 'acodec': acodec,
249 })
250 formats.extend(conn_formats)
251 return formats
252
f13b1e7d 253 def _get_subtitles(self, media, programme_id):
2e3fd9ec
S
254 subtitles = {}
255 for connection in self._extract_connections(media):
256 captions = self._download_xml(connection.get('href'), programme_id, 'Downloading captions')
257 lang = captions.get('{http://www.w3.org/XML/1998/namespace}lang', 'en')
258 ps = captions.findall('./{0}body/{0}div/{0}p'.format('{http://www.w3.org/2006/10/ttaf1}'))
259 srt = ''
f13b1e7d
JMF
260
261 def _extract_text(p):
262 if p.text is not None:
263 stripped_text = p.text.strip()
264 if stripped_text:
265 return stripped_text
266 return ' '.join(span.text.strip() for span in p.findall('{http://www.w3.org/2006/10/ttaf1}span'))
2e3fd9ec 267 for pos, p in enumerate(ps):
f13b1e7d
JMF
268 srt += '%s\r\n%s --> %s\r\n%s\r\n\r\n' % (str(pos), p.get('begin'), p.get('end'), _extract_text(p))
269 subtitles[lang] = [
270 {
271 'url': connection.get('href'),
272 'ext': 'ttml',
273 },
274 {
275 'data': srt,
276 'ext': 'srt',
277 },
278 ]
2e3fd9ec 279 return subtitles
082c6c86 280
c056efa2
S
281 def _download_media_selector(self, programme_id):
282 try:
283 media_selection = self._download_xml(
a8b081a0 284 self.mediaselector_url % programme_id,
c056efa2
S
285 programme_id, 'Downloading media selection XML')
286 except ExtractorError as ee:
287 if isinstance(ee.cause, compat_HTTPError) and ee.cause.code == 403:
974a6146 288 media_selection = xml.etree.ElementTree.fromstring(ee.cause.read().decode('utf-8'))
2e3fd9ec 289 else:
c056efa2 290 raise
082c6c86
S
291
292 formats = []
2e3fd9ec
S
293 subtitles = None
294
c056efa2
S
295 for media in self._extract_medias(media_selection):
296 kind = media.get('kind')
297 if kind == 'audio':
298 formats.extend(self._extract_audio(media, programme_id))
299 elif kind == 'video':
300 formats.extend(self._extract_video(media, programme_id))
301 elif kind == 'captions':
f13b1e7d 302 subtitles = self.extract_subtitles(media, programme_id)
2e3fd9ec 303
c056efa2 304 return formats, subtitles
2e3fd9ec 305
ae6986fb
S
306 def _download_playlist(self, playlist_id):
307 try:
308 playlist = self._download_json(
309 'http://www.bbc.co.uk/programmes/%s/playlist.json' % playlist_id,
310 playlist_id, 'Downloading playlist JSON')
311
312 version = playlist.get('defaultAvailableVersion')
313 if version:
314 smp_config = version['smpConfig']
315 title = smp_config['title']
316 description = smp_config['summary']
317 for item in smp_config['items']:
318 kind = item['kind']
319 if kind != 'programme' and kind != 'radioProgramme':
320 continue
321 programme_id = item.get('vpid')
322 duration = int(item.get('duration'))
323 formats, subtitles = self._download_media_selector(programme_id)
324 return programme_id, title, description, duration, formats, subtitles
325 except ExtractorError as ee:
f813928e 326 if not (isinstance(ee.cause, compat_HTTPError) and ee.cause.code == 404):
ae6986fb
S
327 raise
328
329 # fallback to legacy playlist
330 playlist = self._download_xml(
931e2d1d
PH
331 'http://www.bbc.co.uk/iplayer/playlist/%s' % playlist_id,
332 playlist_id, 'Downloading legacy playlist XML')
ae6986fb
S
333
334 no_items = playlist.find('./{http://bbc.co.uk/2008/emp/playlist}noItems')
335 if no_items is not None:
336 reason = no_items.get('reason')
337 if reason == 'preAvailability':
338 msg = 'Episode %s is not yet available' % playlist_id
339 elif reason == 'postAvailability':
340 msg = 'Episode %s is no longer available' % playlist_id
341 elif reason == 'noMedia':
342 msg = 'Episode %s is not currently available' % playlist_id
343 else:
344 msg = 'Episode %s is not available: %s' % (playlist_id, reason)
345 raise ExtractorError(msg, expected=True)
346
347 for item in self._extract_items(playlist):
348 kind = item.get('kind')
349 if kind != 'programme' and kind != 'radioProgramme':
350 continue
351 title = playlist.find('./{http://bbc.co.uk/2008/emp/playlist}title').text
352 description = playlist.find('./{http://bbc.co.uk/2008/emp/playlist}summary').text
353 programme_id = item.get('identifier')
354 duration = int(item.get('duration'))
355 formats, subtitles = self._download_media_selector(programme_id)
356
357 return programme_id, title, description, duration, formats, subtitles
358
c056efa2
S
359 def _real_extract(self, url):
360 group_id = self._match_id(url)
361
362 webpage = self._download_webpage(url, group_id, 'Downloading video page')
363
8683b4d8
S
364 programme_id = None
365
366 tviplayer = self._search_regex(
367 r'mediator\.bind\(({.+?})\s*,\s*document\.getElementById',
368 webpage, 'player', default=None)
369
370 if tviplayer:
371 player = self._parse_json(tviplayer, group_id).get('player', {})
372 duration = int_or_none(player.get('duration'))
373 programme_id = player.get('vpid')
374
375 if not programme_id:
376 programme_id = self._search_regex(
377 r'"vpid"\s*:\s*"([\da-z]{8})"', webpage, 'vpid', fatal=False, default=None)
378
c056efa2 379 if programme_id:
c056efa2 380 formats, subtitles = self._download_media_selector(programme_id)
8683b4d8
S
381 title = self._og_search_title(webpage)
382 description = self._search_regex(
25fa8d66 383 r'<p class="[^"]*medium-description[^"]*">([^<]+)</p>',
8683b4d8 384 webpage, 'description', fatal=False)
c056efa2 385 else:
ae6986fb 386 programme_id, title, description, duration, formats, subtitles = self._download_playlist(group_id)
2e3fd9ec 387
082c6c86
S
388 self._sort_formats(formats)
389
390 return {
2e3fd9ec 391 'id': programme_id,
082c6c86
S
392 'title': title,
393 'description': description,
650cfd0c 394 'thumbnail': self._og_search_thumbnail(webpage, default=None),
082c6c86
S
395 'duration': duration,
396 'formats': formats,
2e3fd9ec 397 'subtitles': subtitles,
5f6a1245 398 }
10273d6e 399
400
401class BBCNewsIE(BBCCoUkIE):
402 IE_NAME = 'bbc.com'
403 IE_DESC = 'BBC news'
de939d89 404 _VALID_URL = r'https?://(?:www\.)?bbc\.com/.+?/(?P<id>[^/]+)$'
10273d6e 405
406 mediaselector_url = 'http://open.live.bbc.co.uk/mediaselector/4/mtis/stream/%s'
407
408 _TESTS = [{
409 'url': 'http://www.bbc.com/news/world-europe-32668511',
410 'info_dict': {
411 'id': 'world-europe-32668511',
412 'title': 'Russia stages massive WW2 parade despite Western boycott',
413 },
414 'playlist_count': 2,
415 },{
416 'url': 'http://www.bbc.com/news/business-28299555',
417 'info_dict': {
418 'id': 'business-28299555',
419 'title': 'Farnborough Airshow: Video highlights',
420 },
421 'playlist_count': 9,
422 },{
423 'url': 'http://www.bbc.com/news/world-europe-32041533',
424 'note': 'Video',
425 'info_dict': {
426 'id': 'p02mprgb',
427 'ext': 'mp4',
428 'title': 'Aerial footage showed the site of the crash in the Alps - courtesy BFM TV',
429 'description': 'Germanwings plane crash site in aerial video - Aerial footage showed the site of the crash in the Alps - courtesy BFM TV',
430 'duration': 47,
431 },
432 'params': {
433 'skip_download': True,
434 }
de939d89 435 },{
436 'url': 'http://www.bbc.com/turkce/haberler/2015/06/150615_telabyad_kentin_cogu',
437 'note': 'Video',
438 'info_dict': {
439 'id': 'NA',
440 'ext': 'mp4',
441 'title': 'YPG - Tel Abyad..n tamam. kontrol.m.zde',
442 'duration': 47,
443 },
444 'params': {
445 'skip_download': True,
446 }
447 },{
448 'url': 'http://www.bbc.com/mundo/video_fotos/2015/06/150619_video_honduras_militares_hospitales_corrupcion_aw',
449 'note': 'Video',
450 'info_dict': {
451 'id': '39275083',
452 'ext': 'mp4',
453 'title': 'Honduras militariza sus hospitales por nuevo esc.ndalo de corrupci.n',
454 'duration': 87,
455 },
456 'params': {
457 'skip_download': True,
458 }
10273d6e 459 }]
460
461 def _real_extract(self, url):
462 list_id = self._match_id(url)
463 webpage = self._download_webpage(url, list_id)
464
de939d89 465 list_title = self._html_search_regex(r'<title>(.*?)(?:\s*-\s*BBC [^ ]+)?</title>', webpage, 'list title')
10273d6e 466
467 pubdate = self._html_search_regex(r'"datePublished":\s*"(\d+-\d+-\d+)', webpage, 'date', default=None)
468 if pubdate:
469 pubdate = pubdate.replace('-','')
470
471 ret = []
de939d89 472 jsent = []
473
10273d6e 474 # works with bbc.com/news/something-something-123456 articles
de939d89 475 jsent = map(
476 lambda m: self._parse_json(m,list_id),
477 re.findall(r"data-media-meta='({[^']+})'", webpage)
478 )
479
480 if len(jsent) == 0:
481 # http://www.bbc.com/news/video_and_audio/international
482 # and single-video articles
483 masset = self._html_search_regex(r'mediaAssetPage\.init\(\s*({.+?}), "/', webpage, 'mediaassets', default=None)
484 if masset:
485 jmasset = self._parse_json(masset,list_id)
486 for key, val in jmasset.get('videos',{}).items():
487 for skey, sval in val.items():
488 sval['id'] = skey
489 jsent.append(sval)
490
491 if len(jsent) == 0:
10273d6e 492 # stubbornly generic extractor for {json with "image":{allvideoshavethis},etc}
493 # in http://www.bbc.com/news/video_and_audio/international
de939d89 494 # prone to breaking if entries have sourceFiles list
495 jsent = map(
496 lambda m: self._parse_json(m,list_id),
497 re.findall(r"({[^{}]+image\":{[^}]+}[^}]+})", webpage)
498 )
10273d6e 499
de939d89 500 if len(jsent) == 0:
501 raise ExtractorError('No video found', expected=True)
10273d6e 502
de939d89 503 for jent in jsent:
75ab0ebc 504 programme_id = jent.get('externalId')
2a282a3b 505 xml_url = jent.get('href')
de939d89 506
507 title = jent.get('caption',list_title)
10273d6e 508
77c975f5 509 duration = parse_duration(jent.get('duration'))
10273d6e 510 description = list_title + ' - ' + jent.get('caption','')
511 thumbnail = None
512 if jent.has_key('image'):
75ab0ebc 513 thumbnail=jent['image'].get('href')
10273d6e 514
de939d89 515 formats = []
516 subtitles = []
517
10273d6e 518 if programme_id:
519 formats, subtitles = self._download_media_selector(programme_id)
de939d89 520 elif jent.has_key('sourceFiles'):
521 # mediaselector not used at
522 # http://www.bbc.com/turkce/haberler/2015/06/150615_telabyad_kentin_cogu
523 for key, val in jent['sourceFiles'].items():
524 formats.append( {
525 'ext': val.get('encoding'),
526 'url': val.get('url'),
527 'filesize': int(val.get('filesize')),
528 'format_id': key
529 } )
10273d6e 530 elif xml_url:
531 # Cheap fallback
532 # http://playlists.bbc.co.uk/news/(list_id)[ABC..]/playlist.sxml
533 xml = self._download_webpage(xml_url, programme_id, 'Downloading playlist.sxml for externalId (fallback)')
534 programme_id = self._search_regex(r'<mediator [^>]*identifier="(.+?)"', xml, 'playlist.sxml (externalId fallback)')
535 formats, subtitles = self._download_media_selector(programme_id)
de939d89 536
537 if len(formats) == 0:
538 raise ExtractorError('unsupported json media entry.\n '+str(jent)+'\n')
10273d6e 539
540 self._sort_formats(formats)
541
542 ret.append( {
a9dcf4a8 543 'id': jent.get('id') if programme_id == None else programme_id,
10273d6e 544 'uploader': 'BBC News',
545 'upload_date': pubdate,
546 'title': title,
547 'description': description,
548 'thumbnail': thumbnail,
549 'duration': duration,
550 'formats': formats,
551 'subtitles': subtitles,
552 } )
553
554 if len(ret) > 0:
555 return self.playlist_result(ret, list_id, list_title)
556 raise ExtractorError('No video found', expected=True)