bbc.py 46 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064
  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_items(self, playlist):
  222. return playlist.findall('./{%s}item' % self._EMP_PLAYLIST_NS)
  223. def _findall_ns(self, element, xpath):
  224. elements = []
  225. for ns in self._NAMESPACES:
  226. elements.extend(element.findall(xpath % ns))
  227. return elements
  228. def _extract_medias(self, media_selection):
  229. error = media_selection.find('./{%s}error' % self._MEDIASELECTION_NS)
  230. if error is None:
  231. media_selection.find('./{%s}error' % self._EMP_PLAYLIST_NS)
  232. if error is not None:
  233. raise BBCCoUkIE.MediaSelectionError(error.get('id'))
  234. return self._findall_ns(media_selection, './{%s}media')
  235. def _extract_connections(self, media):
  236. return self._findall_ns(media, './{%s}connection')
  237. def _get_subtitles(self, media, programme_id):
  238. subtitles = {}
  239. for connection in self._extract_connections(media):
  240. captions = self._download_xml(connection.get('href'), programme_id, 'Downloading captions')
  241. lang = captions.get('{http://www.w3.org/XML/1998/namespace}lang', 'en')
  242. subtitles[lang] = [
  243. {
  244. 'url': connection.get('href'),
  245. 'ext': 'ttml',
  246. },
  247. ]
  248. return subtitles
  249. def _raise_extractor_error(self, media_selection_error):
  250. raise ExtractorError(
  251. '%s returned error: %s' % (self.IE_NAME, media_selection_error.id),
  252. expected=True)
  253. def _download_media_selector(self, programme_id):
  254. last_exception = None
  255. for mediaselector_url in self._MEDIASELECTOR_URLS:
  256. try:
  257. return self._download_media_selector_url(
  258. mediaselector_url % programme_id, programme_id)
  259. except BBCCoUkIE.MediaSelectionError as e:
  260. if e.id in ('notukerror', 'geolocation', 'selectionunavailable'):
  261. last_exception = e
  262. continue
  263. self._raise_extractor_error(e)
  264. self._raise_extractor_error(last_exception)
  265. def _download_media_selector_url(self, url, programme_id=None):
  266. try:
  267. media_selection = self._download_xml(
  268. url, programme_id, 'Downloading media selection XML')
  269. except ExtractorError as ee:
  270. if isinstance(ee.cause, compat_HTTPError) and ee.cause.code in (403, 404):
  271. media_selection = compat_etree_fromstring(ee.cause.read().decode('utf-8'))
  272. else:
  273. raise
  274. return self._process_media_selector(media_selection, programme_id)
  275. def _process_media_selector(self, media_selection, programme_id):
  276. formats = []
  277. subtitles = None
  278. for media in self._extract_medias(media_selection):
  279. kind = media.get('kind')
  280. if kind in ('video', 'audio'):
  281. bitrate = int_or_none(media.get('bitrate'))
  282. encoding = media.get('encoding')
  283. service = media.get('service')
  284. width = int_or_none(media.get('width'))
  285. height = int_or_none(media.get('height'))
  286. file_size = int_or_none(media.get('media_file_size'))
  287. for connection in self._extract_connections(media):
  288. conn_kind = connection.get('kind')
  289. protocol = connection.get('protocol')
  290. supplier = connection.get('supplier')
  291. href = connection.get('href')
  292. transfer_format = connection.get('transferFormat')
  293. format_id = supplier or conn_kind or protocol
  294. if service:
  295. format_id = '%s_%s' % (service, format_id)
  296. # ASX playlist
  297. if supplier == 'asx':
  298. for i, ref in enumerate(self._extract_asx_playlist(connection, programme_id)):
  299. formats.append({
  300. 'url': ref,
  301. 'format_id': 'ref%s_%s' % (i, format_id),
  302. })
  303. elif transfer_format == 'dash':
  304. formats.extend(self._extract_mpd_formats(
  305. href, programme_id, mpd_id=format_id, fatal=False))
  306. elif transfer_format == 'hls':
  307. formats.extend(self._extract_m3u8_formats(
  308. href, programme_id, ext='mp4', entry_protocol='m3u8_native',
  309. m3u8_id=format_id, fatal=False))
  310. elif transfer_format == 'hds':
  311. formats.extend(self._extract_f4m_formats(
  312. href, programme_id, f4m_id=format_id, fatal=False))
  313. else:
  314. fmt = {
  315. 'format_id': format_id,
  316. 'filesize': file_size,
  317. }
  318. if kind == 'video':
  319. fmt.update({
  320. 'width': width,
  321. 'height': height,
  322. 'vbr': bitrate,
  323. 'vcodec': encoding,
  324. })
  325. else:
  326. fmt.update({
  327. 'abr': bitrate,
  328. 'acodec': encoding,
  329. 'vcodec': 'none',
  330. })
  331. if protocol == 'http':
  332. # Direct link
  333. fmt.update({
  334. 'url': href,
  335. })
  336. elif protocol == 'rtmp':
  337. application = connection.get('application', 'ondemand')
  338. auth_string = connection.get('authString')
  339. identifier = connection.get('identifier')
  340. server = connection.get('server')
  341. fmt.update({
  342. 'url': '%s://%s/%s?%s' % (protocol, server, application, auth_string),
  343. 'play_path': identifier,
  344. 'app': '%s?%s' % (application, auth_string),
  345. 'page_url': 'http://www.bbc.co.uk',
  346. 'player_url': 'http://www.bbc.co.uk/emp/releases/iplayer/revisions/617463_618125_4/617463_618125_4_emp.swf',
  347. 'rtmp_live': False,
  348. 'ext': 'flv',
  349. })
  350. formats.append(fmt)
  351. elif kind == 'captions':
  352. subtitles = self.extract_subtitles(media, programme_id)
  353. return formats, subtitles
  354. def _download_playlist(self, playlist_id):
  355. try:
  356. playlist = self._download_json(
  357. 'http://www.bbc.co.uk/programmes/%s/playlist.json' % playlist_id,
  358. playlist_id, 'Downloading playlist JSON')
  359. version = playlist.get('defaultAvailableVersion')
  360. if version:
  361. smp_config = version['smpConfig']
  362. title = smp_config['title']
  363. description = smp_config['summary']
  364. for item in smp_config['items']:
  365. kind = item['kind']
  366. if kind != 'programme' and kind != 'radioProgramme':
  367. continue
  368. programme_id = item.get('vpid')
  369. duration = int_or_none(item.get('duration'))
  370. formats, subtitles = self._download_media_selector(programme_id)
  371. return programme_id, title, description, duration, formats, subtitles
  372. except ExtractorError as ee:
  373. if not (isinstance(ee.cause, compat_HTTPError) and ee.cause.code == 404):
  374. raise
  375. # fallback to legacy playlist
  376. return self._process_legacy_playlist(playlist_id)
  377. def _process_legacy_playlist_url(self, url, display_id):
  378. playlist = self._download_legacy_playlist_url(url, display_id)
  379. return self._extract_from_legacy_playlist(playlist, display_id)
  380. def _process_legacy_playlist(self, playlist_id):
  381. return self._process_legacy_playlist_url(
  382. 'http://www.bbc.co.uk/iplayer/playlist/%s' % playlist_id, playlist_id)
  383. def _download_legacy_playlist_url(self, url, playlist_id=None):
  384. return self._download_xml(
  385. url, playlist_id, 'Downloading legacy playlist XML')
  386. def _extract_from_legacy_playlist(self, playlist, playlist_id):
  387. no_items = playlist.find('./{%s}noItems' % self._EMP_PLAYLIST_NS)
  388. if no_items is not None:
  389. reason = no_items.get('reason')
  390. if reason == 'preAvailability':
  391. msg = 'Episode %s is not yet available' % playlist_id
  392. elif reason == 'postAvailability':
  393. msg = 'Episode %s is no longer available' % playlist_id
  394. elif reason == 'noMedia':
  395. msg = 'Episode %s is not currently available' % playlist_id
  396. else:
  397. msg = 'Episode %s is not available: %s' % (playlist_id, reason)
  398. raise ExtractorError(msg, expected=True)
  399. for item in self._extract_items(playlist):
  400. kind = item.get('kind')
  401. if kind != 'programme' and kind != 'radioProgramme':
  402. continue
  403. title = playlist.find('./{%s}title' % self._EMP_PLAYLIST_NS).text
  404. description_el = playlist.find('./{%s}summary' % self._EMP_PLAYLIST_NS)
  405. description = description_el.text if description_el is not None else None
  406. def get_programme_id(item):
  407. def get_from_attributes(item):
  408. for p in('identifier', 'group'):
  409. value = item.get(p)
  410. if value and re.match(r'^[pb][\da-z]{7}$', value):
  411. return value
  412. get_from_attributes(item)
  413. mediator = item.find('./{%s}mediator' % self._EMP_PLAYLIST_NS)
  414. if mediator is not None:
  415. return get_from_attributes(mediator)
  416. programme_id = get_programme_id(item)
  417. duration = int_or_none(item.get('duration'))
  418. if programme_id:
  419. formats, subtitles = self._download_media_selector(programme_id)
  420. else:
  421. formats, subtitles = self._process_media_selector(item, playlist_id)
  422. programme_id = playlist_id
  423. return programme_id, title, description, duration, formats, subtitles
  424. def _real_extract(self, url):
  425. group_id = self._match_id(url)
  426. webpage = self._download_webpage(url, group_id, 'Downloading video page')
  427. programme_id = None
  428. duration = None
  429. tviplayer = self._search_regex(
  430. r'mediator\.bind\(({.+?})\s*,\s*document\.getElementById',
  431. webpage, 'player', default=None)
  432. if tviplayer:
  433. player = self._parse_json(tviplayer, group_id).get('player', {})
  434. duration = int_or_none(player.get('duration'))
  435. programme_id = player.get('vpid')
  436. if not programme_id:
  437. programme_id = self._search_regex(
  438. r'"vpid"\s*:\s*"(%s)"' % self._ID_REGEX, webpage, 'vpid', fatal=False, default=None)
  439. if programme_id:
  440. formats, subtitles = self._download_media_selector(programme_id)
  441. title = self._og_search_title(webpage, default=None) or self._html_search_regex(
  442. (r'<h2[^>]+id="parent-title"[^>]*>(.+?)</h2>',
  443. r'<div[^>]+class="info"[^>]*>\s*<h1>(.+?)</h1>'), webpage, 'title')
  444. description = self._search_regex(
  445. (r'<p class="[^"]*medium-description[^"]*">([^<]+)</p>',
  446. r'<div[^>]+class="info_+synopsis"[^>]*>([^<]+)</div>'),
  447. webpage, 'description', default=None)
  448. if not description:
  449. description = self._html_search_meta('description', webpage)
  450. else:
  451. programme_id, title, description, duration, formats, subtitles = self._download_playlist(group_id)
  452. self._sort_formats(formats)
  453. return {
  454. 'id': programme_id,
  455. 'title': title,
  456. 'description': description,
  457. 'thumbnail': self._og_search_thumbnail(webpage, default=None),
  458. 'duration': duration,
  459. 'formats': formats,
  460. 'subtitles': subtitles,
  461. }
  462. class BBCIE(BBCCoUkIE):
  463. IE_NAME = 'bbc'
  464. IE_DESC = 'BBC'
  465. _VALID_URL = r'https?://(?:www\.)?bbc\.(?:com|co\.uk)/(?:[^/]+/)+(?P<id>[^/#?]+)'
  466. _MEDIASELECTOR_URLS = [
  467. # Provides HQ HLS streams but fails with geolocation in some cases when it's
  468. # even not geo restricted at all
  469. 'http://open.live.bbc.co.uk/mediaselector/5/select/version/2.0/mediaset/iptv-all/vpid/%s',
  470. # Provides more formats, namely direct mp4 links, but fails on some videos with
  471. # notukerror for non UK (?) users (e.g.
  472. # http://www.bbc.com/travel/story/20150625-sri-lankas-spicy-secret)
  473. 'http://open.live.bbc.co.uk/mediaselector/4/mtis/stream/%s',
  474. # Provides fewer formats, but works everywhere for everybody (hopefully)
  475. 'http://open.live.bbc.co.uk/mediaselector/5/select/version/2.0/mediaset/journalism-pc/vpid/%s',
  476. ]
  477. _TESTS = [{
  478. # article with multiple videos embedded with data-playable containing vpids
  479. 'url': 'http://www.bbc.com/news/world-europe-32668511',
  480. 'info_dict': {
  481. 'id': 'world-europe-32668511',
  482. 'title': 'Russia stages massive WW2 parade despite Western boycott',
  483. 'description': 'md5:00ff61976f6081841f759a08bf78cc9c',
  484. },
  485. 'playlist_count': 2,
  486. }, {
  487. # article with multiple videos embedded with data-playable (more videos)
  488. 'url': 'http://www.bbc.com/news/business-28299555',
  489. 'info_dict': {
  490. 'id': 'business-28299555',
  491. 'title': 'Farnborough Airshow: Video highlights',
  492. 'description': 'BBC reports and video highlights at the Farnborough Airshow.',
  493. },
  494. 'playlist_count': 9,
  495. 'skip': 'Save time',
  496. }, {
  497. # article with multiple videos embedded with `new SMP()`
  498. # broken
  499. 'url': 'http://www.bbc.co.uk/blogs/adamcurtis/entries/3662a707-0af9-3149-963f-47bea720b460',
  500. 'info_dict': {
  501. 'id': '3662a707-0af9-3149-963f-47bea720b460',
  502. 'title': 'BUGGER',
  503. },
  504. 'playlist_count': 18,
  505. }, {
  506. # single video embedded with data-playable containing vpid
  507. 'url': 'http://www.bbc.com/news/world-europe-32041533',
  508. 'info_dict': {
  509. 'id': 'p02mprgb',
  510. 'ext': 'mp4',
  511. 'title': 'Aerial footage showed the site of the crash in the Alps - courtesy BFM TV',
  512. 'description': 'md5:2868290467291b37feda7863f7a83f54',
  513. 'duration': 47,
  514. 'timestamp': 1427219242,
  515. 'upload_date': '20150324',
  516. },
  517. 'params': {
  518. # rtmp download
  519. 'skip_download': True,
  520. }
  521. }, {
  522. # article with single video embedded with data-playable containing XML playlist
  523. # with direct video links as progressiveDownloadUrl (for now these are extracted)
  524. # and playlist with f4m and m3u8 as streamingUrl
  525. 'url': 'http://www.bbc.com/turkce/haberler/2015/06/150615_telabyad_kentin_cogu',
  526. 'info_dict': {
  527. 'id': '150615_telabyad_kentin_cogu',
  528. 'ext': 'mp4',
  529. 'title': "Tel Abyad'da IŞİD bayrağı indirildi YPG bayrağı çekildi",
  530. 'description': 'md5:33a4805a855c9baf7115fcbde57e7025',
  531. 'timestamp': 1434397334,
  532. 'upload_date': '20150615',
  533. },
  534. 'params': {
  535. 'skip_download': True,
  536. }
  537. }, {
  538. # single video embedded with data-playable containing XML playlists (regional section)
  539. 'url': 'http://www.bbc.com/mundo/video_fotos/2015/06/150619_video_honduras_militares_hospitales_corrupcion_aw',
  540. 'info_dict': {
  541. 'id': '150619_video_honduras_militares_hospitales_corrupcion_aw',
  542. 'ext': 'mp4',
  543. 'title': 'Honduras militariza sus hospitales por nuevo escándalo de corrupción',
  544. 'description': 'md5:1525f17448c4ee262b64b8f0c9ce66c8',
  545. 'timestamp': 1434713142,
  546. 'upload_date': '20150619',
  547. },
  548. 'params': {
  549. 'skip_download': True,
  550. }
  551. }, {
  552. # single video from video playlist embedded with vxp-playlist-data JSON
  553. 'url': 'http://www.bbc.com/news/video_and_audio/must_see/33376376',
  554. 'info_dict': {
  555. 'id': 'p02w6qjc',
  556. 'ext': 'mp4',
  557. 'title': '''Judge Mindy Glazer: "I'm sorry to see you here... I always wondered what happened to you"''',
  558. 'duration': 56,
  559. 'description': '''Judge Mindy Glazer: "I'm sorry to see you here... I always wondered what happened to you"''',
  560. },
  561. 'params': {
  562. 'skip_download': True,
  563. }
  564. }, {
  565. # single video story with digitalData
  566. 'url': 'http://www.bbc.com/travel/story/20150625-sri-lankas-spicy-secret',
  567. 'info_dict': {
  568. 'id': 'p02q6gc4',
  569. 'ext': 'flv',
  570. 'title': 'Sri Lanka’s spicy secret',
  571. 'description': 'As a new train line to Jaffna opens up the country’s north, travellers can experience a truly distinct slice of Tamil culture.',
  572. 'timestamp': 1437674293,
  573. 'upload_date': '20150723',
  574. },
  575. 'params': {
  576. # rtmp download
  577. 'skip_download': True,
  578. }
  579. }, {
  580. # single video story without digitalData
  581. 'url': 'http://www.bbc.com/autos/story/20130513-hyundais-rock-star',
  582. 'info_dict': {
  583. 'id': 'p018zqqg',
  584. 'ext': 'mp4',
  585. 'title': 'Hyundai Santa Fe Sport: Rock star',
  586. 'description': 'md5:b042a26142c4154a6e472933cf20793d',
  587. 'timestamp': 1415867444,
  588. 'upload_date': '20141113',
  589. },
  590. 'params': {
  591. # rtmp download
  592. 'skip_download': True,
  593. }
  594. }, {
  595. # single video with playlist.sxml URL in playlist param
  596. 'url': 'http://www.bbc.com/sport/0/football/33653409',
  597. 'info_dict': {
  598. 'id': 'p02xycnp',
  599. 'ext': 'mp4',
  600. 'title': 'Transfers: Cristiano Ronaldo to Man Utd, Arsenal to spend?',
  601. 'description': 'BBC Sport\'s David Ornstein has the latest transfer gossip, including rumours of a Manchester United return for Cristiano Ronaldo.',
  602. 'duration': 140,
  603. },
  604. 'params': {
  605. # rtmp download
  606. 'skip_download': True,
  607. }
  608. }, {
  609. # article with multiple videos embedded with playlist.sxml in playlist param
  610. 'url': 'http://www.bbc.com/sport/0/football/34475836',
  611. 'info_dict': {
  612. 'id': '34475836',
  613. 'title': 'Jurgen Klopp: Furious football from a witty and winning coach',
  614. 'description': 'Fast-paced football, wit, wisdom and a ready smile - why Liverpool fans should come to love new boss Jurgen Klopp.',
  615. },
  616. 'playlist_count': 3,
  617. }, {
  618. # school report article with single video
  619. 'url': 'http://www.bbc.co.uk/schoolreport/35744779',
  620. 'info_dict': {
  621. 'id': '35744779',
  622. 'title': 'School which breaks down barriers in Jerusalem',
  623. },
  624. 'playlist_count': 1,
  625. }, {
  626. # single video with playlist URL from weather section
  627. 'url': 'http://www.bbc.com/weather/features/33601775',
  628. 'only_matching': True,
  629. }, {
  630. # custom redirection to www.bbc.com
  631. 'url': 'http://www.bbc.co.uk/news/science-environment-33661876',
  632. 'only_matching': True,
  633. }, {
  634. # single video article embedded with data-media-vpid
  635. 'url': 'http://www.bbc.co.uk/sport/rowing/35908187',
  636. 'only_matching': True,
  637. }]
  638. @classmethod
  639. def suitable(cls, url):
  640. EXCLUDE_IE = (BBCCoUkIE, BBCCoUkArticleIE, BBCCoUkIPlayerPlaylistIE, BBCCoUkPlaylistIE)
  641. return (False if any(ie.suitable(url) for ie in EXCLUDE_IE)
  642. else super(BBCIE, cls).suitable(url))
  643. def _extract_from_media_meta(self, media_meta, video_id):
  644. # Direct links to media in media metadata (e.g.
  645. # http://www.bbc.com/turkce/haberler/2015/06/150615_telabyad_kentin_cogu)
  646. # TODO: there are also f4m and m3u8 streams incorporated in playlist.sxml
  647. source_files = media_meta.get('sourceFiles')
  648. if source_files:
  649. return [{
  650. 'url': f['url'],
  651. 'format_id': format_id,
  652. 'ext': f.get('encoding'),
  653. 'tbr': float_or_none(f.get('bitrate'), 1000),
  654. 'filesize': int_or_none(f.get('filesize')),
  655. } for format_id, f in source_files.items() if f.get('url')], []
  656. programme_id = media_meta.get('externalId')
  657. if programme_id:
  658. return self._download_media_selector(programme_id)
  659. # Process playlist.sxml as legacy playlist
  660. href = media_meta.get('href')
  661. if href:
  662. playlist = self._download_legacy_playlist_url(href)
  663. _, _, _, _, formats, subtitles = self._extract_from_legacy_playlist(playlist, video_id)
  664. return formats, subtitles
  665. return [], []
  666. def _extract_from_playlist_sxml(self, url, playlist_id, timestamp):
  667. programme_id, title, description, duration, formats, subtitles = \
  668. self._process_legacy_playlist_url(url, playlist_id)
  669. self._sort_formats(formats)
  670. return {
  671. 'id': programme_id,
  672. 'title': title,
  673. 'description': description,
  674. 'duration': duration,
  675. 'timestamp': timestamp,
  676. 'formats': formats,
  677. 'subtitles': subtitles,
  678. }
  679. def _real_extract(self, url):
  680. playlist_id = self._match_id(url)
  681. webpage = self._download_webpage(url, playlist_id)
  682. json_ld_info = self._search_json_ld(webpage, playlist_id, default=None)
  683. timestamp = json_ld_info.get('timestamp')
  684. playlist_title = json_ld_info.get('title')
  685. if not playlist_title:
  686. playlist_title = self._og_search_title(
  687. webpage, default=None) or self._html_search_regex(
  688. r'<title>(.+?)</title>', webpage, 'playlist title', default=None)
  689. if playlist_title:
  690. playlist_title = re.sub(r'(.+)\s*-\s*BBC.*?$', r'\1', playlist_title).strip()
  691. playlist_description = json_ld_info.get(
  692. 'description') or self._og_search_description(webpage, default=None)
  693. if not timestamp:
  694. timestamp = parse_iso8601(self._search_regex(
  695. [r'<meta[^>]+property="article:published_time"[^>]+content="([^"]+)"',
  696. r'itemprop="datePublished"[^>]+datetime="([^"]+)"',
  697. r'"datePublished":\s*"([^"]+)'],
  698. webpage, 'date', default=None))
  699. entries = []
  700. # article with multiple videos embedded with playlist.sxml (e.g.
  701. # http://www.bbc.com/sport/0/football/34475836)
  702. playlists = re.findall(r'<param[^>]+name="playlist"[^>]+value="([^"]+)"', webpage)
  703. playlists.extend(re.findall(r'data-media-id="([^"]+/playlist\.sxml)"', webpage))
  704. if playlists:
  705. entries = [
  706. self._extract_from_playlist_sxml(playlist_url, playlist_id, timestamp)
  707. for playlist_url in playlists]
  708. # news article with multiple videos embedded with data-playable
  709. data_playables = re.findall(r'data-playable=(["\'])({.+?})\1', webpage)
  710. if data_playables:
  711. for _, data_playable_json in data_playables:
  712. data_playable = self._parse_json(
  713. unescapeHTML(data_playable_json), playlist_id, fatal=False)
  714. if not data_playable:
  715. continue
  716. settings = data_playable.get('settings', {})
  717. if settings:
  718. # data-playable with video vpid in settings.playlistObject.items (e.g.
  719. # http://www.bbc.com/news/world-us-canada-34473351)
  720. playlist_object = settings.get('playlistObject', {})
  721. if playlist_object:
  722. items = playlist_object.get('items')
  723. if items and isinstance(items, list):
  724. title = playlist_object['title']
  725. description = playlist_object.get('summary')
  726. duration = int_or_none(items[0].get('duration'))
  727. programme_id = items[0].get('vpid')
  728. formats, subtitles = self._download_media_selector(programme_id)
  729. self._sort_formats(formats)
  730. entries.append({
  731. 'id': programme_id,
  732. 'title': title,
  733. 'description': description,
  734. 'timestamp': timestamp,
  735. 'duration': duration,
  736. 'formats': formats,
  737. 'subtitles': subtitles,
  738. })
  739. else:
  740. # data-playable without vpid but with a playlist.sxml URLs
  741. # in otherSettings.playlist (e.g.
  742. # http://www.bbc.com/turkce/multimedya/2015/10/151010_vid_ankara_patlama_ani)
  743. playlist = data_playable.get('otherSettings', {}).get('playlist', {})
  744. if playlist:
  745. entry = None
  746. for key in ('streaming', 'progressiveDownload'):
  747. playlist_url = playlist.get('%sUrl' % key)
  748. if not playlist_url:
  749. continue
  750. try:
  751. info = self._extract_from_playlist_sxml(
  752. playlist_url, playlist_id, timestamp)
  753. if not entry:
  754. entry = info
  755. else:
  756. entry['title'] = info['title']
  757. entry['formats'].extend(info['formats'])
  758. except Exception as e:
  759. # Some playlist URL may fail with 500, at the same time
  760. # the other one may work fine (e.g.
  761. # http://www.bbc.com/turkce/haberler/2015/06/150615_telabyad_kentin_cogu)
  762. if isinstance(e.cause, compat_HTTPError) and e.cause.code == 500:
  763. continue
  764. raise
  765. if entry:
  766. self._sort_formats(entry['formats'])
  767. entries.append(entry)
  768. if entries:
  769. return self.playlist_result(entries, playlist_id, playlist_title, playlist_description)
  770. # single video story (e.g. http://www.bbc.com/travel/story/20150625-sri-lankas-spicy-secret)
  771. programme_id = self._search_regex(
  772. [r'data-(?:video-player|media)-vpid="(%s)"' % self._ID_REGEX,
  773. r'<param[^>]+name="externalIdentifier"[^>]+value="(%s)"' % self._ID_REGEX,
  774. r'videoId\s*:\s*["\'](%s)["\']' % self._ID_REGEX],
  775. webpage, 'vpid', default=None)
  776. if programme_id:
  777. formats, subtitles = self._download_media_selector(programme_id)
  778. self._sort_formats(formats)
  779. # digitalData may be missing (e.g. http://www.bbc.com/autos/story/20130513-hyundais-rock-star)
  780. digital_data = self._parse_json(
  781. self._search_regex(
  782. r'var\s+digitalData\s*=\s*({.+?});?\n', webpage, 'digital data', default='{}'),
  783. programme_id, fatal=False)
  784. page_info = digital_data.get('page', {}).get('pageInfo', {})
  785. title = page_info.get('pageName') or self._og_search_title(webpage)
  786. description = page_info.get('description') or self._og_search_description(webpage)
  787. timestamp = parse_iso8601(page_info.get('publicationDate')) or timestamp
  788. return {
  789. 'id': programme_id,
  790. 'title': title,
  791. 'description': description,
  792. 'timestamp': timestamp,
  793. 'formats': formats,
  794. 'subtitles': subtitles,
  795. }
  796. def extract_all(pattern):
  797. return list(filter(None, map(
  798. lambda s: self._parse_json(s, playlist_id, fatal=False),
  799. re.findall(pattern, webpage))))
  800. # Multiple video article (e.g.
  801. # http://www.bbc.co.uk/blogs/adamcurtis/entries/3662a707-0af9-3149-963f-47bea720b460)
  802. EMBED_URL = r'https?://(?:www\.)?bbc\.co\.uk/(?:[^/]+/)+%s(?:\b[^"]+)?' % self._ID_REGEX
  803. entries = []
  804. for match in extract_all(r'new\s+SMP\(({.+?})\)'):
  805. embed_url = match.get('playerSettings', {}).get('externalEmbedUrl')
  806. if embed_url and re.match(EMBED_URL, embed_url):
  807. entries.append(embed_url)
  808. entries.extend(re.findall(
  809. r'setPlaylist\("(%s)"\)' % EMBED_URL, webpage))
  810. if entries:
  811. return self.playlist_result(
  812. [self.url_result(entry, 'BBCCoUk') for entry in entries],
  813. playlist_id, playlist_title, playlist_description)
  814. # Multiple video article (e.g. http://www.bbc.com/news/world-europe-32668511)
  815. medias = extract_all(r"data-media-meta='({[^']+})'")
  816. if not medias:
  817. # Single video article (e.g. http://www.bbc.com/news/video_and_audio/international)
  818. media_asset = self._search_regex(
  819. r'mediaAssetPage\.init\(\s*({.+?}), "/',
  820. webpage, 'media asset', default=None)
  821. if media_asset:
  822. media_asset_page = self._parse_json(media_asset, playlist_id, fatal=False)
  823. medias = []
  824. for video in media_asset_page.get('videos', {}).values():
  825. medias.extend(video.values())
  826. if not medias:
  827. # Multiple video playlist with single `now playing` entry (e.g.
  828. # http://www.bbc.com/news/video_and_audio/must_see/33767813)
  829. vxp_playlist = self._parse_json(
  830. self._search_regex(
  831. r'<script[^>]+class="vxp-playlist-data"[^>]+type="application/json"[^>]*>([^<]+)</script>',
  832. webpage, 'playlist data'),
  833. playlist_id)
  834. playlist_medias = []
  835. for item in vxp_playlist:
  836. media = item.get('media')
  837. if not media:
  838. continue
  839. playlist_medias.append(media)
  840. # Download single video if found media with asset id matching the video id from URL
  841. if item.get('advert', {}).get('assetId') == playlist_id:
  842. medias = [media]
  843. break
  844. # Fallback to the whole playlist
  845. if not medias:
  846. medias = playlist_medias
  847. entries = []
  848. for num, media_meta in enumerate(medias, start=1):
  849. formats, subtitles = self._extract_from_media_meta(media_meta, playlist_id)
  850. if not formats:
  851. continue
  852. self._sort_formats(formats)
  853. video_id = media_meta.get('externalId')
  854. if not video_id:
  855. video_id = playlist_id if len(medias) == 1 else '%s-%s' % (playlist_id, num)
  856. title = media_meta.get('caption')
  857. if not title:
  858. title = playlist_title if len(medias) == 1 else '%s - Video %s' % (playlist_title, num)
  859. duration = int_or_none(media_meta.get('durationInSeconds')) or parse_duration(media_meta.get('duration'))
  860. images = []
  861. for image in media_meta.get('images', {}).values():
  862. images.extend(image.values())
  863. if 'image' in media_meta:
  864. images.append(media_meta['image'])
  865. thumbnails = [{
  866. 'url': image.get('href'),
  867. 'width': int_or_none(image.get('width')),
  868. 'height': int_or_none(image.get('height')),
  869. } for image in images]
  870. entries.append({
  871. 'id': video_id,
  872. 'title': title,
  873. 'thumbnails': thumbnails,
  874. 'duration': duration,
  875. 'timestamp': timestamp,
  876. 'formats': formats,
  877. 'subtitles': subtitles,
  878. })
  879. return self.playlist_result(entries, playlist_id, playlist_title, playlist_description)
  880. class BBCCoUkArticleIE(InfoExtractor):
  881. _VALID_URL = r'https?://www.bbc.co.uk/programmes/articles/(?P<id>[a-zA-Z0-9]+)'
  882. IE_NAME = 'bbc.co.uk:article'
  883. IE_DESC = 'BBC articles'
  884. _TEST = {
  885. 'url': 'http://www.bbc.co.uk/programmes/articles/3jNQLTMrPlYGTBn0WV6M2MS/not-your-typical-role-model-ada-lovelace-the-19th-century-programmer',
  886. 'info_dict': {
  887. 'id': '3jNQLTMrPlYGTBn0WV6M2MS',
  888. 'title': 'Calculating Ada: The Countess of Computing - Not your typical role model: Ada Lovelace the 19th century programmer - BBC Four',
  889. 'description': 'Hannah Fry reveals some of her surprising discoveries about Ada Lovelace during filming.',
  890. },
  891. 'playlist_count': 4,
  892. 'add_ie': ['BBCCoUk'],
  893. }
  894. def _real_extract(self, url):
  895. playlist_id = self._match_id(url)
  896. webpage = self._download_webpage(url, playlist_id)
  897. title = self._og_search_title(webpage)
  898. description = self._og_search_description(webpage).strip()
  899. entries = [self.url_result(programme_url) for programme_url in re.findall(
  900. r'<div[^>]+typeof="Clip"[^>]+resource="([^"]+)"', webpage)]
  901. return self.playlist_result(entries, playlist_id, title, description)
  902. class BBCCoUkPlaylistBaseIE(InfoExtractor):
  903. def _real_extract(self, url):
  904. playlist_id = self._match_id(url)
  905. webpage = self._download_webpage(url, playlist_id)
  906. entries = [
  907. self.url_result(self._URL_TEMPLATE % video_id, BBCCoUkIE.ie_key())
  908. for video_id in re.findall(
  909. self._VIDEO_ID_TEMPLATE % BBCCoUkIE._ID_REGEX, webpage)]
  910. title, description = self._extract_title_and_description(webpage)
  911. return self.playlist_result(entries, playlist_id, title, description)
  912. class BBCCoUkIPlayerPlaylistIE(BBCCoUkPlaylistBaseIE):
  913. IE_NAME = 'bbc.co.uk:iplayer:playlist'
  914. _VALID_URL = r'https?://(?:www\.)?bbc\.co\.uk/iplayer/(?:episodes|group)/(?P<id>%s)' % BBCCoUkIE._ID_REGEX
  915. _URL_TEMPLATE = 'http://www.bbc.co.uk/iplayer/episode/%s'
  916. _VIDEO_ID_TEMPLATE = r'data-ip-id=["\'](%s)'
  917. _TESTS = [{
  918. 'url': 'http://www.bbc.co.uk/iplayer/episodes/b05rcz9v',
  919. 'info_dict': {
  920. 'id': 'b05rcz9v',
  921. 'title': 'The Disappearance',
  922. 'description': 'French thriller serial about a missing teenager.',
  923. },
  924. 'playlist_mincount': 6,
  925. 'skip': 'This programme is not currently available on BBC iPlayer',
  926. }, {
  927. # Available for over a year unlike 30 days for most other programmes
  928. 'url': 'http://www.bbc.co.uk/iplayer/group/p02tcc32',
  929. 'info_dict': {
  930. 'id': 'p02tcc32',
  931. 'title': 'Bohemian Icons',
  932. 'description': 'md5:683e901041b2fe9ba596f2ab04c4dbe7',
  933. },
  934. 'playlist_mincount': 10,
  935. }]
  936. def _extract_title_and_description(self, webpage):
  937. title = self._search_regex(r'<h1>([^<]+)</h1>', webpage, 'title', fatal=False)
  938. description = self._search_regex(
  939. r'<p[^>]+class=(["\'])subtitle\1[^>]*>(?P<value>[^<]+)</p>',
  940. webpage, 'description', fatal=False, group='value')
  941. return title, description
  942. class BBCCoUkPlaylistIE(BBCCoUkPlaylistBaseIE):
  943. IE_NAME = 'bbc.co.uk:playlist'
  944. _VALID_URL = r'https?://(?:www\.)?bbc\.co\.uk/programmes/(?P<id>%s)/(?:episodes|broadcasts|clips)' % BBCCoUkIE._ID_REGEX
  945. _URL_TEMPLATE = 'http://www.bbc.co.uk/programmes/%s'
  946. _VIDEO_ID_TEMPLATE = r'data-pid=["\'](%s)'
  947. _TESTS = [{
  948. 'url': 'http://www.bbc.co.uk/programmes/b05rcz9v/clips',
  949. 'info_dict': {
  950. 'id': 'b05rcz9v',
  951. 'title': 'The Disappearance - Clips - BBC Four',
  952. 'description': 'French thriller serial about a missing teenager.',
  953. },
  954. 'playlist_mincount': 7,
  955. }, {
  956. 'url': 'http://www.bbc.co.uk/programmes/b05rcz9v/broadcasts/2016/06',
  957. 'only_matching': True,
  958. }, {
  959. 'url': 'http://www.bbc.co.uk/programmes/b05rcz9v/clips',
  960. 'only_matching': True,
  961. }, {
  962. 'url': 'http://www.bbc.co.uk/programmes/b055jkys/episodes/player',
  963. 'only_matching': True,
  964. }]
  965. def _extract_title_and_description(self, webpage):
  966. title = self._og_search_title(webpage, fatal=False)
  967. description = self._og_search_description(webpage)
  968. return title, description