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.

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