computercraft/lib/lns.lua

84 lines
1.9 KiB
Lua
Raw Permalink Normal View History

2023-10-09 12:54:35 +02:00
-- Desc: LNS Client
-- Auth: Layla Manley
-- Link: https://gitea.layla.gg/layla/computercraft
2023-10-08 10:04:21 +02:00
local cache = {}
2023-10-08 10:23:25 +02:00
local cache_file = "/var/cache/lns_cache.db"
2023-10-08 07:52:14 +02:00
settings.define("lns_client.allow_dynamic_lns_hosts", {
description = "Allow dynamic LNS hosts",
type = "boolean",
default = false
})
settings.define("lns_client.lns_server", {
description = "LNS Server Rednet ID",
type = "number",
default = 8
})
2023-10-08 07:09:44 +02:00
2023-10-08 10:04:21 +02:00
function _load_cache()
2023-10-08 10:23:25 +02:00
if fs.exists(cache_file) then
db = fs.open(cache_file, "r")
2023-10-08 07:56:24 +02:00
db_contents = db.readAll()
db.close()
cache = textutils.unserialize(db_contents)
end
end
2023-10-08 10:04:21 +02:00
function _save_cache()
2023-10-08 10:23:25 +02:00
db = fs.open(cache_file, "w")
2023-10-08 07:56:24 +02:00
db.write(textutils.serialize(cache))
db.close()
end
2023-10-08 10:04:21 +02:00
function server()
local lns_server_id = settings.get("lns_client.lns_server")
local allow_dynamic_lns_hosts = settings.get("lns_client.allow_dynamic_lns_hosts")
2023-10-08 07:09:44 +02:00
if allow_dynamic_lns_hosts then
lns_server_id = rednet.lookup("lns", lns_server)
if lns_server_id == nil then
io.write("LNS Server not found!\n")
2023-10-08 07:12:05 +02:00
return nil
2023-10-08 07:09:44 +02:00
end
end
2023-10-08 10:04:21 +02:00
return lns_server_id
end
function lookup(remote_hostname)
_load_cache()
if cache[remote_hostname] ~= nil then
return cache[remote_hostname]
end
local data = {
["action"] = "lookup",
["hostname"] = remote_hostname
}
2023-10-08 10:17:33 +02:00
local lns_server_id = server()
rednet.send(lns_server_id, data, "lns")
2023-10-08 07:09:44 +02:00
while true do
2023-10-08 08:44:20 +02:00
id, msg = rednet.receive("lns")
2023-10-08 07:09:44 +02:00
if id == lns_server_id then
if msg == nil then
return nil
else
2023-10-08 10:04:21 +02:00
cache[remote_hostname] = msg
_save_cache()
2023-10-08 07:09:44 +02:00
return msg
end
end
end
end
2023-10-08 10:04:21 +02:00
function clear_cache()
2023-10-08 07:26:35 +02:00
cache = {}
2023-10-08 10:04:21 +02:00
_save_cache()
2023-10-08 07:26:35 +02:00
print("Cleared cache!")
2023-10-08 07:09:44 +02:00
end