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.

780 lines
32 KiB

10 years ago
10 years ago
10 years ago
10 years ago
10 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 from video playlist embedded with vxp-playlist-data JSON
  487. 'url': 'http://www.bbc.com/news/video_and_audio/must_see/33376376',
  488. 'info_dict': {
  489. 'id': 'p02w6qjc',
  490. 'ext': 'mp4',
  491. 'title': '''Judge Mindy Glazer: "I'm sorry to see you here... I always wondered what happened to you"''',
  492. 'duration': 56,
  493. },
  494. 'params': {
  495. 'skip_download': True,
  496. }
  497. }, {
  498. # single video story with digitalData
  499. 'url': 'http://www.bbc.com/travel/story/20150625-sri-lankas-spicy-secret',
  500. 'info_dict': {
  501. 'id': 'p02q6gc4',
  502. 'ext': 'flv',
  503. 'title': 'Sri Lanka’s spicy secret',
  504. 'description': 'As a new train line to Jaffna opens up the country’s north, travellers can experience a truly distinct slice of Tamil culture.',
  505. 'timestamp': 1437674293,
  506. 'upload_date': '20150723',
  507. },
  508. 'params': {
  509. # rtmp download
  510. 'skip_download': True,
  511. }
  512. }, {
  513. # single video story without digitalData
  514. 'url': 'http://www.bbc.com/autos/story/20130513-hyundais-rock-star',
  515. 'info_dict': {
  516. 'id': 'p018zqqg',
  517. 'ext': 'mp4',
  518. 'title': 'Hyundai Santa Fe Sport: Rock star',
  519. 'description': 'md5:b042a26142c4154a6e472933cf20793d',
  520. 'timestamp': 1368473503,
  521. 'upload_date': '20130513',
  522. },
  523. 'params': {
  524. # rtmp download
  525. 'skip_download': True,
  526. }
  527. }, {
  528. # single video with playlist.sxml URL
  529. 'url': 'http://www.bbc.com/sport/0/football/33653409',
  530. 'info_dict': {
  531. 'id': 'p02xycnp',
  532. 'ext': 'mp4',
  533. 'title': 'Transfers: Cristiano Ronaldo to Man Utd, Arsenal to spend?',
  534. 'description': 'md5:398fca0e2e701c609d726e034fa1fc89',
  535. 'duration': 140,
  536. },
  537. 'params': {
  538. # rtmp download
  539. 'skip_download': True,
  540. }
  541. }, {
  542. # single video with playlist URL from weather section
  543. 'url': 'http://www.bbc.com/weather/features/33601775',
  544. 'only_matching': True,
  545. }, {
  546. # custom redirection to www.bbc.com
  547. 'url': 'http://www.bbc.co.uk/news/science-environment-33661876',
  548. 'only_matching': True,
  549. }]
  550. @classmethod
  551. def suitable(cls, url):
  552. return False if BBCCoUkIE.suitable(url) else super(BBCIE, cls).suitable(url)
  553. def _extract_from_media_meta(self, media_meta, video_id):
  554. # Direct links to media in media metadata (e.g.
  555. # http://www.bbc.com/turkce/haberler/2015/06/150615_telabyad_kentin_cogu)
  556. # TODO: there are also f4m and m3u8 streams incorporated in playlist.sxml
  557. source_files = media_meta.get('sourceFiles')
  558. if source_files:
  559. return [{
  560. 'url': f['url'],
  561. 'format_id': format_id,
  562. 'ext': f.get('encoding'),
  563. 'tbr': float_or_none(f.get('bitrate'), 1000),
  564. 'filesize': int_or_none(f.get('filesize')),
  565. } for format_id, f in source_files.items() if f.get('url')], []
  566. programme_id = media_meta.get('externalId')
  567. if programme_id:
  568. return self._download_media_selector(programme_id)
  569. # Process playlist.sxml as legacy playlist
  570. href = media_meta.get('href')
  571. if href:
  572. playlist = self._download_legacy_playlist_url(href)
  573. _, _, _, _, formats, subtitles = self._extract_from_legacy_playlist(playlist, video_id)
  574. return formats, subtitles
  575. return [], []
  576. def _real_extract(self, url):
  577. playlist_id = self._match_id(url)
  578. webpage = self._download_webpage(url, playlist_id)
  579. timestamp = parse_iso8601(self._search_regex(
  580. [r'"datePublished":\s*"([^"]+)',
  581. r'<meta[^>]+property="article:published_time"[^>]+content="([^"]+)"',
  582. r'itemprop="datePublished"[^>]+datetime="([^"]+)"'],
  583. webpage, 'date', default=None))
  584. # single video with playlist.sxml URL (e.g. http://www.bbc.com/sport/0/football/3365340ng)
  585. playlist = self._search_regex(
  586. r'<param[^>]+name="playlist"[^>]+value="([^"]+)"',
  587. webpage, 'playlist', default=None)
  588. if playlist:
  589. programme_id, title, description, duration, formats, subtitles = \
  590. self._process_legacy_playlist_url(playlist, playlist_id)
  591. self._sort_formats(formats)
  592. return {
  593. 'id': programme_id,
  594. 'title': title,
  595. 'description': description,
  596. 'duration': duration,
  597. 'timestamp': timestamp,
  598. 'formats': formats,
  599. 'subtitles': subtitles,
  600. }
  601. # single video story (e.g. http://www.bbc.com/travel/story/20150625-sri-lankas-spicy-secret)
  602. programme_id = self._search_regex(
  603. [r'data-video-player-vpid="([\da-z]{8})"',
  604. r'<param[^>]+name="externalIdentifier"[^>]+value="([\da-z]{8})"'],
  605. webpage, 'vpid', default=None)
  606. if programme_id:
  607. formats, subtitles = self._download_media_selector(programme_id)
  608. self._sort_formats(formats)
  609. # digitalData may be missing (e.g. http://www.bbc.com/autos/story/20130513-hyundais-rock-star)
  610. digital_data = self._parse_json(
  611. self._search_regex(
  612. r'var\s+digitalData\s*=\s*({.+?});?\n', webpage, 'digital data', default='{}'),
  613. programme_id, fatal=False)
  614. page_info = digital_data.get('page', {}).get('pageInfo', {})
  615. title = page_info.get('pageName') or self._og_search_title(webpage)
  616. description = page_info.get('description') or self._og_search_description(webpage)
  617. timestamp = parse_iso8601(page_info.get('publicationDate')) or timestamp
  618. return {
  619. 'id': programme_id,
  620. 'title': title,
  621. 'description': description,
  622. 'timestamp': timestamp,
  623. 'formats': formats,
  624. 'subtitles': subtitles,
  625. }
  626. playlist_title = self._html_search_regex(
  627. r'<title>(.*?)(?:\s*-\s*BBC [^ ]+)?</title>', webpage, 'playlist title')
  628. playlist_description = self._og_search_description(webpage, default=None)
  629. def extract_all(pattern):
  630. return list(filter(None, map(
  631. lambda s: self._parse_json(s, playlist_id, fatal=False),
  632. re.findall(pattern, webpage))))
  633. # Multiple video article (e.g.
  634. # http://www.bbc.co.uk/blogs/adamcurtis/entries/3662a707-0af9-3149-963f-47bea720b460)
  635. EMBED_URL = r'https?://(?:www\.)?bbc\.co\.uk/(?:[^/]+/)+[\da-z]{8}(?:\b[^"]+)?'
  636. entries = []
  637. for match in extract_all(r'new\s+SMP\(({.+?})\)'):
  638. embed_url = match.get('playerSettings', {}).get('externalEmbedUrl')
  639. if embed_url and re.match(EMBED_URL, embed_url):
  640. entries.append(embed_url)
  641. entries.extend(re.findall(
  642. r'setPlaylist\("(%s)"\)' % EMBED_URL, webpage))
  643. if entries:
  644. return self.playlist_result(
  645. [self.url_result(entry, 'BBCCoUk') for entry in entries],
  646. playlist_id, playlist_title, playlist_description)
  647. # Multiple video article (e.g. http://www.bbc.com/news/world-europe-32668511)
  648. medias = extract_all(r"data-media-meta='({[^']+})'")
  649. if not medias:
  650. # Single video article (e.g. http://www.bbc.com/news/video_and_audio/international)
  651. media_asset = self._search_regex(
  652. r'mediaAssetPage\.init\(\s*({.+?}), "/',
  653. webpage, 'media asset', default=None)
  654. if media_asset:
  655. media_asset_page = self._parse_json(media_asset, playlist_id, fatal=False)
  656. medias = []
  657. for video in media_asset_page.get('videos', {}).values():
  658. medias.extend(video.values())
  659. if not medias:
  660. # Multiple video playlist with single `now playing` entry (e.g.
  661. # http://www.bbc.com/news/video_and_audio/must_see/33767813)
  662. vxp_playlist = self._parse_json(
  663. self._search_regex(
  664. r'<script[^>]+class="vxp-playlist-data"[^>]+type="application/json"[^>]*>([^<]+)</script>',
  665. webpage, 'playlist data'),
  666. playlist_id)
  667. playlist_medias = []
  668. for item in vxp_playlist:
  669. media = item.get('media')
  670. if not media:
  671. continue
  672. playlist_medias.append(media)
  673. # Download single video if found media with asset id matching the video id from URL
  674. if item.get('advert', {}).get('assetId') == playlist_id:
  675. medias = [media]
  676. break
  677. # Fallback to the whole playlist
  678. if not medias:
  679. medias = playlist_medias
  680. entries = []
  681. for num, media_meta in enumerate(medias, start=1):
  682. formats, subtitles = self._extract_from_media_meta(media_meta, playlist_id)
  683. if not formats:
  684. continue
  685. self._sort_formats(formats)
  686. video_id = media_meta.get('externalId')
  687. if not video_id:
  688. video_id = playlist_id if len(medias) == 1 else '%s-%s' % (playlist_id, num)
  689. title = media_meta.get('caption')
  690. if not title:
  691. title = playlist_title if len(medias) == 1 else '%s - Video %s' % (playlist_title, num)
  692. duration = int_or_none(media_meta.get('durationInSeconds')) or parse_duration(media_meta.get('duration'))
  693. images = []
  694. for image in media_meta.get('images', {}).values():
  695. images.extend(image.values())
  696. if 'image' in media_meta:
  697. images.append(media_meta['image'])
  698. thumbnails = [{
  699. 'url': image.get('href'),
  700. 'width': int_or_none(image.get('width')),
  701. 'height': int_or_none(image.get('height')),
  702. } for image in images]
  703. entries.append({
  704. 'id': video_id,
  705. 'title': title,
  706. 'thumbnails': thumbnails,
  707. 'duration': duration,
  708. 'timestamp': timestamp,
  709. 'formats': formats,
  710. 'subtitles': subtitles,
  711. })
  712. return self.playlist_result(entries, playlist_id, playlist_title, playlist_description)