-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
116 lines (98 loc) · 2.98 KB
/
Copy pathindex.js
File metadata and controls
116 lines (98 loc) · 2.98 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
const express = require('express');
const http = require('http');
const path = require('path');
const {Server} = require('socket.io');
const port = 4000;
const sqlite3 = require('sqlite3');
const { open } = require('sqlite');
//databases
async function main(){
const db = await open({
filename: 'chat.db',
driver: sqlite3.Database
});
// create our 'messages' table (you can ignore the 'client_offset' column for now)
await db.exec(`
CREATE TABLE IF NOT EXISTS messages (
id INTEGER PRIMARY KEY AUTOINCREMENT,
sender TEXT,
receiver TEXT,
content TEXT
);
`);
//initialization
const app = express();
const myserver = http.createServer(app);
const io = new Server(myserver);
const users = {};
//middlewares
app.use(express.urlencoded({extended : false}));
app.use(express.json());
app.use(express.static('templates'));
app.use(express.static('public'));
//routes
app.get('/', (req, res)=>{
return res.sendFile(path.join(__dirname, 'templates/message.html'));
})
io.on('connection', async (socket)=>{
console.log('a user connected');
socket.on('disconnect', ()=>{
if (socket.name) {
delete users[socket.name];
}
console.log('user disconnected');
})
socket.on('chat message', async ({ to, message }) => {
result = await db.run(
'INSERT INTO messages (sender, receiver, content) VALUES (?, ?, ?)',
[socket.name, to, message]
);
const targetSocketId = users[to];
if (targetSocketId) {
io.to(targetSocketId).emit('chat message', {
from: socket.name,
to: to,
message,
serveroffset: result.lastID,
});
} else {
socket.emit('chat message', {
from: 'System',
message: `User "${to}" is offline. Message saved.`,
});
}
});
socket.on('registration', async (name) => {
users[name] = socket.id;
socket.name = name;
console.log(`${name} registered with ID ${socket.id}`);
try {
// Fetch messages where the user is the receiver or sender
const messages = await db.all(
`SELECT sender, receiver, content FROM messages
WHERE sender = ? OR receiver = ?
ORDER BY id ASC`,
[name, name]
);
for (const msg of messages) {
// Determine the direction: 'sent' or 'received'
const direction = msg.sender === name ? 'sent' : 'received';
// Emit the message with direction
socket.emit('chat message', {
from: msg.sender,
to: msg.receiver,
message: msg.content,
serveroffset: msg.id // if needed
});
}
} catch (err) {
console.error('Error fetching messages:', err);
}
});
})
//setting up a http server
myserver.listen(port, ()=>{
console.log('server has started listening');
})
}
main();