t8rt0t

SMS.lua

Apr 26th, 2024 (edited)
185
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 30.20 KB | None | 0 0
  1. local args = {...}
  2.  
  3. if args[1] == "update" or not fs.exists("apis/encryption.lua") then
  4.     fs.delete("apis/encryption.lua")
  5.     shell.run("pastebin get 0eYmhPMt apis/encryption.lua")
  6. end
  7. if args[1] == "update" or not fs.exists("apis/screen.lua") then
  8.     fs.delete("apis/screen.lua")
  9.     shell.run("pastebin get qudBZVpH apis/screen.lua")
  10. end
  11. if args[1] == "update" or not fs.exists("apis/docs.lua") then
  12.     fs.delete("apis/docs.lua")
  13.     shell.run("pastebin get 97XNLNEw apis/docs.lua")
  14. end
  15. if args[1] == "update" then
  16.     shell.run(".SMSinstaller.lua")
  17. end
  18. if not fs.exists(".SMSinstaller.lua") then shell.run("pastebin get Y58ddpyY .SMSinstaller.lua") end
  19. if not encryption then os.loadAPI("apis/encryption.lua") end
  20. if not screen then os.loadAPI("apis/screen.lua") end
  21.  
  22. --SMS PROTOCOLS
  23. --Unsecure SMS
  24. --#A: Initial message, Encrypted and scrambled by first computer and sent from first computer to second computer
  25. --#B: Return message, Encrypted by both computers and sent from second computer back to the first computer
  26. --#C: Double Return message, Encrypted by the both computers, then decrypted and unscrambled by first computer and sent from first computer to second computer
  27. --Errors
  28. --#E: Error message, retry to send message
  29. --#e: Error message, don't retry to send message
  30. --Secure SMS
  31. --#a: A, but the original message is "<original message><mutual key>"
  32. --#b: B, but the original message is "<original message><mutual key>"
  33. --#c: C, but the original message is "<original message><mutual key>"
  34. --Mutual Key
  35. --#K: First contact procedure, sends an encrypted mutual key (essentially A but the payload is mutual keys)
  36. --#L: Second step of first contact procedure, sends the double encrypted mutual key back (essentially B)
  37. --#M: Third step of first contact procedure (essentially C)
  38. --#N: Mutual Key Confirmation
  39.  
  40. term.clear()
  41. --TODO: remove?
  42. local completion = require("cc.completion")
  43.  
  44. --Startup screen
  45. local base_term = term.current()
  46. local maxX,maxY = term.getSize()
  47. local startup_screen = screen.Screen(1,1,term.getSize())
  48. local startup_msg,isFirstLogin = "Welcome back! Please login",false
  49. if not fs.exists("SMS/settings.encryptedtxt") then
  50.     fs.delete("SMS")
  51.     startup_msg,isFirstLogin = "Create your password. This cannot be changed later.",true
  52. end
  53. term.redirect(startup_screen.wndw)
  54. startup_screen.textBoxes = {
  55.     screen.TextBox(1,1,"Schem Messaging System SMS",maxX,1,colors.white,colors.green),
  56.     screen.TextBox(1,2,startup_msg,maxX,2,colors.white,colors.gray),
  57.     screen.TextBox(1,6,string.rep(" ",maxX),maxX,1,colors.white,colors.gray),
  58.     screen.TextBox(1,9,string.rep(" ",maxX),maxX,1,colors.white,colors.gray)
  59. }
  60. startup_screen.buttons = {
  61.     pass = screen.FormField(2,4,"Enter Password:",maxX-2,2,colors.white,colors.lightGray,true,maxX-2),
  62.     confirmpass = screen.FormField(2,7,"Confirm Password:",maxX-2,2,colors.white,colors.lightGray,true,maxX-2),
  63.     enter = screen.Button(2,10,"Enter",5,1,colors.white,colors.red,nil,"Enter")
  64. }
  65. local password,confirmpass = "",""
  66. local btype,a,b,c
  67. while btype ~= "Enter" or #password <= 0 or password ~= confirmpass do
  68.     local b = startup_screen:waitForClick()
  69.     btype,a,b,c = b:click()
  70.     if btype == "form" and b then
  71.         if a == "Enter Password:" then password = b
  72.         else
  73.             confirmpass = b
  74.         end
  75.     end
  76. end
  77. term.clear()
  78. term.redirect(base_term)
  79.  
  80. --Constants
  81. local receive_queue,send_queue,message_queue,mutual_queue,err_log,retry_queue,onlineComputers = {},{},{},{},{},{},{}
  82. local next_msgID = 1
  83. local current_screen
  84.  
  85. --Random alphanumeric string of length len (or 1)
  86. local function randString(len)
  87.     len = math.floor(tonumber(len) or 1)
  88.     local res = ""
  89.     math.randomseed(os.epoch())
  90.     while #res < len do
  91.         res = res .. (string.match(string.char(math.random(256)-1),"%a") or "")
  92.     end
  93.     return res
  94. end
  95.  
  96. local session_id = randString(16)
  97.  
  98. local settings = {}
  99. local function writeSettings(newSettings,dir)
  100.     if type(newSettings) ~= "table" then return false end
  101.     dir = dir or "/SMS/settings.encryptedtxt"
  102.     local file = fs.open(dir,"w+")
  103.     file.write(textutils.serialiseJSON(newSettings))
  104.     file.close()
  105.     encryption.encryptFile(dir,password)
  106. end
  107.  
  108. local function readSettings(dir)
  109.     dir = dir or "/SMS/settings.encryptedtxt"
  110.     if fs.exists(dir) then
  111.         local data,wasEncrypted = encryption.decryptFile(dir,password)
  112.         local settings = textutils.unserialiseJSON(data)
  113.         if type(settings) ~= "table" or not wasEncrypted then
  114.             term.clear()
  115.             error("Settings are not encrypted or password was invalid")
  116.             --return false
  117.         end
  118.         return settings
  119.     elseif dir == "/SMS/settings.encryptedtxt" then
  120.         local defaultSettings = {
  121.             allowUnsecureMsgs = false,
  122.             allowSecureMsgs = true,
  123.             establishMutuals = true,
  124.             hashSize = 256^2
  125.         }
  126.         writeSettings(defaultSettings,dir)
  127.         return defaultSettings
  128.     else
  129.         return {}
  130.     end
  131. end
  132. settings = readSettings()
  133. mutual_keys = readSettings("/SMS/mutualkeys.encryptedtxt")
  134.  
  135. local hostName
  136. if type(settings.hostName) ~= "string" then hostName = randString(16) end
  137.  
  138.  
  139. --Opening rednet
  140. local modem = peripheral.find("modem",function(name,modem) return modem.isWireless() end)
  141. if not modem then error("No modem attached") end
  142. rednet.open(peripheral.getName(modem))
  143. --Opening rednet host
  144. if settings.allowUnsecureMsgs then
  145.     rednet.host("Unsecure-SMS",hostName)
  146. end
  147. if settings.allowSecureMsgs then
  148.     rednet.host("Secure-SMS",hostName)
  149. end
  150.  
  151. --Rednet lookup
  152. local function getComputerNames()
  153.     if type(onlineComputer) ~= "table" or not onlineComputers.epoch or onlineComputers.epoch + 5000 > os.epoch() then
  154.         local secure_computers = {rednet.lookup("Secure-SMS")}
  155.         local unsecure_computers = {rednet.lookup("Unsecure-SMS")}
  156.         onlineComputers = {epoch=os.epoch()}
  157.         for k,v in pairs(secure_computers) do
  158.             onlineComputers[v] = k
  159.         end
  160.         for k,v in pairs(unsecure_computers) do
  161.             onlineComputers[v] = k
  162.         end
  163.         onlineComputers[os.getComputerID()] = nil
  164.     end
  165.     return onlineComputers
  166. end
  167.  
  168. local log = fs.open("SMS/latest.log","w+")
  169.  
  170.  
  171. --Receive loop protocol
  172. local function receive()
  173.     while true do
  174.         local id,msg,prtcl = rednet.receive() --fck rednet
  175.         if type(prtcl) ~= "string" then prtcl = "" end
  176.         local msgID = tonumber(string.match(prtcl,"%d+")) or 0
  177.         if type(send_queue[id]) ~= "table" then send_queue[id] = {} end
  178.         if type(receive_queue[id]) ~= "table" then receive_queue[id] = {} end
  179.         if type(msg) ~= "string" then msg = "" end
  180.         log.writeLine(id .. " " .. msg .. " " .. prtcl)
  181.         log.flush()
  182.         --Unsecure protocols
  183.         if settings.allowUnsecureMsgs and string.match(prtcl,"SMS#[ABC]") then
  184.             if string.match(prtcl,"SMS#B") then
  185.                 if type(send_queue[id][msgID]) == "table" and #send_queue[id][msgID].payload == #msg then
  186.                     rednet.send(id,encryption.decryptString(msg,password .. session_id,settings.hashSize,true,true,send_queue[id][msgID].epoch),"SMS#C" .. msgID)
  187.                     send_queue[id][msgID] = nil
  188.                 else
  189.                     rednet.send(id,"418 I'm a teapot","SMS#e" .. msgID) --Message length not consistent or original message wasnt sent, another computer trying to get decryption?
  190.                 end
  191.             elseif string.match(prtcl,"SMS#A") then --secure and unsecure A protocol are functionally the same
  192.                 local epoch = os.epoch()
  193.                 if type(receive_queue[id][msgID]) == "table" then --ID already used
  194.                     rednet.send(id,"409 ID already used in session","SMS#E"..msgID)
  195.                 else
  196.                     receive_queue[id][msgID] = {epoch=epoch,payload=msg}
  197.                     rednet.send(id,encryption.encryptString(msg,password .. session_id,settings.hashSize,true,false,epoch),"SMS#B"..msgID)
  198.                 end
  199.             elseif string.match(prtcl,"SMS#C") then
  200.                 if type(receive_queue[id][msgID]) == "table" and #receive_queue[id][msgID].payload == #msg then
  201.                     local msg = encryption.decryptString(msg,password .. session_id,settings.hashSize,true,false,receive_queue[id][msgID].epoch)
  202.                     table.insert(message_queue,{msg=msg,id=id,msgID=msgID,prtcl=prtcl,conversation=id})
  203.                     next_msgID = next_msgID + 1
  204.                 else
  205.                 end
  206.             end
  207.         elseif string.match(prtcl,"SMS#[ABC]") then
  208.             rednet.sent(id,"401 Unsecure messages not supported","SMS#E" .. msgID)
  209.         --Secure a protocol
  210.         elseif string.match(prtcl,"SMS#a") then --secure and unsecure A protocol are functionally the same
  211.             local epoch = os.epoch()
  212.             if type(receive_queue[id][msgID]) == "table" then --ID already used
  213.                 rednet.send(id,"409 ID already used in session","SMS#E"..msgID)
  214.             else
  215.                 receive_queue[id][msgID] = {epoch=epoch,payload=msg}
  216.                 rednet.send(id,encryption.encryptString(msg,password .. session_id,settings.hashSize,true,false,epoch),"SMS#b"..msgID)
  217.             end
  218.         --Secure c protocol
  219.         elseif string.match(prtcl,"SMS#c") then
  220.             if type(receive_queue[id][msgID]) == "table" then
  221.                 local msg = encryption.decryptString(msg,password .. session_id,settings.hashSize,true,false,receive_queue[id][msgID].epoch)
  222.                 msg = encryption.decryptString(msg,mutual_keys["MutualKey"..id],256,true,true) --Unencrypt with mutual key
  223.                 table.insert(message_queue,{msg=msg,id=id,msgID=msgID,prtcl=prtcl,conversation=id})
  224.                 next_msgID = next_msgID + 1
  225.             end
  226.         --Secure b protocol
  227.         elseif string.match(prtcl,"SMS#b") then --Same protocol
  228.             if type(send_queue[id]) == "table" then
  229.                 if type(send_queue[id][msgID]) == "table" and #send_queue[id][msgID].payload == #msg then
  230.                     rednet.send(id,encryption.decryptString(msg,password .. session_id,settings.hashSize,true,true,send_queue[id][msgID].epoch),"SMS#C" .. msgID)
  231.                     send_queue[id][msgID] = nil
  232.                 else
  233.                     rednet.send(id,"418 I'm a teapot","SMS#e" .. msgID) --Message length not consistent or original message wasnt sent, another computer trying to get decryption?
  234.                 end
  235.             end
  236.         --Error Handling
  237.         elseif string.match(prtcl,"SMS#[Ee]") then
  238.             table.insert(err_log,{id=id,msgID=msgID,err=msg,prtcl=prtcl})
  239.             local originalMessage = receive_queue[id][msgID]
  240.             if not originalMessage then originalMessage = send_queue[id][msgID] end
  241.             if not originalMessage then originalMessage = mutual_queue[id] end
  242.             if originalMessage and string.match(prtcl,"SMS#E") then
  243.                 --table.insert(retry_queue,originalMessage) --NYI
  244.             end
  245.             receive_queue[id][msgID] = nil
  246.             send_queue[id][msgID] = nil
  247.             mutual_queue[id] = nil
  248.         --Mutual Key protocols
  249.         elseif settings.establishMutuals and string.match(prtcl,"SMS#[KLMN]") then
  250.             if string.match(prtcl,"SMS#K") then
  251.                 local epoch = os.epoch()
  252.                 if mutual_queue[id] or settings["MutualKey"..id] then --Mutual queue already waiting for response
  253.                     rednet.send(id,"400 Mutual key already established, or is being verified","SMS#E"..msgID)
  254.                 else
  255.                     rednet.send(id,encryption.encryptString(msg,password .. session_id,settings.hashSize,true,true,epoch),"SMS#L" .. msgID)
  256.                     mutual_queue[id] = {epoch=epoch,payload=msg}
  257.                 end
  258.             elseif string.match(prtcl,"SMS#L") then
  259.                 if not mutual_queue[id] then
  260.                     rednet.send(id,"418 I'm a teapot","SMS#e"..msgID)
  261.                 else
  262.                     rednet.send(id,encryption.decryptString(msg,password .. session_id,settings.hashSize,true,true,mutual_queue[id].epoch),"SMS#M"..msgID)
  263.                 end
  264.             elseif string.match(prtcl,"SMS#M") then
  265.                 if not mutual_queue[id] or #mutual_queue[id].payload ~= #msg or mutual_keys["MutualKey"..id] then
  266.                     rednet.send(id,"418 I'm a teapot","SMS#e"..msgID)
  267.                 else
  268.                     mutual_keys["MutualKey"..id] = encryption.decryptString(msg,password .. session_id,settings.hashSize,true,true,mutual_queue[id].epoch)
  269.                     writeSettings(mutual_keys,"SMS/mutualkeys.encryptedtxt")
  270.                     mutual_queue[id] = nil
  271.                     rednet.send(id,encryption.encryptString("200 Key Established",mutual_keys["MutualKey"..id],256^2,true,false),"SMS#N"..msgID)
  272.                     os.queueEvent("mutual_key",id,mutual_keys["MutualKey"..id])
  273.                 end
  274.             elseif string.match(prtcl,"SMS#N") then
  275.                 if encryption.decryptString(msg,mutual_queue[id].payload,256^2,true,false) == "200 Key Established" then
  276.                     mutual_keys["MutualKey"..id] = mutual_queue[id].payload
  277.                     writeSettings(mutual_keys,"SMS/mutualkeys.encryptedtxt")
  278.                     mutual_queue[id] = nil
  279.                     os.queueEvent("mutual_key",id,mutual_keys["MutualKey"..id])
  280.                 else
  281.                     table.insert(err_log,{id=id,msgID=msgID,err="001 No mutual key return for mutual:"..mutual_queue[id].payload,prtcl=prtcl})
  282.                     mutual_queue[id] = nil
  283.                 end
  284.             end
  285.         elseif prtcl ~= "dns" then
  286.             rednet.send(id,"405 Protocol invalid, or attempting to establish unsecure practices with a secure computer","SMS#E"..msgID)
  287.         end
  288.     end
  289. end
  290.  
  291.  
  292.  
  293. local function readMessageHistory(id)
  294.     local dir = "SMS/PrivateMessages/"..id .. ".encryptedtxt"
  295.     local oldData
  296.     if fs.exists(dir) then
  297.         local data = encryption.decryptFile(dir,password)
  298.         oldData = textutils.unserialiseJSON(data)
  299.     end
  300.     if type(oldData) ~= "table" then oldData = {msgs={}} end
  301.     oldData.name = "" .. (oldData.name or id)
  302.     oldData.name = oldData.name:sub(1,8)
  303.     return oldData,dir
  304. end
  305.  
  306. local function addMessageHistory(message,id,conversation)
  307.     local oldData,dir = readMessageHistory(conversation)
  308.     oldData.epoch = os.epoch()
  309.     table.insert(oldData.msgs,{id,message})
  310.     if current_screen.recipient == conversation then
  311.         current_screen.subscreen.messageHistory = oldData
  312.         os.queueEvent("refreshMessages",conversation)
  313.     end
  314.     local file = fs.open(dir,"w+")
  315.     file.write(textutils.serialiseJSON(oldData))
  316.     file.close()
  317.     encryption.encryptFile(dir,password)
  318. end
  319.  
  320. --TODO: implement group messaging protocols so this is actually relevant
  321. local function addGroupMessageHistory(message,id,groupChat)
  322.     local dir = "SMS/GroupMessages/"..groupChat..".encryptedtxt"
  323.     local oldData
  324.     if fs.exists(dir) then
  325.         local data = encryption.decryptFile(dir,password)
  326.         oldData = textutils.unserialiseJSON(data)
  327.     end
  328.     if type(oldData) ~= "table" then oldData = {msgs={}} end
  329.     table.insert(oldData.msgs,{id,message})
  330.     oldData.epoch = os.epoch()
  331.     oldData.name = groupChat
  332.     local file = fs.open(dir,"w+")
  333.     file.write(textutils.serialiseJSON(oldData))
  334.     file.close()
  335.     encryption.encryptFile(dir,password)
  336. end
  337.  
  338.  
  339. --Returns isUnsecure,isSecure,isSecureAndKey
  340. local function canReceive(id)
  341.     local secure_computers = {rednet.lookup("Secure-SMS")}
  342.     local unsecure_computers = {rednet.lookup("Unsecure-SMS")}
  343.     local isUnsecure,isSecure,isSecureAndKey = false,false,false
  344.     if settings.allowSecureMsgs then
  345.         for k,v in pairs(secure_computers) do
  346.             if v == id then
  347.                 isSecure = true
  348.                 if settings["MutualKey"..id] then isSecureAndKey = true end
  349.                 break
  350.             end
  351.         end
  352.     end
  353.     if settings.allowUnsecureMsgs then
  354.         for k,v in pairs(unsecure_computers) do
  355.             if v == id then
  356.                 isUnsecure = true
  357.                 break
  358.             end
  359.         end
  360.     end
  361.     return isUnsecure,isSecure,isSecureAndKey
  362. end
  363.  
  364. --Sends message to recipient with id
  365. local function send(recipient,msg)
  366.     local a,b,c = canReceive(recipient)
  367.     if type(send_queue[recipient]) ~= "table" then send_queue[recipient] = {} end
  368.     if type(receive_queue[recipient]) ~= "table" then receive_queue[recipient] = {} end
  369.     if c then
  370.         local epoch = os.epoch()
  371.         local str = encryption.encryptString(msg,password .. session_id,settings.hashSize,true,true,epoch)
  372.         str = encryption.encryptString(str,settings["MutualKey"..recipient],256^2,true,true)
  373.         rednet.send(recipient,str,"SMS#a"..next_msgID)
  374.         send_queue[recipeint][next_msgID] = {epoch=epoch,payload=msg}
  375.         next_msgID = next_msgID + 1
  376.         table.insert(message_queue,{id=os.getComputerID(),msg=msg,conversation=recipient})
  377.         return 1
  378.     elseif b then
  379.         local epoch = os.epoch()
  380.         if not mutual_queue[recipient] then
  381.             local key = randString(32)
  382.             rednet.send(recipient,encryption.encryptString(key,password .. session_id,settings.hashSize,true,true,epoch),"SMS#K"..next_msgID)
  383.             mutual_queue[recipient] = {epoch=epoch,payload=key}
  384.             table.insert(retry_queue,{id=recipient,payload=msg})
  385.             next_msgID = next_msgID + 1
  386.             return 0
  387.         end
  388.     end
  389.     if a and not secure_success then
  390.         local epoch = os.epoch()
  391.         rednet.send(recipient,encryption.encryptString(msg,password .. session_id, settings.hashSize, true, true, epoch), "SMS#A" .. next_msgID)
  392.         send_queue[recipient][next_msgID] = {epoch=epoch,payload=msg}
  393.         next_msgID = next_msgID + 1
  394.         table.insert(message_queue,{id=os.getComputerID(),msg=msg,conversation=recipient})
  395.         return 1
  396.     end
  397.     table.insert(retry_queue,{id=recipient,payload=msg})
  398.     return 0
  399. end
  400.  
  401.  
  402. --UI bullsh t (PASTEBIN IS CENSORING ME THIS IS LITERALLY 1984 GEORGE ORWELL ANIMAL FARM BIG BROTHER IS WATCHING YOU FREEDOM IS SLAVERY IGNORANCE IS STRENGTH WAR IS PEACE ALL OF US ARE EQUAL BUT SOME OF US ARE MORE EQUAL THAN OTHERS DOUBLETHINK WRONGTHINK NEWSPEAK)
  403. local function ConversationScreen(id)
  404.     term.redirect(base_term)
  405.     term.clear()
  406.     local scn = screen.Screen(1,1,term.getSize())
  407.     term.redirect(scn.wndw)
  408.     scn.type = "conversation_screen"
  409.     scn.isSecure = mutual_keys[id]
  410.     scn.recipient = id
  411.     local temp = "Private Message THP" --TES = triple handshake protocol
  412.     if scn.isSecure then
  413.         temp = "Private Message MKP" -- mutual key protocol
  414.     end
  415.     local messageHistory = readMessageHistory(id)
  416.     scn.textBoxes = {
  417.         header = screen.TextBox(1,1,"Schem Messaging System SMS",maxX,1,colors.white,colors.green),
  418.         chatType = screen.TextBox(1,2,temp,maxX,1,colors.white,colors.gray),
  419.         menubar = screen.TextBox(1,3,messageHistory.name,maxX,1,colors.white,colors.gray)
  420.     }
  421.     scn.buttons = {
  422.         exit = screen.Button(maxX - 3,3,"Exit",4,1,colors.white,colors.red,nil,"Exit"),
  423.         messageEntry = screen.FormField(1,maxY - 3,"",maxX,4,colors.white,colors.lightGray,false,maxX*4)
  424.     }
  425.     scn.buttons.messageEntry.click = function(self) return self.type,self.header,self.pass,self.name end --Fixing form field
  426.     term.redirect(base_term)
  427.     scn.subscreen = screen.Screen(1,4,maxX,maxY - 7)
  428.     scn.subscreen.messageHistory = messageHistory
  429.     term.redirect(base_term)
  430.     return scn
  431. end
  432.  
  433. local function refreshMessages(subscreen)
  434.     --TODO: Add scrolling
  435.     local yPos,index = subscreen.h,#subscreen.messageHistory.msgs
  436.     subscreen.textBoxes = {}
  437.     term.redirect(subscreen.wndw)
  438.     term.clear()
  439.     while yPos > 0 and index > 0 do
  440.         local id,msg = subscreen.messageHistory.msgs[index][1],subscreen.messageHistory.msgs[index][2]
  441.         local txt = "[".. id .. "]: " .. msg
  442.         local buttonHeight = math.ceil(#txt/(subscreen.w - 1))
  443.         local color,xPos = colors.blue,1
  444.         if tonumber(id) == os.getComputerID() then
  445.             color = colors.orange
  446.             xPos = 2
  447.         end
  448.         yPos = yPos - buttonHeight
  449.         index = index - 1
  450.         table.insert(subscreen.textBoxes,screen.TextBox(xPos,yPos+1,txt,subscreen.w - 1, buttonHeight,colors.white,color))
  451.     end
  452. end
  453.    
  454.  
  455. local settings_screen = screen.SettingsScreen(settings)
  456. settings_screen.type = "settings"
  457. term.redirect(base_term)
  458. term.clear()
  459.  
  460. local ui_screen = screen.Screen(1,1,term.getSize())
  461. term.redirect(ui_screen.wndw)
  462. ui_screen.textBoxes = {
  463.     header = screen.TextBox(1,1,"Schem Messaging System SMS",maxX,1,colors.white,colors.green),
  464.     menubar = screen.TextBox(1,2,string.rep(" ",maxX),maxX,1,colors.white,colors.gray), --Just a menu bar
  465.     preview_screen = screen.TextBox(2,5,"",maxX - 2, maxY - 5,colors.white,colors.brown) --Conversation preview screen backdrop
  466. }
  467. ui_screen.buttons = {
  468.     settings = screen.Button(1,2,"Settings",8,1,colors.white,colors.orange,nil,"Settings"),
  469.     dm = screen.FormField(10,2,"DM:",7,1,colors.white,colors.blue,false,4,function(char) return string.match(char,"%d") or "" end), --digit only form field
  470.     errors = screen.Button(18,2,"Errors",6,1,colors.white,colors.red,nil,"Errors"),
  471.     new_conv = screen.Button(2,4,"New Conversation",maxX - 2,1,colors.white,colors.blue,nil,"New Conv"),
  472.     up = screen.Button(maxX,5,"^",1,1,colors.white,colors.gray,nil,"Up"),
  473.     down = screen.Button(maxX,maxY - 1, "v",1,1,colors.white,colors.gray,nil,"Down")
  474. }
  475. ui_screen.scroll = 0
  476.  
  477. local conversation_screen = screen.Screen(2,5,maxX - 2, maxY - 5)
  478. ui_screen.type = "ui_screen"
  479. term.redirect(base_term)
  480. current_screen = ui_screen
  481.  
  482.  
  483. local function drawConversationScreen(page)
  484.     if not fs.isDir("SMS/PrivateMessages") then fs.makeDir("SMS/PrivateMessages") end
  485.     local conversations = fs.list("SMS/PrivateMessages")
  486.     conversation_screen.buttons = {}
  487.     local t = {}
  488.     for k,v in pairs(conversations) do
  489.         local id = tonumber(v)
  490.         if id then
  491.             table.insert(t,{readMessageHistory(id),id})
  492.         end
  493.     end
  494.     table.sort(t,function(a,b) return (a[1].epoch or 0) < (b[1].epoch or 0) end)
  495.     if #t <= 0 then
  496.         conversation_screen:render()
  497.         return 0
  498.     end
  499.     local conversationsPerPage = math.floor(conversation_screen.h/2)
  500.     page = math.max(math.min(page,math.floor(#t/conversationsPerPage)),0)
  501.     term.redirect(conversation_screen.wndw)
  502.     for i=1,conversationsPerPage do
  503.         local conversation = t[page*conversationsPerPage + i][1]
  504.         local bgColor = colors.gray
  505.         if i%2 == 1 then bcGolor = colors.lightGray end
  506.         if conversation then
  507.             local msg = conversation.msgs[#conversation.msgs]
  508.             local text = conversation.name .. ":[" .. msg[1] .. "]" .. msg[2]
  509.             table.insert(conversation_screen.buttons,screen.Button(1,2*i - 1,text,conversation_screen.w,2,colors.white,bgColor,function() return "pm",id end,"pm"))
  510.         end
  511.     end
  512.     return page
  513. end
  514.  
  515. local function trollScreen()
  516.     local errors = {
  517.         {"You have been reported.", "I am not a bot. I am a Volunteer Reddit Moderator. I do not have mod powers but my reports are taken seriously and those who get on my bad side tend to get banned in under 24 hours. I have numerous rules, which you may read in my post history, but 1 is the most important rule of all:", "⁠I am an officer in training, and I expect to be treated the same way I would be with my uniform and badge.", "Watch your back and get used to this face kiddo, you'll be seeing a lot of it."},
  518.         {"Sure, you are a vile piece of sh".."i".."t that does nothing but cause issues, and to be frank at the time I wanted nothing more than to throttle your likely-chubby neck. However I also realize that your awful state of being probably has something to do with your circumstances, that likely being a basement-dwelling reddit-addicted fatso, and that killing you would be a mercy. So, as with all people I despise, I would rather gravely injure you than put an end to your misery."},
  519.         {"Dear @Moderator, I am reaching out to request the opportunity to unrestrict my account in exchange for a promise to showcase a spectacular airship build within the Minecraft valkyrien skies with other of it's addons. I assure you that this project will not only demonstrate my dedication to the mod & it's add-ons but also serve as a testament to the creativity and innovation that can flourish within the community. I am confident that this endeavor will not only benefit my account but also inspire and engage fellow players. Your consideration of this request is greatly appreciated. Sincerely, [SscreamMOrSmg6]"},
  520.         {"Cool mute reason. You know that literally nothing i said related to anything conspiracy-related in any way, and you're just proving how much of a butthurt neckbeard with some desire for power and control you are?"},
  521.         {"I'm want to be a clock","Why I should be on the CIockwork team"," ","I have a good understanding of java.","I know how to write minecraft mods","I have some great features I want to add.","Development has been extremely slow","I have a lot of time to work on the mod","I know kotlin","Those are my reasons of why I should be on the cIockwork Development team."}
  522.     }
  523.     local scn = screen.Screen(1,1,term.getSize())
  524.     scn.type = "troll"
  525.     term.redirect(scn.wndw)
  526.     local yPos = 1,1
  527.     for k,v in ipairs(errors[math.random(#errors)]) do
  528.         table.insert(scn.textBoxes,screen.TextBox(1,yPos,v,maxX,math.ceil(#v/maxX),colors.red,colors.black))
  529.         yPos = yPos + math.ceil(#v/maxX)
  530.     end
  531.     return scn
  532. end
  533.  
  534. local function ui()
  535.     while true do
  536.         sleep(0)
  537.         term.redirect(current_screen.wndw)
  538.         term.clear()
  539.         current_screen:render()
  540.         if current_screen.type == "ui_screen" then
  541.             current_screen.scroll = drawConversationScreen(current_screen.scroll)
  542.             term.redirect(current_screen.wndw)
  543.             local b,x,y
  544.             while not b or not b.click do
  545.                 b,x,y = current_screen:getClick()
  546.                 if not b then b = conversation_screen:getClick(x,y) end
  547.                 sleep(0)
  548.             end
  549.             local btype,a,b,c = b:click()
  550.             sleep(0)
  551.             if btype == "Settings" then
  552.                 term.clear()
  553.                 current_screen = settings_screen
  554.             elseif btype == "Up" then
  555.                 current_screen.scroll = current_screen.scroll - 1
  556.             elseif btype == "Down" then
  557.                 current_screen.scroll = current_screen.scroll + 1
  558.             elseif btype == "form" then
  559.                 if tonumber(b) then
  560.                     term.clear()
  561.                     current_screen = ConversationScreen(tonumber(b))
  562.                 end
  563.             elseif btype == "Errors" then
  564.                 --TODO
  565.                 current_screen = trollScreen()
  566.             elseif btype == "New Conv" then
  567.                 --TODO
  568.                 current_screen = trollScreen()
  569.             elseif btype == "pm" then
  570.                 term.clear()
  571.                 current_screen = ConversationScreen(tonumber(a))
  572.             end
  573.         elseif current_screen.type == "settings" then
  574.             settings = current_screen:updateSettings()
  575.             writeSettings(settings)
  576.             term.clear()
  577.             current_screen = ui_screen
  578.         elseif current_screen.type == "conversation_screen" then
  579.             refreshMessages(current_screen.subscreen)
  580.             term.redirect(current_screen.wndw)
  581.             local flag = 0
  582.             local msgEntry = current_screen.buttons.messageEntry
  583.             term.setCursorBlink(true)
  584.             while flag <= 0 do
  585.                 term.setCursorPos(msgEntry.x + #msgEntry.text%msgEntry.w,msgEntry.y + math.floor(#msgEntry.text/msgEntry.w))
  586.                 local e,a,b,c,d = os.pullEvent()
  587.                 if e == "refreshMessages" and tonumber(a) == tonumber(current_screen.recipient) then
  588.                     refreshMessages(current_screen.subscreen)
  589.                     term.redirect(current_screen.wndw)
  590.                 elseif e == "key" then
  591.                     if a <= 256 and #msgEntry.pass <= msgEntry.maxLength then
  592.                         local _,char = os.pullEvent("char") --Safe because char event always comes right after key event?
  593.                         msgEntry.pass = msgEntry.pass .. char
  594.                         msgEntry:updateText()
  595.                     elseif a == keys.delete or a == keys.backspace then
  596.                         msgEntry.pass = string.sub(msgEntry.pass,1,-2)
  597.                         msgEntry:updateText()
  598.                     elseif a == keys.enter then
  599.                         flag = 1
  600.                     end
  601.                 elseif e == "mouse_click" then
  602.                     local button = current_screen:waitForClick(a,b)
  603.                     if button then
  604.                         local buttonType,f,g,h = button:click()
  605.                         if buttonType == "Exit" then
  606.                             current_screen = ui_screen
  607.                             flag = 2
  608.                         end
  609.                     end
  610.                 end
  611.             end
  612.             term.setCursorBlink(false)
  613.             if flag == 1 then
  614.                 send(tonumber(current_screen.recipient),msgEntry.pass)
  615.                 msgEntry.pass = ""
  616.                 msgEntry:updateText()
  617.             end
  618.         else
  619.             os.pullEvent("mouse_click")
  620.             current_screen = ui_screen
  621.         end
  622.     end
  623. end
  624.  
  625.  
  626. --Queue handling protocol
  627.  
  628. local function handleQueues()
  629.     while true do
  630.         if #message_queue > 0 then
  631.             local msg = table.remove(message_queue)
  632.             addMessageHistory(msg.msg,msg.id,msg.conversation)
  633.         end
  634.         sleep(0)
  635.         if #retry_queue > 0 then
  636.             local msg = table.remove(retry_queue)
  637.             local res = send(msg.id,msg.payload)
  638.             if res < 0 then table.insert(retry_queue,msg) end
  639.         end
  640.         sleep(0)
  641.     end
  642. end
  643.                
  644. parallel.waitForAny(handleQueues,receive,ui) --Wait for any in case I add a logout protocol
  645. term.redirect(base_term)
  646. term.clear()
Advertisement
Add Comment
Please, Sign In to add comment