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.

976 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. 'vcodec': 'none',
  315. })
  316. formats.extend(conn_formats)
  317. return formats
  318. def _get_subtitles(self, media, programme_id):
  319. subtitles = {}
  320. for connection in self._extract_connections(media):
  321. captions = self._download_xml(connection.get('href'), programme_id, 'Downloading captions')
  322. lang = captions.get('{http://www.w3.org/XML/1998/namespace}lang', 'en')
  323. subtitles[lang] = [
  324. {
  325. 'url': connection.get('href'),
  326. 'ext': 'ttml',
  327. },
  328. ]
  329. return subtitles
  330. def _raise_extractor_error(self, media_selection_error):
  331. raise ExtractorError(
  332. '%s returned error: %s' % (self.IE_NAME, media_selection_error.id),
  333. expected=True)
  334. def _download_media_selector(self, programme_id):
  335. last_exception = None
  336. for mediaselector_url in self._MEDIASELECTOR_URLS:
  337. try:
  338. return self._download_media_selector_url(
  339. mediaselector_url % programme_id, programme_id)
  340. except BBCCoUkIE.MediaSelectionError as e:
  341. if e.id in ('notukerror', 'geolocation', 'selectionunavailable'):
  342. last_exception = e
  343. continue
  344. self._raise_extractor_error(e)
  345. self._raise_extractor_error(last_exception)
  346. def _download_media_selector_url(self, url, programme_id=None):
  347. try:
  348. media_selection = self._download_xml(
  349. url, programme_id, 'Downloading media selection XML')
  350. except ExtractorError as ee:
  351. if isinstance(ee.cause, compat_HTTPError) and ee.cause.code in (403, 404):
  352. media_selection = compat_etree_fromstring(ee.cause.read().decode('utf-8'))
  353. else:
  354. raise
  355. return self._process_media_selector(media_selection, programme_id)
  356. def _process_media_selector(self, media_selection, programme_id):
  357. formats = []
  358. subtitles = None
  359. for media in self._extract_medias(media_selection):
  360. kind = media.get('kind')
  361. if kind == 'audio':
  362. formats.extend(self._extract_audio(media, programme_id))
  363. elif kind == 'video':
  364. formats.extend(self._extract_video(media, programme_id))
  365. elif kind == 'captions':
  366. subtitles = self.extract_subtitles(media, programme_id)
  367. return formats, subtitles
  368. def _download_playlist(self, playlist_id):
  369. try:
  370. playlist = self._download_json(
  371. 'http://www.bbc.co.uk/programmes/%s/playlist.json' % playlist_id,
  372. playlist_id, 'Downloading playlist JSON')
  373. version = playlist.get('defaultAvailableVersion')
  374. if version:
  375. smp_config = version['smpConfig']
  376. title = smp_config['title']
  377. description = smp_config['summary']
  378. for item in smp_config['items']:
  379. kind = item['kind']
  380. if kind != 'programme' and kind != 'radioProgramme':
  381. continue
  382. programme_id = item.get('vpid')
  383. duration = int_or_none(item.get('duration'))
  384. formats, subtitles = self._download_media_selector(programme_id)
  385. return programme_id, title, description, duration, formats, subtitles
  386. except ExtractorError as ee:
  387. if not (isinstance(ee.cause, compat_HTTPError) and ee.cause.code == 404):
  388. raise
  389. # fallback to legacy playlist
  390. return self._process_legacy_playlist(playlist_id)
  391. def _process_legacy_playlist_url(self, url, display_id):
  392. playlist = self._download_legacy_playlist_url(url, display_id)
  393. return self._extract_from_legacy_playlist(playlist, display_id)
  394. def _process_legacy_playlist(self, playlist_id):
  395. return self._process_legacy_playlist_url(
  396. 'http://www.bbc.co.uk/iplayer/playlist/%s' % playlist_id, playlist_id)
  397. def _download_legacy_playlist_url(self, url, playlist_id=None):
  398. return self._download_xml(
  399. url, playlist_id, 'Downloading legacy playlist XML')
  400. def _extract_from_legacy_playlist(self, playlist, playlist_id):
  401. no_items = playlist.find('./{%s}noItems' % self._EMP_PLAYLIST_NS)
  402. if no_items is not None:
  403. reason = no_items.get('reason')
  404. if reason == 'preAvailability':
  405. msg = 'Episode %s is not yet available' % playlist_id
  406. elif reason == 'postAvailability':
  407. msg = 'Episode %s is no longer available' % playlist_id
  408. elif reason == 'noMedia':
  409. msg = 'Episode %s is not currently available' % playlist_id
  410. else:
  411. msg = 'Episode %s is not available: %s' % (playlist_id, reason)
  412. raise ExtractorError(msg, expected=True)
  413. for item in self._extract_items(playlist):
  414. kind = item.get('kind')
  415. if kind != 'programme' and kind != 'radioProgramme':
  416. continue
  417. title = playlist.find('./{%s}title' % self._EMP_PLAYLIST_NS).text
  418. description_el = playlist.find('./{%s}summary' % self._EMP_PLAYLIST_NS)
  419. description = description_el.text if description_el is not None else None
  420. def get_programme_id(item):
  421. def get_from_attributes(item):
  422. for p in('identifier', 'group'):
  423. value = item.get(p)
  424. if value and re.match(r'^[pb][\da-z]{7}$', value):
  425. return value
  426. get_from_attributes(item)
  427. mediator = item.find('./{%s}mediator' % self._EMP_PLAYLIST_NS)
  428. if mediator is not None:
  429. return get_from_attributes(mediator)
  430. programme_id = get_programme_id(item)
  431. duration = int_or_none(item.get('duration'))
  432. if programme_id:
  433. formats, subtitles = self._download_media_selector(programme_id)
  434. else:
  435. formats, subtitles = self._process_media_selector(item, playlist_id)
  436. programme_id = playlist_id
  437. return programme_id, title, description, duration, formats, subtitles
  438. def _real_extract(self, url):
  439. group_id = self._match_id(url)
  440. webpage = self._download_webpage(url, group_id, 'Downloading video page')
  441. programme_id = None
  442. duration = None
  443. tviplayer = self._search_regex(
  444. r'mediator\.bind\(({.+?})\s*,\s*document\.getElementById',
  445. webpage, 'player', default=None)
  446. if tviplayer:
  447. player = self._parse_json(tviplayer, group_id).get('player', {})
  448. duration = int_or_none(player.get('duration'))
  449. programme_id = player.get('vpid')
  450. if not programme_id:
  451. programme_id = self._search_regex(
  452. r'"vpid"\s*:\s*"(%s)"' % self._ID_REGEX, webpage, 'vpid', fatal=False, default=None)
  453. if programme_id:
  454. formats, subtitles = self._download_media_selector(programme_id)
  455. title = self._og_search_title(webpage, default=None) or self._html_search_regex(
  456. (r'<h2[^>]+id="parent-title"[^>]*>(.+?)</h2>',
  457. r'<div[^>]+class="info"[^>]*>\s*<h1>(.+?)</h1>'), webpage, 'title')
  458. description = self._search_regex(
  459. (r'<p class="[^"]*medium-description[^"]*">([^<]+)</p>',
  460. r'<div[^>]+class="info_+synopsis"[^>]*>([^<]+)</div>'),
  461. webpage, 'description', default=None)
  462. if not description:
  463. description = self._html_search_meta('description', webpage)
  464. else:
  465. programme_id, title, description, duration, formats, subtitles = self._download_playlist(group_id)
  466. self._sort_formats(formats)
  467. return {
  468. 'id': programme_id,
  469. 'title': title,
  470. 'description': description,
  471. 'thumbnail': self._og_search_thumbnail(webpage, default=None),
  472. 'duration': duration,
  473. 'formats': formats,
  474. 'subtitles': subtitles,
  475. }
  476. class BBCIE(BBCCoUkIE):
  477. IE_NAME = 'bbc'
  478. IE_DESC = 'BBC'
  479. _VALID_URL = r'https?://(?:www\.)?bbc\.(?:com|co\.uk)/(?:[^/]+/)+(?P<id>[^/#?]+)'
  480. _MEDIASELECTOR_URLS = [
  481. # Provides HQ HLS streams but fails with geolocation in some cases when it's
  482. # even not geo restricted at all
  483. 'http://open.live.bbc.co.uk/mediaselector/5/select/version/2.0/mediaset/iptv-all/vpid/%s',
  484. # Provides more formats, namely direct mp4 links, but fails on some videos with
  485. # notukerror for non UK (?) users (e.g.
  486. # http://www.bbc.com/travel/story/20150625-sri-lankas-spicy-secret)
  487. 'http://open.live.bbc.co.uk/mediaselector/4/mtis/stream/%s',
  488. # Provides fewer formats, but works everywhere for everybody (hopefully)
  489. 'http://open.live.bbc.co.uk/mediaselector/5/select/version/2.0/mediaset/journalism-pc/vpid/%s',
  490. ]
  491. _TESTS = [{
  492. # article with multiple videos embedded with data-playable containing vpids
  493. 'url': 'http://www.bbc.com/news/world-europe-32668511',
  494. 'info_dict': {
  495. 'id': 'world-europe-32668511',
  496. 'title': 'Russia stages massive WW2 parade despite Western boycott',
  497. 'description': 'md5:00ff61976f6081841f759a08bf78cc9c',
  498. },
  499. 'playlist_count': 2,
  500. }, {
  501. # article with multiple videos embedded with data-playable (more videos)
  502. 'url': 'http://www.bbc.com/news/business-28299555',
  503. 'info_dict': {
  504. 'id': 'business-28299555',
  505. 'title': 'Farnborough Airshow: Video highlights',
  506. 'description': 'BBC reports and video highlights at the Farnborough Airshow.',
  507. },
  508. 'playlist_count': 9,
  509. 'skip': 'Save time',
  510. }, {
  511. # article with multiple videos embedded with `new SMP()`
  512. # broken
  513. 'url': 'http://www.bbc.co.uk/blogs/adamcurtis/entries/3662a707-0af9-3149-963f-47bea720b460',
  514. 'info_dict': {
  515. 'id': '3662a707-0af9-3149-963f-47bea720b460',
  516. 'title': 'BUGGER',
  517. },
  518. 'playlist_count': 18,
  519. }, {
  520. # single video embedded with data-playable containing vpid
  521. 'url': 'http://www.bbc.com/news/world-europe-32041533',
  522. 'info_dict': {
  523. 'id': 'p02mprgb',
  524. 'ext': 'mp4',
  525. 'title': 'Aerial footage showed the site of the crash in the Alps - courtesy BFM TV',
  526. 'description': 'md5:2868290467291b37feda7863f7a83f54',
  527. 'duration': 47,
  528. 'timestamp': 1427219242,
  529. 'upload_date': '20150324',
  530. },
  531. 'params': {
  532. # rtmp download
  533. 'skip_download': True,
  534. }
  535. }, {
  536. # article with single video embedded with data-playable containing XML playlist
  537. # with direct video links as progressiveDownloadUrl (for now these are extracted)
  538. # and playlist with f4m and m3u8 as streamingUrl
  539. 'url': 'http://www.bbc.com/turkce/haberler/2015/06/150615_telabyad_kentin_cogu',
  540. 'info_dict': {
  541. 'id': '150615_telabyad_kentin_cogu',
  542. 'ext': 'mp4',
  543. 'title': "YPG: Tel Abyad'ın tamamı kontrolümüzde",
  544. 'timestamp': 1434397334,
  545. 'upload_date': '20150615',
  546. },
  547. 'params': {
  548. 'skip_download': True,
  549. }
  550. }, {
  551. # single video embedded with data-playable containing XML playlists (regional section)
  552. 'url': 'http://www.bbc.com/mundo/video_fotos/2015/06/150619_video_honduras_militares_hospitales_corrupcion_aw',
  553. 'info_dict': {
  554. 'id': '150619_video_honduras_militares_hospitales_corrupcion_aw',
  555. 'ext': 'mp4',
  556. 'title': 'Honduras militariza sus hospitales por nuevo escándalo de corrupción',
  557. 'timestamp': 1434713142,
  558. 'upload_date': '20150619',
  559. },
  560. 'params': {
  561. 'skip_download': True,
  562. }
  563. }, {
  564. # single video from video playlist embedded with vxp-playlist-data JSON
  565. 'url': 'http://www.bbc.com/news/video_and_audio/must_see/33376376',
  566. 'info_dict': {
  567. 'id': 'p02w6qjc',
  568. 'ext': 'mp4',
  569. 'title': '''Judge Mindy Glazer: "I'm sorry to see you here... I always wondered what happened to you"''',
  570. 'duration': 56,
  571. 'description': '''Judge Mindy Glazer: "I'm sorry to see you here... I always wondered what happened to you"''',
  572. },
  573. 'params': {
  574. 'skip_download': True,
  575. }
  576. }, {
  577. # single video story with digitalData
  578. 'url': 'http://www.bbc.com/travel/story/20150625-sri-lankas-spicy-secret',
  579. 'info_dict': {
  580. 'id': 'p02q6gc4',
  581. 'ext': 'flv',
  582. 'title': 'Sri Lanka’s spicy secret',
  583. 'description': 'As a new train line to Jaffna opens up the country’s north, travellers can experience a truly distinct slice of Tamil culture.',
  584. 'timestamp': 1437674293,
  585. 'upload_date': '20150723',
  586. },
  587. 'params': {
  588. # rtmp download
  589. 'skip_download': True,
  590. }
  591. }, {
  592. # single video story without digitalData
  593. 'url': 'http://www.bbc.com/autos/story/20130513-hyundais-rock-star',
  594. 'info_dict': {
  595. 'id': 'p018zqqg',
  596. 'ext': 'mp4',
  597. 'title': 'Hyundai Santa Fe Sport: Rock star',
  598. 'description': 'md5:b042a26142c4154a6e472933cf20793d',
  599. 'timestamp': 1415867444,
  600. 'upload_date': '20141113',
  601. },
  602. 'params': {
  603. # rtmp download
  604. 'skip_download': True,
  605. }
  606. }, {
  607. # single video with playlist.sxml URL in playlist param
  608. 'url': 'http://www.bbc.com/sport/0/football/33653409',
  609. 'info_dict': {
  610. 'id': 'p02xycnp',
  611. 'ext': 'mp4',
  612. 'title': 'Transfers: Cristiano Ronaldo to Man Utd, Arsenal to spend?',
  613. 'description': 'BBC Sport\'s David Ornstein has the latest transfer gossip, including rumours of a Manchester United return for Cristiano Ronaldo.',
  614. 'duration': 140,
  615. },
  616. 'params': {
  617. # rtmp download
  618. 'skip_download': True,
  619. }
  620. }, {
  621. # article with multiple videos embedded with playlist.sxml in playlist param
  622. 'url': 'http://www.bbc.com/sport/0/football/34475836',
  623. 'info_dict': {
  624. 'id': '34475836',
  625. 'title': 'Jurgen Klopp: Furious football from a witty and winning coach',
  626. },
  627. 'playlist_count': 3,
  628. }, {
  629. # school report article with single video
  630. 'url': 'http://www.bbc.co.uk/schoolreport/35744779',
  631. 'info_dict': {
  632. 'id': '35744779',
  633. 'title': 'School which breaks down barriers in Jerusalem',
  634. },
  635. 'playlist_count': 1,
  636. }, {
  637. # single video with playlist URL from weather section
  638. 'url': 'http://www.bbc.com/weather/features/33601775',
  639. 'only_matching': True,
  640. }, {
  641. # custom redirection to www.bbc.com
  642. 'url': 'http://www.bbc.co.uk/news/science-environment-33661876',
  643. 'only_matching': True,
  644. }, {
  645. # single video article embedded with data-media-vpid
  646. 'url': 'http://www.bbc.co.uk/sport/rowing/35908187',
  647. 'only_matching': True,
  648. }]
  649. @classmethod
  650. def suitable(cls, url):
  651. return False if BBCCoUkIE.suitable(url) or BBCCoUkArticleIE.suitable(url) else super(BBCIE, cls).suitable(url)
  652. def _extract_from_media_meta(self, media_meta, video_id):
  653. # Direct links to media in media metadata (e.g.
  654. # http://www.bbc.com/turkce/haberler/2015/06/150615_telabyad_kentin_cogu)
  655. # TODO: there are also f4m and m3u8 streams incorporated in playlist.sxml
  656. source_files = media_meta.get('sourceFiles')
  657. if source_files:
  658. return [{
  659. 'url': f['url'],
  660. 'format_id': format_id,
  661. 'ext': f.get('encoding'),
  662. 'tbr': float_or_none(f.get('bitrate'), 1000),
  663. 'filesize': int_or_none(f.get('filesize')),
  664. } for format_id, f in source_files.items() if f.get('url')], []
  665. programme_id = media_meta.get('externalId')
  666. if programme_id:
  667. return self._download_media_selector(programme_id)
  668. # Process playlist.sxml as legacy playlist
  669. href = media_meta.get('href')
  670. if href:
  671. playlist = self._download_legacy_playlist_url(href)
  672. _, _, _, _, formats, subtitles = self._extract_from_legacy_playlist(playlist, video_id)
  673. return formats, subtitles
  674. return [], []
  675. def _extract_from_playlist_sxml(self, url, playlist_id, timestamp):
  676. programme_id, title, description, duration, formats, subtitles = \
  677. self._process_legacy_playlist_url(url, playlist_id)
  678. self._sort_formats(formats)
  679. return {
  680. 'id': programme_id,
  681. 'title': title,
  682. 'description': description,
  683. 'duration': duration,
  684. 'timestamp': timestamp,
  685. 'formats': formats,
  686. 'subtitles': subtitles,
  687. }
  688. def _real_extract(self, url):
  689. playlist_id = self._match_id(url)
  690. webpage = self._download_webpage(url, playlist_id)
  691. json_ld_info = self._search_json_ld(webpage, playlist_id, default=None)
  692. timestamp = json_ld_info.get('timestamp')
  693. playlist_title = json_ld_info.get('title')
  694. if not playlist_title:
  695. playlist_title = self._og_search_title(
  696. webpage, default=None) or self._html_search_regex(
  697. r'<title>(.+?)</title>', webpage, 'playlist title', default=None)
  698. if playlist_title:
  699. playlist_title = re.sub(r'(.+)\s*-\s*BBC.*?$', r'\1', playlist_title).strip()
  700. playlist_description = json_ld_info.get(
  701. 'description') or self._og_search_description(webpage, default=None)
  702. if not timestamp:
  703. timestamp = parse_iso8601(self._search_regex(
  704. [r'<meta[^>]+property="article:published_time"[^>]+content="([^"]+)"',
  705. r'itemprop="datePublished"[^>]+datetime="([^"]+)"',
  706. r'"datePublished":\s*"([^"]+)'],
  707. webpage, 'date', default=None))
  708. entries = []
  709. # article with multiple videos embedded with playlist.sxml (e.g.
  710. # http://www.bbc.com/sport/0/football/34475836)
  711. playlists = re.findall(r'<param[^>]+name="playlist"[^>]+value="([^"]+)"', webpage)
  712. playlists.extend(re.findall(r'data-media-id="([^"]+/playlist\.sxml)"', webpage))
  713. if playlists:
  714. entries = [
  715. self._extract_from_playlist_sxml(playlist_url, playlist_id, timestamp)
  716. for playlist_url in playlists]
  717. # news article with multiple videos embedded with data-playable
  718. data_playables = re.findall(r'data-playable=(["\'])({.+?})\1', webpage)
  719. if data_playables:
  720. for _, data_playable_json in data_playables:
  721. data_playable = self._parse_json(
  722. unescapeHTML(data_playable_json), playlist_id, fatal=False)
  723. if not data_playable:
  724. continue
  725. settings = data_playable.get('settings', {})
  726. if settings:
  727. # data-playable with video vpid in settings.playlistObject.items (e.g.
  728. # http://www.bbc.com/news/world-us-canada-34473351)
  729. playlist_object = settings.get('playlistObject', {})
  730. if playlist_object:
  731. items = playlist_object.get('items')
  732. if items and isinstance(items, list):
  733. title = playlist_object['title']
  734. description = playlist_object.get('summary')
  735. duration = int_or_none(items[0].get('duration'))
  736. programme_id = items[0].get('vpid')
  737. formats, subtitles = self._download_media_selector(programme_id)
  738. self._sort_formats(formats)
  739. entries.append({
  740. 'id': programme_id,
  741. 'title': title,
  742. 'description': description,
  743. 'timestamp': timestamp,
  744. 'duration': duration,
  745. 'formats': formats,
  746. 'subtitles': subtitles,
  747. })
  748. else:
  749. # data-playable without vpid but with a playlist.sxml URLs
  750. # in otherSettings.playlist (e.g.
  751. # http://www.bbc.com/turkce/multimedya/2015/10/151010_vid_ankara_patlama_ani)
  752. playlist = data_playable.get('otherSettings', {}).get('playlist', {})
  753. if playlist:
  754. entries.append(self._extract_from_playlist_sxml(
  755. playlist.get('progressiveDownloadUrl'), playlist_id, timestamp))
  756. if entries:
  757. return self.playlist_result(entries, playlist_id, playlist_title, playlist_description)
  758. # single video story (e.g. http://www.bbc.com/travel/story/20150625-sri-lankas-spicy-secret)
  759. programme_id = self._search_regex(
  760. [r'data-(?:video-player|media)-vpid="(%s)"' % self._ID_REGEX,
  761. r'<param[^>]+name="externalIdentifier"[^>]+value="(%s)"' % self._ID_REGEX,
  762. r'videoId\s*:\s*["\'](%s)["\']' % self._ID_REGEX],
  763. webpage, 'vpid', default=None)
  764. if programme_id:
  765. formats, subtitles = self._download_media_selector(programme_id)
  766. self._sort_formats(formats)
  767. # digitalData may be missing (e.g. http://www.bbc.com/autos/story/20130513-hyundais-rock-star)
  768. digital_data = self._parse_json(
  769. self._search_regex(
  770. r'var\s+digitalData\s*=\s*({.+?});?\n', webpage, 'digital data', default='{}'),
  771. programme_id, fatal=False)
  772. page_info = digital_data.get('page', {}).get('pageInfo', {})
  773. title = page_info.get('pageName') or self._og_search_title(webpage)
  774. description = page_info.get('description') or self._og_search_description(webpage)
  775. timestamp = parse_iso8601(page_info.get('publicationDate')) or timestamp
  776. return {
  777. 'id': programme_id,
  778. 'title': title,
  779. 'description': description,
  780. 'timestamp': timestamp,
  781. 'formats': formats,
  782. 'subtitles': subtitles,
  783. }
  784. def extract_all(pattern):
  785. return list(filter(None, map(
  786. lambda s: self._parse_json(s, playlist_id, fatal=False),
  787. re.findall(pattern, webpage))))
  788. # Multiple video article (e.g.
  789. # http://www.bbc.co.uk/blogs/adamcurtis/entries/3662a707-0af9-3149-963f-47bea720b460)
  790. EMBED_URL = r'https?://(?:www\.)?bbc\.co\.uk/(?:[^/]+/)+%s(?:\b[^"]+)?' % self._ID_REGEX
  791. entries = []
  792. for match in extract_all(r'new\s+SMP\(({.+?})\)'):
  793. embed_url = match.get('playerSettings', {}).get('externalEmbedUrl')
  794. if embed_url and re.match(EMBED_URL, embed_url):
  795. entries.append(embed_url)
  796. entries.extend(re.findall(
  797. r'setPlaylist\("(%s)"\)' % EMBED_URL, webpage))
  798. if entries:
  799. return self.playlist_result(
  800. [self.url_result(entry, 'BBCCoUk') for entry in entries],
  801. playlist_id, playlist_title, playlist_description)
  802. # Multiple video article (e.g. http://www.bbc.com/news/world-europe-32668511)
  803. medias = extract_all(r"data-media-meta='({[^']+})'")
  804. if not medias:
  805. # Single video article (e.g. http://www.bbc.com/news/video_and_audio/international)
  806. media_asset = self._search_regex(
  807. r'mediaAssetPage\.init\(\s*({.+?}), "/',
  808. webpage, 'media asset', default=None)
  809. if media_asset:
  810. media_asset_page = self._parse_json(media_asset, playlist_id, fatal=False)
  811. medias = []
  812. for video in media_asset_page.get('videos', {}).values():
  813. medias.extend(video.values())
  814. if not medias:
  815. # Multiple video playlist with single `now playing` entry (e.g.
  816. # http://www.bbc.com/news/video_and_audio/must_see/33767813)
  817. vxp_playlist = self._parse_json(
  818. self._search_regex(
  819. r'<script[^>]+class="vxp-playlist-data"[^>]+type="application/json"[^>]*>([^<]+)</script>',
  820. webpage, 'playlist data'),
  821. playlist_id)
  822. playlist_medias = []
  823. for item in vxp_playlist:
  824. media = item.get('media')
  825. if not media:
  826. continue
  827. playlist_medias.append(media)
  828. # Download single video if found media with asset id matching the video id from URL
  829. if item.get('advert', {}).get('assetId') == playlist_id:
  830. medias = [media]
  831. break
  832. # Fallback to the whole playlist
  833. if not medias:
  834. medias = playlist_medias
  835. entries = []
  836. for num, media_meta in enumerate(medias, start=1):
  837. formats, subtitles = self._extract_from_media_meta(media_meta, playlist_id)
  838. if not formats:
  839. continue
  840. self._sort_formats(formats)
  841. video_id = media_meta.get('externalId')
  842. if not video_id:
  843. video_id = playlist_id if len(medias) == 1 else '%s-%s' % (playlist_id, num)
  844. title = media_meta.get('caption')
  845. if not title:
  846. title = playlist_title if len(medias) == 1 else '%s - Video %s' % (playlist_title, num)
  847. duration = int_or_none(media_meta.get('durationInSeconds')) or parse_duration(media_meta.get('duration'))
  848. images = []
  849. for image in media_meta.get('images', {}).values():
  850. images.extend(image.values())
  851. if 'image' in media_meta:
  852. images.append(media_meta['image'])
  853. thumbnails = [{
  854. 'url': image.get('href'),
  855. 'width': int_or_none(image.get('width')),
  856. 'height': int_or_none(image.get('height')),
  857. } for image in images]
  858. entries.append({
  859. 'id': video_id,
  860. 'title': title,
  861. 'thumbnails': thumbnails,
  862. 'duration': duration,
  863. 'timestamp': timestamp,
  864. 'formats': formats,
  865. 'subtitles': subtitles,
  866. })
  867. return self.playlist_result(entries, playlist_id, playlist_title, playlist_description)
  868. class BBCCoUkArticleIE(InfoExtractor):
  869. _VALID_URL = r'https?://www.bbc.co.uk/programmes/articles/(?P<id>[a-zA-Z0-9]+)'
  870. IE_NAME = 'bbc.co.uk:article'
  871. IE_DESC = 'BBC articles'
  872. _TEST = {
  873. 'url': 'http://www.bbc.co.uk/programmes/articles/3jNQLTMrPlYGTBn0WV6M2MS/not-your-typical-role-model-ada-lovelace-the-19th-century-programmer',
  874. 'info_dict': {
  875. 'id': '3jNQLTMrPlYGTBn0WV6M2MS',
  876. 'title': 'Calculating Ada: The Countess of Computing - Not your typical role model: Ada Lovelace the 19th century programmer - BBC Four',
  877. 'description': 'Hannah Fry reveals some of her surprising discoveries about Ada Lovelace during filming.',
  878. },
  879. 'playlist_count': 4,
  880. 'add_ie': ['BBCCoUk'],
  881. }
  882. def _real_extract(self, url):
  883. playlist_id = self._match_id(url)
  884. webpage = self._download_webpage(url, playlist_id)
  885. title = self._og_search_title(webpage)
  886. description = self._og_search_description(webpage).strip()
  887. entries = [self.url_result(programme_url) for programme_url in re.findall(
  888. r'<div[^>]+typeof="Clip"[^>]+resource="([^"]+)"', webpage)]
  889. return self.playlist_result(entries, playlist_id, title, description)