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.

977 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. 'description': 'Fast-paced football, wit, wisdom and a ready smile - why Liverpool fans should come to love new boss Jurgen Klopp.',
  627. },
  628. 'playlist_count': 3,
  629. }, {
  630. # school report article with single video
  631. 'url': 'http://www.bbc.co.uk/schoolreport/35744779',
  632. 'info_dict': {
  633. 'id': '35744779',
  634. 'title': 'School which breaks down barriers in Jerusalem',
  635. },
  636. 'playlist_count': 1,
  637. }, {
  638. # single video with playlist URL from weather section
  639. 'url': 'http://www.bbc.com/weather/features/33601775',
  640. 'only_matching': True,
  641. }, {
  642. # custom redirection to www.bbc.com
  643. 'url': 'http://www.bbc.co.uk/news/science-environment-33661876',
  644. 'only_matching': True,
  645. }, {
  646. # single video article embedded with data-media-vpid
  647. 'url': 'http://www.bbc.co.uk/sport/rowing/35908187',
  648. 'only_matching': True,
  649. }]
  650. @classmethod
  651. def suitable(cls, url):
  652. return False if BBCCoUkIE.suitable(url) or BBCCoUkArticleIE.suitable(url) else super(BBCIE, cls).suitable(url)
  653. def _extract_from_media_meta(self, media_meta, video_id):
  654. # Direct links to media in media metadata (e.g.
  655. # http://www.bbc.com/turkce/haberler/2015/06/150615_telabyad_kentin_cogu)
  656. # TODO: there are also f4m and m3u8 streams incorporated in playlist.sxml
  657. source_files = media_meta.get('sourceFiles')
  658. if source_files:
  659. return [{
  660. 'url': f['url'],
  661. 'format_id': format_id,
  662. 'ext': f.get('encoding'),
  663. 'tbr': float_or_none(f.get('bitrate'), 1000),
  664. 'filesize': int_or_none(f.get('filesize')),
  665. } for format_id, f in source_files.items() if f.get('url')], []
  666. programme_id = media_meta.get('externalId')
  667. if programme_id:
  668. return self._download_media_selector(programme_id)
  669. # Process playlist.sxml as legacy playlist
  670. href = media_meta.get('href')
  671. if href:
  672. playlist = self._download_legacy_playlist_url(href)
  673. _, _, _, _, formats, subtitles = self._extract_from_legacy_playlist(playlist, video_id)
  674. return formats, subtitles
  675. return [], []
  676. def _extract_from_playlist_sxml(self, url, playlist_id, timestamp):
  677. programme_id, title, description, duration, formats, subtitles = \
  678. self._process_legacy_playlist_url(url, playlist_id)
  679. self._sort_formats(formats)
  680. return {
  681. 'id': programme_id,
  682. 'title': title,
  683. 'description': description,
  684. 'duration': duration,
  685. 'timestamp': timestamp,
  686. 'formats': formats,
  687. 'subtitles': subtitles,
  688. }
  689. def _real_extract(self, url):
  690. playlist_id = self._match_id(url)
  691. webpage = self._download_webpage(url, playlist_id)
  692. json_ld_info = self._search_json_ld(webpage, playlist_id, default=None)
  693. timestamp = json_ld_info.get('timestamp')
  694. playlist_title = json_ld_info.get('title')
  695. if not playlist_title:
  696. playlist_title = self._og_search_title(
  697. webpage, default=None) or self._html_search_regex(
  698. r'<title>(.+?)</title>', webpage, 'playlist title', default=None)
  699. if playlist_title:
  700. playlist_title = re.sub(r'(.+)\s*-\s*BBC.*?$', r'\1', playlist_title).strip()
  701. playlist_description = json_ld_info.get(
  702. 'description') or self._og_search_description(webpage, default=None)
  703. if not timestamp:
  704. timestamp = parse_iso8601(self._search_regex(
  705. [r'<meta[^>]+property="article:published_time"[^>]+content="([^"]+)"',
  706. r'itemprop="datePublished"[^>]+datetime="([^"]+)"',
  707. r'"datePublished":\s*"([^"]+)'],
  708. webpage, 'date', default=None))
  709. entries = []
  710. # article with multiple videos embedded with playlist.sxml (e.g.
  711. # http://www.bbc.com/sport/0/football/34475836)
  712. playlists = re.findall(r'<param[^>]+name="playlist"[^>]+value="([^"]+)"', webpage)
  713. playlists.extend(re.findall(r'data-media-id="([^"]+/playlist\.sxml)"', webpage))
  714. if playlists:
  715. entries = [
  716. self._extract_from_playlist_sxml(playlist_url, playlist_id, timestamp)
  717. for playlist_url in playlists]
  718. # news article with multiple videos embedded with data-playable
  719. data_playables = re.findall(r'data-playable=(["\'])({.+?})\1', webpage)
  720. if data_playables:
  721. for _, data_playable_json in data_playables:
  722. data_playable = self._parse_json(
  723. unescapeHTML(data_playable_json), playlist_id, fatal=False)
  724. if not data_playable:
  725. continue
  726. settings = data_playable.get('settings', {})
  727. if settings:
  728. # data-playable with video vpid in settings.playlistObject.items (e.g.
  729. # http://www.bbc.com/news/world-us-canada-34473351)
  730. playlist_object = settings.get('playlistObject', {})
  731. if playlist_object:
  732. items = playlist_object.get('items')
  733. if items and isinstance(items, list):
  734. title = playlist_object['title']
  735. description = playlist_object.get('summary')
  736. duration = int_or_none(items[0].get('duration'))
  737. programme_id = items[0].get('vpid')
  738. formats, subtitles = self._download_media_selector(programme_id)
  739. self._sort_formats(formats)
  740. entries.append({
  741. 'id': programme_id,
  742. 'title': title,
  743. 'description': description,
  744. 'timestamp': timestamp,
  745. 'duration': duration,
  746. 'formats': formats,
  747. 'subtitles': subtitles,
  748. })
  749. else:
  750. # data-playable without vpid but with a playlist.sxml URLs
  751. # in otherSettings.playlist (e.g.
  752. # http://www.bbc.com/turkce/multimedya/2015/10/151010_vid_ankara_patlama_ani)
  753. playlist = data_playable.get('otherSettings', {}).get('playlist', {})
  754. if playlist:
  755. entries.append(self._extract_from_playlist_sxml(
  756. playlist.get('progressiveDownloadUrl'), playlist_id, timestamp))
  757. if entries:
  758. return self.playlist_result(entries, playlist_id, playlist_title, playlist_description)
  759. # single video story (e.g. http://www.bbc.com/travel/story/20150625-sri-lankas-spicy-secret)
  760. programme_id = self._search_regex(
  761. [r'data-(?:video-player|media)-vpid="(%s)"' % self._ID_REGEX,
  762. r'<param[^>]+name="externalIdentifier"[^>]+value="(%s)"' % self._ID_REGEX,
  763. r'videoId\s*:\s*["\'](%s)["\']' % self._ID_REGEX],
  764. webpage, 'vpid', default=None)
  765. if programme_id:
  766. formats, subtitles = self._download_media_selector(programme_id)
  767. self._sort_formats(formats)
  768. # digitalData may be missing (e.g. http://www.bbc.com/autos/story/20130513-hyundais-rock-star)
  769. digital_data = self._parse_json(
  770. self._search_regex(
  771. r'var\s+digitalData\s*=\s*({.+?});?\n', webpage, 'digital data', default='{}'),
  772. programme_id, fatal=False)
  773. page_info = digital_data.get('page', {}).get('pageInfo', {})
  774. title = page_info.get('pageName') or self._og_search_title(webpage)
  775. description = page_info.get('description') or self._og_search_description(webpage)
  776. timestamp = parse_iso8601(page_info.get('publicationDate')) or timestamp
  777. return {
  778. 'id': programme_id,
  779. 'title': title,
  780. 'description': description,
  781. 'timestamp': timestamp,
  782. 'formats': formats,
  783. 'subtitles': subtitles,
  784. }
  785. def extract_all(pattern):
  786. return list(filter(None, map(
  787. lambda s: self._parse_json(s, playlist_id, fatal=False),
  788. re.findall(pattern, webpage))))
  789. # Multiple video article (e.g.
  790. # http://www.bbc.co.uk/blogs/adamcurtis/entries/3662a707-0af9-3149-963f-47bea720b460)
  791. EMBED_URL = r'https?://(?:www\.)?bbc\.co\.uk/(?:[^/]+/)+%s(?:\b[^"]+)?' % self._ID_REGEX
  792. entries = []
  793. for match in extract_all(r'new\s+SMP\(({.+?})\)'):
  794. embed_url = match.get('playerSettings', {}).get('externalEmbedUrl')
  795. if embed_url and re.match(EMBED_URL, embed_url):
  796. entries.append(embed_url)
  797. entries.extend(re.findall(
  798. r'setPlaylist\("(%s)"\)' % EMBED_URL, webpage))
  799. if entries:
  800. return self.playlist_result(
  801. [self.url_result(entry, 'BBCCoUk') for entry in entries],
  802. playlist_id, playlist_title, playlist_description)
  803. # Multiple video article (e.g. http://www.bbc.com/news/world-europe-32668511)
  804. medias = extract_all(r"data-media-meta='({[^']+})'")
  805. if not medias:
  806. # Single video article (e.g. http://www.bbc.com/news/video_and_audio/international)
  807. media_asset = self._search_regex(
  808. r'mediaAssetPage\.init\(\s*({.+?}), "/',
  809. webpage, 'media asset', default=None)
  810. if media_asset:
  811. media_asset_page = self._parse_json(media_asset, playlist_id, fatal=False)
  812. medias = []
  813. for video in media_asset_page.get('videos', {}).values():
  814. medias.extend(video.values())
  815. if not medias:
  816. # Multiple video playlist with single `now playing` entry (e.g.
  817. # http://www.bbc.com/news/video_and_audio/must_see/33767813)
  818. vxp_playlist = self._parse_json(
  819. self._search_regex(
  820. r'<script[^>]+class="vxp-playlist-data"[^>]+type="application/json"[^>]*>([^<]+)</script>',
  821. webpage, 'playlist data'),
  822. playlist_id)
  823. playlist_medias = []
  824. for item in vxp_playlist:
  825. media = item.get('media')
  826. if not media:
  827. continue
  828. playlist_medias.append(media)
  829. # Download single video if found media with asset id matching the video id from URL
  830. if item.get('advert', {}).get('assetId') == playlist_id:
  831. medias = [media]
  832. break
  833. # Fallback to the whole playlist
  834. if not medias:
  835. medias = playlist_medias
  836. entries = []
  837. for num, media_meta in enumerate(medias, start=1):
  838. formats, subtitles = self._extract_from_media_meta(media_meta, playlist_id)
  839. if not formats:
  840. continue
  841. self._sort_formats(formats)
  842. video_id = media_meta.get('externalId')
  843. if not video_id:
  844. video_id = playlist_id if len(medias) == 1 else '%s-%s' % (playlist_id, num)
  845. title = media_meta.get('caption')
  846. if not title:
  847. title = playlist_title if len(medias) == 1 else '%s - Video %s' % (playlist_title, num)
  848. duration = int_or_none(media_meta.get('durationInSeconds')) or parse_duration(media_meta.get('duration'))
  849. images = []
  850. for image in media_meta.get('images', {}).values():
  851. images.extend(image.values())
  852. if 'image' in media_meta:
  853. images.append(media_meta['image'])
  854. thumbnails = [{
  855. 'url': image.get('href'),
  856. 'width': int_or_none(image.get('width')),
  857. 'height': int_or_none(image.get('height')),
  858. } for image in images]
  859. entries.append({
  860. 'id': video_id,
  861. 'title': title,
  862. 'thumbnails': thumbnails,
  863. 'duration': duration,
  864. 'timestamp': timestamp,
  865. 'formats': formats,
  866. 'subtitles': subtitles,
  867. })
  868. return self.playlist_result(entries, playlist_id, playlist_title, playlist_description)
  869. class BBCCoUkArticleIE(InfoExtractor):
  870. _VALID_URL = r'https?://www.bbc.co.uk/programmes/articles/(?P<id>[a-zA-Z0-9]+)'
  871. IE_NAME = 'bbc.co.uk:article'
  872. IE_DESC = 'BBC articles'
  873. _TEST = {
  874. 'url': 'http://www.bbc.co.uk/programmes/articles/3jNQLTMrPlYGTBn0WV6M2MS/not-your-typical-role-model-ada-lovelace-the-19th-century-programmer',
  875. 'info_dict': {
  876. 'id': '3jNQLTMrPlYGTBn0WV6M2MS',
  877. 'title': 'Calculating Ada: The Countess of Computing - Not your typical role model: Ada Lovelace the 19th century programmer - BBC Four',
  878. 'description': 'Hannah Fry reveals some of her surprising discoveries about Ada Lovelace during filming.',
  879. },
  880. 'playlist_count': 4,
  881. 'add_ie': ['BBCCoUk'],
  882. }
  883. def _real_extract(self, url):
  884. playlist_id = self._match_id(url)
  885. webpage = self._download_webpage(url, playlist_id)
  886. title = self._og_search_title(webpage)
  887. description = self._og_search_description(webpage).strip()
  888. entries = [self.url_result(programme_url) for programme_url in re.findall(
  889. r'<div[^>]+typeof="Clip"[^>]+resource="([^"]+)"', webpage)]
  890. return self.playlist_result(entries, playlist_id, title, description)