Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- shaka = require("API")
- if fs.exists("viewAll") == false then
- shell.run("pastebin", "get", "CTsf2Rbb", "viewAll")
- end
- if not fs.exists("serverID") then
- rednet.broadcast("give", "serverID")
- local id, message = rednet.receive("idSupply")
- local file = fs.open("serverID", "w")
- file.write(id)
- file.close()
- serverID = tonumber(id)
- else
- local file = fs.open("serverID", "r")
- serverID = file.readAll()
- file.close()
- serverID = tonumber(serverID)
- end
- local function receiveInfos()
- local msg = nil
- local file = fs.open(".userData", "r")
- local userName = file.readAll()
- file.close()
- rednet.broadcast(userName, "anyMessages?")
- local sender, msg = rednet.receive("notificationReminder", 1)
- if msg ~= nil then
- if tonumber(msg) ~= 0 then
- term.setCursorPos(1,1)
- shaka.changeColors(colors.green, colors.black)
- term.clearLine()
- if tonumber(msg) > 1 then
- shaka.centerText("New messages: " ..msg)
- else
- shaka.centerText("New message!")
- end
- end
- else
- shaka.changeColors(colors.red, colors.black)
- term.clear()
- shaka.centerText("Server not responding!", 7)
- term.setCursorPos(8, 9)
- textutils.slowPrint("Restarting..", 10)
- sleep(2)
- os.reboot()
- end
- end
- function saveUserName()
- shaka.clearScreen()
- -- Prompt the user to enter their name
- term.setBackgroundColor(colors.gray)
- term.setTextColor(colors.black)
- term.clearLine()
- print("Please enter your name:\n")
- shaka.resetColors()
- local name = tostring(read())
- if name ~= nil and name ~= "" then
- --send information to server
- rednet.send(serverID, name, "newUser")
- local sender, message = rednet.receive("userConfirm", 2)
- if message == "worked" then
- -- Open the ".userData" file for writing
- local file = fs.open(".userData", "w")
- -- Write the user's name to the file
- file.writeLine(name)
- -- Close the file
- file.close()
- shaka.clearScreen()
- term.setTextColor(colors.black)
- term.setBackgroundColor(colors.green)
- term.clearLine()
- textutils.slowPrint("Success!", 5)
- shaka.resetColors()
- print("\nThank you, " ..name.."!")
- print("\nYour name has been saved.")
- elseif message == nil then -- no response
- shaka.clearScreen()
- shaka.changeColors(colors.red, colors.black)
- term.clearLine()
- print("Server not responding!")
- shaka.resetColors()
- elseif message == "fail" then -- username already exists
- shaka.nextLine()
- shaka.changeColors(colors.red, colors.black)
- term.clearLine()
- print("User " ..name.. " already exists!\n")
- shaka.changeColors(colors.black, colors.yellow)
- print("Please choose another name.\n")
- term.setTextColor(colors.gray)
- textutils.slowPrint("Press any key to continue..")
- event = os.pullEvent("key")
- shell.run("messenger")
- return
- end
- else
- term.setBackgroundColor(colors.red)
- term.clear()
- shaka.centerText("Not a valid name!\n", 8)
- end
- term.setTextColor(colors.gray)
- textutils.slowPrint("\nPress any key to continue..")
- event = os.pullEvent("key")
- end
- if not fs.exists(".userData") then ---if no username exists create one
- saveUserName()
- end
- function getUserList()
- knownUsers = {}
- rednet.broadcast("give", "requestUserList")
- local sender, message = rednet.receive("userRequestAnswer", 2)
- if message ~= "noUsers" and message ~= "" and message ~= nil then
- message = textutils.unserialize(message)
- for k, v in pairs(message) do
- knownUsers[k] = v.name
- end
- -- table.sort(knownUsers)
- elseif message == "noUsers" or message == "" then
- knownUsers = {}
- else
- term.setBackgroundColor(colors.red)
- term.clear()
- term.setTextColor(colors.black)
- shaka.centerText("Can't connect to server", 8)
- sleep(2)
- os.reboot()
- end
- end
- function sendMessage()
- -- Load the user's name from the ".userData" file
- local file = fs.open(".userData", "r")
- local userName = file.readAll()
- file.close()
- -- Load the list of known users from the "knownUsers" table
- getUserList()
- local function checkUserInDatabase()
- for k, v in ipairs(knownUsers) do
- if v == userName then
- return true
- end
- end
- return false
- end
- if checkUserInDatabase() == false then
- shaka.clearScreen()
- shaka.changeColors(colors.red, colors.black)
- print("User " ..userName.. " doesn't exist on the server.")
- shaka.changeColors(colors.black, colors.yellow)
- textutils.slowPrint("\nPlease register your user!")
- shaka.changeColors(colors.black, colors.gray)
- textutils.slowPrint("\nPress any key to continue..")
- os.pullEvent("key")
- saveUserName()
- os.reboot()
- end
- -- Prompt the user to select a receiver from the list of known users
- shaka.clearScreen()
- shaka.changeColors(colors.lightBlue, colors.black)
- term.clearLine()
- print("Click a recipient:\n")
- local a, b = term.getSize()
- local xa, ya = term.getCursorPos()
- term.setCursorPos(a - 1, 1)
- term.setBackgroundColor(colors.red)
- term.write(" X")
- term.setCursorPos(xa,ya)
- for i, user in ipairs(knownUsers) do
- if i % 2 == 0 then -- alternate gray background
- term.setBackgroundColor(colors.gray)
- term.setTextColor(colors.black)
- term.clearLine()
- else
- term.setBackgroundColor(colors.lightGray)
- term.setTextColor(colors.black)
- term.clearLine()
- end
- user = shortenString(user, 26)
- userShort = shortenString(userName, 26)
- if user == userShort then
- print("Note to Self")
- else
- print(user)
- end
- end
- -- Wait for the user to click on a receiver
- local receiverIndex
- while not receiverIndex do
- local event, button, x, y = os.pullEvent("mouse_click")
- if y == 1 then
- shell.run("messenger")
- return
- end
- -- Check if the click is within the bounds of the receiver list
- if x >= 1 and x <= term.getSize() and y >= 3 and y <= 2 + #knownUsers then
- receiverIndex = y - 2
- end
- end
- -- Get the selected receiver from the list
- local receiver = knownUsers[receiverIndex]
- -- Prompt the user to enter a message
- shaka.clearScreen()
- shaka.changeColors(colors.lightBlue, colors.black)
- term.clearLine()
- term.write("Message to: ")
- term.setTextColor(colors.black)
- if user == userShort then
- term.write("Self")
- else
- term.write(shaka.shortenString(receiver, 12))
- end
- shaka.nextLine()
- shaka.changeColors(colors.black, colors.gray)
- term.clearLine()
- print("(double enter to send)\n")
- shaka.changeColors(colors.black, colors.white)
- local messageLines = {}
- local function readAllText()
- repeat
- local line = read()
- if line ~= "" then
- table.insert(messageLines, line)
- end
- until line == ""
- message = table.concat(messageLines, "\n")
- if message ~= "" then
- shaka.clearScreen()
- shaka.changeColors(colors.yellow, colors.black)
- term.clearLine()
- print("Send to " ..receiver.. "?")
- shaka.changeColors(colors.black, colors.lightGray)
- term.clearLine()
- print("Enter to send\nAny other key to cancel\n")
- shaka.resetColors()
- print(message)
- event, key = os.pullEvent("key")
- if key ~= keys.enter then
- shaka.nextLine()
- shaka.changeColors(colors.yellow, colors.black)
- term.clearLine()
- textutils.slowPrint("Aborting..")
- sleep(1)
- shell.run("messenger")
- return
- else
- shaka.nextLine()
- shaka.changeColors(colors.yellow, colors.black)
- term.clearLine()
- textutils.slowPrint("Sending..", 10)
- -- Send the message to the selected receiver
- if receiver then
- rednet.send(serverID, userName .. "+|" .. message .. "+|" .. receiver, "newMessage")
- else
- print("Invalid receiver selection.")
- end
- local sender, text = rednet.receive("messageConfirm", 2)
- if text == nil then
- term.setBackgroundColor(colors.red)
- term.clear()
- term.setTextColor(colors.black)
- print("No confirmation! Is server offline?")
- textutils.slowPrint("Restarting..")
- sleep(1)
- shell.run("messenger")
- return
- elseif text == "failed" then
- shaka.clearScreen()
- shaka.changeColors(colors.red, colors.black)
- print("User " ..userName.. " isn't registered with the server.")
- shaka.changeColors(colors.black, colors.yellow)
- textutils.slowPrint("\nPlease register your user!")
- shaka.changeColors(colors.black, colors.gray)
- textutils.slowPrint("\nPress any key to continue..")
- os.pullEvent("key")
- saveUserName()
- return
- else
- local plz, kk = term.getCursorPos()
- term.setCursorPos(1, 1)
- shaka.changeColors(colors.green, colors.black)
- term.clearLine()
- print("Send to " ..receiver.. "?\n")
- term.setCursorPos(1, kk)
- shaka.nextLine()
- local plz, kk = term.getCursorPos()
- kkUp = kk - 2
- term.setCursorPos(1, kkUp)
- shaka.changeColors(colors.green, colors.black)
- term.clearLine()
- print("Sending..")
- term.setCursorPos(plz, kk)
- shaka.changeColors(colors.black, colors.green)
- term.clearLine()
- textutils.slowPrint("Success!", 10)
- end
- sleep(1)
- end
- else
- shaka.nextLine()
- shaka.changeColors(colors.orange, colors.black)
- term.clearLine()
- print("Message is empty!\n")
- shaka.changeColors(colors.black, colors.yellow)
- textutils.slowPrint("Restarting..", 10)
- sleep(1)
- end
- shell.run("messenger")
- return
- end
- readAllText()
- end
- local function getMessages()
- local file = fs.open(".userData", "r")
- local userName = file.readAll()
- file.close()
- rednet.broadcast(userName, "messageUpdate")
- local id, msg = rednet.receive("allMessages", 2)
- if fs.exists(".myMessages") then
- fs.delete(".myMessages")
- end
- local file = fs.open(".myMessages", "w")
- file.write(msg)
- file.close()
- if msg == nil then
- term.setBackgroundColor(colors.red)
- term.clear()
- term.setTextColor(colors.black)
- shaka.centerText("Can't connect to server", 8)
- sleep(2)
- os.reboot()
- else
- msg = textutils.unserialize(msg)
- return msg
- end
- end
- function shortenString(str, length)
- if string.len(str) > length then
- return string.sub(str, 1, length)
- else
- return str
- end
- end
- function inverseTable(t)
- local inversedTable = {}
- for i = #t, 1, -1 do
- table.insert(inversedTable, t[i])
- end
- return inversedTable
- end
- function filterTable(tableName, userName)
- local filtered = {}
- for _, message in ipairs(tableName) do
- if message.receiver == userName then
- table.insert(filtered, message)
- end
- end
- return filtered
- end
- local function displayMessages()
- local file = fs.open(".userData", "r")
- local userName = file.readAll()
- file.close()
- rednet.broadcast(userName, "delNotifications")
- local msg = getMessages()
- msg = filterTable(msg, userName)
- shaka.clearScreen()
- shaka.changeColors(colors.green, colors.black)
- term.clearLine()
- print("Recent inbox:")
- local a, b = term.getSize()
- local xa, ya = term.getCursorPos()
- term.setCursorPos(a - 1, 1)
- term.setBackgroundColor(colors.red)
- term.write(" X")
- term.setCursorPos(xa,ya)
- -- Display the last 6 messages
- local startIndex = math.max(1, #msg - 5)
- for i = #msg, startIndex, -1 do
- local message = msg[i]
- local sender = shortenString(message.sender, 16)
- local receiver = shortenString(message.receiver, 11)
- local date = message.date
- local time = message.time
- local text = message.text
- -- Check if the user is the receiver
- local isReceiver = string.find(userName, receiver) ~= nil
- -- Check if the sender and receiver are the same
- local isSameUser = sender == receiver
- -- Set the text color based on whether the user is the receiver or the sender
- if isSameUser then
- term.setTextColor(colors.yellow)
- elseif isReceiver then
- term.setTextColor(colors.green)
- else
- term.setTextColor(colors.white)
- end
- -- Display message information without text
- term.setBackgroundColor(colors.black)
- term.clearLine()
- term.setBackgroundColor(colors.black)
- print()
- term.setBackgroundColor(colors.gray)
- term.clearLine()
- shaka.centerText(date .. " - " .. time)
- shaka.nextLine()
- term.clearLine()
- if isSameUser then
- shaka.centerText("Note to Self")
- else
- shaka.centerText("Sender: " ..sender)
- end
- shaka.nextLine()
- end
- -- Wait for mouse click event
- while true do
- local event, _, x, y = os.pullEvent("mouse_click")
- if y == 1 then
- shell.run("messenger")
- return
- end
- y = y - 2 ------adjustments
- if _ == 1 then
- -- Calculate the index of the clicked message based on the y coordinate
- if #msg < 6 then
- clickedIndex = (startIndex + (#msg - 1)) - math.floor(y / 3)
- else
- clickedIndex = (startIndex + 5) - math.floor(y / 3)
- end
- -- Check if the clicked message is within the valid range
- if clickedIndex >= startIndex and clickedIndex <= #msg then
- local message = msg[clickedIndex]
- local sender = shortenString(message.sender, 16)
- local receiver = shortenString(message.receiver, 13)
- local date = message.date
- local time = message.time
- local text = message.text
- -- Define the maximum number of lines that can fit on the screen
- local maxLines = 15
- -- Define the current line number and the total number of lines
- local currentLine = 0
- local totalLines = 0
- -- Split the message text into lines
- local lines = {}
- for line in string.gmatch(text, "[^\r\n]+") do
- table.insert(lines, line)
- totalLines = totalLines + 1
- end
- ---check if scrolling makes sense
- if totalLines > maxLines then
- scrollAble = true
- else
- scrollAble = false
- end
- -- Clear the screen and display the message text
- shaka.clearScreen()
- term.setTextColor(colors.gray)
- print(date .. " - " .. time)
- shaka.changeColors(colors.gray, colors.lightBlue)
- term.clearLine()
- if sender == receiver then
- print("Note to Self")
- else
- print(sender .. " -> " .. receiver)
- end
- shaka.resetColors()
- shaka.nextLine()
- if scrollAble then
- local ab, cd = term.getCursorPos()
- local ba, dc = term.getSize()
- term.setCursorPos(1, dc-1)
- term.setTextColor(colors.gray)
- print("Scrolling available..")
- term.setTextColor(colors.white)
- term.setCursorPos(ab, cd)
- end
- -- Print the first set of lines that can fit on the screen
- for i = currentLine, math.min(totalLines, currentLine + maxLines - 1) do
- if i ~= 0 then
- print(lines[i])
- end
- end
- -- Listen for mouse scroll to scroll up or down or click to end
- -- sleep(0.5)
- repeat
- local eventData = {os.pullEvent()}
- local event = eventData[1]
- button = tonumber(eventData[2])
- if button == -1 and currentLine > 1 then
- -- Scroll up
- currentLine = currentLine - 1
- shaka.clearScreen()
- term.setTextColor(colors.gray)
- print(date .. " - " .. time)
- shaka.changeColors(colors.black, colors.lightBlue)
- print(sender .. " -> " .. receiver)
- shaka.resetColors()
- print()
- for i = currentLine, math.min(totalLines, currentLine + maxLines - 1) do
- print(lines[i])
- end
- elseif button == 1 and currentLine < totalLines - maxLines + 1 then
- -- Scroll down
- currentLine = currentLine + 1
- shaka.clearScreen()
- term.setTextColor(colors.gray)
- print(date .. " - " .. time)
- shaka.changeColors(colors.black, colors.lightBlue)
- print(sender .. " -> " .. receiver)
- shaka.resetColors()
- print()
- for i = currentLine, math.min(totalLines, currentLine + maxLines - 1) do
- print(lines[i])
- end
- end
- until event == "mouse_click"
- -- Redraw the messages on the screen
- shaka.clearScreen()
- shaka.changeColors(colors.green, colors.black)
- term.clearLine()
- print("Recent Inbox:")
- local a, b = term.getSize()
- local xa, ya = term.getCursorPos()
- term.setCursorPos(a - 1, 1)
- term.setBackgroundColor(colors.red)
- term.write(" X")
- term.setCursorPos(xa,ya)
- for i = #msg, startIndex, -1 do
- local message = msg[i]
- local sender = shortenString(message.sender, 10)
- local receiver = shortenString(message.receiver, 10)
- local date = message.date
- local time = message.time
- -- Check if the user is the receiver
- local isReceiver = string.find(userName, receiver) ~= nil
- -- Check if the sender and receiver are the same
- local isSameUser = sender == receiver
- -- Set the text color based on whether the user is the receiver or the sender
- if isSameUser then
- term.setTextColor(colors.yellow)
- elseif isReceiver then
- term.setTextColor(colors.green)
- else
- term.setTextColor(colors.white)
- end
- -- Display message information without text
- term.setBackgroundColor(colors.black)
- term.clearLine()
- term.setBackgroundColor(colors.black)
- print()
- term.setBackgroundColor(colors.gray)
- term.clearLine()
- shaka.centerText(date .. " - " .. time)
- shaka.nextLine()
- term.clearLine()
- if isSameUser then
- shaka.centerText("Note to Self")
- else
- shaka.centerText("Sender: " ..sender)
- end
- shaka.nextLine()
- end
- end
- end
- end
- end
- function reboot()
- os.reboot()
- end
- function viewAll()
- getMessages()
- shell.run("viewAll")
- end
- function showButtons()
- term.setBackgroundColor(colors.black)
- term.clear()
- -- Define the buttons and their associated programs and colors
- local buttons = {
- {label="Send message", program=sendMessage, color = colors.lightBlue},
- {label="Recent inbox", program=displayMessages, color = colors.green},
- {label="View all messages", program=viewAll, color = colors.gray},
- {label="Exit", program=reboot, color = colors.red},
- -- {label="Program 5", program="program3.lua", color = colors.red}
- }
- -- Set the background color and padding size
- local bgColor = colors.black
- local padding = 2
- -- Calculate the size of the buttons and the total size of the interface
- local buttonWidth = 24
- local buttonHeight = 3
- local interfaceWidth, interfaceHeight = term.getSize()
- interfaceHeight = (buttonHeight + padding) * #buttons + padding
- -- Create a new canvas to draw the interface on
- local canvas = {}
- for y = 1, interfaceHeight do
- canvas[y] = {}
- for x = 1, interfaceWidth do
- canvas[y][x] = {bg = bgColor, fg = colors.white, char = " "}
- end
- end
- -- Draw the buttons on the canvas
- for i, button in ipairs(buttons) do
- local x = padding
- local y = padding + (i-1) * (buttonHeight + padding)
- for y2 = y, y + buttonHeight - 1 do
- for x2 = x, x + buttonWidth - 1 do
- canvas[y2][x2].bg = button.color
- end
- end
- local label = string.sub(button.label, 1, buttonWidth)
- local labelLength = #label
- local labelX = x + math.floor((buttonWidth - labelLength) / 2)
- local labelY = y + math.floor((buttonHeight - 1) / 2)
- for j = 1, labelLength do
- canvas[labelY][labelX+j-1] = {bg = button.color, fg = colors.black, char = string.sub(label, j, j)}
- end
- end
- -- Draw the canvas on the screen
- term.setBackgroundColor(bgColor)
- term.clear()
- for y = 1, interfaceHeight do
- for x = 1, interfaceWidth do
- term.setCursorPos(x, y)
- term.setTextColor(canvas[y][x].fg)
- term.setBackgroundColor(canvas[y][x].bg)
- term.write(canvas[y][x].char)
- end
- end
- receiveInfos()
- -- Wait for a button to be clicked
- while true do
- local event, _, x, y = os.pullEvent("mouse_click")
- for i, button in ipairs(buttons) do
- local buttonX = padding
- local buttonY = padding + (i-1) * (buttonHeight + padding)
- if x >= buttonX and x < buttonX + buttonWidth and y >= buttonY and y < buttonY + buttonHeight then
- showNotifications = false
- -- print(button.label)
- button.program()
- return
- end
- end
- end
- end
- while true do
- showButtons()
- end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement