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.

937 lines
39 KiB

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