Advertisement
osmarks

Web2Tape

Dec 24th, 2019 (edited)
540
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 1.55 KB | None | 0 0
  1. local tape = peripheral.find "tape_drive"
  2. local url, opt = ...
  3. if not tape then error "Tape drive required." end
  4. if not url then error "Specify a URL to download. This may need to be in quotes." end
  5.  
  6. if opt == "range" then
  7.         print "Fetching in range mode"
  8.         -- horrible bodge to fetch content length as CC appears to mess it up
  9.         local test = http.get { url = url, binary = true, headers = { Range = "bytes=0-1" } }
  10.         local headers = test.getResponseHeaders()
  11.         test.close()
  12.         local range = headers["Content-Range"]
  13.         if not range then error "range not supported?" end
  14.         local z = tonumber(range:match "0%-1/(%d+)")
  15.         print("total size is", z / 1e6, "MB")
  16.         local pos = 0
  17.         local chunk_size = 6e6 -- maximum is 12MB
  18.         if z > tape.getSize() then printError "tape too small, will be truncated" end
  19.         while true do
  20.                 local was = pos
  21.                 pos = pos + chunk_size
  22.                 local range = ("bytes=%d-%d"):format(was, pos - 1)
  23.                 local h = http.get { url = url, binary = true, headers = { Range = range } }
  24.                 tape.write(h.readAll())
  25.                 h.close()
  26.                 print("fetched up to", pos / 1e6, "MB")
  27.                 if pos > z then print "done!" break end
  28.         end
  29.         print "written successfully"
  30.         return
  31. end
  32.  
  33. print "Downloading..."
  34. local h = http.get(url, nil, true) -- binary mode
  35. local data = h.readAll()
  36. h.close()
  37. print "Downloaded."
  38.  
  39. if opt ~= "norestart" then
  40.         print "Seeking to start."
  41.         tape.seek(-tape.getPosition())
  42. end
  43.  
  44. if #data > (tape.getSize() - tape.getPosition()) then printError "WARNING: Data is longer than tape." end
  45.  
  46. tape.write(data)
  47. print "Data written."
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement