Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- local protocol = "sync_protocol"
- local serverPath = "/users/"
- -- Open the modem
- rednet.open(peripheral.getName(peripheral.find("modem") or error("No modem found")))
- local serverID = os.getComputerID()
- print("Server running. Computer ID:", serverID)
- -- Function to compute file hashes
- local function getFileHash(filePath)
- if not fs.exists(filePath) then return nil end
- local f = fs.open(filePath, "r")
- local content = f.readAll()
- f.close()
- return textutils.serialize(content)
- end
- -- Get file list with hashes
- local function getFileList(path)
- local files = {}
- local function scan(dir)
- for _, file in pairs(fs.list(dir)) do
- local fullPath = dir .. file
- if fs.isDir(fullPath) then
- scan(fullPath .. "/")
- else
- files[fullPath:sub(#serverPath + 1)] = getFileHash(fullPath)
- end
- end
- end
- scan(path)
- return files
- end
- -- Handle sync requests
- while true do
- local id, request = rednet.receive(protocol)
- if request then
- if request.action == "sync_request" then
- print("Sync request received from client", id)
- -- Check what action the client requested
- local syncMode = request.mode or "full" -- Default to full sync if no mode provided
- local serverFiles = getFileList(serverPath)
- local files_to_client = {}
- local files_to_delete = {}
- -- Identify files that need to be sent or deleted
- for file, hash in pairs(serverFiles) do
- if request.files[file] ~= hash then
- local f = fs.open(serverPath .. file, "r")
- files_to_client[file] = f.readAll()
- f.close()
- end
- end
- -- Identify files that need to be deleted (on server)
- for file, hash in pairs(request.files) do
- if not serverFiles[file] then
- table.insert(files_to_delete, file)
- end
- end
- -- Send response to the client
- rednet.send(id, {
- action = "sync_response",
- files_to_client = files_to_client,
- files_to_delete = files_to_delete
- }, protocol)
- -- Handle upload request (client to server)
- if syncMode == "upload" or syncMode == "full" then
- rednet.send(id, { action = "sync_upload_request", files_needed = {}, files_to_server = {} }, protocol)
- local id2, clientUpload = rednet.receive(protocol, 5)
- if id2 == id and clientUpload.action == "sync_upload" then
- for file, content in pairs(clientUpload.files_to_server) do
- local filePath = serverPath .. file
- local f = fs.open(filePath, "w")
- f.write(content)
- f.close()
- print("Updated from client:", file)
- end
- end
- end
- end
- end
- end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement