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.

961 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. remove_end,
  12. unescapeHTML,
  13. )
  14. from ..compat import (
  15. compat_etree_fromstring,
  16. compat_HTTPError,
  17. )
  18. class BBCCoUkIE(InfoExtractor):
  19. IE_NAME = 'bbc.co.uk'
  20. IE_DESC = 'BBC iPlayer'
  21. _ID_REGEX = r'[pb][\da-z]{7}'
  22. _VALID_URL = r'''(?x)
  23. https?://
  24. (?:www\.)?bbc\.co\.uk/
  25. (?:
  26. programmes/(?!articles/)|
  27. iplayer(?:/[^/]+)?/(?:episode/|playlist/)|
  28. music/clips[/#]|
  29. radio/player/
  30. )
  31. (?P<id>%s)
  32. ''' % _ID_REGEX
  33. _MEDIASELECTOR_URLS = [
  34. # Provides HQ HLS streams with even better quality that pc mediaset but fails
  35. # with geolocation in some cases when it's even not geo restricted at all (e.g.
  36. # http://www.bbc.co.uk/programmes/b06bp7lf). Also may fail with selectionunavailable.
  37. 'http://open.live.bbc.co.uk/mediaselector/5/select/version/2.0/mediaset/iptv-all/vpid/%s',
  38. 'http://open.live.bbc.co.uk/mediaselector/5/select/version/2.0/mediaset/pc/vpid/%s',
  39. ]
  40. _MEDIASELECTION_NS = 'http://bbc.co.uk/2008/mp/mediaselection'
  41. _EMP_PLAYLIST_NS = 'http://bbc.co.uk/2008/emp/playlist'
  42. _NAMESPACES = (
  43. _MEDIASELECTION_NS,
  44. _EMP_PLAYLIST_NS,
  45. )
  46. _TESTS = [
  47. {
  48. 'url': 'http://www.bbc.co.uk/programmes/b039g8p7',
  49. 'info_dict': {
  50. 'id': 'b039d07m',
  51. 'ext': 'flv',
  52. 'title': 'Leonard Cohen, Kaleidoscope - BBC Radio 4',
  53. 'description': 'The Canadian poet and songwriter reflects on his musical career.',
  54. },
  55. 'params': {
  56. # rtmp download
  57. 'skip_download': True,
  58. }
  59. },
  60. {
  61. 'url': 'http://www.bbc.co.uk/iplayer/episode/b00yng5w/The_Man_in_Black_Series_3_The_Printed_Name/',
  62. 'info_dict': {
  63. 'id': 'b00yng1d',
  64. 'ext': 'flv',
  65. 'title': 'The Man in Black: Series 3: The Printed Name',
  66. 'description': "Mark Gatiss introduces Nicholas Pierpan's chilling tale of a writer's devilish pact with a mysterious man. Stars Ewan Bailey.",
  67. 'duration': 1800,
  68. },
  69. 'params': {
  70. # rtmp download
  71. 'skip_download': True,
  72. },
  73. 'skip': 'Episode is no longer available on BBC iPlayer Radio',
  74. },
  75. {
  76. 'url': 'http://www.bbc.co.uk/iplayer/episode/b03vhd1f/The_Voice_UK_Series_3_Blind_Auditions_5/',
  77. 'info_dict': {
  78. 'id': 'b00yng1d',
  79. 'ext': 'flv',
  80. 'title': 'The Voice UK: Series 3: Blind Auditions 5',
  81. 'description': "Emma Willis and Marvin Humes present the fifth set of blind auditions in the singing competition, as the coaches continue to build their teams based on voice alone.",
  82. 'duration': 5100,
  83. },
  84. 'params': {
  85. # rtmp download
  86. 'skip_download': True,
  87. },
  88. 'skip': 'Currently BBC iPlayer TV programmes are available to play in the UK only',
  89. },
  90. {
  91. 'url': 'http://www.bbc.co.uk/iplayer/episode/p026c7jt/tomorrows-worlds-the-unearthly-history-of-science-fiction-2-invasion',
  92. 'info_dict': {
  93. 'id': 'b03k3pb7',
  94. 'ext': 'flv',
  95. 'title': "Tomorrow's Worlds: The Unearthly History of Science Fiction",
  96. 'description': '2. Invasion',
  97. 'duration': 3600,
  98. },
  99. 'params': {
  100. # rtmp download
  101. 'skip_download': True,
  102. },
  103. 'skip': 'Currently BBC iPlayer TV programmes are available to play in the UK only',
  104. }, {
  105. 'url': 'http://www.bbc.co.uk/programmes/b04v20dw',
  106. 'info_dict': {
  107. 'id': 'b04v209v',
  108. 'ext': 'flv',
  109. 'title': 'Pete Tong, The Essential New Tune Special',
  110. 'description': "Pete has a very special mix - all of 2014's Essential New Tunes!",
  111. 'duration': 10800,
  112. },
  113. 'params': {
  114. # rtmp download
  115. 'skip_download': True,
  116. },
  117. 'skip': 'Episode is no longer available on BBC iPlayer Radio',
  118. }, {
  119. 'url': 'http://www.bbc.co.uk/music/clips/p022h44b',
  120. 'note': 'Audio',
  121. 'info_dict': {
  122. 'id': 'p022h44j',
  123. 'ext': 'flv',
  124. 'title': 'BBC Proms Music Guides, Rachmaninov: Symphonic Dances',
  125. 'description': "In this Proms Music Guide, Andrew McGregor looks at Rachmaninov's Symphonic Dances.",
  126. 'duration': 227,
  127. },
  128. 'params': {
  129. # rtmp download
  130. 'skip_download': True,
  131. }
  132. }, {
  133. 'url': 'http://www.bbc.co.uk/music/clips/p025c0zz',
  134. 'note': 'Video',
  135. 'info_dict': {
  136. 'id': 'p025c103',
  137. 'ext': 'flv',
  138. 'title': 'Reading and Leeds Festival, 2014, Rae Morris - Closer (Live on BBC Three)',
  139. 'description': 'Rae Morris performs Closer for BBC Three at Reading 2014',
  140. 'duration': 226,
  141. },
  142. 'params': {
  143. # rtmp download
  144. 'skip_download': True,
  145. }
  146. }, {
  147. 'url': 'http://www.bbc.co.uk/iplayer/episode/b054fn09/ad/natural-world-20152016-2-super-powered-owls',
  148. 'info_dict': {
  149. 'id': 'p02n76xf',
  150. 'ext': 'flv',
  151. 'title': 'Natural World, 2015-2016: 2. Super Powered Owls',
  152. 'description': 'md5:e4db5c937d0e95a7c6b5e654d429183d',
  153. 'duration': 3540,
  154. },
  155. 'params': {
  156. # rtmp download
  157. 'skip_download': True,
  158. },
  159. 'skip': 'geolocation',
  160. }, {
  161. 'url': 'http://www.bbc.co.uk/iplayer/episode/b05zmgwn/royal-academy-summer-exhibition',
  162. 'info_dict': {
  163. 'id': 'b05zmgw1',
  164. 'ext': 'flv',
  165. 'description': 'Kirsty Wark and Morgan Quaintance visit the Royal Academy as it prepares for its annual artistic extravaganza, meeting people who have come together to make the show unique.',
  166. 'title': 'Royal Academy Summer Exhibition',
  167. 'duration': 3540,
  168. },
  169. 'params': {
  170. # rtmp download
  171. 'skip_download': True,
  172. },
  173. 'skip': 'geolocation',
  174. }, {
  175. # iptv-all mediaset fails with geolocation however there is no geo restriction
  176. # for this programme at all
  177. 'url': 'http://www.bbc.co.uk/programmes/b06rkn85',
  178. 'info_dict': {
  179. 'id': 'b06rkms3',
  180. 'ext': 'flv',
  181. 'title': "Best of the Mini-Mixes 2015: Part 3, Annie Mac's Friday Night - BBC Radio 1",
  182. 'description': "Annie has part three in the Best of the Mini-Mixes 2015, plus the year's Most Played!",
  183. },
  184. 'params': {
  185. # rtmp download
  186. 'skip_download': True,
  187. },
  188. }, {
  189. # compact player (https://github.com/rg3/youtube-dl/issues/8147)
  190. 'url': 'http://www.bbc.co.uk/programmes/p028bfkf/player',
  191. 'info_dict': {
  192. 'id': 'p028bfkj',
  193. 'ext': 'flv',
  194. 'title': 'Extract from BBC documentary Look Stranger - Giant Leeks and Magic Brews',
  195. 'description': 'Extract from BBC documentary Look Stranger - Giant Leeks and Magic Brews',
  196. },
  197. 'params': {
  198. # rtmp download
  199. 'skip_download': True,
  200. },
  201. }, {
  202. 'url': 'http://www.bbc.co.uk/iplayer/playlist/p01dvks4',
  203. 'only_matching': True,
  204. }, {
  205. 'url': 'http://www.bbc.co.uk/music/clips#p02frcc3',
  206. 'only_matching': True,
  207. }, {
  208. 'url': 'http://www.bbc.co.uk/iplayer/cbeebies/episode/b0480276/bing-14-atchoo',
  209. 'only_matching': True,
  210. }, {
  211. 'url': 'http://www.bbc.co.uk/radio/player/p03cchwf',
  212. 'only_matching': True,
  213. }
  214. ]
  215. class MediaSelectionError(Exception):
  216. def __init__(self, id):
  217. self.id = id
  218. def _extract_asx_playlist(self, connection, programme_id):
  219. asx = self._download_xml(connection.get('href'), programme_id, 'Downloading ASX playlist')
  220. return [ref.get('href') for ref in asx.findall('./Entry/ref')]
  221. def _extract_connection(self, connection, programme_id):
  222. formats = []
  223. kind = connection.get('kind')
  224. protocol = connection.get('protocol')
  225. supplier = connection.get('supplier')
  226. if protocol == 'http':
  227. href = connection.get('href')
  228. transfer_format = connection.get('transferFormat')
  229. # ASX playlist
  230. if supplier == 'asx':
  231. for i, ref in enumerate(self._extract_asx_playlist(connection, programme_id)):
  232. formats.append({
  233. 'url': ref,
  234. 'format_id': 'ref%s_%s' % (i, supplier),
  235. })
  236. # Skip DASH until supported
  237. elif transfer_format == 'dash':
  238. pass
  239. elif transfer_format == 'hls':
  240. formats.extend(self._extract_m3u8_formats(
  241. href, programme_id, ext='mp4', entry_protocol='m3u8_native',
  242. m3u8_id=supplier, fatal=False))
  243. # Direct link
  244. else:
  245. formats.append({
  246. 'url': href,
  247. 'format_id': supplier or kind or protocol,
  248. })
  249. elif protocol == 'rtmp':
  250. application = connection.get('application', 'ondemand')
  251. auth_string = connection.get('authString')
  252. identifier = connection.get('identifier')
  253. server = connection.get('server')
  254. formats.append({
  255. 'url': '%s://%s/%s?%s' % (protocol, server, application, auth_string),
  256. 'play_path': identifier,
  257. 'app': '%s?%s' % (application, auth_string),
  258. 'page_url': 'http://www.bbc.co.uk',
  259. 'player_url': 'http://www.bbc.co.uk/emp/releases/iplayer/revisions/617463_618125_4/617463_618125_4_emp.swf',
  260. 'rtmp_live': False,
  261. 'ext': 'flv',
  262. 'format_id': supplier,
  263. })
  264. return formats
  265. def _extract_items(self, playlist):
  266. return playlist.findall('./{%s}item' % self._EMP_PLAYLIST_NS)
  267. def _findall_ns(self, element, xpath):
  268. elements = []
  269. for ns in self._NAMESPACES:
  270. elements.extend(element.findall(xpath % ns))
  271. return elements
  272. def _extract_medias(self, media_selection):
  273. error = media_selection.find('./{%s}error' % self._MEDIASELECTION_NS)
  274. if error is None:
  275. media_selection.find('./{%s}error' % self._EMP_PLAYLIST_NS)
  276. if error is not None:
  277. raise BBCCoUkIE.MediaSelectionError(error.get('id'))
  278. return self._findall_ns(media_selection, './{%s}media')
  279. def _extract_connections(self, media):
  280. return self._findall_ns(media, './{%s}connection')
  281. def _extract_video(self, media, programme_id):
  282. formats = []
  283. vbr = int_or_none(media.get('bitrate'))
  284. vcodec = media.get('encoding')
  285. service = media.get('service')
  286. width = int_or_none(media.get('width'))
  287. height = int_or_none(media.get('height'))
  288. file_size = int_or_none(media.get('media_file_size'))
  289. for connection in self._extract_connections(media):
  290. conn_formats = self._extract_connection(connection, programme_id)
  291. for format in conn_formats:
  292. format.update({
  293. 'width': width,
  294. 'height': height,
  295. 'vbr': vbr,
  296. 'vcodec': vcodec,
  297. 'filesize': file_size,
  298. })
  299. if service:
  300. format['format_id'] = '%s_%s' % (service, format['format_id'])
  301. formats.extend(conn_formats)
  302. return formats
  303. def _extract_audio(self, media, programme_id):
  304. formats = []
  305. abr = int_or_none(media.get('bitrate'))
  306. acodec = media.get('encoding')
  307. service = media.get('service')
  308. for connection in self._extract_connections(media):
  309. conn_formats = self._extract_connection(connection, programme_id)
  310. for format in conn_formats:
  311. format.update({
  312. 'format_id': '%s_%s' % (service, format['format_id']),
  313. 'abr': abr,
  314. 'acodec': acodec,
  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': 'BBC Blogs - Adam Curtis - 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': 'What Liverpool can expect from Klopp',
  626. },
  627. 'playlist_count': 3,
  628. }, {
  629. # single video with playlist URL from weather section
  630. 'url': 'http://www.bbc.com/weather/features/33601775',
  631. 'only_matching': True,
  632. }, {
  633. # custom redirection to www.bbc.com
  634. 'url': 'http://www.bbc.co.uk/news/science-environment-33661876',
  635. 'only_matching': True,
  636. }]
  637. @classmethod
  638. def suitable(cls, url):
  639. return False if BBCCoUkIE.suitable(url) or BBCCoUkArticleIE.suitable(url) else super(BBCIE, cls).suitable(url)
  640. def _extract_from_media_meta(self, media_meta, video_id):
  641. # Direct links to media in media metadata (e.g.
  642. # http://www.bbc.com/turkce/haberler/2015/06/150615_telabyad_kentin_cogu)
  643. # TODO: there are also f4m and m3u8 streams incorporated in playlist.sxml
  644. source_files = media_meta.get('sourceFiles')
  645. if source_files:
  646. return [{
  647. 'url': f['url'],
  648. 'format_id': format_id,
  649. 'ext': f.get('encoding'),
  650. 'tbr': float_or_none(f.get('bitrate'), 1000),
  651. 'filesize': int_or_none(f.get('filesize')),
  652. } for format_id, f in source_files.items() if f.get('url')], []
  653. programme_id = media_meta.get('externalId')
  654. if programme_id:
  655. return self._download_media_selector(programme_id)
  656. # Process playlist.sxml as legacy playlist
  657. href = media_meta.get('href')
  658. if href:
  659. playlist = self._download_legacy_playlist_url(href)
  660. _, _, _, _, formats, subtitles = self._extract_from_legacy_playlist(playlist, video_id)
  661. return formats, subtitles
  662. return [], []
  663. def _extract_from_playlist_sxml(self, url, playlist_id, timestamp):
  664. programme_id, title, description, duration, formats, subtitles = \
  665. self._process_legacy_playlist_url(url, playlist_id)
  666. self._sort_formats(formats)
  667. return {
  668. 'id': programme_id,
  669. 'title': title,
  670. 'description': description,
  671. 'duration': duration,
  672. 'timestamp': timestamp,
  673. 'formats': formats,
  674. 'subtitles': subtitles,
  675. }
  676. def _real_extract(self, url):
  677. playlist_id = self._match_id(url)
  678. webpage = self._download_webpage(url, playlist_id)
  679. json_ld_info = self._search_json_ld(webpage, playlist_id, default=None)
  680. timestamp = json_ld_info.get('timestamp')
  681. playlist_title = json_ld_info.get('title')
  682. playlist_description = json_ld_info.get('description')
  683. if not timestamp:
  684. timestamp = parse_iso8601(self._search_regex(
  685. [r'<meta[^>]+property="article:published_time"[^>]+content="([^"]+)"',
  686. r'itemprop="datePublished"[^>]+datetime="([^"]+)"',
  687. r'"datePublished":\s*"([^"]+)'],
  688. webpage, 'date', default=None))
  689. entries = []
  690. # article with multiple videos embedded with playlist.sxml (e.g.
  691. # http://www.bbc.com/sport/0/football/34475836)
  692. playlists = re.findall(r'<param[^>]+name="playlist"[^>]+value="([^"]+)"', webpage)
  693. playlists.extend(re.findall(r'data-media-id="([^"]+/playlist\.sxml)"', webpage))
  694. if playlists:
  695. entries = [
  696. self._extract_from_playlist_sxml(playlist_url, playlist_id, timestamp)
  697. for playlist_url in playlists]
  698. # news article with multiple videos embedded with data-playable
  699. data_playables = re.findall(r'data-playable=(["\'])({.+?})\1', webpage)
  700. if data_playables:
  701. for _, data_playable_json in data_playables:
  702. data_playable = self._parse_json(
  703. unescapeHTML(data_playable_json), playlist_id, fatal=False)
  704. if not data_playable:
  705. continue
  706. settings = data_playable.get('settings', {})
  707. if settings:
  708. # data-playable with video vpid in settings.playlistObject.items (e.g.
  709. # http://www.bbc.com/news/world-us-canada-34473351)
  710. playlist_object = settings.get('playlistObject', {})
  711. if playlist_object:
  712. items = playlist_object.get('items')
  713. if items and isinstance(items, list):
  714. title = playlist_object['title']
  715. description = playlist_object.get('summary')
  716. duration = int_or_none(items[0].get('duration'))
  717. programme_id = items[0].get('vpid')
  718. formats, subtitles = self._download_media_selector(programme_id)
  719. self._sort_formats(formats)
  720. entries.append({
  721. 'id': programme_id,
  722. 'title': title,
  723. 'description': description,
  724. 'timestamp': timestamp,
  725. 'duration': duration,
  726. 'formats': formats,
  727. 'subtitles': subtitles,
  728. })
  729. else:
  730. # data-playable without vpid but with a playlist.sxml URLs
  731. # in otherSettings.playlist (e.g.
  732. # http://www.bbc.com/turkce/multimedya/2015/10/151010_vid_ankara_patlama_ani)
  733. playlist = data_playable.get('otherSettings', {}).get('playlist', {})
  734. if playlist:
  735. entries.append(self._extract_from_playlist_sxml(
  736. playlist.get('progressiveDownloadUrl'), playlist_id, timestamp))
  737. if entries:
  738. playlist_title = playlist_title or remove_end(self._og_search_title(webpage), ' - BBC News')
  739. playlist_description = playlist_description or self._og_search_description(webpage, default=None)
  740. return self.playlist_result(entries, playlist_id, playlist_title, playlist_description)
  741. # single video story (e.g. http://www.bbc.com/travel/story/20150625-sri-lankas-spicy-secret)
  742. programme_id = self._search_regex(
  743. [r'data-video-player-vpid="(%s)"' % self._ID_REGEX,
  744. r'<param[^>]+name="externalIdentifier"[^>]+value="(%s)"' % self._ID_REGEX,
  745. r'videoId\s*:\s*["\'](%s)["\']' % self._ID_REGEX],
  746. webpage, 'vpid', default=None)
  747. if programme_id:
  748. formats, subtitles = self._download_media_selector(programme_id)
  749. self._sort_formats(formats)
  750. # digitalData may be missing (e.g. http://www.bbc.com/autos/story/20130513-hyundais-rock-star)
  751. digital_data = self._parse_json(
  752. self._search_regex(
  753. r'var\s+digitalData\s*=\s*({.+?});?\n', webpage, 'digital data', default='{}'),
  754. programme_id, fatal=False)
  755. page_info = digital_data.get('page', {}).get('pageInfo', {})
  756. title = page_info.get('pageName') or self._og_search_title(webpage)
  757. description = page_info.get('description') or self._og_search_description(webpage)
  758. timestamp = parse_iso8601(page_info.get('publicationDate')) or timestamp
  759. return {
  760. 'id': programme_id,
  761. 'title': title,
  762. 'description': description,
  763. 'timestamp': timestamp,
  764. 'formats': formats,
  765. 'subtitles': subtitles,
  766. }
  767. playlist_title = self._html_search_regex(
  768. r'<title>(.*?)(?:\s*-\s*BBC [^ ]+)?</title>', webpage, 'playlist title')
  769. playlist_description = self._og_search_description(webpage, default=None)
  770. def extract_all(pattern):
  771. return list(filter(None, map(
  772. lambda s: self._parse_json(s, playlist_id, fatal=False),
  773. re.findall(pattern, webpage))))
  774. # Multiple video article (e.g.
  775. # http://www.bbc.co.uk/blogs/adamcurtis/entries/3662a707-0af9-3149-963f-47bea720b460)
  776. EMBED_URL = r'https?://(?:www\.)?bbc\.co\.uk/(?:[^/]+/)+%s(?:\b[^"]+)?' % self._ID_REGEX
  777. entries = []
  778. for match in extract_all(r'new\s+SMP\(({.+?})\)'):
  779. embed_url = match.get('playerSettings', {}).get('externalEmbedUrl')
  780. if embed_url and re.match(EMBED_URL, embed_url):
  781. entries.append(embed_url)
  782. entries.extend(re.findall(
  783. r'setPlaylist\("(%s)"\)' % EMBED_URL, webpage))
  784. if entries:
  785. return self.playlist_result(
  786. [self.url_result(entry, 'BBCCoUk') for entry in entries],
  787. playlist_id, playlist_title, playlist_description)
  788. # Multiple video article (e.g. http://www.bbc.com/news/world-europe-32668511)
  789. medias = extract_all(r"data-media-meta='({[^']+})'")
  790. if not medias:
  791. # Single video article (e.g. http://www.bbc.com/news/video_and_audio/international)
  792. media_asset = self._search_regex(
  793. r'mediaAssetPage\.init\(\s*({.+?}), "/',
  794. webpage, 'media asset', default=None)
  795. if media_asset:
  796. media_asset_page = self._parse_json(media_asset, playlist_id, fatal=False)
  797. medias = []
  798. for video in media_asset_page.get('videos', {}).values():
  799. medias.extend(video.values())
  800. if not medias:
  801. # Multiple video playlist with single `now playing` entry (e.g.
  802. # http://www.bbc.com/news/video_and_audio/must_see/33767813)
  803. vxp_playlist = self._parse_json(
  804. self._search_regex(
  805. r'<script[^>]+class="vxp-playlist-data"[^>]+type="application/json"[^>]*>([^<]+)</script>',
  806. webpage, 'playlist data'),
  807. playlist_id)
  808. playlist_medias = []
  809. for item in vxp_playlist:
  810. media = item.get('media')
  811. if not media:
  812. continue
  813. playlist_medias.append(media)
  814. # Download single video if found media with asset id matching the video id from URL
  815. if item.get('advert', {}).get('assetId') == playlist_id:
  816. medias = [media]
  817. break
  818. # Fallback to the whole playlist
  819. if not medias:
  820. medias = playlist_medias
  821. entries = []
  822. for num, media_meta in enumerate(medias, start=1):
  823. formats, subtitles = self._extract_from_media_meta(media_meta, playlist_id)
  824. if not formats:
  825. continue
  826. self._sort_formats(formats)
  827. video_id = media_meta.get('externalId')
  828. if not video_id:
  829. video_id = playlist_id if len(medias) == 1 else '%s-%s' % (playlist_id, num)
  830. title = media_meta.get('caption')
  831. if not title:
  832. title = playlist_title if len(medias) == 1 else '%s - Video %s' % (playlist_title, num)
  833. duration = int_or_none(media_meta.get('durationInSeconds')) or parse_duration(media_meta.get('duration'))
  834. images = []
  835. for image in media_meta.get('images', {}).values():
  836. images.extend(image.values())
  837. if 'image' in media_meta:
  838. images.append(media_meta['image'])
  839. thumbnails = [{
  840. 'url': image.get('href'),
  841. 'width': int_or_none(image.get('width')),
  842. 'height': int_or_none(image.get('height')),
  843. } for image in images]
  844. entries.append({
  845. 'id': video_id,
  846. 'title': title,
  847. 'thumbnails': thumbnails,
  848. 'duration': duration,
  849. 'timestamp': timestamp,
  850. 'formats': formats,
  851. 'subtitles': subtitles,
  852. })
  853. return self.playlist_result(entries, playlist_id, playlist_title, playlist_description)
  854. class BBCCoUkArticleIE(InfoExtractor):
  855. _VALID_URL = 'http://www.bbc.co.uk/programmes/articles/(?P<id>[a-zA-Z0-9]+)'
  856. IE_NAME = 'bbc.co.uk:article'
  857. IE_DESC = 'BBC articles'
  858. _TEST = {
  859. 'url': 'http://www.bbc.co.uk/programmes/articles/3jNQLTMrPlYGTBn0WV6M2MS/not-your-typical-role-model-ada-lovelace-the-19th-century-programmer',
  860. 'info_dict': {
  861. 'id': '3jNQLTMrPlYGTBn0WV6M2MS',
  862. 'title': 'Calculating Ada: The Countess of Computing - Not your typical role model: Ada Lovelace the 19th century programmer - BBC Four',
  863. 'description': 'Hannah Fry reveals some of her surprising discoveries about Ada Lovelace during filming.',
  864. },
  865. 'playlist_count': 4,
  866. 'add_ie': ['BBCCoUk'],
  867. }
  868. def _real_extract(self, url):
  869. playlist_id = self._match_id(url)
  870. webpage = self._download_webpage(url, playlist_id)
  871. title = self._og_search_title(webpage)
  872. description = self._og_search_description(webpage).strip()
  873. entries = [self.url_result(programme_url) for programme_url in re.findall(
  874. r'<div[^>]+typeof="Clip"[^>]+resource="([^"]+)"', webpage)]
  875. return self.playlist_result(entries, playlist_id, title, description)