keypadOS/src/updater.lua
2024-08-25 21:30:33 +03:00

104 lines
2.7 KiB
Lua

local log = require("log");
local json = require("json");
--- @class UpdaterEntry
--- @field url string
--- @field branch string
local _;
--- @class Updater
--- @field last_check integer
--- @field threshold integer in hours (mc time)
--- @field api_url string
--- @field curr_commit_hash string
--- @field updated_files table<string, UpdaterEntry> {path: {url, branch}}
local updater = {};
updater.__index = updater;
function updater.new()
local c = setmetatable({}, updater);
c.last_check = os.time();
c.threshold = ((20*60)/24/60) * 5;
c.api_url = "https://git.mcorangehq.xyz/api/v1/repos/xomf/keypadOS";
c.curr_commit_hash = "";
c.updated_files["startup.lua"] = {
url = "https://git.mcorangehq.xyz/xomf/keypadOS/raw/branch/main/rtmc.lua",
branch = "main"
};
return c
end
function updater:addEntry(path, branch, url)
self.updated_files[path] = {
branch = branch,
url = url
};
end
function updater:checkAndUpdateAll()
for path, entry in pairs(self.updated_files) do
if self:check(entry.branch) then
self:update(path, entry.url);
os.reboot();
end
end
end
function updater:check(branch)
local curr = os.time();
if (math.abs(curr - self.last_check) >= self.threshold) and (self.curr_commit_hash ~= "") then
self.last_check = curr;
return true;
end
local req, rerr = http.get(self.api_url .. "/commits?sha="..branch);
if not req then
log.error("Updater:check: Could not send request: " .. rerr);
return false;
end
local body, berr = req.readAll();
if not req then
log.error("Updater:check: Could not get body of request: " .. berr);
return false;
end
local data = json.decode(body);
if self.curr_commit_hash == "" then
self.curr_commit_hash = data[1].hash;
elseif data[1].hash == self.curr_commit_hash then
return true;
end
return false;
end
function updater:update(path, url)
local req, rerr = http.get(url .. "?x=" .. tostring(math.random(0,69420)));
if not req then
log.error("Updater:update: Could not send request for update: " .. rerr);
return;
end
local body, berr = req.readAll();
if not body then
log.error("Updater:update: Could not get file for update: " .. berr);
return;
end
if fs.exists(path .. ".bak") then
fs.delete(path .. ".bak");
end
fs.copy(path, path..".bak");
local fd = fs.open(path, "w");
fd.write(body);
fd.close();
end
function updater:notify()
-- http.post(config.ntfy_url, "Computer #" .. tostring( os.getComputerID() ) .. " updating")
end
return updater;