mail/util/channel.lua

94 lines
1.7 KiB
Lua
Raw Normal View History

2018-12-06 09:29:03 +01:00
-- bi-directional http-channel
-- with long-poll GET and POST on the same URL
2018-12-12 10:56:35 +01:00
local debug = false
2018-12-11 19:58:38 +01:00
2019-01-12 22:13:19 +00:00
local function Channel(http, url, cfg)
2018-12-06 09:29:03 +01:00
cfg = cfg or {}
local extra_headers = cfg.extra_headers or {}
local timeout = cfg.timeout or 1
local long_poll_timeout = cfg.long_poll_timeout or 30
local error_retry = cfg.error_retry or 10
-- assemble post-header with json content
local post_headers = { "Content-Type: application/json" }
for _,header in pairs(cfg.extra_headers) do
table.insert(post_headers, header)
end
local recv_listeners = {}
local run = true
local recv_loop
recv_loop = function()
2019-01-12 22:13:19 +00:00
assert(run)
2018-12-06 09:29:03 +01:00
-- long-poll GET
http.fetch({
url = url,
extra_headers = extra_headers,
timeout = long_poll_timeout
}, function(res)
if res.succeeded and res.code == 200 then
local data = minetest.parse_json(res.data)
2018-12-11 19:58:38 +01:00
if debug then
minetest.log("action", "[webmail-rx] " .. dump(data))
end
2018-12-06 09:29:03 +01:00
if data then
for _,listener in pairs(recv_listeners) do
listener(data)
end
end
-- reschedule immediately
minetest.after(0, recv_loop)
else
-- error, retry after some time
minetest.after(error_retry, recv_loop)
end
end)
end
local send = function(data)
2019-01-12 22:13:19 +00:00
assert(run)
2018-12-06 09:29:03 +01:00
-- POST
2018-12-11 19:58:38 +01:00
if debug then
minetest.log("action", "[webmail-tx] " .. dump(data))
end
2018-12-06 09:29:03 +01:00
http.fetch({
url = url,
extra_headers = post_headers,
timeout = timeout,
post_data = minetest.write_json(data)
}, function(res)
-- TODO: error-handling
end)
end
local receive = function(listener)
table.insert(recv_listeners, listener)
end
local close = function()
run = false
end
recv_loop();
return {
send = send,
receive = receive,
close = close
}
end
2019-01-12 22:13:19 +00:00
return Channel