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.

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