Advertisement
Guest User

OpenComputer File Sharing Host

a guest
Jun 10th, 2014
650
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 1.99 KB | None | 0 0
  1. local component = require("component")
  2. local event = require("event")
  3. local serialization = require("serialization")
  4. local modem = component.proxy(component.modem.address)
  5. local fs = require("filesystem")
  6. local term = require("term")
  7.  
  8. term.clear()
  9. modem.setStrength(128)
  10. modem.open(7766)
  11.  
  12. event.timer(1, function() modem.broadcast(999, modem.address) end, math.huge)
  13.  
  14. function SendError(from, msg)
  15.   local toSend = serialization.serialize({ type = "error", error = msg })
  16.   modem.send(from, 7766, toSend)
  17. end
  18.  
  19. while true do
  20.   local type, _, from, _, _, message = event.pull("modem_message")
  21.   local obj = serialization.unserialize(message)
  22.   local path = obj.path
  23.   if path ~= nil then
  24.     path = fs.concat("/share/", fs.canonical(path))
  25.   end
  26.  
  27.   if obj.type == "info" then
  28.     local share = fs.get("/share/")
  29.     local info = { type = "info" }
  30.     info.spaceTotal = share.spaceTotal()
  31.     info.spaceUsed = share.spaceUsed()
  32.     modem.send(from, 7766, serialization.serialize(info))
  33.   elseif path == nil then
  34.     print("Recieved invalid path")
  35.     SendError(from, "Not a valid path")
  36.   elseif obj.type == "list" then
  37.     print("Recieved list for "..path)
  38.     local fsList = {}
  39.     for file in fs.list(path) do
  40.       table.insert(fsList, file)
  41.     end
  42.     modem.send(from, 7766, serialization.serialize({ type = "list",  list = fsList }))
  43.   elseif obj.type == "type" then
  44.     print("Recieved type for "..path)
  45.     local toSend = { type = "type" }
  46.     toSend.isDir = fs.isDirectory(path)
  47.     toSend.size = fs.size(path)
  48.     toSend.lastModified = fs.lastModified(path)
  49.     modem.send(from, 7766, serialization.serialize(toSend))
  50.   elseif obj.type == "get" then
  51.     print("Recieved get for "..path)
  52.     local file = fs.open(path, "rb")
  53.     if file == nil then
  54.       SendError(from, "Not a valid file")
  55.     else
  56.       local data = file:read(fs.size(path))
  57.       file:close()
  58.       modem.send(from, 7766, serialization.serialize({ type = "get", data = data }))
  59.     end
  60.   end
  61. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement