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