120 lines
2.4 KiB
Lua
120 lines
2.4 KiB
Lua
local json = require('cjson')
|
|
local cURL = require("cURL")
|
|
local date = require("date")
|
|
local log = require('utils.log')
|
|
local config = require('config.replicate')
|
|
local url = require('utils.url')
|
|
|
|
local _M = {}
|
|
|
|
_M.result = nil
|
|
_M.base = config.url
|
|
_M.format = config.format
|
|
|
|
log.outfile = 'logs/replicate_'..os.date('%Y-%m-%d')..'.log'
|
|
log.level = 'trace'
|
|
|
|
function query(data)
|
|
if not data then return '' end
|
|
local str = '?'
|
|
for k,v in pairs(data) do str = str..'&'..k..'='..v end
|
|
return str
|
|
end
|
|
|
|
local function get_result(str,url)
|
|
local result, err = pcall(json.decode,str)
|
|
if result then
|
|
_M.result = json.decode(str)
|
|
if _M.result.status and _M.result.status == 'error' then
|
|
log.error(url..':'..json.encode(_M.result.error))
|
|
return nil, _M.result.error
|
|
end
|
|
else
|
|
log.error(url..':'..err)
|
|
return nil, err
|
|
end
|
|
return _M.result
|
|
end
|
|
|
|
local function poster(data)
|
|
if data then
|
|
local result = {}
|
|
for i,k in pairs(data) do table.insert(result, i..'='..k) end
|
|
return table.concat(result,'&')
|
|
end
|
|
end
|
|
|
|
function _M.get(url,data)
|
|
local str = ''
|
|
url = _M.base..url..query(data)
|
|
local headers = {
|
|
'Content-type: application/json',
|
|
'Accept: application/json'
|
|
}
|
|
local c = cURL.easy{
|
|
url = url,
|
|
httpheader = headers,
|
|
writefunction = function(st)
|
|
str = str..st
|
|
collectgarbage("collect")
|
|
return #st
|
|
end
|
|
}
|
|
local ok, err = c:perform()
|
|
local code = c:getinfo_response_code()
|
|
c:close()
|
|
if not ok then return nil, err end
|
|
if code ~= 200 then
|
|
log.error(url..':'..str)
|
|
return nil,str
|
|
end
|
|
if _M.format == 'json' then
|
|
res,err = get_result(str,url,full)
|
|
else
|
|
res = str
|
|
end
|
|
if not res then return nil,err end
|
|
return res
|
|
end
|
|
|
|
function _M.post(url,data,add)
|
|
local str = ''
|
|
url = _M.base..url..query(add)
|
|
local headers = {
|
|
'Content-type: application/x-www-form-urlencoded',
|
|
'Accept: application/json'
|
|
}
|
|
local c = cURL.easy{
|
|
url = url,
|
|
post = true,
|
|
postfields = poster(data),
|
|
httpheader = headers,
|
|
writefunction = function(st)
|
|
str = str..st
|
|
collectgarbage("collect")
|
|
return #st
|
|
end
|
|
}
|
|
local ok, err = c:perform()
|
|
local code = c:getinfo_response_code()
|
|
c:close()
|
|
if not ok then return nil, err end
|
|
if code ~= 200 then
|
|
log.error(url..':'..str)
|
|
return nil,str
|
|
end
|
|
if _M.format == 'json' then
|
|
res,err = get_result(str,url,full)
|
|
else
|
|
res = str
|
|
end
|
|
if not res then return nil,err end
|
|
return res
|
|
end
|
|
|
|
function _M.predictions(data)
|
|
return _M.post('predictions',data)
|
|
end
|
|
|
|
return _M
|