diff --git a/js/commands.js b/js/commands.js index 1ee509d..2990120 100644 --- a/js/commands.js +++ b/js/commands.js @@ -63,24 +63,43 @@ function cmd_echo(input) { return input.join(' '); } +function cmd_nick(input) { + if (input === undefined) + return "No nickname was given!"; + user.name = input[0]; + fetch('/nickname', { + method: 'POST', + headers: { + 'Accept': 'application/json', + 'Content-Type': 'application/json' + }, + body: JSON.stringify({ + name: user.name, + id: user.id + }) + }).then(res => {}); + return `Applied name '${user.name}'.`; +} + async function cmd_msg(input) { if (input === undefined) return "No message given!"; - const data = { - id: user.id, - message: input.join(' ') - }; + if (!user.connected) + return "You are not connected!"; const res = await fetch('/message', { method: 'POST', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' }, - body: JSON.stringify(data) + body: JSON.stringify({ + message: input.join(' '), + id: user.id + }) }); if (res.status === 200) { - const resData = await res.json(); - return resData.message; + const { message } = await res.json(); + return message; } else return "Server returned status " + res.status; } \ No newline at end of file diff --git a/js/main.js b/js/main.js index 5325589..ee096b6 100644 --- a/js/main.js +++ b/js/main.js @@ -1,4 +1,31 @@ -const user = { id: crypto.randomUUID(), name: "", history: [] }; +// Handle server connection +document.body.onunload = () => { + if (user.connected) + fetch('/disconnect', { + method: 'POST', + headers: { + 'Accept': 'application/json', + 'Content-Type': 'application/json' + }, + body: JSON.stringify({ + id: user.id + }) + }).then(res => {}); +}; +fetch('/connect').then(res => { + if (res.status === 200) { + user.connected = true; + return res.json(); + } + console.error("Could not connect to server!"); +}).then(res => { + if (res === undefined) + return; + const { id } = res; + user.id = id; +}); +const user = { id: "", name: "", history: [], connected: false }; + let pretext = "root@baipyr.us:~# "; // Initiating variables @@ -6,7 +33,7 @@ const length = pretext.length+1; let startPosition = length; let cursorPosition = 0; let cursorYOffset = 7; -let history = {index: 0, list: []}; +let history = { index: 0, list: [] }; // Initiating constants const tbDiv = document.getElementById("textbox");