// Global networking variables const user = { id: "", name: "", history: [], connected: false, chatPull: null }; let chatMode = "default"; // Tell server to disconnect document.body.onunload = document.body.onbeforeunload = () => { if (user.connected) fetch('/disconnect', { method: 'POST', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' }, body: JSON.stringify({ name: user.name, id: user.id }) }).then(res => {}); }; // Connect to server function connect(name) { user.name = name; fetch('/connect', { method: 'POST', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' }, body: JSON.stringify({ name }) }).then(res => { if (res.status === 200) { user.connected = true; return res.json(); } // No valid status code was sent console.error("Could not connect to server!"); }).then(res => { if (res === undefined) return; // Save provided id const { id } = res; user.id = id; outputText({output: `Connected as '${name}#${id}'.`}); }); } // Send nickname to server, receive verification function sendNickname(name) { fetch('/nickname', { method: 'POST', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' }, body: JSON.stringify({ oldName: user.name, id: user.id, name }) }).then(res => { if (res.status === 200) return res.json(); }).then(res => { // No valid status code if (res === undefined) return; // Receive name and save it const { id } = res; user.name = name; user.id = id; // Reply whether name is taken or not outputText({output: `Applied name '${name}#${id}'.`}); }); } // Pull incoming chat messages function getChatMessages() { fetch('/getChat', { method: 'POST', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' }, body: JSON.stringify({ name: user.name, id: user.id }) }).then(res => { // Incoming messages if (res.status === 200) return res.json(); // No new messages else if (res.status === 204) return; cmd_exit("Error occurred while fetching messages!"); }).then(res => { // No messages or invalid status code if (res === undefined) return; // Output all messages by user for (const user in res) for (const msg of res[user]) outputText({ preNext: `${user}: `, output: msg }); }); } // Send a direct message, do not look at response function directMessage(name, message) { fetch('/message', { method: 'POST', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' }, body: JSON.stringify({ recipient: name, name: user.name, id: user.id, message }) }).then(res => {}); } // function globalMessage(message) {} // Request all usernames and number of anonymous users function requestUsernames() { fetch('/getNames', { method: 'GET', headers: { 'Accept': 'application/json', } }).then(res => { if (res.status === 200) return res.json(); }).then(res => { if (res === undefined) return; let output = ""; for (const u of res) output += `${u.name}#${u.id} `; outputText({ output }); }); }