Skip to content

Instantly share code, notes, and snippets.

@InDieTasten
Created February 24, 2018 20:54
Show Gist options
  • Save InDieTasten/0b7dabc9b13f8d81a90e154bf1568468 to your computer and use it in GitHub Desktop.
Save InDieTasten/0b7dabc9b13f8d81a90e154bf1568468 to your computer and use it in GitHub Desktop.
-- Author: InDieTasten on tekkit.lycodon.com
-- Date created: 2018-02-24
-- Lua script for use in ComputerCraft
local args = {...}
local function printUsage()
local pathToMe = shell.getRunningProgram()
local fileName = fs.getName(pathToMe)
print("Usage:")
print(string.format("%s <url> <filename>", fileName))
print(" url - HTTP(S) url of a file in the www")
print(" filename - Target file to download to")
end
local function main(args)
if (#args ~= 2) then
printUsage()
return
end
local url = args[1]
local filePath = args[2]
-- test url
if (http.checkURI) then
if (not http.checkURI(url)) then
printError("Provided URL is not whitelisted in the ComputerCraft config")
return
end
end
-- download content
term.write("Downloading...")
local success, requestHandle = pcall(http.get, url)
if (not success) then
printError(requestHandle)
end
if (requestHandle == nil) then
printError("Not found")
return
end
local responseBody = requestHandle.readAll()
requestHandle.close()
print(string.format("done (%i bytes)", #responseBody))
-- check for existing file
local resolvedFilePath = shell.resolve(filePath)
if (fs.exists(resolvedFilePath)) then
printError(string.format("File %q already exists", resolvedFilePath))
return
end
-- write to file
term.write("Writing to file...")
local fileHandler = fs.open(resolvedFilePath, "w")
if (not fileHandler) then
printError("Write-access to %q was denied", resolvedFilePath)
return
end
fileHandler.write(responseBody)
fileHandler.close()
print("done")
end
main({...})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment