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.

939 lines
39 KiB

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