diff --git a/wget.lua b/wget.lua new file mode 100644 index 0000000..af3b6f0 --- /dev/null +++ b/wget.lua @@ -0,0 +1,50 @@ +--[[ +Utility for downloading files via http. +By 00asdf +]] + +local argParser = require("argparse").parser("wget", "Utility for downloading files via http") + :optional("f", "override an existing file") + :positional("url", "download target") + :endRequired() + :positional("filename", "optional name of the file, per default the last part of the url is taken") + +local ok, opt, pos = argParser:parse(...) +if not ok then + print(opt) + return -1 +end +local TARGET = pos.url +local FILENAME +if not pos.filename then + local t = TARGET:split("/") + FILENAME = t[#t] + if not FILENAME or FILENAME == "" then + error("The target does not specify a valid filename, please an explicit filename!") + end +else + FILENAME = pos.filename +end + +local fs = require "filesystem" +if not opt.f and fs:fileExists(FILENAME) then + error(string.format("File '%s' already exists! Specify '-f' to replace the file", FILENAME)) +end + +print("Downloading from " .. TARGET) +print("to " .. FILENAME) + +local http = components:getFirst("internet") +if not http.isHttpEnabled or not http.isConnectedToWan then + error("Failed to download: Connection failure, not connected to internet") +end + +local response = http:sendHttpRequest(TARGET, "GET") +if response:getStatusCode() ~= 200 then + error("Failed to download: Server responded with " .. tostring(response:getStatusCode())) +end + +local content = response:getResponseBody() +print("Downloaded content, writing to file...") +fs:writeAllText(FILENAME, content) +print("Successfully downloaded file!")