Advertisement
YuRaNnNzZZ

wget by Cyrixus (based on HttpTest)

Nov 25th, 2014
215
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 2.21 KB | None | 0 0
  1. --[[
  2. wget
  3. A program adapted from HttpTest, by Epsen:
  4. http://www.computercraft.info/forums2/index.php?/topic/82-121-httptest-v13/page__hl__http__fromsearch__1
  5. Credit for the original work goes to him. Additional modifications have been
  6. made to the file to make it suitable for my own purposes.
  7. Matthew DiBernardo [04.14.2012]
  8. --]]
  9.  
  10. --[[ Setting up variables ]]
  11. local fileWriteOK
  12. local url
  13. local filename
  14. local tArgs = { ... }
  15.  
  16.  
  17. local function getHttpBody( url )
  18. http.request( url )
  19. while true do
  20. local event, url, hBody = os.pullEvent()
  21. if event == "http_success" then
  22. print( "HTTP SUCCESS\nURL = "..url )
  23. return hBody
  24. else
  25. error( "HTTP FAILURE\nURL = "..url ) -- If the error is not catched, this will exit the program.
  26. return nil -- In case this function is called via pcall.
  27. end
  28. end
  29. end
  30.  
  31. local function processHttpBody( hBody, filename )
  32. local hFile
  33. if hBody then
  34. local body = hBody.readAll() -- Read the whole body.
  35. hFile = io.open( filename, "w" ) -- Open the provided filename for writing.
  36. hFile:write( body ) -- Write the body to the file.
  37. hFile:close() -- Save the changes and close the file.
  38. else
  39. print( "Sorry, no body to process." )
  40. end
  41. hBody.close() -- Do not know for sure if this is really necessary, but just in case.
  42. end
  43.  
  44. local function checkOverwrite( filename )
  45. term.setCursorBlink( false )
  46. print("\nWarning: File already exists. Overwrite? (Y/N)")
  47. while true do
  48. event, choice = os.pullEvent( "char" ) -- Only listen for "char" events.
  49. if string.lower( choice ) == "y" then return true end
  50. if string.lower( choice ) == "n" then return false end
  51. end
  52. end
  53.  
  54. local function printUsage()
  55. print("wget <url> [outfile]")
  56. end
  57.  
  58.  
  59. --[[ ===== Execution Entry ===== ]]
  60.  
  61. --[[ Processing arguments ]]
  62. if tArgs[1] then url = tArgs[1] end
  63. if tArgs[2] then filename = tArgs[2] end
  64.  
  65. --[[ Making sure all necessary arguments were provided by the user ]]
  66. if not url then
  67. printUsage()
  68. elseif not filename then
  69. b = getHttpBody(url)
  70. print(b.readAll())
  71. b.close()
  72. elseif not fs.exists( filename ) or checkOverwrite( filename ) then
  73. processHttpBody( getHttpBody( url ), filename ) --If getHttpBody successfully returns a body, we continue with processing the body and saving it to a file.
  74. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement