local SwarmUtils = {} local cjson = require "cjson" local curl = require "cURL.safe" SwarmUtils.SwarmAPI = "v9" SwarmUtils.version = nil local utils = {} -- Function to convert the cURL/Swarm return values into something -- easier for consuming functions to use. function curlResponseFmt( url, ok, data ) local msg = "Error getting data from Swarm (" .. url .. "): " if not ok then return false, url, msg .. tostring( data ) end if data[ "error" ] ~= nil then return false, url, msg .. data[ "error" ] end return true, url, data end -- Connect to a Swarm instance and convert the JSON response to -- a table. Verifies the Swarm host's TLS certificate. function getData( address, type ) local c = curl.easy() local rsp = "" -- todo: ensure there's a trailing slash on the address local url = address .. "api/" .. SwarmUtils.SwarmAPI .. "/" .. type c:setopt( curl.OPT_URL, url ) -- Store all the data in memory in the 'rsp' variable. c:setopt( curl.OPT_WRITEFUNCTION, function( chunk ) rsp = rsp .. chunk end ) -- https://curl.haxx.se/docs/caextract.html c:setopt_cainfo( Helix.Core.Server.GetArchDirFileName( "cacert.pem" ) ) c:setopt_useragent( utils.getID() ) c:setopt( curl.OPT_SSL_VERIFYPEER,true ); c:setopt( curl.OPT_SSL_VERIFYHOST, true ); local ok, err = c:perform() c:close() return curlResponseFmt( url, ok, ok and cjson.decode( rsp ) or err ) end function SwarmUtils.getReviews( address, author ) return getData( address, "reviews?author=" .. author ) end function SwarmUtils.checkVersion( address ) local ok, url, data = getData( address, "version" ) -- This relies on the fact that we hardcode the 'v9' API and if that doesn't -- exist, Swarm returns an error - we don't actually care about the version -- returned here - we just want to know that the API version is supported. if ok then SwarmUtils.version = data[ "version" ] end return ok end function SwarmUtils.init( us ) utils = us local url = utils.gCfgData[ "Swarm-URL" ] if url ~= nil then SwarmUtils.checkVersion( url ) end end return SwarmUtils