-
Notifications
You must be signed in to change notification settings - Fork 194
Expand file tree
/
Copy pathwget.lua
More file actions
65 lines (52 loc) · 1.26 KB
/
wget.lua
File metadata and controls
65 lines (52 loc) · 1.26 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
local function printUsage()
print( "Usage:" )
print( "wget <url> [filename]" )
end
local tArgs = { ... }
if #tArgs < 1 then
printUsage()
return
end
if not http then
printError( "wget requires http API" )
printError( "Set http_enable to true in ComputerCraft.cfg" )
return
end
local function getFilename( sUrl )
sUrl = sUrl:gsub( "[#?].*" , "" ):gsub( "/+$" , "" )
return sUrl:match( "/([^/]+)$" )
end
local function get( sUrl )
write( "Connecting to " .. sUrl .. "... " )
local response = http.get( sUrl , nil , true )
if not response then
print( "Failed." )
return nil
end
print( "Success." )
local sResponse = response.readAll()
response.close()
return sResponse
end
-- Determine file to download
local sUrl = tArgs[1]
--Check if the URL is valid
local ok, err = http.checkURL( sUrl )
if not ok then
printError( err or "Invalid URL." )
return
end
local sFile = tArgs[2] or getFilename( sUrl )
local sPath = shell.resolve( sFile )
if fs.exists( sPath ) then
print( "File already exists" )
return
end
-- Do the get
local res = get( sUrl )
if res then
local file = fs.open( sPath, "wb" )
file.write( res )
file.close()
print( "Downloaded as "..sFile )
end