ircz/server/socket/index.js

71 lines
2.2 KiB
JavaScript

const users = {}
module.exports = io => {
io.on('connection', async socket => {
console.log(`A socket connection to the server has been made: ${socket.id}`)
users[socket.id] = { socketId: socket.id, nick: socket.id }
socket.join('#projex', () => {
sendUsers() // back to socket
sendUser(users[socket.id]) // announced to all
sendNamespaces()
})
socket.on('message', message => {
console.log('sending message to namespace', message.namespace, message)
io.to(message.namespace).emit('message', message)
})
socket.on('join', namespace => {
console.log('join:', namespace)
socket.join(namespace, () => {
sendNamespaces()
})
})
socket.on('chat', user => {
const target = io.sockets.sockets[user.socketId]
if (!target) return
if (socket.id === target.id) {
console.log('Not allowing chat with itself', socket.id, target.id)
return
}
// create a shared namespace
const namespace = `${socket.id.substr(0, 5)}.${target.id.substr(0, 5)}`
console.log(`${socket.id} starts chat with ${target.id} in ${namespace}`)
socket.join(namespace)
target.join(namespace)
sendNamespaces()
})
socket.on('part', namespace => {
console.log('part', socket.id, namespace)
socket.leave(namespace, () => {
sendNamespaces()
})
})
socket.on('change nick', nick => {
io.emit('nick changed', { socketId: socket.id, nick: nick })
})
socket.on('get namespaces', () => sendNamespaces())
const sendNamespaces = () => {
const namespaces = Object.keys(io.sockets.adapter.rooms).map(k => ({
namespace: k,
sockets: Object.keys(io.sockets.adapter.rooms[k]['sockets']),
}))
io.emit('got namespaces', namespaces)
}
const sendUser = user => socket.broadcast.emit('user connected', user)
const sendUsers = () =>
socket.emit('got users', Object.keys(users).map(u => users[u]))
socket.on('disconnect', async () => {
io.emit('user disconnected', { socketId: socket.id })
console.log(`${socket.id} has disconnected.`)
sendNamespaces()
})
})
}