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.

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