-
Notifications
You must be signed in to change notification settings - Fork 0
/
minitchat.js
110 lines (91 loc) · 2.58 KB
/
minitchat.js
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
const express = require('express')
const app = express()
const server = require('http').createServer(app)
const port = process.env.PORT || 3000
const io = require('socket.io')(server)
const path = require('path')
const formidable = require('formidable')
const sqlite3 = require('sqlite3').verbose()
const db = new sqlite3.Database('./db/minitchat.db', err => {
if (err) {
return console.error(err.message)
}
console.log('Connected to the minitchat database !')
})
let users = []
function removeItemOnce(arr, value) {
const index = arr.indexOf(value)
if (index > -1) {
arr.splice(index, 1)
}
return arr
}
app.use(express.static(path.join(__dirname + '/public')))
app.route('/files')
.get((req, res) => {
res.redirect(`/liens`)
})
.post((req, res, next) => {
const form = formidable({
uploadDir: `${__dirname}/public/files`,
keepExtensions: true,
maxFileSize: 10000000,
filename: (name, ext, part, form) => {
return part.originalFilename.replaceAll(' ', '_')
}
})
form.parse(req, (err, fields, files) => {
if (err) {
next(err)
return
}
res.json(String(files.file.newFilename))
})
})
db.run('CREATE TABLE IF NOT EXISTS messages(text, time, name)')
io.on('connection', socket => {
// Display number of connected users
console.log(io.engine.clientsCount)
// On user connexion, add name to names array
// Then send name & user list to client
socket.on('user', name => {
socket.name = name
users.push(name)
io.emit('newUser', {name, users})
socket.on('disconnect', () => {
users = removeItemOnce(users, socket.name)
io.emit('leave', {name: socket.name, users})
})
})
socket.on('getMessages', () => {
db.all('SELECT * FROM messages ORDER BY time DESC LIMIT 100', [], (err, messages) => {
io.emit('setMessages', messages.reverse())
})
})
socket.on('chat', message => {
db.run(`INSERT INTO messages(text, time, name) VALUES (?, ?, ?)`, [message.text, message.time, message.name], err => {
if (err) {
throw err
}
})
io.emit('chat', message)
})
socket.on('isTyping', name => {
io.emit('isTyping', name)
})
socket.on('stopTyping', name => {
io.emit('stopTyping', name)
})
// Get All messages containing "<a href="
socket.on('getLinks', () => {
db.all(`SELECT * FROM messages WHERE text GLOB '*<a href=*'`, [], (err, links) => {
if (err) {
throw err
}
io.emit('allLinks', (links))
})
})
})
server.listen(port, () => {
console.log(`Server is running on port: ${port}`)
})