cc-stuff/tapeget.lua

94 lines
1.9 KiB
Lua

local args = { ... }
local function n_to_kib(value)
return string.format("%6.1f kiB", value / 1024)
end
local function textProgress(p, c1, c2, fmt, ...)
p = math.min(p, 1)
local tw = term.getSize()
local str = string.format(fmt, ...)
local w1 = math.ceil(p * tw)
local w2 = tw - w1
local bg = term.getBackgroundColor()
term.setBackgroundColor(c1)
term.write(str:sub(1, w1))
local rem = w1 - #str
if rem > 0 then
term.write(string.rep(" ", rem))
end
term.setBackgroundColor(c2)
term.write(str:sub(w1 + 1, w1 + w2))
rem = math.min(tw - #str, w2)
if rem > 0 then
term.write(string.rep(" ", rem))
end
term.setBackgroundColor(bg)
end
local tape = peripheral.find("tape_drive")
if not tape then
print("tape where")
return
end
if not http then
print("no http, check config")
return
end
local req, err = http.get(args[1], {}, true)
if not req then
print("oopsie: "..err)
return
end
local headers = req.getResponseHeaders()
local length = tonumber(headers["content-length"]) or 1
if length > tape.getSize() then
printError("Tape is smaller than the file you're trying to write")
printError("Are you sure?")
io.write("Write anyways? [y/N]: ")
local r = read()
if r ~= "y" and r ~= "Y" then
return
end
end
tape.stop()
tape.seek(-tape.getSize())
tape.stop()
local _, y = term.getCursorPos()
local written = 0
local i = 1
while true do
local chunk = req.read(256)
if not chunk then
break
end
written = written + #chunk
tape.write(chunk)
if i % 10 == 0 then
term.setCursorPos(1, y)
term.clearLine()
textProgress(written / length, colors.green, colors.gray, "%s / %s", n_to_kib(written), n_to_kib(length))
os.sleep(0.01)
end
end
term.setCursorPos(1, y)
term.clearLine()
print("Written "..n_to_kib(written))
tape.stop()
tape.seek(-tape.getSize())
tape.stop()