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