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.

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