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.

935 lines
39 KiB

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