]> jfr.im git - yt-dlp.git/blame - youtube_dl/extractor/bbc.py
[trilulilu] handle errors
[yt-dlp.git] / youtube_dl / extractor / bbc.py
CommitLineData
9afa1770 1# coding: utf-8
082c6c86
S
2from __future__ import unicode_literals
3
9afa1770 4import re
082c6c86 5
f13b1e7d 6from .common import InfoExtractor
8683b4d8
S
7from ..utils import (
8 ExtractorError,
9afa1770 9 float_or_none,
8683b4d8 10 int_or_none,
9afa1770
S
11 parse_duration,
12 parse_iso8601,
ae8bdfd1 13 remove_end,
dab062fb 14 unescapeHTML,
8683b4d8 15)
36e6f62c
JMF
16from ..compat import (
17 compat_etree_fromstring,
18 compat_HTTPError,
19)
082c6c86 20
d12a1a47 21
f13b1e7d 22class BBCCoUkIE(InfoExtractor):
082c6c86 23 IE_NAME = 'bbc.co.uk'
2e3fd9ec 24 IE_DESC = 'BBC iPlayer'
22d7368d 25 _ID_REGEX = r'[pb][\da-z]{7}'
49358274 26 _VALID_URL = r'https?://(?:www\.)?bbc\.co\.uk/(?:(?:programmes/(?!articles/)|iplayer(?:/[^/]+)?/(?:episode/|playlist/))|music/clips[/#])(?P<id>%s)' % _ID_REGEX
082c6c86 27
d12a1a47 28 _MEDIASELECTOR_URLS = [
26ccc68b
S
29 # Provides HQ HLS streams with even better quality that pc mediaset but fails
30 # with geolocation in some cases when it's even not geo restricted at all (e.g.
d781e293 31 # http://www.bbc.co.uk/programmes/b06bp7lf). Also may fail with selectionunavailable.
d1c694ea 32 'http://open.live.bbc.co.uk/mediaselector/5/select/version/2.0/mediaset/iptv-all/vpid/%s',
d12a1a47
S
33 'http://open.live.bbc.co.uk/mediaselector/5/select/version/2.0/mediaset/pc/vpid/%s',
34 ]
a8b081a0 35
e6174ee9
S
36 _MEDIASELECTION_NS = 'http://bbc.co.uk/2008/mp/mediaselection'
37 _EMP_PLAYLIST_NS = 'http://bbc.co.uk/2008/emp/playlist'
38
39 _NAMESPACES = (
40 _MEDIASELECTION_NS,
41 _EMP_PLAYLIST_NS,
42 )
43
2e3fd9ec
S
44 _TESTS = [
45 {
f2d0fc68 46 'url': 'http://www.bbc.co.uk/programmes/b039g8p7',
2e3fd9ec 47 'info_dict': {
f2d0fc68 48 'id': 'b039d07m',
2e3fd9ec 49 'ext': 'flv',
c4914185
S
50 'title': 'Kaleidoscope, Leonard Cohen',
51 'description': 'The Canadian poet and songwriter reflects on his musical career.',
f2d0fc68 52 'duration': 1740,
2e3fd9ec
S
53 },
54 'params': {
55 # rtmp download
56 'skip_download': True,
57 }
082c6c86 58 },
2e3fd9ec
S
59 {
60 'url': 'http://www.bbc.co.uk/iplayer/episode/b00yng5w/The_Man_in_Black_Series_3_The_Printed_Name/',
61 'info_dict': {
62 'id': 'b00yng1d',
63 'ext': 'flv',
64 'title': 'The Man in Black: Series 3: The Printed Name',
65 'description': "Mark Gatiss introduces Nicholas Pierpan's chilling tale of a writer's devilish pact with a mysterious man. Stars Ewan Bailey.",
66 'duration': 1800,
67 },
68 'params': {
69 # rtmp download
70 'skip_download': True,
c7f0177f
S
71 },
72 'skip': 'Episode is no longer available on BBC iPlayer Radio',
2e3fd9ec
S
73 },
74 {
75 'url': 'http://www.bbc.co.uk/iplayer/episode/b03vhd1f/The_Voice_UK_Series_3_Blind_Auditions_5/',
76 'info_dict': {
77 'id': 'b00yng1d',
78 'ext': 'flv',
17968e44
S
79 'title': 'The Voice UK: Series 3: Blind Auditions 5',
80 '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.",
81 'duration': 5100,
2e3fd9ec
S
82 },
83 'params': {
84 # rtmp download
85 'skip_download': True,
86 },
87 'skip': 'Currently BBC iPlayer TV programmes are available to play in the UK only',
c056efa2
S
88 },
89 {
90 'url': 'http://www.bbc.co.uk/iplayer/episode/p026c7jt/tomorrows-worlds-the-unearthly-history-of-science-fiction-2-invasion',
91 'info_dict': {
92 'id': 'b03k3pb7',
93 'ext': 'flv',
94 'title': "Tomorrow's Worlds: The Unearthly History of Science Fiction",
95 'description': '2. Invasion',
96 'duration': 3600,
97 },
98 'params': {
99 # rtmp download
100 'skip_download': True,
101 },
102 'skip': 'Currently BBC iPlayer TV programmes are available to play in the UK only',
ae6986fb
S
103 }, {
104 'url': 'http://www.bbc.co.uk/programmes/b04v20dw',
105 'info_dict': {
106 'id': 'b04v209v',
107 'ext': 'flv',
108 'title': 'Pete Tong, The Essential New Tune Special',
109 'description': "Pete has a very special mix - all of 2014's Essential New Tunes!",
110 'duration': 10800,
111 },
112 'params': {
113 # rtmp download
114 'skip_download': True,
115 }
c7e67594
S
116 }, {
117 'url': 'http://www.bbc.co.uk/music/clips/p02frcc3',
118 'note': 'Audio',
119 'info_dict': {
120 'id': 'p02frcch',
121 'ext': 'flv',
122 'title': 'Pete Tong, Past, Present and Future Special, Madeon - After Hours mix',
123 'description': 'French house superstar Madeon takes us out of the club and onto the after party.',
124 'duration': 3507,
125 },
126 'params': {
127 # rtmp download
128 'skip_download': True,
129 }
130 }, {
131 'url': 'http://www.bbc.co.uk/music/clips/p025c0zz',
132 'note': 'Video',
133 'info_dict': {
134 'id': 'p025c103',
135 'ext': 'flv',
136 'title': 'Reading and Leeds Festival, 2014, Rae Morris - Closer (Live on BBC Three)',
137 'description': 'Rae Morris performs Closer for BBC Three at Reading 2014',
138 'duration': 226,
139 },
140 'params': {
141 # rtmp download
142 'skip_download': True,
143 }
e68ae99a
S
144 }, {
145 'url': 'http://www.bbc.co.uk/iplayer/episode/b054fn09/ad/natural-world-20152016-2-super-powered-owls',
146 'info_dict': {
147 'id': 'p02n76xf',
148 'ext': 'flv',
149 'title': 'Natural World, 2015-2016: 2. Super Powered Owls',
150 'description': 'md5:e4db5c937d0e95a7c6b5e654d429183d',
151 'duration': 3540,
152 },
153 'params': {
154 # rtmp download
155 'skip_download': True,
156 },
157 'skip': 'geolocation',
25fa8d66
YCH
158 }, {
159 'url': 'http://www.bbc.co.uk/iplayer/episode/b05zmgwn/royal-academy-summer-exhibition',
160 'info_dict': {
161 'id': 'b05zmgw1',
162 'ext': 'flv',
163 '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.',
164 'title': 'Royal Academy Summer Exhibition',
165 'duration': 3540,
166 },
167 'params': {
168 # rtmp download
169 'skip_download': True,
170 },
171 'skip': 'geolocation',
54914380
S
172 }, {
173 # iptv-all mediaset fails with geolocation however there is no geo restriction
174 # for this programme at all
175 'url': 'http://www.bbc.co.uk/programmes/b06bp7lf',
176 'info_dict': {
177 'id': 'b06bp7kf',
178 'ext': 'flv',
179 'title': "Annie Mac's Friday Night, B.Traits sits in for Annie",
180 'description': 'B.Traits sits in for Annie Mac with a Mini-Mix from Disclosure.',
181 'duration': 10800,
182 },
183 'params': {
184 # rtmp download
185 'skip_download': True,
186 },
31763975
S
187 }, {
188 'url': 'http://www.bbc.co.uk/iplayer/playlist/p01dvks4',
189 'only_matching': True,
c7e67594
S
190 }, {
191 'url': 'http://www.bbc.co.uk/music/clips#p02frcc3',
192 'only_matching': True,
0692ef86
S
193 }, {
194 'url': 'http://www.bbc.co.uk/iplayer/cbeebies/episode/b0480276/bing-14-atchoo',
195 'only_matching': True,
ae6986fb 196 }
2e3fd9ec
S
197 ]
198
d12a1a47
S
199 class MediaSelectionError(Exception):
200 def __init__(self, id):
201 self.id = id
202
2e3fd9ec
S
203 def _extract_asx_playlist(self, connection, programme_id):
204 asx = self._download_xml(connection.get('href'), programme_id, 'Downloading ASX playlist')
205 return [ref.get('href') for ref in asx.findall('./Entry/ref')]
206
207 def _extract_connection(self, connection, programme_id):
208 formats = []
e6174ee9 209 kind = connection.get('kind')
2e3fd9ec
S
210 protocol = connection.get('protocol')
211 supplier = connection.get('supplier')
212 if protocol == 'http':
213 href = connection.get('href')
7a896817 214 transfer_format = connection.get('transferFormat')
2e3fd9ec
S
215 # ASX playlist
216 if supplier == 'asx':
217 for i, ref in enumerate(self._extract_asx_playlist(connection, programme_id)):
218 formats.append({
219 'url': ref,
220 'format_id': 'ref%s_%s' % (i, supplier),
221 })
7a896817
S
222 # Skip DASH until supported
223 elif transfer_format == 'dash':
224 pass
d1c694ea
S
225 elif transfer_format == 'hls':
226 m3u8_formats = self._extract_m3u8_formats(
227 href, programme_id, ext='mp4', entry_protocol='m3u8_native',
228 m3u8_id=supplier, fatal=False)
229 if m3u8_formats:
230 formats.extend(m3u8_formats)
2e3fd9ec
S
231 # Direct link
232 else:
233 formats.append({
234 'url': href,
e6174ee9 235 'format_id': supplier or kind or protocol,
2e3fd9ec
S
236 })
237 elif protocol == 'rtmp':
238 application = connection.get('application', 'ondemand')
239 auth_string = connection.get('authString')
240 identifier = connection.get('identifier')
241 server = connection.get('server')
242 formats.append({
243 'url': '%s://%s/%s?%s' % (protocol, server, application, auth_string),
244 'play_path': identifier,
245 'app': '%s?%s' % (application, auth_string),
246 'page_url': 'http://www.bbc.co.uk',
247 'player_url': 'http://www.bbc.co.uk/emp/releases/iplayer/revisions/617463_618125_4/617463_618125_4_emp.swf',
248 'rtmp_live': False,
249 'ext': 'flv',
250 'format_id': supplier,
251 })
252 return formats
253
254 def _extract_items(self, playlist):
e6174ee9
S
255 return playlist.findall('./{%s}item' % self._EMP_PLAYLIST_NS)
256
257 def _findall_ns(self, element, xpath):
258 elements = []
259 for ns in self._NAMESPACES:
260 elements.extend(element.findall(xpath % ns))
261 return elements
2e3fd9ec
S
262
263 def _extract_medias(self, media_selection):
e6174ee9
S
264 error = media_selection.find('./{%s}error' % self._MEDIASELECTION_NS)
265 if error is None:
266 media_selection.find('./{%s}error' % self._EMP_PLAYLIST_NS)
c056efa2 267 if error is not None:
d12a1a47 268 raise BBCCoUkIE.MediaSelectionError(error.get('id'))
e6174ee9 269 return self._findall_ns(media_selection, './{%s}media')
2e3fd9ec
S
270
271 def _extract_connections(self, media):
e6174ee9 272 return self._findall_ns(media, './{%s}connection')
2e3fd9ec
S
273
274 def _extract_video(self, media, programme_id):
275 formats = []
d97f5cd7 276 vbr = int_or_none(media.get('bitrate'))
2e3fd9ec
S
277 vcodec = media.get('encoding')
278 service = media.get('service')
d97f5cd7
S
279 width = int_or_none(media.get('width'))
280 height = int_or_none(media.get('height'))
281 file_size = int_or_none(media.get('media_file_size'))
2e3fd9ec
S
282 for connection in self._extract_connections(media):
283 conn_formats = self._extract_connection(connection, programme_id)
284 for format in conn_formats:
285 format.update({
2e3fd9ec
S
286 'width': width,
287 'height': height,
288 'vbr': vbr,
289 'vcodec': vcodec,
290 'filesize': file_size,
291 })
e6174ee9
S
292 if service:
293 format['format_id'] = '%s_%s' % (service, format['format_id'])
2e3fd9ec
S
294 formats.extend(conn_formats)
295 return formats
296
297 def _extract_audio(self, media, programme_id):
298 formats = []
d97f5cd7 299 abr = int_or_none(media.get('bitrate'))
2e3fd9ec
S
300 acodec = media.get('encoding')
301 service = media.get('service')
302 for connection in self._extract_connections(media):
303 conn_formats = self._extract_connection(connection, programme_id)
304 for format in conn_formats:
305 format.update({
306 'format_id': '%s_%s' % (service, format['format_id']),
307 'abr': abr,
308 'acodec': acodec,
309 })
310 formats.extend(conn_formats)
311 return formats
312
f13b1e7d 313 def _get_subtitles(self, media, programme_id):
2e3fd9ec
S
314 subtitles = {}
315 for connection in self._extract_connections(media):
316 captions = self._download_xml(connection.get('href'), programme_id, 'Downloading captions')
317 lang = captions.get('{http://www.w3.org/XML/1998/namespace}lang', 'en')
f13b1e7d
JMF
318 subtitles[lang] = [
319 {
320 'url': connection.get('href'),
321 'ext': 'ttml',
322 },
f13b1e7d 323 ]
2e3fd9ec 324 return subtitles
082c6c86 325
d12a1a47
S
326 def _raise_extractor_error(self, media_selection_error):
327 raise ExtractorError(
328 '%s returned error: %s' % (self.IE_NAME, media_selection_error.id),
329 expected=True)
330
c056efa2 331 def _download_media_selector(self, programme_id):
d12a1a47
S
332 last_exception = None
333 for mediaselector_url in self._MEDIASELECTOR_URLS:
334 try:
335 return self._download_media_selector_url(
336 mediaselector_url % programme_id, programme_id)
337 except BBCCoUkIE.MediaSelectionError as e:
d781e293 338 if e.id in ('notukerror', 'geolocation', 'selectionunavailable'):
d12a1a47
S
339 last_exception = e
340 continue
341 self._raise_extractor_error(e)
342 self._raise_extractor_error(last_exception)
9afa1770
S
343
344 def _download_media_selector_url(self, url, programme_id=None):
c056efa2
S
345 try:
346 media_selection = self._download_xml(
9afa1770 347 url, programme_id, 'Downloading media selection XML')
c056efa2 348 except ExtractorError as ee:
d781e293 349 if isinstance(ee.cause, compat_HTTPError) and ee.cause.code in (403, 404):
36e6f62c 350 media_selection = compat_etree_fromstring(ee.cause.read().decode('utf-8'))
2e3fd9ec 351 else:
c056efa2 352 raise
9afa1770 353 return self._process_media_selector(media_selection, programme_id)
082c6c86 354
9afa1770 355 def _process_media_selector(self, media_selection, programme_id):
082c6c86 356 formats = []
2e3fd9ec
S
357 subtitles = None
358
c056efa2
S
359 for media in self._extract_medias(media_selection):
360 kind = media.get('kind')
361 if kind == 'audio':
362 formats.extend(self._extract_audio(media, programme_id))
363 elif kind == 'video':
364 formats.extend(self._extract_video(media, programme_id))
365 elif kind == 'captions':
f13b1e7d 366 subtitles = self.extract_subtitles(media, programme_id)
c056efa2 367 return formats, subtitles
2e3fd9ec 368
ae6986fb
S
369 def _download_playlist(self, playlist_id):
370 try:
371 playlist = self._download_json(
372 'http://www.bbc.co.uk/programmes/%s/playlist.json' % playlist_id,
373 playlist_id, 'Downloading playlist JSON')
374
375 version = playlist.get('defaultAvailableVersion')
376 if version:
377 smp_config = version['smpConfig']
378 title = smp_config['title']
379 description = smp_config['summary']
380 for item in smp_config['items']:
381 kind = item['kind']
382 if kind != 'programme' and kind != 'radioProgramme':
383 continue
384 programme_id = item.get('vpid')
d97f5cd7 385 duration = int_or_none(item.get('duration'))
ae6986fb
S
386 formats, subtitles = self._download_media_selector(programme_id)
387 return programme_id, title, description, duration, formats, subtitles
388 except ExtractorError as ee:
f813928e 389 if not (isinstance(ee.cause, compat_HTTPError) and ee.cause.code == 404):
ae6986fb
S
390 raise
391
392 # fallback to legacy playlist
9afa1770
S
393 return self._process_legacy_playlist(playlist_id)
394
395 def _process_legacy_playlist_url(self, url, display_id):
396 playlist = self._download_legacy_playlist_url(url, display_id)
397 return self._extract_from_legacy_playlist(playlist, display_id)
398
399 def _process_legacy_playlist(self, playlist_id):
400 return self._process_legacy_playlist_url(
401 'http://www.bbc.co.uk/iplayer/playlist/%s' % playlist_id, playlist_id)
402
403 def _download_legacy_playlist_url(self, url, playlist_id=None):
404 return self._download_xml(
405 url, playlist_id, 'Downloading legacy playlist XML')
ae6986fb 406
9afa1770 407 def _extract_from_legacy_playlist(self, playlist, playlist_id):
e6174ee9 408 no_items = playlist.find('./{%s}noItems' % self._EMP_PLAYLIST_NS)
ae6986fb
S
409 if no_items is not None:
410 reason = no_items.get('reason')
411 if reason == 'preAvailability':
412 msg = 'Episode %s is not yet available' % playlist_id
413 elif reason == 'postAvailability':
414 msg = 'Episode %s is no longer available' % playlist_id
415 elif reason == 'noMedia':
416 msg = 'Episode %s is not currently available' % playlist_id
417 else:
418 msg = 'Episode %s is not available: %s' % (playlist_id, reason)
419 raise ExtractorError(msg, expected=True)
420
421 for item in self._extract_items(playlist):
422 kind = item.get('kind')
423 if kind != 'programme' and kind != 'radioProgramme':
424 continue
e6174ee9
S
425 title = playlist.find('./{%s}title' % self._EMP_PLAYLIST_NS).text
426 description_el = playlist.find('./{%s}summary' % self._EMP_PLAYLIST_NS)
8daeeedc 427 description = description_el.text if description_el is not None else None
9afa1770
S
428
429 def get_programme_id(item):
430 def get_from_attributes(item):
431 for p in('identifier', 'group'):
432 value = item.get(p)
433 if value and re.match(r'^[pb][\da-z]{7}$', value):
434 return value
435 get_from_attributes(item)
e6174ee9 436 mediator = item.find('./{%s}mediator' % self._EMP_PLAYLIST_NS)
9afa1770
S
437 if mediator is not None:
438 return get_from_attributes(mediator)
439
440 programme_id = get_programme_id(item)
d97f5cd7 441 duration = int_or_none(item.get('duration'))
e6174ee9
S
442
443 if programme_id:
444 formats, subtitles = self._download_media_selector(programme_id)
445 else:
446 formats, subtitles = self._process_media_selector(item, playlist_id)
447 programme_id = playlist_id
ae6986fb
S
448
449 return programme_id, title, description, duration, formats, subtitles
450
c056efa2
S
451 def _real_extract(self, url):
452 group_id = self._match_id(url)
453
454 webpage = self._download_webpage(url, group_id, 'Downloading video page')
455
8683b4d8
S
456 programme_id = None
457
458 tviplayer = self._search_regex(
459 r'mediator\.bind\(({.+?})\s*,\s*document\.getElementById',
460 webpage, 'player', default=None)
461
462 if tviplayer:
463 player = self._parse_json(tviplayer, group_id).get('player', {})
464 duration = int_or_none(player.get('duration'))
465 programme_id = player.get('vpid')
466
467 if not programme_id:
468 programme_id = self._search_regex(
22d7368d 469 r'"vpid"\s*:\s*"(%s)"' % self._ID_REGEX, webpage, 'vpid', fatal=False, default=None)
8683b4d8 470
c056efa2 471 if programme_id:
c056efa2 472 formats, subtitles = self._download_media_selector(programme_id)
8683b4d8
S
473 title = self._og_search_title(webpage)
474 description = self._search_regex(
25fa8d66 475 r'<p class="[^"]*medium-description[^"]*">([^<]+)</p>',
8683b4d8 476 webpage, 'description', fatal=False)
c056efa2 477 else:
ae6986fb 478 programme_id, title, description, duration, formats, subtitles = self._download_playlist(group_id)
2e3fd9ec 479
082c6c86
S
480 self._sort_formats(formats)
481
482 return {
2e3fd9ec 483 'id': programme_id,
082c6c86
S
484 'title': title,
485 'description': description,
650cfd0c 486 'thumbnail': self._og_search_thumbnail(webpage, default=None),
082c6c86
S
487 'duration': duration,
488 'formats': formats,
2e3fd9ec 489 'subtitles': subtitles,
5f6a1245 490 }
10273d6e 491
492
9afa1770
S
493class BBCIE(BBCCoUkIE):
494 IE_NAME = 'bbc'
495 IE_DESC = 'BBC'
496 _VALID_URL = r'https?://(?:www\.)?bbc\.(?:com|co\.uk)/(?:[^/]+/)+(?P<id>[^/#?]+)'
10273d6e 497
d12a1a47 498 _MEDIASELECTOR_URLS = [
55ebae26
S
499 # Provides HQ HLS streams but fails with geolocation in some cases when it's
500 # even not geo restricted at all
501 'http://open.live.bbc.co.uk/mediaselector/5/select/version/2.0/mediaset/iptv-all/vpid/%s',
d12a1a47
S
502 # Provides more formats, namely direct mp4 links, but fails on some videos with
503 # notukerror for non UK (?) users (e.g.
504 # http://www.bbc.com/travel/story/20150625-sri-lankas-spicy-secret)
505 'http://open.live.bbc.co.uk/mediaselector/4/mtis/stream/%s',
506 # Provides fewer formats, but works everywhere for everybody (hopefully)
507 'http://open.live.bbc.co.uk/mediaselector/5/select/version/2.0/mediaset/journalism-pc/vpid/%s',
508 ]
10273d6e 509
510 _TESTS = [{
6a747190 511 # article with multiple videos embedded with data-playable containing vpids
10273d6e 512 'url': 'http://www.bbc.com/news/world-europe-32668511',
513 'info_dict': {
514 'id': 'world-europe-32668511',
515 'title': 'Russia stages massive WW2 parade despite Western boycott',
9afa1770 516 'description': 'md5:00ff61976f6081841f759a08bf78cc9c',
10273d6e 517 },
518 'playlist_count': 2,
a3bfddfa 519 }, {
6a747190 520 # article with multiple videos embedded with data-playable (more videos)
10273d6e 521 'url': 'http://www.bbc.com/news/business-28299555',
522 'info_dict': {
523 'id': 'business-28299555',
524 'title': 'Farnborough Airshow: Video highlights',
9afa1770 525 'description': 'BBC reports and video highlights at the Farnborough Airshow.',
10273d6e 526 },
527 'playlist_count': 9,
9afa1770 528 'skip': 'Save time',
88ed52ae
S
529 }, {
530 # article with multiple videos embedded with `new SMP()`
6a747190 531 # broken
88ed52ae
S
532 'url': 'http://www.bbc.co.uk/blogs/adamcurtis/entries/3662a707-0af9-3149-963f-47bea720b460',
533 'info_dict': {
534 'id': '3662a707-0af9-3149-963f-47bea720b460',
535 'title': 'BBC Blogs - Adam Curtis - BUGGER',
536 },
537 'playlist_count': 18,
a3bfddfa 538 }, {
6a747190 539 # single video embedded with data-playable containing vpid
10273d6e 540 'url': 'http://www.bbc.com/news/world-europe-32041533',
10273d6e 541 'info_dict': {
542 'id': 'p02mprgb',
55ebae26 543 'ext': 'mp4',
10273d6e 544 'title': 'Aerial footage showed the site of the crash in the Alps - courtesy BFM TV',
55ebae26 545 'description': 'md5:2868290467291b37feda7863f7a83f54',
10273d6e 546 'duration': 47,
9afa1770 547 'timestamp': 1427219242,
da92eeae 548 'upload_date': '20150324',
10273d6e 549 },
550 'params': {
9afa1770 551 # rtmp download
10273d6e 552 'skip_download': True,
553 }
a3bfddfa 554 }, {
6a747190
S
555 # article with single video embedded with data-playable containing XML playlist
556 # with direct video links as progressiveDownloadUrl (for now these are extracted)
557 # and playlist with f4m and m3u8 as streamingUrl
de939d89 558 'url': 'http://www.bbc.com/turkce/haberler/2015/06/150615_telabyad_kentin_cogu',
de939d89 559 'info_dict': {
9afa1770 560 'id': '150615_telabyad_kentin_cogu',
de939d89 561 'ext': 'mp4',
9afa1770 562 'title': "YPG: Tel Abyad'ın tamamı kontrolümüzde",
9afa1770 563 'timestamp': 1434397334,
da92eeae 564 'upload_date': '20150615',
de939d89 565 },
566 'params': {
567 'skip_download': True,
568 }
c936d8cc 569 }, {
6a747190 570 # single video embedded with data-playable containing XML playlists (regional section)
de939d89 571 'url': 'http://www.bbc.com/mundo/video_fotos/2015/06/150619_video_honduras_militares_hospitales_corrupcion_aw',
de939d89 572 'info_dict': {
9afa1770 573 'id': '150619_video_honduras_militares_hospitales_corrupcion_aw',
de939d89 574 'ext': 'mp4',
9afa1770 575 'title': 'Honduras militariza sus hospitales por nuevo escándalo de corrupción',
9afa1770 576 'timestamp': 1434713142,
da92eeae 577 'upload_date': '20150619',
de939d89 578 },
579 'params': {
580 'skip_download': True,
581 }
a346b1ff
S
582 }, {
583 # single video from video playlist embedded with vxp-playlist-data JSON
584 'url': 'http://www.bbc.com/news/video_and_audio/must_see/33376376',
585 'info_dict': {
586 'id': 'p02w6qjc',
55ebae26 587 'ext': 'mp4',
a346b1ff
S
588 'title': '''Judge Mindy Glazer: "I'm sorry to see you here... I always wondered what happened to you"''',
589 'duration': 56,
590 },
591 'params': {
592 'skip_download': True,
593 }
9afa1770
S
594 }, {
595 # single video story with digitalData
596 'url': 'http://www.bbc.com/travel/story/20150625-sri-lankas-spicy-secret',
597 'info_dict': {
598 'id': 'p02q6gc4',
599 'ext': 'flv',
600 'title': 'Sri Lanka’s spicy secret',
601 'description': 'As a new train line to Jaffna opens up the country’s north, travellers can experience a truly distinct slice of Tamil culture.',
602 'timestamp': 1437674293,
603 'upload_date': '20150723',
604 },
605 'params': {
606 # rtmp download
607 'skip_download': True,
608 }
609 }, {
610 # single video story without digitalData
611 'url': 'http://www.bbc.com/autos/story/20130513-hyundais-rock-star',
612 'info_dict': {
613 'id': 'p018zqqg',
55ebae26 614 'ext': 'mp4',
9afa1770
S
615 'title': 'Hyundai Santa Fe Sport: Rock star',
616 'description': 'md5:b042a26142c4154a6e472933cf20793d',
ae8bdfd1
S
617 'timestamp': 1415867444,
618 'upload_date': '20141113',
9afa1770
S
619 },
620 'params': {
621 # rtmp download
622 'skip_download': True,
623 }
624 }, {
6a747190 625 # single video with playlist.sxml URL in playlist param
9afa1770
S
626 'url': 'http://www.bbc.com/sport/0/football/33653409',
627 'info_dict': {
628 'id': 'p02xycnp',
55ebae26 629 'ext': 'mp4',
9afa1770 630 'title': 'Transfers: Cristiano Ronaldo to Man Utd, Arsenal to spend?',
7033bc1a 631 'description': 'BBC Sport\'s David Ornstein has the latest transfer gossip, including rumours of a Manchester United return for Cristiano Ronaldo.',
9afa1770
S
632 'duration': 140,
633 },
634 'params': {
635 # rtmp download
636 'skip_download': True,
637 }
b5d48cb1 638 }, {
6a747190 639 # article with multiple videos embedded with playlist.sxml in playlist param
b5d48cb1
S
640 'url': 'http://www.bbc.com/sport/0/football/34475836',
641 'info_dict': {
642 'id': '34475836',
643 'title': 'What Liverpool can expect from Klopp',
644 },
645 'playlist_count': 3,
9afa1770
S
646 }, {
647 # single video with playlist URL from weather section
648 'url': 'http://www.bbc.com/weather/features/33601775',
649 'only_matching': True,
650 }, {
651 # custom redirection to www.bbc.com
652 'url': 'http://www.bbc.co.uk/news/science-environment-33661876',
653 'only_matching': True,
10273d6e 654 }]
655
9afa1770
S
656 @classmethod
657 def suitable(cls, url):
a65402ef 658 return False if BBCCoUkIE.suitable(url) or BBCCoUkArticleIE.suitable(url) else super(BBCIE, cls).suitable(url)
9afa1770
S
659
660 def _extract_from_media_meta(self, media_meta, video_id):
661 # Direct links to media in media metadata (e.g.
662 # http://www.bbc.com/turkce/haberler/2015/06/150615_telabyad_kentin_cogu)
663 # TODO: there are also f4m and m3u8 streams incorporated in playlist.sxml
664 source_files = media_meta.get('sourceFiles')
665 if source_files:
666 return [{
667 'url': f['url'],
668 'format_id': format_id,
669 'ext': f.get('encoding'),
670 'tbr': float_or_none(f.get('bitrate'), 1000),
671 'filesize': int_or_none(f.get('filesize')),
672 } for format_id, f in source_files.items() if f.get('url')], []
673
674 programme_id = media_meta.get('externalId')
675 if programme_id:
676 return self._download_media_selector(programme_id)
677
678 # Process playlist.sxml as legacy playlist
679 href = media_meta.get('href')
680 if href:
681 playlist = self._download_legacy_playlist_url(href)
682 _, _, _, _, formats, subtitles = self._extract_from_legacy_playlist(playlist, video_id)
683 return formats, subtitles
684
685 return [], []
686
baf39a1a
S
687 def _extract_from_playlist_sxml(self, url, playlist_id, timestamp):
688 programme_id, title, description, duration, formats, subtitles = \
689 self._process_legacy_playlist_url(url, playlist_id)
690 self._sort_formats(formats)
691 return {
692 'id': programme_id,
693 'title': title,
694 'description': description,
695 'duration': duration,
696 'timestamp': timestamp,
697 'formats': formats,
698 'subtitles': subtitles,
699 }
700
10273d6e 701 def _real_extract(self, url):
9afa1770
S
702 playlist_id = self._match_id(url)
703
704 webpage = self._download_webpage(url, playlist_id)
705
ae8bdfd1
S
706 timestamp = None
707 playlist_title = None
708 playlist_description = None
709
710 ld = self._parse_json(
711 self._search_regex(
712 r'(?s)<script type="application/ld\+json">(.+?)</script>',
713 webpage, 'ld json', default='{}'),
714 playlist_id, fatal=False)
715 if ld:
716 timestamp = parse_iso8601(ld.get('datePublished'))
717 playlist_title = ld.get('headline')
718 playlist_description = ld.get('articleBody')
719
720 if not timestamp:
721 timestamp = parse_iso8601(self._search_regex(
722 [r'<meta[^>]+property="article:published_time"[^>]+content="([^"]+)"',
723 r'itemprop="datePublished"[^>]+datetime="([^"]+)"',
6f789365 724 r'"datePublished":\s*"([^"]+)'],
ae8bdfd1 725 webpage, 'date', default=None))
9afa1770 726
78f9d843
S
727 entries = []
728
de665713
S
729 # article with multiple videos embedded with playlist.sxml (e.g.
730 # http://www.bbc.com/sport/0/football/34475836)
731 playlists = re.findall(r'<param[^>]+name="playlist"[^>]+value="([^"]+)"', webpage)
732 if playlists:
baf39a1a
S
733 entries = [
734 self._extract_from_playlist_sxml(playlist_url, playlist_id, timestamp)
735 for playlist_url in playlists]
de939d89 736
78f9d843
S
737 # news article with multiple videos embedded with data-playable
738 data_playables = re.findall(r'data-playable=(["\'])({.+?})\1', webpage)
739 if data_playables:
740 for _, data_playable_json in data_playables:
741 data_playable = self._parse_json(
742 unescapeHTML(data_playable_json), playlist_id, fatal=False)
743 if not data_playable:
744 continue
baf39a1a
S
745 settings = data_playable.get('settings', {})
746 if settings:
78f9d843
S
747 # data-playable with video vpid in settings.playlistObject.items (e.g.
748 # http://www.bbc.com/news/world-us-canada-34473351)
baf39a1a
S
749 playlist_object = settings.get('playlistObject', {})
750 if playlist_object:
751 items = playlist_object.get('items')
752 if items and isinstance(items, list):
78f9d843
S
753 title = playlist_object['title']
754 description = playlist_object.get('summary')
baf39a1a
S
755 duration = int_or_none(items[0].get('duration'))
756 programme_id = items[0].get('vpid')
78f9d843
S
757 formats, subtitles = self._download_media_selector(programme_id)
758 self._sort_formats(formats)
759 entries.append({
760 'id': programme_id,
761 'title': title,
762 'description': description,
763 'timestamp': timestamp,
764 'duration': duration,
765 'formats': formats,
766 'subtitles': subtitles,
767 })
768 else:
769 # data-playable without vpid but with a playlist.sxml URLs
770 # in otherSettings.playlist (e.g.
771 # http://www.bbc.com/turkce/multimedya/2015/10/151010_vid_ankara_patlama_ani)
772 playlist = data_playable.get('otherSettings', {}).get('playlist', {})
773 if playlist:
774 entries.append(self._extract_from_playlist_sxml(
775 playlist.get('progressiveDownloadUrl'), playlist_id, timestamp))
776
777 if entries:
ae8bdfd1
S
778 playlist_title = playlist_title or remove_end(self._og_search_title(webpage), ' - BBC News')
779 playlist_description = playlist_description or self._og_search_description(webpage, default=None)
78f9d843
S
780 return self.playlist_result(entries, playlist_id, playlist_title, playlist_description)
781
782 # single video story (e.g. http://www.bbc.com/travel/story/20150625-sri-lankas-spicy-secret)
783 programme_id = self._search_regex(
22d7368d
S
784 [r'data-video-player-vpid="(%s)"' % self._ID_REGEX,
785 r'<param[^>]+name="externalIdentifier"[^>]+value="(%s)"' % self._ID_REGEX,
786 r'videoId\s*:\s*["\'](%s)["\']' % self._ID_REGEX],
78f9d843 787 webpage, 'vpid', default=None)
dab062fb 788
9afa1770
S
789 if programme_id:
790 formats, subtitles = self._download_media_selector(programme_id)
791 self._sort_formats(formats)
792 # digitalData may be missing (e.g. http://www.bbc.com/autos/story/20130513-hyundais-rock-star)
793 digital_data = self._parse_json(
794 self._search_regex(
795 r'var\s+digitalData\s*=\s*({.+?});?\n', webpage, 'digital data', default='{}'),
796 programme_id, fatal=False)
797 page_info = digital_data.get('page', {}).get('pageInfo', {})
798 title = page_info.get('pageName') or self._og_search_title(webpage)
799 description = page_info.get('description') or self._og_search_description(webpage)
800 timestamp = parse_iso8601(page_info.get('publicationDate')) or timestamp
801 return {
802 'id': programme_id,
803 'title': title,
804 'description': description,
805 'timestamp': timestamp,
806 'formats': formats,
807 'subtitles': subtitles,
808 }
a3bfddfa 809
9afa1770
S
810 playlist_title = self._html_search_regex(
811 r'<title>(.*?)(?:\s*-\s*BBC [^ ]+)?</title>', webpage, 'playlist title')
88ed52ae
S
812 playlist_description = self._og_search_description(webpage, default=None)
813
814 def extract_all(pattern):
815 return list(filter(None, map(
816 lambda s: self._parse_json(s, playlist_id, fatal=False),
817 re.findall(pattern, webpage))))
818
819 # Multiple video article (e.g.
820 # http://www.bbc.co.uk/blogs/adamcurtis/entries/3662a707-0af9-3149-963f-47bea720b460)
22d7368d 821 EMBED_URL = r'https?://(?:www\.)?bbc\.co\.uk/(?:[^/]+/)+%s(?:\b[^"]+)?' % self._ID_REGEX
88ed52ae
S
822 entries = []
823 for match in extract_all(r'new\s+SMP\(({.+?})\)'):
824 embed_url = match.get('playerSettings', {}).get('externalEmbedUrl')
825 if embed_url and re.match(EMBED_URL, embed_url):
826 entries.append(embed_url)
827 entries.extend(re.findall(
828 r'setPlaylist\("(%s)"\)' % EMBED_URL, webpage))
829 if entries:
830 return self.playlist_result(
831 [self.url_result(entry, 'BBCCoUk') for entry in entries],
832 playlist_id, playlist_title, playlist_description)
9afa1770
S
833
834 # Multiple video article (e.g. http://www.bbc.com/news/world-europe-32668511)
88ed52ae 835 medias = extract_all(r"data-media-meta='({[^']+})'")
9afa1770
S
836
837 if not medias:
838 # Single video article (e.g. http://www.bbc.com/news/video_and_audio/international)
a346b1ff
S
839 media_asset = self._search_regex(
840 r'mediaAssetPage\.init\(\s*({.+?}), "/',
841 webpage, 'media asset', default=None)
842 if media_asset:
843 media_asset_page = self._parse_json(media_asset, playlist_id, fatal=False)
844 medias = []
845 for video in media_asset_page.get('videos', {}).values():
846 medias.extend(video.values())
847
848 if not medias:
849 # Multiple video playlist with single `now playing` entry (e.g.
850 # http://www.bbc.com/news/video_and_audio/must_see/33767813)
851 vxp_playlist = self._parse_json(
9afa1770 852 self._search_regex(
a346b1ff
S
853 r'<script[^>]+class="vxp-playlist-data"[^>]+type="application/json"[^>]*>([^<]+)</script>',
854 webpage, 'playlist data'),
9afa1770 855 playlist_id)
a346b1ff
S
856 playlist_medias = []
857 for item in vxp_playlist:
858 media = item.get('media')
859 if not media:
860 continue
861 playlist_medias.append(media)
862 # Download single video if found media with asset id matching the video id from URL
863 if item.get('advert', {}).get('assetId') == playlist_id:
864 medias = [media]
865 break
866 # Fallback to the whole playlist
867 if not medias:
868 medias = playlist_medias
9afa1770
S
869
870 entries = []
871 for num, media_meta in enumerate(medias, start=1):
872 formats, subtitles = self._extract_from_media_meta(media_meta, playlist_id)
873 if not formats:
874 continue
10273d6e 875 self._sort_formats(formats)
876
9afa1770
S
877 video_id = media_meta.get('externalId')
878 if not video_id:
879 video_id = playlist_id if len(medias) == 1 else '%s-%s' % (playlist_id, num)
880
881 title = media_meta.get('caption')
882 if not title:
883 title = playlist_title if len(medias) == 1 else '%s - Video %s' % (playlist_title, num)
884
885 duration = int_or_none(media_meta.get('durationInSeconds')) or parse_duration(media_meta.get('duration'))
da92eeae 886
9afa1770
S
887 images = []
888 for image in media_meta.get('images', {}).values():
889 images.extend(image.values())
890 if 'image' in media_meta:
891 images.append(media_meta['image'])
892
893 thumbnails = [{
894 'url': image.get('href'),
895 'width': int_or_none(image.get('width')),
896 'height': int_or_none(image.get('height')),
897 } for image in images]
898
899 entries.append({
900 'id': video_id,
10273d6e 901 'title': title,
9afa1770 902 'thumbnails': thumbnails,
10273d6e 903 'duration': duration,
9afa1770 904 'timestamp': timestamp,
10273d6e 905 'formats': formats,
906 'subtitles': subtitles,
a3bfddfa 907 })
10273d6e 908
9afa1770 909 return self.playlist_result(entries, playlist_id, playlist_title, playlist_description)
a65402ef
YCH
910
911
912class BBCCoUkArticleIE(InfoExtractor):
913 _VALID_URL = 'http://www.bbc.co.uk/programmes/articles/(?P<id>[a-zA-Z0-9]+)'
914 IE_NAME = 'bbc.co.uk:article'
915 IE_DESC = 'BBC articles'
916
917 _TEST = {
918 'url': 'http://www.bbc.co.uk/programmes/articles/3jNQLTMrPlYGTBn0WV6M2MS/not-your-typical-role-model-ada-lovelace-the-19th-century-programmer',
919 'info_dict': {
920 'id': '3jNQLTMrPlYGTBn0WV6M2MS',
921 'title': 'Calculating Ada: The Countess of Computing - Not your typical role model: Ada Lovelace the 19th century programmer - BBC Four',
922 'description': 'Hannah Fry reveals some of her surprising discoveries about Ada Lovelace during filming.',
923 },
924 'playlist_count': 4,
925 'add_ie': ['BBCCoUk'],
926 }
927
928 def _real_extract(self, url):
929 playlist_id = self._match_id(url)
930
931 webpage = self._download_webpage(url, playlist_id)
932
933 title = self._og_search_title(webpage)
934 description = self._og_search_description(webpage).strip()
935
936 entries = [self.url_result(programme_url) for programme_url in re.findall(
937 r'<div[^>]+typeof="Clip"[^>]+resource="([^"]+)"', webpage)]
938
939 return self.playlist_result(entries, playlist_id, title, description)