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.

745 lines
30 KiB

10 years ago
9 years ago
9 years ago
9 years ago
9 years ago
  1. # coding: utf-8
  2. from __future__ import unicode_literals
  3. import re
  4. import xml.etree.ElementTree
  5. from .common import InfoExtractor
  6. from ..utils import (
  7. ExtractorError,
  8. float_or_none,
  9. int_or_none,
  10. parse_duration,
  11. parse_iso8601,
  12. )
  13. from ..compat import compat_HTTPError
  14. class BBCCoUkIE(InfoExtractor):
  15. IE_NAME = 'bbc.co.uk'
  16. IE_DESC = 'BBC iPlayer'
  17. _VALID_URL = r'https?://(?:www\.)?bbc\.co\.uk/(?:(?:(?:programmes|iplayer(?:/[^/]+)?/(?:episode|playlist))/)|music/clips[/#])(?P<id>[\da-z]{8})'
  18. _MEDIASELECTOR_URLS = [
  19. 'http://open.live.bbc.co.uk/mediaselector/5/select/version/2.0/mediaset/pc/vpid/%s',
  20. ]
  21. _TESTS = [
  22. {
  23. 'url': 'http://www.bbc.co.uk/programmes/b039g8p7',
  24. 'info_dict': {
  25. 'id': 'b039d07m',
  26. 'ext': 'flv',
  27. 'title': 'Kaleidoscope, Leonard Cohen',
  28. 'description': 'The Canadian poet and songwriter reflects on his musical career.',
  29. 'duration': 1740,
  30. },
  31. 'params': {
  32. # rtmp download
  33. 'skip_download': True,
  34. }
  35. },
  36. {
  37. 'url': 'http://www.bbc.co.uk/iplayer/episode/b00yng5w/The_Man_in_Black_Series_3_The_Printed_Name/',
  38. 'info_dict': {
  39. 'id': 'b00yng1d',
  40. 'ext': 'flv',
  41. 'title': 'The Man in Black: Series 3: The Printed Name',
  42. 'description': "Mark Gatiss introduces Nicholas Pierpan's chilling tale of a writer's devilish pact with a mysterious man. Stars Ewan Bailey.",
  43. 'duration': 1800,
  44. },
  45. 'params': {
  46. # rtmp download
  47. 'skip_download': True,
  48. },
  49. 'skip': 'Episode is no longer available on BBC iPlayer Radio',
  50. },
  51. {
  52. 'url': 'http://www.bbc.co.uk/iplayer/episode/b03vhd1f/The_Voice_UK_Series_3_Blind_Auditions_5/',
  53. 'info_dict': {
  54. 'id': 'b00yng1d',
  55. 'ext': 'flv',
  56. 'title': 'The Voice UK: Series 3: Blind Auditions 5',
  57. '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.",
  58. 'duration': 5100,
  59. },
  60. 'params': {
  61. # rtmp download
  62. 'skip_download': True,
  63. },
  64. 'skip': 'Currently BBC iPlayer TV programmes are available to play in the UK only',
  65. },
  66. {
  67. 'url': 'http://www.bbc.co.uk/iplayer/episode/p026c7jt/tomorrows-worlds-the-unearthly-history-of-science-fiction-2-invasion',
  68. 'info_dict': {
  69. 'id': 'b03k3pb7',
  70. 'ext': 'flv',
  71. 'title': "Tomorrow's Worlds: The Unearthly History of Science Fiction",
  72. 'description': '2. Invasion',
  73. 'duration': 3600,
  74. },
  75. 'params': {
  76. # rtmp download
  77. 'skip_download': True,
  78. },
  79. 'skip': 'Currently BBC iPlayer TV programmes are available to play in the UK only',
  80. }, {
  81. 'url': 'http://www.bbc.co.uk/programmes/b04v20dw',
  82. 'info_dict': {
  83. 'id': 'b04v209v',
  84. 'ext': 'flv',
  85. 'title': 'Pete Tong, The Essential New Tune Special',
  86. 'description': "Pete has a very special mix - all of 2014's Essential New Tunes!",
  87. 'duration': 10800,
  88. },
  89. 'params': {
  90. # rtmp download
  91. 'skip_download': True,
  92. }
  93. }, {
  94. 'url': 'http://www.bbc.co.uk/music/clips/p02frcc3',
  95. 'note': 'Audio',
  96. 'info_dict': {
  97. 'id': 'p02frcch',
  98. 'ext': 'flv',
  99. 'title': 'Pete Tong, Past, Present and Future Special, Madeon - After Hours mix',
  100. 'description': 'French house superstar Madeon takes us out of the club and onto the after party.',
  101. 'duration': 3507,
  102. },
  103. 'params': {
  104. # rtmp download
  105. 'skip_download': True,
  106. }
  107. }, {
  108. 'url': 'http://www.bbc.co.uk/music/clips/p025c0zz',
  109. 'note': 'Video',
  110. 'info_dict': {
  111. 'id': 'p025c103',
  112. 'ext': 'flv',
  113. 'title': 'Reading and Leeds Festival, 2014, Rae Morris - Closer (Live on BBC Three)',
  114. 'description': 'Rae Morris performs Closer for BBC Three at Reading 2014',
  115. 'duration': 226,
  116. },
  117. 'params': {
  118. # rtmp download
  119. 'skip_download': True,
  120. }
  121. }, {
  122. 'url': 'http://www.bbc.co.uk/iplayer/episode/b054fn09/ad/natural-world-20152016-2-super-powered-owls',
  123. 'info_dict': {
  124. 'id': 'p02n76xf',
  125. 'ext': 'flv',
  126. 'title': 'Natural World, 2015-2016: 2. Super Powered Owls',
  127. 'description': 'md5:e4db5c937d0e95a7c6b5e654d429183d',
  128. 'duration': 3540,
  129. },
  130. 'params': {
  131. # rtmp download
  132. 'skip_download': True,
  133. },
  134. 'skip': 'geolocation',
  135. }, {
  136. 'url': 'http://www.bbc.co.uk/iplayer/episode/b05zmgwn/royal-academy-summer-exhibition',
  137. 'info_dict': {
  138. 'id': 'b05zmgw1',
  139. 'ext': 'flv',
  140. '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.',
  141. 'title': 'Royal Academy Summer Exhibition',
  142. 'duration': 3540,
  143. },
  144. 'params': {
  145. # rtmp download
  146. 'skip_download': True,
  147. },
  148. 'skip': 'geolocation',
  149. }, {
  150. 'url': 'http://www.bbc.co.uk/iplayer/playlist/p01dvks4',
  151. 'only_matching': True,
  152. }, {
  153. 'url': 'http://www.bbc.co.uk/music/clips#p02frcc3',
  154. 'only_matching': True,
  155. }, {
  156. 'url': 'http://www.bbc.co.uk/iplayer/cbeebies/episode/b0480276/bing-14-atchoo',
  157. 'only_matching': True,
  158. }
  159. ]
  160. class MediaSelectionError(Exception):
  161. def __init__(self, id):
  162. self.id = id
  163. def _extract_asx_playlist(self, connection, programme_id):
  164. asx = self._download_xml(connection.get('href'), programme_id, 'Downloading ASX playlist')
  165. return [ref.get('href') for ref in asx.findall('./Entry/ref')]
  166. def _extract_connection(self, connection, programme_id):
  167. formats = []
  168. protocol = connection.get('protocol')
  169. supplier = connection.get('supplier')
  170. if protocol == 'http':
  171. href = connection.get('href')
  172. transfer_format = connection.get('transferFormat')
  173. # ASX playlist
  174. if supplier == 'asx':
  175. for i, ref in enumerate(self._extract_asx_playlist(connection, programme_id)):
  176. formats.append({
  177. 'url': ref,
  178. 'format_id': 'ref%s_%s' % (i, supplier),
  179. })
  180. # Skip DASH until supported
  181. elif transfer_format == 'dash':
  182. pass
  183. # Direct link
  184. else:
  185. formats.append({
  186. 'url': href,
  187. 'format_id': supplier,
  188. })
  189. elif protocol == 'rtmp':
  190. application = connection.get('application', 'ondemand')
  191. auth_string = connection.get('authString')
  192. identifier = connection.get('identifier')
  193. server = connection.get('server')
  194. formats.append({
  195. 'url': '%s://%s/%s?%s' % (protocol, server, application, auth_string),
  196. 'play_path': identifier,
  197. 'app': '%s?%s' % (application, auth_string),
  198. 'page_url': 'http://www.bbc.co.uk',
  199. 'player_url': 'http://www.bbc.co.uk/emp/releases/iplayer/revisions/617463_618125_4/617463_618125_4_emp.swf',
  200. 'rtmp_live': False,
  201. 'ext': 'flv',
  202. 'format_id': supplier,
  203. })
  204. return formats
  205. def _extract_items(self, playlist):
  206. return playlist.findall('./{http://bbc.co.uk/2008/emp/playlist}item')
  207. def _extract_medias(self, media_selection):
  208. error = media_selection.find('./{http://bbc.co.uk/2008/mp/mediaselection}error')
  209. if error is not None:
  210. raise BBCCoUkIE.MediaSelectionError(error.get('id'))
  211. return media_selection.findall('./{http://bbc.co.uk/2008/mp/mediaselection}media')
  212. def _extract_connections(self, media):
  213. return media.findall('./{http://bbc.co.uk/2008/mp/mediaselection}connection')
  214. def _extract_video(self, media, programme_id):
  215. formats = []
  216. vbr = int_or_none(media.get('bitrate'))
  217. vcodec = media.get('encoding')
  218. service = media.get('service')
  219. width = int_or_none(media.get('width'))
  220. height = int_or_none(media.get('height'))
  221. file_size = int_or_none(media.get('media_file_size'))
  222. for connection in self._extract_connections(media):
  223. conn_formats = self._extract_connection(connection, programme_id)
  224. for format in conn_formats:
  225. format.update({
  226. 'format_id': '%s_%s' % (service, format['format_id']),
  227. 'width': width,
  228. 'height': height,
  229. 'vbr': vbr,
  230. 'vcodec': vcodec,
  231. 'filesize': file_size,
  232. })
  233. formats.extend(conn_formats)
  234. return formats
  235. def _extract_audio(self, media, programme_id):
  236. formats = []
  237. abr = int_or_none(media.get('bitrate'))
  238. acodec = media.get('encoding')
  239. service = media.get('service')
  240. for connection in self._extract_connections(media):
  241. conn_formats = self._extract_connection(connection, programme_id)
  242. for format in conn_formats:
  243. format.update({
  244. 'format_id': '%s_%s' % (service, format['format_id']),
  245. 'abr': abr,
  246. 'acodec': acodec,
  247. })
  248. formats.extend(conn_formats)
  249. return formats
  250. def _get_subtitles(self, media, programme_id):
  251. subtitles = {}
  252. for connection in self._extract_connections(media):
  253. captions = self._download_xml(connection.get('href'), programme_id, 'Downloading captions')
  254. lang = captions.get('{http://www.w3.org/XML/1998/namespace}lang', 'en')
  255. subtitles[lang] = [
  256. {
  257. 'url': connection.get('href'),
  258. 'ext': 'ttml',
  259. },
  260. ]
  261. return subtitles
  262. def _raise_extractor_error(self, media_selection_error):
  263. raise ExtractorError(
  264. '%s returned error: %s' % (self.IE_NAME, media_selection_error.id),
  265. expected=True)
  266. def _download_media_selector(self, programme_id):
  267. last_exception = None
  268. for mediaselector_url in self._MEDIASELECTOR_URLS:
  269. try:
  270. return self._download_media_selector_url(
  271. mediaselector_url % programme_id, programme_id)
  272. except BBCCoUkIE.MediaSelectionError as e:
  273. if e.id == 'notukerror':
  274. last_exception = e
  275. continue
  276. self._raise_extractor_error(e)
  277. self._raise_extractor_error(last_exception)
  278. def _download_media_selector_url(self, url, programme_id=None):
  279. try:
  280. media_selection = self._download_xml(
  281. url, programme_id, 'Downloading media selection XML')
  282. except ExtractorError as ee:
  283. if isinstance(ee.cause, compat_HTTPError) and ee.cause.code == 403:
  284. media_selection = xml.etree.ElementTree.fromstring(ee.cause.read().decode('utf-8'))
  285. else:
  286. raise
  287. return self._process_media_selector(media_selection, programme_id)
  288. def _process_media_selector(self, media_selection, programme_id):
  289. formats = []
  290. subtitles = None
  291. for media in self._extract_medias(media_selection):
  292. kind = media.get('kind')
  293. if kind == 'audio':
  294. formats.extend(self._extract_audio(media, programme_id))
  295. elif kind == 'video':
  296. formats.extend(self._extract_video(media, programme_id))
  297. elif kind == 'captions':
  298. subtitles = self.extract_subtitles(media, programme_id)
  299. return formats, subtitles
  300. def _download_playlist(self, playlist_id):
  301. try:
  302. playlist = self._download_json(
  303. 'http://www.bbc.co.uk/programmes/%s/playlist.json' % playlist_id,
  304. playlist_id, 'Downloading playlist JSON')
  305. version = playlist.get('defaultAvailableVersion')
  306. if version:
  307. smp_config = version['smpConfig']
  308. title = smp_config['title']
  309. description = smp_config['summary']
  310. for item in smp_config['items']:
  311. kind = item['kind']
  312. if kind != 'programme' and kind != 'radioProgramme':
  313. continue
  314. programme_id = item.get('vpid')
  315. duration = int_or_none(item.get('duration'))
  316. formats, subtitles = self._download_media_selector(programme_id)
  317. return programme_id, title, description, duration, formats, subtitles
  318. except ExtractorError as ee:
  319. if not (isinstance(ee.cause, compat_HTTPError) and ee.cause.code == 404):
  320. raise
  321. # fallback to legacy playlist
  322. return self._process_legacy_playlist(playlist_id)
  323. def _process_legacy_playlist_url(self, url, display_id):
  324. playlist = self._download_legacy_playlist_url(url, display_id)
  325. return self._extract_from_legacy_playlist(playlist, display_id)
  326. def _process_legacy_playlist(self, playlist_id):
  327. return self._process_legacy_playlist_url(
  328. 'http://www.bbc.co.uk/iplayer/playlist/%s' % playlist_id, playlist_id)
  329. def _download_legacy_playlist_url(self, url, playlist_id=None):
  330. return self._download_xml(
  331. url, playlist_id, 'Downloading legacy playlist XML')
  332. def _extract_from_legacy_playlist(self, playlist, playlist_id):
  333. no_items = playlist.find('./{http://bbc.co.uk/2008/emp/playlist}noItems')
  334. if no_items is not None:
  335. reason = no_items.get('reason')
  336. if reason == 'preAvailability':
  337. msg = 'Episode %s is not yet available' % playlist_id
  338. elif reason == 'postAvailability':
  339. msg = 'Episode %s is no longer available' % playlist_id
  340. elif reason == 'noMedia':
  341. msg = 'Episode %s is not currently available' % playlist_id
  342. else:
  343. msg = 'Episode %s is not available: %s' % (playlist_id, reason)
  344. raise ExtractorError(msg, expected=True)
  345. for item in self._extract_items(playlist):
  346. kind = item.get('kind')
  347. if kind != 'programme' and kind != 'radioProgramme':
  348. continue
  349. title = playlist.find('./{http://bbc.co.uk/2008/emp/playlist}title').text
  350. description = playlist.find('./{http://bbc.co.uk/2008/emp/playlist}summary').text
  351. def get_programme_id(item):
  352. def get_from_attributes(item):
  353. for p in('identifier', 'group'):
  354. value = item.get(p)
  355. if value and re.match(r'^[pb][\da-z]{7}$', value):
  356. return value
  357. get_from_attributes(item)
  358. mediator = item.find('./{http://bbc.co.uk/2008/emp/playlist}mediator')
  359. if mediator is not None:
  360. return get_from_attributes(mediator)
  361. programme_id = get_programme_id(item)
  362. duration = int_or_none(item.get('duration'))
  363. # TODO: programme_id can be None and media items can be incorporated right inside
  364. # playlist's item (e.g. http://www.bbc.com/turkce/haberler/2015/06/150615_telabyad_kentin_cogu)
  365. # as f4m and m3u8
  366. formats, subtitles = self._download_media_selector(programme_id)
  367. return programme_id, title, description, duration, formats, subtitles
  368. def _real_extract(self, url):
  369. group_id = self._match_id(url)
  370. webpage = self._download_webpage(url, group_id, 'Downloading video page')
  371. programme_id = None
  372. tviplayer = self._search_regex(
  373. r'mediator\.bind\(({.+?})\s*,\s*document\.getElementById',
  374. webpage, 'player', default=None)
  375. if tviplayer:
  376. player = self._parse_json(tviplayer, group_id).get('player', {})
  377. duration = int_or_none(player.get('duration'))
  378. programme_id = player.get('vpid')
  379. if not programme_id:
  380. programme_id = self._search_regex(
  381. r'"vpid"\s*:\s*"([\da-z]{8})"', webpage, 'vpid', fatal=False, default=None)
  382. if programme_id:
  383. formats, subtitles = self._download_media_selector(programme_id)
  384. title = self._og_search_title(webpage)
  385. description = self._search_regex(
  386. r'<p class="[^"]*medium-description[^"]*">([^<]+)</p>',
  387. webpage, 'description', fatal=False)
  388. else:
  389. programme_id, title, description, duration, formats, subtitles = self._download_playlist(group_id)
  390. self._sort_formats(formats)
  391. return {
  392. 'id': programme_id,
  393. 'title': title,
  394. 'description': description,
  395. 'thumbnail': self._og_search_thumbnail(webpage, default=None),
  396. 'duration': duration,
  397. 'formats': formats,
  398. 'subtitles': subtitles,
  399. }
  400. class BBCIE(BBCCoUkIE):
  401. IE_NAME = 'bbc'
  402. IE_DESC = 'BBC'
  403. _VALID_URL = r'https?://(?:www\.)?bbc\.(?:com|co\.uk)/(?:[^/]+/)+(?P<id>[^/#?]+)'
  404. _MEDIASELECTOR_URLS = [
  405. # Provides more formats, namely direct mp4 links, but fails on some videos with
  406. # notukerror for non UK (?) users (e.g.
  407. # http://www.bbc.com/travel/story/20150625-sri-lankas-spicy-secret)
  408. 'http://open.live.bbc.co.uk/mediaselector/4/mtis/stream/%s',
  409. # Provides fewer formats, but works everywhere for everybody (hopefully)
  410. 'http://open.live.bbc.co.uk/mediaselector/5/select/version/2.0/mediaset/journalism-pc/vpid/%s',
  411. ]
  412. _TESTS = [{
  413. # article with multiple videos embedded with data-media-meta containing
  414. # playlist.sxml, externalId and no direct video links
  415. 'url': 'http://www.bbc.com/news/world-europe-32668511',
  416. 'info_dict': {
  417. 'id': 'world-europe-32668511',
  418. 'title': 'Russia stages massive WW2 parade despite Western boycott',
  419. 'description': 'md5:00ff61976f6081841f759a08bf78cc9c',
  420. },
  421. 'playlist_count': 2,
  422. }, {
  423. # article with multiple videos embedded with data-media-meta (more videos)
  424. 'url': 'http://www.bbc.com/news/business-28299555',
  425. 'info_dict': {
  426. 'id': 'business-28299555',
  427. 'title': 'Farnborough Airshow: Video highlights',
  428. 'description': 'BBC reports and video highlights at the Farnborough Airshow.',
  429. },
  430. 'playlist_count': 9,
  431. 'skip': 'Save time',
  432. }, {
  433. # article with multiple videos embedded with `new SMP()`
  434. 'url': 'http://www.bbc.co.uk/blogs/adamcurtis/entries/3662a707-0af9-3149-963f-47bea720b460',
  435. 'info_dict': {
  436. 'id': '3662a707-0af9-3149-963f-47bea720b460',
  437. 'title': 'BBC Blogs - Adam Curtis - BUGGER',
  438. },
  439. 'playlist_count': 18,
  440. }, {
  441. # single video embedded with mediaAssetPage.init()
  442. 'url': 'http://www.bbc.com/news/world-europe-32041533',
  443. 'info_dict': {
  444. 'id': 'p02mprgb',
  445. 'ext': 'mp4',
  446. 'title': 'Aerial footage showed the site of the crash in the Alps - courtesy BFM TV',
  447. 'duration': 47,
  448. 'timestamp': 1427219242,
  449. 'upload_date': '20150324',
  450. },
  451. 'params': {
  452. # rtmp download
  453. 'skip_download': True,
  454. }
  455. }, {
  456. # article with single video embedded with data-media-meta containing
  457. # direct video links (for now these are extracted) and playlist.xml (with
  458. # media items as f4m and m3u8 - currently unsupported)
  459. 'url': 'http://www.bbc.com/turkce/haberler/2015/06/150615_telabyad_kentin_cogu',
  460. 'info_dict': {
  461. 'id': '150615_telabyad_kentin_cogu',
  462. 'ext': 'mp4',
  463. 'title': "YPG: Tel Abyad'ın tamamı kontrolümüzde",
  464. 'duration': 47,
  465. 'timestamp': 1434397334,
  466. 'upload_date': '20150615',
  467. },
  468. 'params': {
  469. 'skip_download': True,
  470. }
  471. }, {
  472. # single video embedded with mediaAssetPage.init() (regional section)
  473. 'url': 'http://www.bbc.com/mundo/video_fotos/2015/06/150619_video_honduras_militares_hospitales_corrupcion_aw',
  474. 'info_dict': {
  475. 'id': '150619_video_honduras_militares_hospitales_corrupcion_aw',
  476. 'ext': 'mp4',
  477. 'title': 'Honduras militariza sus hospitales por nuevo escándalo de corrupción',
  478. 'duration': 87,
  479. 'timestamp': 1434713142,
  480. 'upload_date': '20150619',
  481. },
  482. 'params': {
  483. 'skip_download': True,
  484. }
  485. }, {
  486. # single video story with digitalData
  487. 'url': 'http://www.bbc.com/travel/story/20150625-sri-lankas-spicy-secret',
  488. 'info_dict': {
  489. 'id': 'p02q6gc4',
  490. 'ext': 'flv',
  491. 'title': 'Sri Lanka’s spicy secret',
  492. 'description': 'As a new train line to Jaffna opens up the country’s north, travellers can experience a truly distinct slice of Tamil culture.',
  493. 'timestamp': 1437674293,
  494. 'upload_date': '20150723',
  495. },
  496. 'params': {
  497. # rtmp download
  498. 'skip_download': True,
  499. }
  500. }, {
  501. # single video story without digitalData
  502. 'url': 'http://www.bbc.com/autos/story/20130513-hyundais-rock-star',
  503. 'info_dict': {
  504. 'id': 'p018zqqg',
  505. 'ext': 'mp4',
  506. 'title': 'Hyundai Santa Fe Sport: Rock star',
  507. 'description': 'md5:b042a26142c4154a6e472933cf20793d',
  508. 'timestamp': 1368473503,
  509. 'upload_date': '20130513',
  510. },
  511. 'params': {
  512. # rtmp download
  513. 'skip_download': True,
  514. }
  515. }, {
  516. # single video with playlist.sxml URL
  517. 'url': 'http://www.bbc.com/sport/0/football/33653409',
  518. 'info_dict': {
  519. 'id': 'p02xycnp',
  520. 'ext': 'mp4',
  521. 'title': 'Transfers: Cristiano Ronaldo to Man Utd, Arsenal to spend?',
  522. 'description': 'md5:398fca0e2e701c609d726e034fa1fc89',
  523. 'duration': 140,
  524. },
  525. 'params': {
  526. # rtmp download
  527. 'skip_download': True,
  528. }
  529. }, {
  530. # single video with playlist URL from weather section
  531. 'url': 'http://www.bbc.com/weather/features/33601775',
  532. 'only_matching': True,
  533. }, {
  534. # custom redirection to www.bbc.com
  535. 'url': 'http://www.bbc.co.uk/news/science-environment-33661876',
  536. 'only_matching': True,
  537. }]
  538. @classmethod
  539. def suitable(cls, url):
  540. return False if BBCCoUkIE.suitable(url) else super(BBCIE, cls).suitable(url)
  541. def _extract_from_media_meta(self, media_meta, video_id):
  542. # Direct links to media in media metadata (e.g.
  543. # http://www.bbc.com/turkce/haberler/2015/06/150615_telabyad_kentin_cogu)
  544. # TODO: there are also f4m and m3u8 streams incorporated in playlist.sxml
  545. source_files = media_meta.get('sourceFiles')
  546. if source_files:
  547. return [{
  548. 'url': f['url'],
  549. 'format_id': format_id,
  550. 'ext': f.get('encoding'),
  551. 'tbr': float_or_none(f.get('bitrate'), 1000),
  552. 'filesize': int_or_none(f.get('filesize')),
  553. } for format_id, f in source_files.items() if f.get('url')], []
  554. programme_id = media_meta.get('externalId')
  555. if programme_id:
  556. return self._download_media_selector(programme_id)
  557. # Process playlist.sxml as legacy playlist
  558. href = media_meta.get('href')
  559. if href:
  560. playlist = self._download_legacy_playlist_url(href)
  561. _, _, _, _, formats, subtitles = self._extract_from_legacy_playlist(playlist, video_id)
  562. return formats, subtitles
  563. return [], []
  564. def _real_extract(self, url):
  565. playlist_id = self._match_id(url)
  566. webpage = self._download_webpage(url, playlist_id)
  567. timestamp = parse_iso8601(self._search_regex(
  568. [r'"datePublished":\s*"([^"]+)',
  569. r'<meta[^>]+property="article:published_time"[^>]+content="([^"]+)"',
  570. r'itemprop="datePublished"[^>]+datetime="([^"]+)"'],
  571. webpage, 'date', default=None))
  572. # single video with playlist.sxml URL (e.g. http://www.bbc.com/sport/0/football/3365340ng)
  573. playlist = self._search_regex(
  574. r'<param[^>]+name="playlist"[^>]+value="([^"]+)"',
  575. webpage, 'playlist', default=None)
  576. if playlist:
  577. programme_id, title, description, duration, formats, subtitles = \
  578. self._process_legacy_playlist_url(playlist, playlist_id)
  579. self._sort_formats(formats)
  580. return {
  581. 'id': programme_id,
  582. 'title': title,
  583. 'description': description,
  584. 'duration': duration,
  585. 'timestamp': timestamp,
  586. 'formats': formats,
  587. 'subtitles': subtitles,
  588. }
  589. # single video story (e.g. http://www.bbc.com/travel/story/20150625-sri-lankas-spicy-secret)
  590. programme_id = self._search_regex(
  591. [r'data-video-player-vpid="([\da-z]{8})"',
  592. r'<param[^>]+name="externalIdentifier"[^>]+value="([\da-z]{8})"'],
  593. webpage, 'vpid', default=None)
  594. if programme_id:
  595. formats, subtitles = self._download_media_selector(programme_id)
  596. self._sort_formats(formats)
  597. # digitalData may be missing (e.g. http://www.bbc.com/autos/story/20130513-hyundais-rock-star)
  598. digital_data = self._parse_json(
  599. self._search_regex(
  600. r'var\s+digitalData\s*=\s*({.+?});?\n', webpage, 'digital data', default='{}'),
  601. programme_id, fatal=False)
  602. page_info = digital_data.get('page', {}).get('pageInfo', {})
  603. title = page_info.get('pageName') or self._og_search_title(webpage)
  604. description = page_info.get('description') or self._og_search_description(webpage)
  605. timestamp = parse_iso8601(page_info.get('publicationDate')) or timestamp
  606. return {
  607. 'id': programme_id,
  608. 'title': title,
  609. 'description': description,
  610. 'timestamp': timestamp,
  611. 'formats': formats,
  612. 'subtitles': subtitles,
  613. }
  614. playlist_title = self._html_search_regex(
  615. r'<title>(.*?)(?:\s*-\s*BBC [^ ]+)?</title>', webpage, 'playlist title')
  616. playlist_description = self._og_search_description(webpage, default=None)
  617. def extract_all(pattern):
  618. return list(filter(None, map(
  619. lambda s: self._parse_json(s, playlist_id, fatal=False),
  620. re.findall(pattern, webpage))))
  621. # Multiple video article (e.g.
  622. # http://www.bbc.co.uk/blogs/adamcurtis/entries/3662a707-0af9-3149-963f-47bea720b460)
  623. EMBED_URL = r'https?://(?:www\.)?bbc\.co\.uk/(?:[^/]+/)+[\da-z]{8}(?:\b[^"]+)?'
  624. entries = []
  625. for match in extract_all(r'new\s+SMP\(({.+?})\)'):
  626. embed_url = match.get('playerSettings', {}).get('externalEmbedUrl')
  627. if embed_url and re.match(EMBED_URL, embed_url):
  628. entries.append(embed_url)
  629. entries.extend(re.findall(
  630. r'setPlaylist\("(%s)"\)' % EMBED_URL, webpage))
  631. if entries:
  632. return self.playlist_result(
  633. [self.url_result(entry, 'BBCCoUk') for entry in entries],
  634. playlist_id, playlist_title, playlist_description)
  635. # Multiple video article (e.g. http://www.bbc.com/news/world-europe-32668511)
  636. medias = extract_all(r"data-media-meta='({[^']+})'")
  637. if not medias:
  638. # Single video article (e.g. http://www.bbc.com/news/video_and_audio/international)
  639. media_asset_page = self._parse_json(
  640. self._search_regex(
  641. r'mediaAssetPage\.init\(\s*({.+?}), "/', webpage, 'media asset'),
  642. playlist_id)
  643. medias = []
  644. for video in media_asset_page.get('videos', {}).values():
  645. medias.extend(video.values())
  646. entries = []
  647. for num, media_meta in enumerate(medias, start=1):
  648. formats, subtitles = self._extract_from_media_meta(media_meta, playlist_id)
  649. if not formats:
  650. continue
  651. self._sort_formats(formats)
  652. video_id = media_meta.get('externalId')
  653. if not video_id:
  654. video_id = playlist_id if len(medias) == 1 else '%s-%s' % (playlist_id, num)
  655. title = media_meta.get('caption')
  656. if not title:
  657. title = playlist_title if len(medias) == 1 else '%s - Video %s' % (playlist_title, num)
  658. duration = int_or_none(media_meta.get('durationInSeconds')) or parse_duration(media_meta.get('duration'))
  659. images = []
  660. for image in media_meta.get('images', {}).values():
  661. images.extend(image.values())
  662. if 'image' in media_meta:
  663. images.append(media_meta['image'])
  664. thumbnails = [{
  665. 'url': image.get('href'),
  666. 'width': int_or_none(image.get('width')),
  667. 'height': int_or_none(image.get('height')),
  668. } for image in images]
  669. entries.append({
  670. 'id': video_id,
  671. 'title': title,
  672. 'thumbnails': thumbnails,
  673. 'duration': duration,
  674. 'timestamp': timestamp,
  675. 'formats': formats,
  676. 'subtitles': subtitles,
  677. })
  678. return self.playlist_result(entries, playlist_id, playlist_title, playlist_description)