84 lines
1.9 KiB
Lua
84 lines
1.9 KiB
Lua
-- Desc: LNS Client
|
|
-- Auth: Layla Manley
|
|
-- Link: https://gitea.layla.gg/layla/computercraft
|
|
local cache = {}
|
|
local cache_file = "/var/cache/lns_cache.db"
|
|
|
|
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
|
|
})
|
|
|
|
|
|
function _load_cache()
|
|
if fs.exists(cache_file) then
|
|
db = fs.open(cache_file, "r")
|
|
db_contents = db.readAll()
|
|
db.close()
|
|
|
|
cache = textutils.unserialize(db_contents)
|
|
end
|
|
end
|
|
|
|
function _save_cache()
|
|
db = fs.open(cache_file, "w")
|
|
db.write(textutils.serialize(cache))
|
|
db.close()
|
|
end
|
|
|
|
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")
|
|
|
|
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")
|
|
return nil
|
|
end
|
|
end
|
|
|
|
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
|
|
}
|
|
|
|
local lns_server_id = server()
|
|
rednet.send(lns_server_id, data, "lns")
|
|
|
|
while true do
|
|
id, msg = rednet.receive("lns")
|
|
if id == lns_server_id then
|
|
if msg == nil then
|
|
return nil
|
|
else
|
|
cache[remote_hostname] = msg
|
|
_save_cache()
|
|
return msg
|
|
end
|
|
end
|
|
end
|
|
end
|
|
|
|
function clear_cache()
|
|
cache = {}
|
|
_save_cache()
|
|
print("Cleared cache!")
|
|
end |