vybe/client/chat.js

84 lines
2.9 KiB
JavaScript

async function register(e) {
e.preventDefault();
const name = document.getElementById("name").value;
if (!name) return;
const keys = await openpgp.generateKey({
userIDs: [{ name }],
});
const priv = await openpgp.readKey({ armoredKey: keys.privateKey });
const pub = await openpgp.readKey({ armoredKey: keys.publicKey });
window.keys = { priv, pub };
localStorage.setItem("keys", JSON.stringify(keys));
localStorage.setItem("name", name);
window.name = name;
window.socket.emit("create_user", { name, pubkey: keys.publicKey });
}
async function message(e) {
e.preventDefault();
const msg = document.getElementById("msg").value;
if (!msg) return;
const sig = await openpgp.sign({
message: new openpgp.CleartextMessage(msg, ""),
signingKeys: window.keys.priv,
});
window.socket.emit("send_message", { name: window.name, message: sig });
document.getElementById("msg").value = "";
const el = document.createElement("div");
el.classList.add("message");
el.innerHTML = `<strong>${window.name}: </strong>${msg}`;
document.getElementById("messages").appendChild(el);
}
function swap() {
document.getElementById("register").classList.add("hidden");
document.getElementById("chat").classList.remove("hidden");
}
async function loadKeys(keys) {
const priv = await openpgp.readKey({ armoredKey: keys.privateKey });
const pub = await openpgp.readKey({ armoredKey: keys.publicKey });
window.keys = { priv, pub };
}
async function loadMessages() {
window.socket.emit(
"get_history",
window.earliestMessage ? { before: window.earliestMessage } : {}
);
}
window.onload = () => {
window.socket = io();
window.socket.on("create_user", swap);
window.socket.on("new_message", (msg) => {
const el = document.createElement("div");
el.classList.add("message");
el.innerHTML = `<strong>${msg.name}: </strong>${msg.message}`;
document.getElementById("messages").appendChild(el);
if (!window.earliestMessage) window.earliestMessage = msg.id;
});
window.socket.on("send_message", (msg) => {
if (!window.earliestMessage) window.earliestMessage = msg.id;
});
window.socket.on("get_history", (msg) => {
window.earliestMessage = msg.messages[msg.messages.length - 1].id;
for (let message of msg.messages) {
const el = document.createElement("div");
el.classList.add("message");
el.innerHTML = `<strong>${message.name}: </strong>${message.message}`;
document.getElementById("messages").prepend(el);
}
if (!msg.more) document.getElementById("loadmore").classList.add("hidden");
});
const keys = localStorage.getItem("keys");
if (keys) {
window.name = localStorage.getItem("name");
loadKeys(JSON.parse(keys)).then(swap);
}
document.getElementById("registerform").onsubmit = register;
document.getElementById("msginput").onsubmit = message;
document.getElementById("loadmore").onclick = loadMessages;
};