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.

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