You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

955 lines
40 KiB

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