2023-02-12 15:15:44 +00:00
|
|
|
let tableKey = {
|
|
|
|
name: "",
|
|
|
|
passcode: ""
|
|
|
|
}
|
|
|
|
|
|
|
|
let table = null;
|
|
|
|
|
|
|
|
let conn = null;
|
|
|
|
|
|
|
|
function dial() {
|
|
|
|
// get tableKey from UI
|
|
|
|
const tblNameInput = document.getElementById("input_table_name");
|
|
|
|
const tblPassInput = document.getElementById("input_table_pass");
|
|
|
|
if (tblNameInput && tblPassInput && tblNameInput.value && tblPassInput.value) {
|
|
|
|
tableKey.name = tblNameInput.value;
|
|
|
|
tableKey.passcode = tblPassInput.value;
|
|
|
|
|
|
|
|
conn = new WebSocket(`ws://${location.host}/subscribe`, `${tableKey.name}.${tableKey.passcode}`);
|
|
|
|
conn.addEventListener("close", e => {
|
|
|
|
if (e.code !== 1001) {
|
|
|
|
// TODO: add message to let user know they are reconnecting
|
|
|
|
setTimeout(dial, 1000)
|
|
|
|
}
|
|
|
|
});
|
|
|
|
conn.addEventListener("open", e => {
|
|
|
|
// TODO: add message to let user know they are at the table
|
|
|
|
console.info("socket connected");
|
|
|
|
});
|
|
|
|
conn.addEventListener("message", e => {
|
2023-02-18 06:35:29 +00:00
|
|
|
const data = JSON.parse(e.data);
|
2023-02-13 04:25:14 +00:00
|
|
|
if (table == null) {
|
2023-02-18 06:35:29 +00:00
|
|
|
// first fetch comes from mongo, so the rolls array in each diceRoll is a byte array and needs to be decoded
|
|
|
|
data.diceRolls.forEach(r=>{
|
|
|
|
r.roll = Uint8Array.from(atob(r.roll), c => c.charCodeAt(0))
|
|
|
|
})
|
2023-02-13 04:25:14 +00:00
|
|
|
table = JSON.parse(e.data);
|
|
|
|
} else {
|
|
|
|
// UPDATE THE TABLE!
|
|
|
|
}
|
2023-02-18 06:35:29 +00:00
|
|
|
console.log(data);
|
2023-02-12 15:15:44 +00:00
|
|
|
});
|
|
|
|
}
|
2023-02-13 04:25:14 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
async function publish(msg) {
|
|
|
|
msg.key = tableKey;
|
|
|
|
const res = await fetch('/publish', {
|
|
|
|
method: 'POST',
|
|
|
|
body: JSON.stringify(msg)
|
|
|
|
});
|
|
|
|
if (!res.ok) {
|
|
|
|
setErr("Failed to publish message");
|
|
|
|
}
|
2023-02-12 15:15:44 +00:00
|
|
|
}
|