/var/www/greso.tech/server/nsm/services
Edit: /var/www/greso.tech/server/nsm/services/webSocket.service.js (4611B)
const jwt = require('jsonwebtoken')
const config = require('../config/app.json')
const { Server } = require('socket.io')
const { isSet, isEmpty } = require('../utils/validator.util')
const logger = require('../logger')({ service: 'WebSocketService' })
module.exports = class WebSocketService {
constructor({ db, httpServer }) {
this.io = new Server(httpServer, {
origin: "*:*",
cors: {
origin: "*",
methods: ["GET", "POST"]
}
})
this.io.on('connection', (socket) => {
logger.child({ socket: socket.id, event: 'connection', status: 'success' }).info()
socket.on('login', async ({ token, appId }) => {
logger.child({ socket: socket.id }).info('login')
try {
if (!isSet(token) || isEmpty(token)) {
throw new Error('Token required')
}
if (!isSet(appId) || isEmpty(appId)) {
throw new Error('appId required')
}
var user;
jwt.verify(token, config.jwt.secret, (err, decoded) => {
if (err) {
throw new Unauthorized({ code: 401 })
}
user = decoded
})
// const user = await db.user.findOne({
// include: [{ model: db.branch, through: 'branch_users', as: 'userBranches' }],
// where: { id: id }
// })
// if (!user) {
// throw new Error('User not found')
// }
// всякие проверки, подкрлючение к группам ...
socket.user = user
socket.userId = user.id
if (appId) {
socket.appId = appId
switch (parseInt(appId)) {
case APPID.CRM:
socket.join('crm')
if (user.companies) {
for (const c of user.companies) {
socket.join(`crm-company-${c.companyId}`)
}
}
if (user.branches) {
for (const b of user.branches) {
socket.join(`crm-branch-${b.branchId}`)
}
}
break
case APPID.CLIENT:
socket.join('clients')
}
}
socket.emit('login', { status: 'success' })
logger.child({ socket: socket.id, event: 'login', status: 'success' }).info()
} catch (error) {
socket.emit('login', { status: 'error', message: error.message })
logger
.child({ socket: socket.id, event: 'login', status: 'error' })
.info(error.message)
}
})
socket.on('selectRole', async ({ roleId }) => {
logger.child({ socket: socket.id }).info('selectRole')
try {
if (!isSet(roleId) || isEmpty(roleId)) {
throw new Error('Role required')
}
// socket.user = user
// if (appId) {
// socket.appId = appId
// switch (parseInt(appId)) {
// case APPID.CRM:
// socket.join('crm')
// if (user.branches) {
// for (const b of user.branches) {
// socket.join(`crm-branch-${b.branchId}`)
// }
// }
// break
// case APPID.CLIENT:
// socket.join('clients')
// }
// }
socket.emit('selectRole', { status: 'success' })
logger.child({ socket: socket.id, event: 'selectRole', status: 'success' }).info()
} catch (error) {
socket.emit('selectRole', { status: 'error', message: error.message })
logger
.child({ socket: socket.id, event: 'selectRole', status: 'error' })
.info(error.message)
}
})
socket.on('disconnect', (reason) => {
logger.child({ socket: socket.id, event: 'disconnect' }).info(reason)
})
})
}
SendToAll = (event, param) => {
return this.io.emit(event, param)
}
SendToClients = async (event, param) => {
return this.io.to('clients').emit(event, param)
}
SendToClient = async (userId, event, param) => {
const sockets = (await this.io.in('clients').fetchSockets())?.filter(
(p) => p.userId == userId
)
if (sockets.length == 0) {
return false
}
for (const socket of sockets) {
socket.emit(event, param)
}
return true
}
SendToCrm = async (event, param) => {
// const opers = await this.io.in('crm').fetchSockets()
// console.log(opers)
return this.io.to('crm').emit(event, param)
}
SendToCrmByCompany = async (companyId, event, param) => {
return this.io.to(`crm-company-${companyId}`).emit(event, param)
}
SendToCrmByBranch = async (branchId, event, param) => {
return this.io.to(`crm-branch-${branchId}`).emit(event, param)
}
SendToOperator = async (userId, event, param) => {
const sockets = (await this.io.in('crm').fetchSockets())?.filter(
(p) => p.userId == userId
)
if (sockets.length == 0) {
return false
}
for (const socket of sockets) {
socket.emit(event, param)
}
return true
}
}