Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- --[[
- wget
- A program adapted from HttpTest, by Epsen:
- http://www.computercraft.info/forums2/index.php?/topic/82-121-httptest-v13/page__hl__http__fromsearch__1
- Credit for the original work goes to him. Additional modifications have been
- made to the file to make it suitable for my own purposes.
- Matthew DiBernardo [04.14.2012]
- --]]
- --[[ Setting up variables ]]
- local fileWriteOK
- local url
- local filename
- local tArgs = { ... }
- local function getHttpBody( url )
- http.request( url )
- while true do
- local event, url, hBody = os.pullEvent()
- if event == "http_success" then
- print( "HTTP SUCCESS\nURL = "..url )
- return hBody
- else
- error( "HTTP FAILURE\nURL = "..url ) -- If the error is not catched, this will exit the program.
- return nil -- In case this function is called via pcall.
- end
- end
- end
- local function processHttpBody( hBody, filename )
- local hFile
- if hBody then
- local body = hBody.readAll() -- Read the whole body.
- hFile = io.open( filename, "w" ) -- Open the provided filename for writing.
- hFile:write( body ) -- Write the body to the file.
- hFile:close() -- Save the changes and close the file.
- else
- print( "Sorry, no body to process." )
- end
- hBody.close() -- Do not know for sure if this is really necessary, but just in case.
- end
- local function checkOverwrite( filename )
- term.setCursorBlink( false )
- print("\nWarning: File already exists. Overwrite? (Y/N)")
- while true do
- event, choice = os.pullEvent( "char" ) -- Only listen for "char" events.
- if string.lower( choice ) == "y" then return true end
- if string.lower( choice ) == "n" then return false end
- end
- end
- local function printUsage()
- print("wget <url> [outfile]")
- end
- --[[ ===== Execution Entry ===== ]]
- --[[ Processing arguments ]]
- if tArgs[1] then url = tArgs[1] end
- if tArgs[2] then filename = tArgs[2] end
- --[[ Making sure all necessary arguments were provided by the user ]]
- if not url then
- printUsage()
- elseif not filename then
- b = getHttpBody(url)
- print(b.readAll())
- b.close()
- elseif not fs.exists( filename ) or checkOverwrite( filename ) then
- processHttpBody( getHttpBody( url ), filename ) --If getHttpBody successfully returns a body, we continue with processing the body and saving it to a file.
- end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement