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.

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