-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
73 lines (63 loc) · 2 KB
/
Copy pathindex.js
File metadata and controls
73 lines (63 loc) · 2 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
const express = require('express');
const app = express();
const http = require('http').Server(app);
const io = require('socket.io')(http);
const port = process.env.PORT || 5000;
const moniker = require('moniker');
//TODO: is their a better way, like a way where i can use the whole js file with require
const {
randomColorFromString,
remove_from,
escapeHtml,
getTimeStamp
} = require('./helper');
var users = [];
var randomName = moniker.generator([moniker.adjective, moniker.noun]);
app.use(express.static('public'));
http.listen(port, function() {
console.log(`webserver listening on *:${port}`);
});
io.on('connection', function(socket) {
console.log('a user connected');
var user = {
role: "user",
socketID: socket.id,
name: randomName.choose(),
message: null,
color: "crimson",
time: null
};
user.color = randomColorFromString(user.name);
users.push(user);
var bot = {
role: "bot",
message: `🟢 ${users.length} users connected`
}
io.emit('chat message', bot);
if (users.length == 1) {
bot.message = "🔴 only you in chat"
io.emit('chat message', bot);
}
socket.on('chat message', function(msg) {
if (msg.slice(0, 5) == "/name" && msg.slice(6)) {
console.log(`user ${user.name} changed his name to ${msg.slice(6)}`);
user.name = msg.slice(6);
} else {
console.log(`got message '${msg}', broadcasting to all`);
user.message = escapeHtml(msg);
user.time = getTimeStamp();
io.emit('chat message', user);
}
});
socket.on('reaction', function(msg) {
console.log(`got reaction, broadcasting to all`);
user.message = msg;
user.time = getTimeStamp();
io.emit('reaction', user);
});
socket.on('disconnect', function() {
remove_from(users, socket);
io.emit('chat message', bot);
console.log('user disconnected');
});
});