Code cleanup

This commit is contained in:
Pascal Engélibert 2022-01-29 23:44:56 +01:00
parent c33d1e9cb6
commit e307c24e06
Signed by: tuxmain
GPG Key ID: 3504BC6D362F7DCA
2 changed files with 160 additions and 161 deletions

View File

@ -32,7 +32,7 @@ See [Matrix API docs](https://www.matrix.org/docs/guides/client-server-api).
A bit of code comes from [diggers-mt/matrix_chat](https://github.com/diggers-mt/matrix_chat): BSD-2-Clause, Copyright 2017 Jon Neverland (joenas) A bit of code comes from [diggers-mt/matrix_chat](https://github.com/diggers-mt/matrix_chat): BSD-2-Clause, Copyright 2017 Jon Neverland (joenas)
GNU AGPL v3, CopyLeft 2022 Pascal Engélibert (tuxmain) GNU AGPL v3, CopyLeft 2022 Pascal Engélibert (tuxmain), scuti
This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, version 3 of the License. This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, version 3 of the License.
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.

319
init.lua
View File

@ -11,180 +11,180 @@ end
-- defines functions for matrix protocol -- defines functions for matrix protocol
local MatrixChat = { local MatrixChat = {
server = MATRIX_SERVER, server = MATRIX_SERVER,
username = MATRIX_USERNAME, username = MATRIX_USERNAME,
password = MATRIX_PASSWORD, password = MATRIX_PASSWORD,
room = MATRIX_ROOM, room = MATRIX_ROOM,
-- acquired on login -- acquired on login
userid = nil, userid = nil,
token = nil, token = nil,
since = nil, since = nil,
eventid = nil eventid = nil
} }
function MatrixChat:minechat(data) function MatrixChat:minechat(data)
if data == nil then if data == nil then
return return
end end
if self.since == data.next_batch then if self.since == data.next_batch then
return return
end end
-- lets just get this working -- lets just get this working
if data["rooms"] == nil then if data["rooms"] == nil then
return return
end end
if data["rooms"]["join"] == nil then if data["rooms"]["join"] == nil then
return return
end end
if data["rooms"]["join"][self.room] == nil then if data["rooms"]["join"][self.room] == nil then
return return
end end
if data["rooms"]["join"][self.room]["timeline"] == nil then if data["rooms"]["join"][self.room]["timeline"] == nil then
return return
else else
local events = data["rooms"]["join"][self.room]["timeline"]["events"] local events = data["rooms"]["join"][self.room]["timeline"]["events"]
if events == nil then if events == nil then
minetest.log("action", "matrix_bridge - found timeline but no events") minetest.log("action", "matrix_bridge - found timeline but no events")
return return
end end
minetest.log("action", "matrix_bridge - sync'd and found new messages") minetest.log("action", "matrix_bridge - sync'd and found new messages")
for i, event in ipairs(events) do for i, event in ipairs(events) do
if event.type == "m.room.message" if event.type == "m.room.message"
and event.sender ~= self.userid then and event.sender ~= self.userid then
local message = event.sender .. ": " .. event.content.body local message = event.sender .. ": " .. event.content.body
minetest.log("action", message) minetest.log("action", message)
minetest.chat_send_all(message) minetest.chat_send_all(message)
end end
end end
end end
end end
-- https://matrix.org/docs/api/client-server/#get-/sync -- https://matrix.org/docs/api/client-server/#get-/sync
-- GET /sync -- GET /sync
function MatrixChat:get_sync_table(timeout) function MatrixChat:get_sync_table(timeout)
local params = {} local params = {}
if self.since ~= nil then if self.since ~= nil then
table.insert(params, "since=" .. self.since) table.insert(params, "since=" .. self.since)
end end
if timeout ~= nil then if timeout ~= nil then
table.insert(params, "timeout=" .. timeout) table.insert(params, "timeout=" .. timeout)
end end
local u = self.server .."/_matrix/client/r0/sync" local u = self.server .."/_matrix/client/r0/sync"
if #params > 0 then if #params > 0 then
u = u .. "?" .. table.concat(params, "&") u = u .. "?" .. table.concat(params, "&")
end end
local h = {"Authorization: Bearer " .. self.token} local h = {"Authorization: Bearer " .. self.token}
return {url=u, method="GET", extra_headers=h} return {url=u, method="GET", extra_headers=h}
end end
function MatrixChat:sync(timeout) function MatrixChat:sync(timeout)
http.fetch(MatrixChat:get_sync_table(timeout), http.fetch(MatrixChat:get_sync_table(timeout),
function (res) function(res)
if res == nil then -- received nothing from server if res == nil then -- received nothing from server
minetest.log("error", "matrix_bridge - sync response is nil") minetest.log("error", "matrix_bridge - sync response is nil")
elseif res.code == 0 then elseif res.code == 0 then
minetest.log("info", "matrix_bridge - not found / timeout") minetest.log("info", "matrix_bridge - not found / timeout")
elseif res.code == 404 then elseif res.code == 404 then
else else
local response = minetest.parse_json(res.data) local response = minetest.parse_json(res.data)
if response ~= nil then if response ~= nil then
MatrixChat:minechat(response) MatrixChat:minechat(response)
self.since = response.next_batch self.since = response.next_batch
end end
end end
end end
) )
end end
-- https://matrix.org/docs/api/client-server/#post-/login -- https://matrix.org/docs/api/client-server/#post-/login
-- POST /login -- POST /login
function MatrixChat:login() function MatrixChat:login()
local u = self.server .."/_matrix/client/r0/login" local u = self.server .."/_matrix/client/r0/login"
local d = '{"type":"m.login.password","password":"'.. self.password ..'","identifier":{"type":"m.id.user","user":"'.. self.username ..'"}}' local d = '{"type":"m.login.password","password":"'.. self.password ..'","identifier":{"type":"m.id.user","user":"'.. self.username ..'"}}'
local h = {"Content-Type: application/json"} local h = {"Content-Type: application/json"}
http.fetch({url=u, method="POST", extra_headers=h, data=d}, http.fetch({url=u, method="POST", extra_headers=h, data=d},
function(res) function(res)
if res.code == 200 then if res.code == 200 then
minetest.log("action", res.data) minetest.log("action", res.data)
local data = minetest.parse_json(res.data) local data = minetest.parse_json(res.data)
self.token = data.access_token self.token = data.access_token
self.userid = data.user_id self.userid = data.user_id
MatrixChat:sync() MatrixChat:sync()
minetest.log("action", "Matrix authenticated") minetest.log("action", "Matrix authenticated")
else else
minetest.log("error", to_string(res)) minetest.log("error", to_string(res))
end end
end end
) )
end end
MatrixChat:login() MatrixChat:login()
-- https://matrix.org/docs/api/client-server/#put-/rooms/-roomId-/send/-eventType-/-txnId- -- https://matrix.org/docs/api/client-server/#put-/rooms/-roomId-/send/-eventType-/-txnId-
-- PUT /rooms/{roomId}/send/{eventType}/{txnId} -- PUT /rooms/{roomId}/send/{eventType}/{txnId}
function MatrixChat:send(msg) function MatrixChat:send(msg)
if self.token == nil then if self.token == nil then
return return
end end
local txid = os.time() local txid = os.time()
local u = self.server .."/_matrix/client/r0/rooms/".. self.room .."/send/m.room.message/" .. txid -- ?access_token=..token local u = self.server .."/_matrix/client/r0/rooms/".. self.room .."/send/m.room.message/" .. txid -- ?access_token=..token
local h = {"Content-Type: application/json", "Authorization: Bearer " .. self.token} local h = {"Content-Type: application/json", "Authorization: Bearer " .. self.token}
local d = minetest.write_json({msgtype="m.text", body=msg}) local d = minetest.write_json({msgtype="m.text", body=msg})
http.fetch({url=u, method="PUT", extra_headers=h, data=d}, http.fetch({url=u, method="PUT", extra_headers=h, data=d},
function (res) function(res)
if res.code == 200 then if res.code == 200 then
local data = minetest.parse_json(res.data) local data = minetest.parse_json(res.data)
minetest.log("action", "got " .. data["event_id"]) minetest.log("action", "got " .. data["event_id"])
self.eventid = data["event_id"] self.eventid = data["event_id"]
elseif res.code == 401 then elseif res.code == 401 then
minetest.log("error", "matrix_bridge - not authorized to send messages") minetest.log("error", "matrix_bridge - not authorized to send messages")
elseif res.code == 404 then elseif res.code == 404 then
minetest.log("error", "matrix_bridge - could not find endpoint for send") minetest.log("error", "matrix_bridge - could not find endpoint for send")
end end
end) end)
end end
-- https://matrix.org/docs/api/client-server/#post-/logout/all -- https://matrix.org/docs/api/client-server/#post-/logout/all
-- POST /logout/all -- POST /logout/all
function MatrixChat:logout () function MatrixChat:logout()
local u = self.server .."/logout/all" local u = self.server .."/logout/all"
local h = {"Authorization: Bearer " .. self.token} local h = {"Authorization: Bearer " .. self.token}
http.fetch({url=u, method="POST", extra_headers=h, function (res) end}) http.fetch({url=u, method="POST", extra_headers=h, function(res) end})
minetest.log("action", "matrix_bridge - signing out.") minetest.log("action", "matrix_bridge - signing out.")
end end
-- print a sync url to console to test matrix connection in other applications -- print a sync url to console to test matrix connection in other applications
function MatrixChat:get_access_url() function MatrixChat:get_access_url()
local params = {} local params = {}
if self.since ~= nil then if self.since ~= nil then
table.insert(params, "since=" .. self.since) table.insert(params, "since=" .. self.since)
end end
table.insert(params, "access_token=" .. self.token) table.insert(params, "access_token=" .. self.token)
local u = self.server .. "/_matrix/client/r0/sync?" .. table.concat(params, "&") local u = self.server .. "/_matrix/client/r0/sync?" .. table.concat(params, "&")
print(u) print(u)
end end
local INTERVAL = 60 local INTERVAL = 60
local HANDLE = nil local HANDLE = nil
minetest.register_globalstep(function(dtime) minetest.register_globalstep(function(dtime)
if HANDLE == nil then if HANDLE == nil then
local request = MatrixChat:get_sync_table(INTERVAL * 1000) local request = MatrixChat:get_sync_table(INTERVAL * 1000)
request.timeout = INTERVAL request.timeout = INTERVAL
HANDLE = http.fetch_async(request) HANDLE = http.fetch_async(request)
elseif HANDLE ~= nil then elseif HANDLE ~= nil then
local result = http.fetch_async_get(HANDLE) local result = http.fetch_async_get(HANDLE)
if result.completed then if result.completed then
if result.code == 200 then if result.code == 200 then
local activity = minetest.parse_json(result.data) local activity = minetest.parse_json(result.data)
if activity ~= nil then if activity ~= nil then
MatrixChat:minechat(activity) MatrixChat:minechat(activity)
end end
MatrixChat.since = activity.next_batch MatrixChat.since = activity.next_batch
elseif result.code == 0 then elseif result.code == 0 then
elseif result.code == 404 then elseif result.code == 404 then
end end
HANDLE = nil HANDLE = nil
end end
end end
end) end)
minetest.register_privilege("matrix", { minetest.register_privilege("matrix", {
@ -194,38 +194,37 @@ minetest.register_privilege("matrix", {
}) })
minetest.register_chatcommand("matrix", { minetest.register_chatcommand("matrix", {
privs = { privs = {
matrix = true matrix = true
}, },
func = function(name, param) func = function(name, param)
if param == "sync" then -- test sync as called from login if param == "sync" then -- test sync as called from login
MatrixChat:sync() MatrixChat:sync()
return true, "[matrix_bridge] command: sync" return true, "[matrix_bridge] command: sync"
elseif param == "logout" then elseif param == "logout" then
MatrixChat:logout() MatrixChat:logout()
return true, "[matrix_bridge] command: log out" return true, "[matrix_bridge] command: log out"
elseif param == "login" then elseif param == "login" then
MatrixChat:login() MatrixChat:login()
return true, "[matrix_bridge] command: log in" return true, "[matrix_bridge] command: log in"
elseif param == "print" then elseif param == "print" then
MatrixChat:get_access_url() MatrixChat:get_access_url()
return true, "[matrix_bridge] printed url to server console" return true, "[matrix_bridge] printed url to server console"
end end
end}) end})
minetest.register_on_shutdown(function() minetest.register_on_shutdown(function()
MatrixChat:logout() MatrixChat:logout()
end) end)
minetest.register_on_joinplayer(function(player) minetest.register_on_joinplayer(function(player)
local name = player:get_player_name() local name = player:get_player_name()
MatrixChat:send("*** "..name.." joined the game") MatrixChat:send("*** "..name.." joined the game")
end) end)
minetest.register_on_leaveplayer(function(player, timed_out) minetest.register_on_leaveplayer(function(player, timed_out)
local name = player:get_player_name() local name = player:get_player_name()
MatrixChat:send("*** "..name.." left the game".. MatrixChat:send("*** "..name.." left the game"..(timed_out and " (Timed out)" or ""))
(timed_out and " (Timed out)" or ""))
end) end)
minetest.register_on_chat_message(function(name, message) minetest.register_on_chat_message(function(name, message)
@ -236,7 +235,7 @@ minetest.register_on_chat_message(function(name, message)
end end
local nl = message:find("\n", 1, true) local nl = message:find("\n", 1, true)
if nl then if nl then
message = message:sub(1, nl - 1) message = message:sub(1, nl - 1)
end end
MatrixChat:send("<"..name.."> "..message) MatrixChat:send("<"..name.."> "..message)
end) end)