mt-matrix/lua/sync.lua

76 lines
2.4 KiB
Lua
Raw Normal View History

2024-02-20 09:57:29 +00:00
sync_so_far = nil
function matrix.sync(http_api, callback, global_callback)
local s = ""
if sync_so_far ~= nil then
s = "since=" .. sync_so_far .. "&"
end
local url = ( config.url .. "/_matrix/client/v3/sync?" .. s ..
"full_state=false&set_presence=online&" ..
"timeout=" .. (config.sync_timeout * 1000) .. "&"
)
http_api.fetch({
url = url,
method = "GET",
timeout = config.sync_timeout + 1,
extra_headers = { "Authorization: Bearer " .. config.access_token },
multipart = false
}, function(result)
if result.code ~= 200 then
minetest.debug("Failed to sync with Matrix server; received code " .. result.code)
minetest.debug(result.data)
else
local answer = json.decode(result.data)
if answer.next_batch ~= nil then
sync_so_far = answer.next_batch
end
if answer.rooms == nil then
elseif answer.rooms.join == nil then
elseif callback == nil then
else
for room_id, room in pairs(answer.rooms.join) do
if room_id == config.room_id then
-- Iterate over old state event updates
if room.state == nil then
elseif room.state.events == nil then
else
for _, event in pairs(room.state.events) do
callback(event)
end
end
-- Iterate over most recent timeline
if room.timeline == nil then
elseif room.timeline.events == nil then
else
for _, event in pairs(room.timeline.events) do
callback(event)
end
end
end
end
end
end
global_callback(result)
end)
end
local function sleep(duration)
local time = os.time()
while os.time() < time + duration do
end
end
function matrix.sync_forever(http_api, callback)
matrix.sync(http_api, callback, function(result)
sleep(1)
matrix.sync_forever(http_api, callback)
end)
end