]> Raphaƫl G. Git Repositories - youtubedl/blob - youtube_dl/extractor/bbc.py
New upstream version 2017.02.24.1
[youtubedl] / youtube_dl / extractor / bbc.py
1 # coding: utf-8
2 from __future__ import unicode_literals
3
4 import re
5 import itertools
6
7 from .common import InfoExtractor
8 from ..utils import (
9 dict_get,
10 ExtractorError,
11 float_or_none,
12 int_or_none,
13 parse_duration,
14 parse_iso8601,
15 try_get,
16 unescapeHTML,
17 )
18 from ..compat import (
19 compat_etree_fromstring,
20 compat_HTTPError,
21 compat_urlparse,
22 )
23
24
25 class BBCCoUkIE(InfoExtractor):
26 IE_NAME = 'bbc.co.uk'
27 IE_DESC = 'BBC iPlayer'
28 _ID_REGEX = r'[pb][\da-z]{7}'
29 _VALID_URL = r'''(?x)
30 https?://
31 (?:www\.)?bbc\.co\.uk/
32 (?:
33 programmes/(?!articles/)|
34 iplayer(?:/[^/]+)?/(?:episode/|playlist/)|
35 music/clips[/#]|
36 radio/player/
37 )
38 (?P<id>%s)(?!/(?:episodes|broadcasts|clips))
39 ''' % _ID_REGEX
40
41 _MEDIASELECTOR_URLS = [
42 # Provides HQ HLS streams with even better quality that pc mediaset but fails
43 # with geolocation in some cases when it's even not geo restricted at all (e.g.
44 # http://www.bbc.co.uk/programmes/b06bp7lf). Also may fail with selectionunavailable.
45 'http://open.live.bbc.co.uk/mediaselector/5/select/version/2.0/mediaset/iptv-all/vpid/%s',
46 'http://open.live.bbc.co.uk/mediaselector/5/select/version/2.0/mediaset/pc/vpid/%s',
47 ]
48
49 _MEDIASELECTION_NS = 'http://bbc.co.uk/2008/mp/mediaselection'
50 _EMP_PLAYLIST_NS = 'http://bbc.co.uk/2008/emp/playlist'
51
52 _NAMESPACES = (
53 _MEDIASELECTION_NS,
54 _EMP_PLAYLIST_NS,
55 )
56
57 _TESTS = [
58 {
59 'url': 'http://www.bbc.co.uk/programmes/b039g8p7',
60 'info_dict': {
61 'id': 'b039d07m',
62 'ext': 'flv',
63 'title': 'Leonard Cohen, Kaleidoscope - BBC Radio 4',
64 'description': 'The Canadian poet and songwriter reflects on his musical career.',
65 },
66 'params': {
67 # rtmp download
68 'skip_download': True,
69 }
70 },
71 {
72 'url': 'http://www.bbc.co.uk/iplayer/episode/b00yng5w/The_Man_in_Black_Series_3_The_Printed_Name/',
73 'info_dict': {
74 'id': 'b00yng1d',
75 'ext': 'flv',
76 'title': 'The Man in Black: Series 3: The Printed Name',
77 'description': "Mark Gatiss introduces Nicholas Pierpan's chilling tale of a writer's devilish pact with a mysterious man. Stars Ewan Bailey.",
78 'duration': 1800,
79 },
80 'params': {
81 # rtmp download
82 'skip_download': True,
83 },
84 'skip': 'Episode is no longer available on BBC iPlayer Radio',
85 },
86 {
87 'url': 'http://www.bbc.co.uk/iplayer/episode/b03vhd1f/The_Voice_UK_Series_3_Blind_Auditions_5/',
88 'info_dict': {
89 'id': 'b00yng1d',
90 'ext': 'flv',
91 'title': 'The Voice UK: Series 3: Blind Auditions 5',
92 '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.',
93 'duration': 5100,
94 },
95 'params': {
96 # rtmp download
97 'skip_download': True,
98 },
99 'skip': 'Currently BBC iPlayer TV programmes are available to play in the UK only',
100 },
101 {
102 'url': 'http://www.bbc.co.uk/iplayer/episode/p026c7jt/tomorrows-worlds-the-unearthly-history-of-science-fiction-2-invasion',
103 'info_dict': {
104 'id': 'b03k3pb7',
105 'ext': 'flv',
106 'title': "Tomorrow's Worlds: The Unearthly History of Science Fiction",
107 'description': '2. Invasion',
108 'duration': 3600,
109 },
110 'params': {
111 # rtmp download
112 'skip_download': True,
113 },
114 'skip': 'Currently BBC iPlayer TV programmes are available to play in the UK only',
115 }, {
116 'url': 'http://www.bbc.co.uk/programmes/b04v20dw',
117 'info_dict': {
118 'id': 'b04v209v',
119 'ext': 'flv',
120 'title': 'Pete Tong, The Essential New Tune Special',
121 'description': "Pete has a very special mix - all of 2014's Essential New Tunes!",
122 'duration': 10800,
123 },
124 'params': {
125 # rtmp download
126 'skip_download': True,
127 },
128 'skip': 'Episode is no longer available on BBC iPlayer Radio',
129 }, {
130 'url': 'http://www.bbc.co.uk/music/clips/p022h44b',
131 'note': 'Audio',
132 'info_dict': {
133 'id': 'p022h44j',
134 'ext': 'flv',
135 'title': 'BBC Proms Music Guides, Rachmaninov: Symphonic Dances',
136 'description': "In this Proms Music Guide, Andrew McGregor looks at Rachmaninov's Symphonic Dances.",
137 'duration': 227,
138 },
139 'params': {
140 # rtmp download
141 'skip_download': True,
142 }
143 }, {
144 'url': 'http://www.bbc.co.uk/music/clips/p025c0zz',
145 'note': 'Video',
146 'info_dict': {
147 'id': 'p025c103',
148 'ext': 'flv',
149 'title': 'Reading and Leeds Festival, 2014, Rae Morris - Closer (Live on BBC Three)',
150 'description': 'Rae Morris performs Closer for BBC Three at Reading 2014',
151 'duration': 226,
152 },
153 'params': {
154 # rtmp download
155 'skip_download': True,
156 }
157 }, {
158 'url': 'http://www.bbc.co.uk/iplayer/episode/b054fn09/ad/natural-world-20152016-2-super-powered-owls',
159 'info_dict': {
160 'id': 'p02n76xf',
161 'ext': 'flv',
162 'title': 'Natural World, 2015-2016: 2. Super Powered Owls',
163 'description': 'md5:e4db5c937d0e95a7c6b5e654d429183d',
164 'duration': 3540,
165 },
166 'params': {
167 # rtmp download
168 'skip_download': True,
169 },
170 'skip': 'geolocation',
171 }, {
172 'url': 'http://www.bbc.co.uk/iplayer/episode/b05zmgwn/royal-academy-summer-exhibition',
173 'info_dict': {
174 'id': 'b05zmgw1',
175 'ext': 'flv',
176 '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.',
177 'title': 'Royal Academy Summer Exhibition',
178 'duration': 3540,
179 },
180 'params': {
181 # rtmp download
182 'skip_download': True,
183 },
184 'skip': 'geolocation',
185 }, {
186 # iptv-all mediaset fails with geolocation however there is no geo restriction
187 # for this programme at all
188 'url': 'http://www.bbc.co.uk/programmes/b06rkn85',
189 'info_dict': {
190 'id': 'b06rkms3',
191 'ext': 'flv',
192 'title': "Best of the Mini-Mixes 2015: Part 3, Annie Mac's Friday Night - BBC Radio 1",
193 'description': "Annie has part three in the Best of the Mini-Mixes 2015, plus the year's Most Played!",
194 },
195 'params': {
196 # rtmp download
197 'skip_download': True,
198 },
199 'skip': 'Now it\'s really geo-restricted',
200 }, {
201 # compact player (https://github.com/rg3/youtube-dl/issues/8147)
202 'url': 'http://www.bbc.co.uk/programmes/p028bfkf/player',
203 'info_dict': {
204 'id': 'p028bfkj',
205 'ext': 'flv',
206 'title': 'Extract from BBC documentary Look Stranger - Giant Leeks and Magic Brews',
207 'description': 'Extract from BBC documentary Look Stranger - Giant Leeks and Magic Brews',
208 },
209 'params': {
210 # rtmp download
211 'skip_download': True,
212 },
213 }, {
214 'url': 'http://www.bbc.co.uk/iplayer/playlist/p01dvks4',
215 'only_matching': True,
216 }, {
217 'url': 'http://www.bbc.co.uk/music/clips#p02frcc3',
218 'only_matching': True,
219 }, {
220 'url': 'http://www.bbc.co.uk/iplayer/cbeebies/episode/b0480276/bing-14-atchoo',
221 'only_matching': True,
222 }, {
223 'url': 'http://www.bbc.co.uk/radio/player/p03cchwf',
224 'only_matching': True,
225 }
226 ]
227
228 _USP_RE = r'/([^/]+?)\.ism(?:\.hlsv2\.ism)?/[^/]+\.m3u8'
229
230 class MediaSelectionError(Exception):
231 def __init__(self, id):
232 self.id = id
233
234 def _extract_asx_playlist(self, connection, programme_id):
235 asx = self._download_xml(connection.get('href'), programme_id, 'Downloading ASX playlist')
236 return [ref.get('href') for ref in asx.findall('./Entry/ref')]
237
238 def _extract_items(self, playlist):
239 return playlist.findall('./{%s}item' % self._EMP_PLAYLIST_NS)
240
241 def _findall_ns(self, element, xpath):
242 elements = []
243 for ns in self._NAMESPACES:
244 elements.extend(element.findall(xpath % ns))
245 return elements
246
247 def _extract_medias(self, media_selection):
248 error = media_selection.find('./{%s}error' % self._MEDIASELECTION_NS)
249 if error is None:
250 media_selection.find('./{%s}error' % self._EMP_PLAYLIST_NS)
251 if error is not None:
252 raise BBCCoUkIE.MediaSelectionError(error.get('id'))
253 return self._findall_ns(media_selection, './{%s}media')
254
255 def _extract_connections(self, media):
256 return self._findall_ns(media, './{%s}connection')
257
258 def _get_subtitles(self, media, programme_id):
259 subtitles = {}
260 for connection in self._extract_connections(media):
261 captions = self._download_xml(connection.get('href'), programme_id, 'Downloading captions')
262 lang = captions.get('{http://www.w3.org/XML/1998/namespace}lang', 'en')
263 subtitles[lang] = [
264 {
265 'url': connection.get('href'),
266 'ext': 'ttml',
267 },
268 ]
269 return subtitles
270
271 def _raise_extractor_error(self, media_selection_error):
272 raise ExtractorError(
273 '%s returned error: %s' % (self.IE_NAME, media_selection_error.id),
274 expected=True)
275
276 def _download_media_selector(self, programme_id):
277 last_exception = None
278 for mediaselector_url in self._MEDIASELECTOR_URLS:
279 try:
280 return self._download_media_selector_url(
281 mediaselector_url % programme_id, programme_id)
282 except BBCCoUkIE.MediaSelectionError as e:
283 if e.id in ('notukerror', 'geolocation', 'selectionunavailable'):
284 last_exception = e
285 continue
286 self._raise_extractor_error(e)
287 self._raise_extractor_error(last_exception)
288
289 def _download_media_selector_url(self, url, programme_id=None):
290 try:
291 media_selection = self._download_xml(
292 url, programme_id, 'Downloading media selection XML')
293 except ExtractorError as ee:
294 if isinstance(ee.cause, compat_HTTPError) and ee.cause.code in (403, 404):
295 media_selection = compat_etree_fromstring(ee.cause.read().decode('utf-8'))
296 else:
297 raise
298 return self._process_media_selector(media_selection, programme_id)
299
300 def _process_media_selector(self, media_selection, programme_id):
301 formats = []
302 subtitles = None
303 urls = []
304
305 for media in self._extract_medias(media_selection):
306 kind = media.get('kind')
307 if kind in ('video', 'audio'):
308 bitrate = int_or_none(media.get('bitrate'))
309 encoding = media.get('encoding')
310 service = media.get('service')
311 width = int_or_none(media.get('width'))
312 height = int_or_none(media.get('height'))
313 file_size = int_or_none(media.get('media_file_size'))
314 for connection in self._extract_connections(media):
315 href = connection.get('href')
316 if href in urls:
317 continue
318 if href:
319 urls.append(href)
320 conn_kind = connection.get('kind')
321 protocol = connection.get('protocol')
322 supplier = connection.get('supplier')
323 transfer_format = connection.get('transferFormat')
324 format_id = supplier or conn_kind or protocol
325 if service:
326 format_id = '%s_%s' % (service, format_id)
327 # ASX playlist
328 if supplier == 'asx':
329 for i, ref in enumerate(self._extract_asx_playlist(connection, programme_id)):
330 formats.append({
331 'url': ref,
332 'format_id': 'ref%s_%s' % (i, format_id),
333 })
334 elif transfer_format == 'dash':
335 formats.extend(self._extract_mpd_formats(
336 href, programme_id, mpd_id=format_id, fatal=False))
337 elif transfer_format == 'hls':
338 formats.extend(self._extract_m3u8_formats(
339 href, programme_id, ext='mp4', entry_protocol='m3u8_native',
340 m3u8_id=format_id, fatal=False))
341 if re.search(self._USP_RE, href):
342 usp_formats = self._extract_m3u8_formats(
343 re.sub(self._USP_RE, r'/\1.ism/\1.m3u8', href),
344 programme_id, ext='mp4', entry_protocol='m3u8_native',
345 m3u8_id=format_id, fatal=False)
346 for f in usp_formats:
347 if f.get('height') and f['height'] > 720:
348 continue
349 formats.append(f)
350 elif transfer_format == 'hds':
351 formats.extend(self._extract_f4m_formats(
352 href, programme_id, f4m_id=format_id, fatal=False))
353 else:
354 if not service and not supplier and bitrate:
355 format_id += '-%d' % bitrate
356 fmt = {
357 'format_id': format_id,
358 'filesize': file_size,
359 }
360 if kind == 'video':
361 fmt.update({
362 'width': width,
363 'height': height,
364 'vbr': bitrate,
365 'vcodec': encoding,
366 })
367 else:
368 fmt.update({
369 'abr': bitrate,
370 'acodec': encoding,
371 'vcodec': 'none',
372 })
373 if protocol == 'http':
374 # Direct link
375 fmt.update({
376 'url': href,
377 })
378 elif protocol == 'rtmp':
379 application = connection.get('application', 'ondemand')
380 auth_string = connection.get('authString')
381 identifier = connection.get('identifier')
382 server = connection.get('server')
383 fmt.update({
384 'url': '%s://%s/%s?%s' % (protocol, server, application, auth_string),
385 'play_path': identifier,
386 'app': '%s?%s' % (application, auth_string),
387 'page_url': 'http://www.bbc.co.uk',
388 'player_url': 'http://www.bbc.co.uk/emp/releases/iplayer/revisions/617463_618125_4/617463_618125_4_emp.swf',
389 'rtmp_live': False,
390 'ext': 'flv',
391 })
392 formats.append(fmt)
393 elif kind == 'captions':
394 subtitles = self.extract_subtitles(media, programme_id)
395 return formats, subtitles
396
397 def _download_playlist(self, playlist_id):
398 try:
399 playlist = self._download_json(
400 'http://www.bbc.co.uk/programmes/%s/playlist.json' % playlist_id,
401 playlist_id, 'Downloading playlist JSON')
402
403 version = playlist.get('defaultAvailableVersion')
404 if version:
405 smp_config = version['smpConfig']
406 title = smp_config['title']
407 description = smp_config['summary']
408 for item in smp_config['items']:
409 kind = item['kind']
410 if kind != 'programme' and kind != 'radioProgramme':
411 continue
412 programme_id = item.get('vpid')
413 duration = int_or_none(item.get('duration'))
414 formats, subtitles = self._download_media_selector(programme_id)
415 return programme_id, title, description, duration, formats, subtitles
416 except ExtractorError as ee:
417 if not (isinstance(ee.cause, compat_HTTPError) and ee.cause.code == 404):
418 raise
419
420 # fallback to legacy playlist
421 return self._process_legacy_playlist(playlist_id)
422
423 def _process_legacy_playlist_url(self, url, display_id):
424 playlist = self._download_legacy_playlist_url(url, display_id)
425 return self._extract_from_legacy_playlist(playlist, display_id)
426
427 def _process_legacy_playlist(self, playlist_id):
428 return self._process_legacy_playlist_url(
429 'http://www.bbc.co.uk/iplayer/playlist/%s' % playlist_id, playlist_id)
430
431 def _download_legacy_playlist_url(self, url, playlist_id=None):
432 return self._download_xml(
433 url, playlist_id, 'Downloading legacy playlist XML')
434
435 def _extract_from_legacy_playlist(self, playlist, playlist_id):
436 no_items = playlist.find('./{%s}noItems' % self._EMP_PLAYLIST_NS)
437 if no_items is not None:
438 reason = no_items.get('reason')
439 if reason == 'preAvailability':
440 msg = 'Episode %s is not yet available' % playlist_id
441 elif reason == 'postAvailability':
442 msg = 'Episode %s is no longer available' % playlist_id
443 elif reason == 'noMedia':
444 msg = 'Episode %s is not currently available' % playlist_id
445 else:
446 msg = 'Episode %s is not available: %s' % (playlist_id, reason)
447 raise ExtractorError(msg, expected=True)
448
449 for item in self._extract_items(playlist):
450 kind = item.get('kind')
451 if kind != 'programme' and kind != 'radioProgramme':
452 continue
453 title = playlist.find('./{%s}title' % self._EMP_PLAYLIST_NS).text
454 description_el = playlist.find('./{%s}summary' % self._EMP_PLAYLIST_NS)
455 description = description_el.text if description_el is not None else None
456
457 def get_programme_id(item):
458 def get_from_attributes(item):
459 for p in('identifier', 'group'):
460 value = item.get(p)
461 if value and re.match(r'^[pb][\da-z]{7}$', value):
462 return value
463 get_from_attributes(item)
464 mediator = item.find('./{%s}mediator' % self._EMP_PLAYLIST_NS)
465 if mediator is not None:
466 return get_from_attributes(mediator)
467
468 programme_id = get_programme_id(item)
469 duration = int_or_none(item.get('duration'))
470
471 if programme_id:
472 formats, subtitles = self._download_media_selector(programme_id)
473 else:
474 formats, subtitles = self._process_media_selector(item, playlist_id)
475 programme_id = playlist_id
476
477 return programme_id, title, description, duration, formats, subtitles
478
479 def _real_extract(self, url):
480 group_id = self._match_id(url)
481
482 webpage = self._download_webpage(url, group_id, 'Downloading video page')
483
484 programme_id = None
485 duration = None
486
487 tviplayer = self._search_regex(
488 r'mediator\.bind\(({.+?})\s*,\s*document\.getElementById',
489 webpage, 'player', default=None)
490
491 if tviplayer:
492 player = self._parse_json(tviplayer, group_id).get('player', {})
493 duration = int_or_none(player.get('duration'))
494 programme_id = player.get('vpid')
495
496 if not programme_id:
497 programme_id = self._search_regex(
498 r'"vpid"\s*:\s*"(%s)"' % self._ID_REGEX, webpage, 'vpid', fatal=False, default=None)
499
500 if programme_id:
501 formats, subtitles = self._download_media_selector(programme_id)
502 title = self._og_search_title(webpage, default=None) or self._html_search_regex(
503 (r'<h2[^>]+id="parent-title"[^>]*>(.+?)</h2>',
504 r'<div[^>]+class="info"[^>]*>\s*<h1>(.+?)</h1>'), webpage, 'title')
505 description = self._search_regex(
506 (r'<p class="[^"]*medium-description[^"]*">([^<]+)</p>',
507 r'<div[^>]+class="info_+synopsis"[^>]*>([^<]+)</div>'),
508 webpage, 'description', default=None)
509 if not description:
510 description = self._html_search_meta('description', webpage)
511 else:
512 programme_id, title, description, duration, formats, subtitles = self._download_playlist(group_id)
513
514 self._sort_formats(formats)
515
516 return {
517 'id': programme_id,
518 'title': title,
519 'description': description,
520 'thumbnail': self._og_search_thumbnail(webpage, default=None),
521 'duration': duration,
522 'formats': formats,
523 'subtitles': subtitles,
524 }
525
526
527 class BBCIE(BBCCoUkIE):
528 IE_NAME = 'bbc'
529 IE_DESC = 'BBC'
530 _VALID_URL = r'https?://(?:www\.)?bbc\.(?:com|co\.uk)/(?:[^/]+/)+(?P<id>[^/#?]+)'
531
532 _MEDIASELECTOR_URLS = [
533 # Provides HQ HLS streams but fails with geolocation in some cases when it's
534 # even not geo restricted at all
535 'http://open.live.bbc.co.uk/mediaselector/5/select/version/2.0/mediaset/iptv-all/vpid/%s',
536 # Provides more formats, namely direct mp4 links, but fails on some videos with
537 # notukerror for non UK (?) users (e.g.
538 # http://www.bbc.com/travel/story/20150625-sri-lankas-spicy-secret)
539 'http://open.live.bbc.co.uk/mediaselector/4/mtis/stream/%s',
540 # Provides fewer formats, but works everywhere for everybody (hopefully)
541 'http://open.live.bbc.co.uk/mediaselector/5/select/version/2.0/mediaset/journalism-pc/vpid/%s',
542 ]
543
544 _TESTS = [{
545 # article with multiple videos embedded with data-playable containing vpids
546 'url': 'http://www.bbc.com/news/world-europe-32668511',
547 'info_dict': {
548 'id': 'world-europe-32668511',
549 'title': 'Russia stages massive WW2 parade despite Western boycott',
550 'description': 'md5:00ff61976f6081841f759a08bf78cc9c',
551 },
552 'playlist_count': 2,
553 }, {
554 # article with multiple videos embedded with data-playable (more videos)
555 'url': 'http://www.bbc.com/news/business-28299555',
556 'info_dict': {
557 'id': 'business-28299555',
558 'title': 'Farnborough Airshow: Video highlights',
559 'description': 'BBC reports and video highlights at the Farnborough Airshow.',
560 },
561 'playlist_count': 9,
562 'skip': 'Save time',
563 }, {
564 # article with multiple videos embedded with `new SMP()`
565 # broken
566 'url': 'http://www.bbc.co.uk/blogs/adamcurtis/entries/3662a707-0af9-3149-963f-47bea720b460',
567 'info_dict': {
568 'id': '3662a707-0af9-3149-963f-47bea720b460',
569 'title': 'BUGGER',
570 },
571 'playlist_count': 18,
572 }, {
573 # single video embedded with data-playable containing vpid
574 'url': 'http://www.bbc.com/news/world-europe-32041533',
575 'info_dict': {
576 'id': 'p02mprgb',
577 'ext': 'mp4',
578 'title': 'Aerial footage showed the site of the crash in the Alps - courtesy BFM TV',
579 'description': 'md5:2868290467291b37feda7863f7a83f54',
580 'duration': 47,
581 'timestamp': 1427219242,
582 'upload_date': '20150324',
583 },
584 'params': {
585 # rtmp download
586 'skip_download': True,
587 }
588 }, {
589 # article with single video embedded with data-playable containing XML playlist
590 # with direct video links as progressiveDownloadUrl (for now these are extracted)
591 # and playlist with f4m and m3u8 as streamingUrl
592 'url': 'http://www.bbc.com/turkce/haberler/2015/06/150615_telabyad_kentin_cogu',
593 'info_dict': {
594 'id': '150615_telabyad_kentin_cogu',
595 'ext': 'mp4',
596 'title': "YPG: Tel Abyad'ın tamamı kontrolĆ¼mĆ¼zde",
597 'description': 'md5:33a4805a855c9baf7115fcbde57e7025',
598 'timestamp': 1434397334,
599 'upload_date': '20150615',
600 },
601 'params': {
602 'skip_download': True,
603 }
604 }, {
605 # single video embedded with data-playable containing XML playlists (regional section)
606 'url': 'http://www.bbc.com/mundo/video_fotos/2015/06/150619_video_honduras_militares_hospitales_corrupcion_aw',
607 'info_dict': {
608 'id': '150619_video_honduras_militares_hospitales_corrupcion_aw',
609 'ext': 'mp4',
610 'title': 'Honduras militariza sus hospitales por nuevo escĆ”ndalo de corrupciĆ³n',
611 'description': 'md5:1525f17448c4ee262b64b8f0c9ce66c8',
612 'timestamp': 1434713142,
613 'upload_date': '20150619',
614 },
615 'params': {
616 'skip_download': True,
617 }
618 }, {
619 # single video from video playlist embedded with vxp-playlist-data JSON
620 'url': 'http://www.bbc.com/news/video_and_audio/must_see/33376376',
621 'info_dict': {
622 'id': 'p02w6qjc',
623 'ext': 'mp4',
624 'title': '''Judge Mindy Glazer: "I'm sorry to see you here... I always wondered what happened to you"''',
625 'duration': 56,
626 'description': '''Judge Mindy Glazer: "I'm sorry to see you here... I always wondered what happened to you"''',
627 },
628 'params': {
629 'skip_download': True,
630 }
631 }, {
632 # single video story with digitalData
633 'url': 'http://www.bbc.com/travel/story/20150625-sri-lankas-spicy-secret',
634 'info_dict': {
635 'id': 'p02q6gc4',
636 'ext': 'flv',
637 'title': 'Sri Lankaā€™s spicy secret',
638 'description': 'As a new train line to Jaffna opens up the countryā€™s north, travellers can experience a truly distinct slice of Tamil culture.',
639 'timestamp': 1437674293,
640 'upload_date': '20150723',
641 },
642 'params': {
643 # rtmp download
644 'skip_download': True,
645 }
646 }, {
647 # single video story without digitalData
648 'url': 'http://www.bbc.com/autos/story/20130513-hyundais-rock-star',
649 'info_dict': {
650 'id': 'p018zqqg',
651 'ext': 'mp4',
652 'title': 'Hyundai Santa Fe Sport: Rock star',
653 'description': 'md5:b042a26142c4154a6e472933cf20793d',
654 'timestamp': 1415867444,
655 'upload_date': '20141113',
656 },
657 'params': {
658 # rtmp download
659 'skip_download': True,
660 }
661 }, {
662 # single video embedded with Morph
663 'url': 'http://www.bbc.co.uk/sport/live/olympics/36895975',
664 'info_dict': {
665 'id': 'p041vhd0',
666 'ext': 'mp4',
667 'title': "Nigeria v Japan - Men's First Round",
668 'description': 'Live coverage of the first round from Group B at the Amazonia Arena.',
669 'duration': 7980,
670 'uploader': 'BBC Sport',
671 'uploader_id': 'bbc_sport',
672 },
673 'params': {
674 # m3u8 download
675 'skip_download': True,
676 },
677 'skip': 'Georestricted to UK',
678 }, {
679 # single video with playlist.sxml URL in playlist param
680 'url': 'http://www.bbc.com/sport/0/football/33653409',
681 'info_dict': {
682 'id': 'p02xycnp',
683 'ext': 'mp4',
684 'title': 'Transfers: Cristiano Ronaldo to Man Utd, Arsenal to spend?',
685 'description': 'BBC Sport\'s David Ornstein has the latest transfer gossip, including rumours of a Manchester United return for Cristiano Ronaldo.',
686 'duration': 140,
687 },
688 'params': {
689 # rtmp download
690 'skip_download': True,
691 }
692 }, {
693 # article with multiple videos embedded with playlist.sxml in playlist param
694 'url': 'http://www.bbc.com/sport/0/football/34475836',
695 'info_dict': {
696 'id': '34475836',
697 'title': 'Jurgen Klopp: Furious football from a witty and winning coach',
698 'description': 'Fast-paced football, wit, wisdom and a ready smile - why Liverpool fans should come to love new boss Jurgen Klopp.',
699 },
700 'playlist_count': 3,
701 }, {
702 # school report article with single video
703 'url': 'http://www.bbc.co.uk/schoolreport/35744779',
704 'info_dict': {
705 'id': '35744779',
706 'title': 'School which breaks down barriers in Jerusalem',
707 },
708 'playlist_count': 1,
709 }, {
710 # single video with playlist URL from weather section
711 'url': 'http://www.bbc.com/weather/features/33601775',
712 'only_matching': True,
713 }, {
714 # custom redirection to www.bbc.com
715 'url': 'http://www.bbc.co.uk/news/science-environment-33661876',
716 'only_matching': True,
717 }, {
718 # single video article embedded with data-media-vpid
719 'url': 'http://www.bbc.co.uk/sport/rowing/35908187',
720 'only_matching': True,
721 }]
722
723 @classmethod
724 def suitable(cls, url):
725 EXCLUDE_IE = (BBCCoUkIE, BBCCoUkArticleIE, BBCCoUkIPlayerPlaylistIE, BBCCoUkPlaylistIE)
726 return (False if any(ie.suitable(url) for ie in EXCLUDE_IE)
727 else super(BBCIE, cls).suitable(url))
728
729 def _extract_from_media_meta(self, media_meta, video_id):
730 # Direct links to media in media metadata (e.g.
731 # http://www.bbc.com/turkce/haberler/2015/06/150615_telabyad_kentin_cogu)
732 # TODO: there are also f4m and m3u8 streams incorporated in playlist.sxml
733 source_files = media_meta.get('sourceFiles')
734 if source_files:
735 return [{
736 'url': f['url'],
737 'format_id': format_id,
738 'ext': f.get('encoding'),
739 'tbr': float_or_none(f.get('bitrate'), 1000),
740 'filesize': int_or_none(f.get('filesize')),
741 } for format_id, f in source_files.items() if f.get('url')], []
742
743 programme_id = media_meta.get('externalId')
744 if programme_id:
745 return self._download_media_selector(programme_id)
746
747 # Process playlist.sxml as legacy playlist
748 href = media_meta.get('href')
749 if href:
750 playlist = self._download_legacy_playlist_url(href)
751 _, _, _, _, formats, subtitles = self._extract_from_legacy_playlist(playlist, video_id)
752 return formats, subtitles
753
754 return [], []
755
756 def _extract_from_playlist_sxml(self, url, playlist_id, timestamp):
757 programme_id, title, description, duration, formats, subtitles = \
758 self._process_legacy_playlist_url(url, playlist_id)
759 self._sort_formats(formats)
760 return {
761 'id': programme_id,
762 'title': title,
763 'description': description,
764 'duration': duration,
765 'timestamp': timestamp,
766 'formats': formats,
767 'subtitles': subtitles,
768 }
769
770 def _real_extract(self, url):
771 playlist_id = self._match_id(url)
772
773 webpage = self._download_webpage(url, playlist_id)
774
775 json_ld_info = self._search_json_ld(webpage, playlist_id, default={})
776 timestamp = json_ld_info.get('timestamp')
777
778 playlist_title = json_ld_info.get('title')
779 if not playlist_title:
780 playlist_title = self._og_search_title(
781 webpage, default=None) or self._html_search_regex(
782 r'<title>(.+?)</title>', webpage, 'playlist title', default=None)
783 if playlist_title:
784 playlist_title = re.sub(r'(.+)\s*-\s*BBC.*?$', r'\1', playlist_title).strip()
785
786 playlist_description = json_ld_info.get(
787 'description') or self._og_search_description(webpage, default=None)
788
789 if not timestamp:
790 timestamp = parse_iso8601(self._search_regex(
791 [r'<meta[^>]+property="article:published_time"[^>]+content="([^"]+)"',
792 r'itemprop="datePublished"[^>]+datetime="([^"]+)"',
793 r'"datePublished":\s*"([^"]+)'],
794 webpage, 'date', default=None))
795
796 entries = []
797
798 # article with multiple videos embedded with playlist.sxml (e.g.
799 # http://www.bbc.com/sport/0/football/34475836)
800 playlists = re.findall(r'<param[^>]+name="playlist"[^>]+value="([^"]+)"', webpage)
801 playlists.extend(re.findall(r'data-media-id="([^"]+/playlist\.sxml)"', webpage))
802 if playlists:
803 entries = [
804 self._extract_from_playlist_sxml(playlist_url, playlist_id, timestamp)
805 for playlist_url in playlists]
806
807 # news article with multiple videos embedded with data-playable
808 data_playables = re.findall(r'data-playable=(["\'])({.+?})\1', webpage)
809 if data_playables:
810 for _, data_playable_json in data_playables:
811 data_playable = self._parse_json(
812 unescapeHTML(data_playable_json), playlist_id, fatal=False)
813 if not data_playable:
814 continue
815 settings = data_playable.get('settings', {})
816 if settings:
817 # data-playable with video vpid in settings.playlistObject.items (e.g.
818 # http://www.bbc.com/news/world-us-canada-34473351)
819 playlist_object = settings.get('playlistObject', {})
820 if playlist_object:
821 items = playlist_object.get('items')
822 if items and isinstance(items, list):
823 title = playlist_object['title']
824 description = playlist_object.get('summary')
825 duration = int_or_none(items[0].get('duration'))
826 programme_id = items[0].get('vpid')
827 formats, subtitles = self._download_media_selector(programme_id)
828 self._sort_formats(formats)
829 entries.append({
830 'id': programme_id,
831 'title': title,
832 'description': description,
833 'timestamp': timestamp,
834 'duration': duration,
835 'formats': formats,
836 'subtitles': subtitles,
837 })
838 else:
839 # data-playable without vpid but with a playlist.sxml URLs
840 # in otherSettings.playlist (e.g.
841 # http://www.bbc.com/turkce/multimedya/2015/10/151010_vid_ankara_patlama_ani)
842 playlist = data_playable.get('otherSettings', {}).get('playlist', {})
843 if playlist:
844 entry = None
845 for key in ('streaming', 'progressiveDownload'):
846 playlist_url = playlist.get('%sUrl' % key)
847 if not playlist_url:
848 continue
849 try:
850 info = self._extract_from_playlist_sxml(
851 playlist_url, playlist_id, timestamp)
852 if not entry:
853 entry = info
854 else:
855 entry['title'] = info['title']
856 entry['formats'].extend(info['formats'])
857 except Exception as e:
858 # Some playlist URL may fail with 500, at the same time
859 # the other one may work fine (e.g.
860 # http://www.bbc.com/turkce/haberler/2015/06/150615_telabyad_kentin_cogu)
861 if isinstance(e.cause, compat_HTTPError) and e.cause.code == 500:
862 continue
863 raise
864 if entry:
865 self._sort_formats(entry['formats'])
866 entries.append(entry)
867
868 if entries:
869 return self.playlist_result(entries, playlist_id, playlist_title, playlist_description)
870
871 # single video story (e.g. http://www.bbc.com/travel/story/20150625-sri-lankas-spicy-secret)
872 programme_id = self._search_regex(
873 [r'data-(?:video-player|media)-vpid="(%s)"' % self._ID_REGEX,
874 r'<param[^>]+name="externalIdentifier"[^>]+value="(%s)"' % self._ID_REGEX,
875 r'videoId\s*:\s*["\'](%s)["\']' % self._ID_REGEX],
876 webpage, 'vpid', default=None)
877
878 if programme_id:
879 formats, subtitles = self._download_media_selector(programme_id)
880 self._sort_formats(formats)
881 # digitalData may be missing (e.g. http://www.bbc.com/autos/story/20130513-hyundais-rock-star)
882 digital_data = self._parse_json(
883 self._search_regex(
884 r'var\s+digitalData\s*=\s*({.+?});?\n', webpage, 'digital data', default='{}'),
885 programme_id, fatal=False)
886 page_info = digital_data.get('page', {}).get('pageInfo', {})
887 title = page_info.get('pageName') or self._og_search_title(webpage)
888 description = page_info.get('description') or self._og_search_description(webpage)
889 timestamp = parse_iso8601(page_info.get('publicationDate')) or timestamp
890 return {
891 'id': programme_id,
892 'title': title,
893 'description': description,
894 'timestamp': timestamp,
895 'formats': formats,
896 'subtitles': subtitles,
897 }
898
899 # Morph based embed (e.g. http://www.bbc.co.uk/sport/live/olympics/36895975)
900 # There are several setPayload calls may be present but the video
901 # seems to be always related to the first one
902 morph_payload = self._parse_json(
903 self._search_regex(
904 r'Morph\.setPayload\([^,]+,\s*({.+?})\);',
905 webpage, 'morph payload', default='{}'),
906 playlist_id, fatal=False)
907 if morph_payload:
908 components = try_get(morph_payload, lambda x: x['body']['components'], list) or []
909 for component in components:
910 if not isinstance(component, dict):
911 continue
912 lead_media = try_get(component, lambda x: x['props']['leadMedia'], dict)
913 if not lead_media:
914 continue
915 identifiers = lead_media.get('identifiers')
916 if not identifiers or not isinstance(identifiers, dict):
917 continue
918 programme_id = identifiers.get('vpid') or identifiers.get('playablePid')
919 if not programme_id:
920 continue
921 title = lead_media.get('title') or self._og_search_title(webpage)
922 formats, subtitles = self._download_media_selector(programme_id)
923 self._sort_formats(formats)
924 description = lead_media.get('summary')
925 uploader = lead_media.get('masterBrand')
926 uploader_id = lead_media.get('mid')
927 duration = None
928 duration_d = lead_media.get('duration')
929 if isinstance(duration_d, dict):
930 duration = parse_duration(dict_get(
931 duration_d, ('rawDuration', 'formattedDuration', 'spokenDuration')))
932 return {
933 'id': programme_id,
934 'title': title,
935 'description': description,
936 'duration': duration,
937 'uploader': uploader,
938 'uploader_id': uploader_id,
939 'formats': formats,
940 'subtitles': subtitles,
941 }
942
943 def extract_all(pattern):
944 return list(filter(None, map(
945 lambda s: self._parse_json(s, playlist_id, fatal=False),
946 re.findall(pattern, webpage))))
947
948 # Multiple video article (e.g.
949 # http://www.bbc.co.uk/blogs/adamcurtis/entries/3662a707-0af9-3149-963f-47bea720b460)
950 EMBED_URL = r'https?://(?:www\.)?bbc\.co\.uk/(?:[^/]+/)+%s(?:\b[^"]+)?' % self._ID_REGEX
951 entries = []
952 for match in extract_all(r'new\s+SMP\(({.+?})\)'):
953 embed_url = match.get('playerSettings', {}).get('externalEmbedUrl')
954 if embed_url and re.match(EMBED_URL, embed_url):
955 entries.append(embed_url)
956 entries.extend(re.findall(
957 r'setPlaylist\("(%s)"\)' % EMBED_URL, webpage))
958 if entries:
959 return self.playlist_result(
960 [self.url_result(entry_, 'BBCCoUk') for entry_ in entries],
961 playlist_id, playlist_title, playlist_description)
962
963 # Multiple video article (e.g. http://www.bbc.com/news/world-europe-32668511)
964 medias = extract_all(r"data-media-meta='({[^']+})'")
965
966 if not medias:
967 # Single video article (e.g. http://www.bbc.com/news/video_and_audio/international)
968 media_asset = self._search_regex(
969 r'mediaAssetPage\.init\(\s*({.+?}), "/',
970 webpage, 'media asset', default=None)
971 if media_asset:
972 media_asset_page = self._parse_json(media_asset, playlist_id, fatal=False)
973 medias = []
974 for video in media_asset_page.get('videos', {}).values():
975 medias.extend(video.values())
976
977 if not medias:
978 # Multiple video playlist with single `now playing` entry (e.g.
979 # http://www.bbc.com/news/video_and_audio/must_see/33767813)
980 vxp_playlist = self._parse_json(
981 self._search_regex(
982 r'<script[^>]+class="vxp-playlist-data"[^>]+type="application/json"[^>]*>([^<]+)</script>',
983 webpage, 'playlist data'),
984 playlist_id)
985 playlist_medias = []
986 for item in vxp_playlist:
987 media = item.get('media')
988 if not media:
989 continue
990 playlist_medias.append(media)
991 # Download single video if found media with asset id matching the video id from URL
992 if item.get('advert', {}).get('assetId') == playlist_id:
993 medias = [media]
994 break
995 # Fallback to the whole playlist
996 if not medias:
997 medias = playlist_medias
998
999 entries = []
1000 for num, media_meta in enumerate(medias, start=1):
1001 formats, subtitles = self._extract_from_media_meta(media_meta, playlist_id)
1002 if not formats:
1003 continue
1004 self._sort_formats(formats)
1005
1006 video_id = media_meta.get('externalId')
1007 if not video_id:
1008 video_id = playlist_id if len(medias) == 1 else '%s-%s' % (playlist_id, num)
1009
1010 title = media_meta.get('caption')
1011 if not title:
1012 title = playlist_title if len(medias) == 1 else '%s - Video %s' % (playlist_title, num)
1013
1014 duration = int_or_none(media_meta.get('durationInSeconds')) or parse_duration(media_meta.get('duration'))
1015
1016 images = []
1017 for image in media_meta.get('images', {}).values():
1018 images.extend(image.values())
1019 if 'image' in media_meta:
1020 images.append(media_meta['image'])
1021
1022 thumbnails = [{
1023 'url': image.get('href'),
1024 'width': int_or_none(image.get('width')),
1025 'height': int_or_none(image.get('height')),
1026 } for image in images]
1027
1028 entries.append({
1029 'id': video_id,
1030 'title': title,
1031 'thumbnails': thumbnails,
1032 'duration': duration,
1033 'timestamp': timestamp,
1034 'formats': formats,
1035 'subtitles': subtitles,
1036 })
1037
1038 return self.playlist_result(entries, playlist_id, playlist_title, playlist_description)
1039
1040
1041 class BBCCoUkArticleIE(InfoExtractor):
1042 _VALID_URL = r'https?://(?:www\.)?bbc\.co\.uk/programmes/articles/(?P<id>[a-zA-Z0-9]+)'
1043 IE_NAME = 'bbc.co.uk:article'
1044 IE_DESC = 'BBC articles'
1045
1046 _TEST = {
1047 'url': 'http://www.bbc.co.uk/programmes/articles/3jNQLTMrPlYGTBn0WV6M2MS/not-your-typical-role-model-ada-lovelace-the-19th-century-programmer',
1048 'info_dict': {
1049 'id': '3jNQLTMrPlYGTBn0WV6M2MS',
1050 'title': 'Calculating Ada: The Countess of Computing - Not your typical role model: Ada Lovelace the 19th century programmer - BBC Four',
1051 'description': 'Hannah Fry reveals some of her surprising discoveries about Ada Lovelace during filming.',
1052 },
1053 'playlist_count': 4,
1054 'add_ie': ['BBCCoUk'],
1055 }
1056
1057 def _real_extract(self, url):
1058 playlist_id = self._match_id(url)
1059
1060 webpage = self._download_webpage(url, playlist_id)
1061
1062 title = self._og_search_title(webpage)
1063 description = self._og_search_description(webpage).strip()
1064
1065 entries = [self.url_result(programme_url) for programme_url in re.findall(
1066 r'<div[^>]+typeof="Clip"[^>]+resource="([^"]+)"', webpage)]
1067
1068 return self.playlist_result(entries, playlist_id, title, description)
1069
1070
1071 class BBCCoUkPlaylistBaseIE(InfoExtractor):
1072 def _entries(self, webpage, url, playlist_id):
1073 single_page = 'page' in compat_urlparse.parse_qs(
1074 compat_urlparse.urlparse(url).query)
1075 for page_num in itertools.count(2):
1076 for video_id in re.findall(
1077 self._VIDEO_ID_TEMPLATE % BBCCoUkIE._ID_REGEX, webpage):
1078 yield self.url_result(
1079 self._URL_TEMPLATE % video_id, BBCCoUkIE.ie_key())
1080 if single_page:
1081 return
1082 next_page = self._search_regex(
1083 r'<li[^>]+class=(["\'])pagination_+next\1[^>]*><a[^>]+href=(["\'])(?P<url>(?:(?!\2).)+)\2',
1084 webpage, 'next page url', default=None, group='url')
1085 if not next_page:
1086 break
1087 webpage = self._download_webpage(
1088 compat_urlparse.urljoin(url, next_page), playlist_id,
1089 'Downloading page %d' % page_num, page_num)
1090
1091 def _real_extract(self, url):
1092 playlist_id = self._match_id(url)
1093
1094 webpage = self._download_webpage(url, playlist_id)
1095
1096 title, description = self._extract_title_and_description(webpage)
1097
1098 return self.playlist_result(
1099 self._entries(webpage, url, playlist_id),
1100 playlist_id, title, description)
1101
1102
1103 class BBCCoUkIPlayerPlaylistIE(BBCCoUkPlaylistBaseIE):
1104 IE_NAME = 'bbc.co.uk:iplayer:playlist'
1105 _VALID_URL = r'https?://(?:www\.)?bbc\.co\.uk/iplayer/(?:episodes|group)/(?P<id>%s)' % BBCCoUkIE._ID_REGEX
1106 _URL_TEMPLATE = 'http://www.bbc.co.uk/iplayer/episode/%s'
1107 _VIDEO_ID_TEMPLATE = r'data-ip-id=["\'](%s)'
1108 _TESTS = [{
1109 'url': 'http://www.bbc.co.uk/iplayer/episodes/b05rcz9v',
1110 'info_dict': {
1111 'id': 'b05rcz9v',
1112 'title': 'The Disappearance',
1113 'description': 'French thriller serial about a missing teenager.',
1114 },
1115 'playlist_mincount': 6,
1116 'skip': 'This programme is not currently available on BBC iPlayer',
1117 }, {
1118 # Available for over a year unlike 30 days for most other programmes
1119 'url': 'http://www.bbc.co.uk/iplayer/group/p02tcc32',
1120 'info_dict': {
1121 'id': 'p02tcc32',
1122 'title': 'Bohemian Icons',
1123 'description': 'md5:683e901041b2fe9ba596f2ab04c4dbe7',
1124 },
1125 'playlist_mincount': 10,
1126 }]
1127
1128 def _extract_title_and_description(self, webpage):
1129 title = self._search_regex(r'<h1>([^<]+)</h1>', webpage, 'title', fatal=False)
1130 description = self._search_regex(
1131 r'<p[^>]+class=(["\'])subtitle\1[^>]*>(?P<value>[^<]+)</p>',
1132 webpage, 'description', fatal=False, group='value')
1133 return title, description
1134
1135
1136 class BBCCoUkPlaylistIE(BBCCoUkPlaylistBaseIE):
1137 IE_NAME = 'bbc.co.uk:playlist'
1138 _VALID_URL = r'https?://(?:www\.)?bbc\.co\.uk/programmes/(?P<id>%s)/(?:episodes|broadcasts|clips)' % BBCCoUkIE._ID_REGEX
1139 _URL_TEMPLATE = 'http://www.bbc.co.uk/programmes/%s'
1140 _VIDEO_ID_TEMPLATE = r'data-pid=["\'](%s)'
1141 _TESTS = [{
1142 'url': 'http://www.bbc.co.uk/programmes/b05rcz9v/clips',
1143 'info_dict': {
1144 'id': 'b05rcz9v',
1145 'title': 'The Disappearance - Clips - BBC Four',
1146 'description': 'French thriller serial about a missing teenager.',
1147 },
1148 'playlist_mincount': 7,
1149 }, {
1150 # multipage playlist, explicit page
1151 'url': 'http://www.bbc.co.uk/programmes/b00mfl7n/clips?page=1',
1152 'info_dict': {
1153 'id': 'b00mfl7n',
1154 'title': 'Frozen Planet - Clips - BBC One',
1155 'description': 'md5:65dcbf591ae628dafe32aa6c4a4a0d8c',
1156 },
1157 'playlist_mincount': 24,
1158 }, {
1159 # multipage playlist, all pages
1160 'url': 'http://www.bbc.co.uk/programmes/b00mfl7n/clips',
1161 'info_dict': {
1162 'id': 'b00mfl7n',
1163 'title': 'Frozen Planet - Clips - BBC One',
1164 'description': 'md5:65dcbf591ae628dafe32aa6c4a4a0d8c',
1165 },
1166 'playlist_mincount': 142,
1167 }, {
1168 'url': 'http://www.bbc.co.uk/programmes/b05rcz9v/broadcasts/2016/06',
1169 'only_matching': True,
1170 }, {
1171 'url': 'http://www.bbc.co.uk/programmes/b05rcz9v/clips',
1172 'only_matching': True,
1173 }, {
1174 'url': 'http://www.bbc.co.uk/programmes/b055jkys/episodes/player',
1175 'only_matching': True,
1176 }]
1177
1178 def _extract_title_and_description(self, webpage):
1179 title = self._og_search_title(webpage, fatal=False)
1180 description = self._og_search_description(webpage)
1181 return title, description