one-way communication without frontent :)
This commit is contained in:
parent
3a742b1f34
commit
81ae05c583
|
@ -63,3 +63,11 @@ CREATE UNIQUE INDEX IF NOT EXISTS hwids_publickey_idx ON hwids (publickey);
|
||||||
|
|
||||||
-- Add the foreign key constraint to the users table if it doesn't exist
|
-- Add the foreign key constraint to the users table if it doesn't exist
|
||||||
-- ALTER TABLE public.users ADD CONSTRAINT IF NOT EXISTS users_hwids_fk FOREIGN KEY (hwidid) REFERENCES public.hwids(id);
|
-- ALTER TABLE public.users ADD CONSTRAINT IF NOT EXISTS users_hwids_fk FOREIGN KEY (hwidid) REFERENCES public.hwids(id);
|
||||||
|
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS chat_messages (
|
||||||
|
id SERIAL PRIMARY KEY,
|
||||||
|
author VARCHAR(32) REFERENCES users(username),
|
||||||
|
datetime TIMESTAMP,
|
||||||
|
content TEXT
|
||||||
|
);
|
|
@ -1,6 +1,29 @@
|
||||||
|
function getCookie(name) {
|
||||||
|
const value = `; ${document.cookie}`;
|
||||||
|
const parts = value.split(`; ${name}=`);
|
||||||
|
if (parts.length === 2) return parts.pop().split(';').shift();
|
||||||
|
}
|
||||||
|
|
||||||
$(document).ready(() => {
|
$(document).ready(() => {
|
||||||
|
//prod
|
||||||
|
// const socket = new WebSocket('wss://auth.foxarmy.org');
|
||||||
|
//dev
|
||||||
|
const socket = new WebSocket('ws://localhost:3000');
|
||||||
|
|
||||||
|
socket.onmessage = message => {
|
||||||
|
console.log(message)
|
||||||
|
}
|
||||||
|
|
||||||
const sendData = async () => {
|
const sendData = async () => {
|
||||||
alert(1);
|
const jwt = getCookie("jwt");
|
||||||
|
const author = await (await fetch(`/api/getUsername`)).json()
|
||||||
|
const content = $("#chat-input").val();
|
||||||
|
|
||||||
|
const message = {
|
||||||
|
jwt, author, content
|
||||||
|
};
|
||||||
|
|
||||||
|
socket.send(JSON.stringify(message));
|
||||||
}
|
}
|
||||||
|
|
||||||
$("#send-message-button").click(sendData);
|
$("#send-message-button").click(sendData);
|
||||||
|
|
|
@ -6,6 +6,7 @@ import path from 'path';
|
||||||
|
|
||||||
import ApiRouter from './routers/api.js';
|
import ApiRouter from './routers/api.js';
|
||||||
import UserRouter from './routers/user.js';
|
import UserRouter from './routers/user.js';
|
||||||
|
import startChat from './messages.js';
|
||||||
|
|
||||||
const app = express();
|
const app = express();
|
||||||
|
|
||||||
|
@ -29,6 +30,7 @@ app.use('/', UserRouter);
|
||||||
|
|
||||||
const server = app.listen(process.env.PORT, () => {
|
const server = app.listen(process.env.PORT, () => {
|
||||||
console.log("App has been started!");
|
console.log("App has been started!");
|
||||||
|
startChat();
|
||||||
});
|
});
|
||||||
|
|
||||||
export default server;
|
export default server;
|
||||||
|
|
138
src/messages.js
138
src/messages.js
|
@ -1,68 +1,102 @@
|
||||||
import { Kafka } from "kafkajs";
|
import { Kafka } from "kafkajs";
|
||||||
import ws from 'ws';
|
import { WebSocketServer } from 'ws';
|
||||||
import jwt from 'jwt';
|
import jwt from 'jsonwebtoken';
|
||||||
|
|
||||||
import server from './index.js';
|
import server from './index.js';
|
||||||
|
import db from './db.js';
|
||||||
|
|
||||||
const kafka = new Kafka({
|
const startChat = async () => {
|
||||||
clientId: 'backend',
|
|
||||||
brokers: ['kafka:9092']
|
|
||||||
});
|
|
||||||
|
|
||||||
const wsClients = [];
|
const kafka = new Kafka({
|
||||||
|
clientId: 'backend',
|
||||||
|
brokers: ['localhost:9092']
|
||||||
|
// brokers: ['kafka:9092']
|
||||||
|
});
|
||||||
|
|
||||||
const producer = kafka.producer();
|
let wsClients = [];
|
||||||
const consumer = kafka.consumer();
|
|
||||||
|
|
||||||
await producer.connect();
|
const producer = kafka.producer();
|
||||||
await consumer.connect();
|
const consumer = kafka.consumer({ groupId: 'chat-group' });
|
||||||
await consumer.subscribe({
|
|
||||||
topic: "chatMessage",
|
|
||||||
fromBeginning: true
|
|
||||||
});
|
|
||||||
|
|
||||||
const onMessageFromServer = async ({ topic, partition, message }) => {
|
await producer.connect();
|
||||||
wsClients.forEach(client => {
|
await consumer.connect();
|
||||||
client.send({
|
await consumer.subscribe({
|
||||||
message
|
topic: "chatMessage",
|
||||||
})
|
fromBeginning: true
|
||||||
})
|
});
|
||||||
};
|
|
||||||
|
|
||||||
await consumer.run({
|
await consumer.run({
|
||||||
eachMessage: onMessageFromServer
|
eachMessage: async ({topic, partition, message}) => {
|
||||||
});
|
const jsonMessage = JSON.parse(message.value.toString())
|
||||||
|
if (jsonMessage.origin == "website") return;
|
||||||
const wsServer = new ws.Server({ noServer: true });
|
console.log(wsClients.length)
|
||||||
wsServer.on('connection', socket => {
|
wsClients.forEach(client => {
|
||||||
wsClients.push(socket);
|
console.log("sending message to a client")
|
||||||
socket.on('message', async (message) => {
|
client.send(JSON.stringify({
|
||||||
|
author: jsonMessage.author,
|
||||||
const token = message.jwt;
|
content: jsonMessage.content,
|
||||||
if (!jwt.verify(token, process.env.secret)) {
|
timestamp: jsonMessage.timestamp
|
||||||
socket.send("JWT is not valid.")
|
}));
|
||||||
return;
|
});
|
||||||
|
console.log(message.value.toString());
|
||||||
}
|
}
|
||||||
|
|
||||||
await producer.send({
|
});
|
||||||
topic: 'chatMessage',
|
|
||||||
messages: [{
|
const wsServer = new WebSocketServer({ noServer: true });
|
||||||
author: message.author,
|
wsServer.on('connection', socket => {
|
||||||
content: message.content,
|
console.log("Hooray! New socket connection")
|
||||||
date: message.date
|
wsClients.push(socket);
|
||||||
}]
|
socket.on('message', async (message) => {
|
||||||
|
message = JSON.parse(message.toString());
|
||||||
|
if (!message || !message.author || !message.content || !message.jwt) {
|
||||||
|
socket.send("Malformed package.");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
console.log(message);
|
||||||
|
const token = message.jwt;
|
||||||
|
if (!jwt.verify(token, process.env.SECRET)) {
|
||||||
|
socket.send("JWT is not valid.");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const datetime = Math.round(Date.now() / 1000);
|
||||||
|
|
||||||
|
await db.query(
|
||||||
|
"INSERT INTO chat_messages(author, datetime, content) VALUES ($1, to_timestamp($2)::timestamp, $3)",
|
||||||
|
[message.author, datetime, message.content])
|
||||||
|
.catch(e => {
|
||||||
|
console.log("Error on inserting data into the DB: ", e);
|
||||||
|
});
|
||||||
|
|
||||||
|
|
||||||
|
await producer.send({
|
||||||
|
topic: 'chatMessage',
|
||||||
|
messages: [{
|
||||||
|
value: JSON.stringify({
|
||||||
|
author: message.author,
|
||||||
|
content: message.content,
|
||||||
|
timestamp: datetime,
|
||||||
|
origin: "website"
|
||||||
|
})
|
||||||
|
}]
|
||||||
|
});
|
||||||
|
// we are not sending this message to all websockets right now, because plugin will emit
|
||||||
|
// a chat event once it'll catch this message from kafka, triggering a new message
|
||||||
|
// that will return here as if it was send from the minecraft.
|
||||||
|
});
|
||||||
|
|
||||||
|
socket.on('close', async () => {
|
||||||
|
wsClients = wsClients.filter(s => s !== socket);
|
||||||
|
await producer.disconnect();
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
socket.on('close', async () => {
|
server.on('upgrade', (request, socket, head) => {
|
||||||
wsClients = wsClients.filter(s => s !== socket);
|
wsServer.handleUpgrade(request, socket, head, socket => {
|
||||||
await producer.disconnect();
|
wsServer.emit('connection', socket, request);
|
||||||
});
|
})
|
||||||
});
|
|
||||||
|
|
||||||
server.on('upgrade', (request, socket, head) => {
|
|
||||||
wsServer.handleUpgrade(request, socket, head, socket => {
|
|
||||||
wsServer.emit('connection', socket, request);
|
|
||||||
})
|
})
|
||||||
})
|
}
|
||||||
|
|
||||||
|
export default startChat;
|
Loading…
Reference in New Issue