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.

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