computercraft/lns.lua
2023-10-08 02:44:20 -04:00

98 lines
2.0 KiB
Lua

args = { ... }
cache = {}
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
})
allow_dynamic_lns_hosts = settings.get("lns_client.allow_dynamic_lns_hosts")
lns_server_id = settings.get("lns_client.lns_server")
function load_cache()
if fs.exists("lns_cache.db") then
db = fs.open("lns_cache.db", "r")
db_contents = db.readAll()
db.close()
cache = textutils.unserialize(db_contents)
end
end
function save_cache()
db = fs.open("lns_cache.db", "w")
db.write(textutils.serialize(cache))
db.close()
end
function lns_lookup(remote_hostname)
local data = {
["action"] = "lookup",
["hostname"] = remote_hostname
}
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
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
return msg
end
end
end
end
local action = args[1]
if action == nil then
io.write("Usage: lns <action>\n")
return
end
if action == "lookup" then
load_cache()
local hostname = args[2]
if hostname == nil then
io.write("Usage: lns lookup <hostname>\n")
return
end
if cache[hostname] ~= nil then
io.write(cache[hostname])
return
end
local result = lns_lookup(hostname)
if result ~= nil then
io.write(result)
cache[hostname] = result
save_cache()
end
elseif action == "clear" then
cache = {}
save_cache()
print("Cleared cache!")
end