AMONUWNA

Downloader

Feb 14th, 2020
325
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 1.54 KB | None | 0 0
  1. local internet = require("internet")
  2. local fs = require("filesystem")
  3.  
  4. local downloader = {}
  5.  
  6. function downloader.downloadFile(url, savePath)
  7.   local response = downloader._tryDownloadFile(url)
  8.  
  9.   downloader._saveDowloadFile(response, savePath)
  10. end
  11.  
  12. function downloader._tryDownloadFile(url)
  13.   local result, response = pcall(internet.request, url)
  14.  
  15.   if result == true then
  16.     return response
  17.   else
  18.     error("Failed download file!")
  19.   end
  20. end
  21.  
  22. function downloader._saveDowloadFile(response, savePath)
  23.   local file = downloader._prepareFileToWrite(savePath)
  24.  
  25.   for chunk in response do
  26.     string.gsub(chunk, "\r\n", "\n")
  27.     file:write(chunk)
  28.   end
  29.  
  30.   file:close()
  31. end
  32.  
  33. function downloader._prepareFileToWrite(path)
  34.   downloader._deleteFileIfItExist(path)
  35.   downloader._createFoldersIfItIsNessesary(path)
  36.  
  37.   local file, errorInfo = io.open(path, "w")
  38.   downloader._throwErrorIfOpeningFileForWritingIsFailed(file, errorInfo)
  39.  
  40.   return file
  41. end
  42.  
  43. function downloader._deleteFileIfItExist(path)
  44.   if fs.exists(path) then
  45.     fs.remove(path)
  46.   end
  47. end
  48.  
  49. function downloader._createFoldersIfItIsNessesary(path)
  50.   local pathWithoutName = string.gsub(path, fs.name(path), " ")
  51.  
  52.   fs.makeDirectory(pathWithoutName)
  53. end
  54.  
  55.  
  56. function downloader._throwErrorIfOpeningFileForWritingIsFailed(file, errorInfo)
  57.   if not file then
  58.     error("Failed opening file for writing! " .. errorInfo)
  59.   end
  60. end
  61.  
  62. downloader.downloadFile("https://raw.githubusercontent.com/AmonDeShir/AmonLuaApi/master/console/menu.lua", "/home/edit/test.lua")
Add Comment
Please, Sign In to add comment