2022-11-24 22:53:58 +01:00
|
|
|
const SocketIO = require('socket.io')
|
|
|
|
const Logger = require('./Logger')
|
2023-07-05 01:14:44 +02:00
|
|
|
const Database = require('./Database')
|
2023-11-22 18:00:11 +01:00
|
|
|
const Auth = require('./Auth')
|
2022-11-24 22:53:58 +01:00
|
|
|
|
2024-08-10 22:46:04 +02:00
|
|
|
/**
|
|
|
|
* @typedef SocketClient
|
|
|
|
* @property {string} id socket id
|
|
|
|
* @property {SocketIO.Socket} socket
|
|
|
|
* @property {number} connected_at
|
|
|
|
* @property {import('./models/User')} user
|
|
|
|
*/
|
|
|
|
|
2022-11-24 22:53:58 +01:00
|
|
|
class SocketAuthority {
|
|
|
|
constructor() {
|
|
|
|
this.Server = null
|
|
|
|
this.io = null
|
|
|
|
|
2024-08-10 22:46:04 +02:00
|
|
|
/** @type {Object.<string, SocketClient>} */
|
2022-11-24 22:53:58 +01:00
|
|
|
this.clients = {}
|
|
|
|
}
|
|
|
|
|
2023-08-12 23:11:58 +02:00
|
|
|
/**
|
|
|
|
* returns an array of User.toJSONForPublic with `connections` for the # of socket connections
|
|
|
|
* a user can have many socket connections
|
|
|
|
* @returns {object[]}
|
|
|
|
*/
|
2022-11-24 22:53:58 +01:00
|
|
|
getUsersOnline() {
|
|
|
|
const onlineUsersMap = {}
|
2024-08-10 22:46:04 +02:00
|
|
|
Object.values(this.clients)
|
|
|
|
.filter((c) => c.user)
|
|
|
|
.forEach((client) => {
|
|
|
|
if (onlineUsersMap[client.user.id]) {
|
|
|
|
onlineUsersMap[client.user.id].connections++
|
|
|
|
} else {
|
|
|
|
onlineUsersMap[client.user.id] = {
|
|
|
|
...client.user.toJSONForPublic(this.Server.playbackSessionManager.sessions),
|
|
|
|
connections: 1
|
|
|
|
}
|
2022-11-24 22:53:58 +01:00
|
|
|
}
|
2024-08-10 22:46:04 +02:00
|
|
|
})
|
2022-11-24 22:53:58 +01:00
|
|
|
return Object.values(onlineUsersMap)
|
|
|
|
}
|
|
|
|
|
|
|
|
getClientsForUser(userId) {
|
2024-08-10 22:46:04 +02:00
|
|
|
return Object.values(this.clients).filter((c) => c.user?.id === userId)
|
2022-11-24 22:53:58 +01:00
|
|
|
}
|
|
|
|
|
2023-08-26 23:33:27 +02:00
|
|
|
/**
|
|
|
|
* Emits event to all authorized clients
|
2024-08-10 22:46:04 +02:00
|
|
|
* @param {string} evt
|
|
|
|
* @param {any} data
|
2023-08-26 23:33:27 +02:00
|
|
|
* @param {Function} [filter] optional filter function to only send event to specific users
|
|
|
|
*/
|
2022-12-01 00:32:59 +01:00
|
|
|
emitter(evt, data, filter = null) {
|
2022-11-24 22:53:58 +01:00
|
|
|
for (const socketId in this.clients) {
|
2022-11-24 23:35:26 +01:00
|
|
|
if (this.clients[socketId].user) {
|
2022-12-01 00:32:59 +01:00
|
|
|
if (filter && !filter(this.clients[socketId].user)) continue
|
|
|
|
|
2022-11-24 23:35:26 +01:00
|
|
|
this.clients[socketId].socket.emit(evt, data)
|
|
|
|
}
|
2022-11-24 22:53:58 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-11-24 23:35:26 +01:00
|
|
|
// Emits event to all clients for a specific user
|
|
|
|
clientEmitter(userId, evt, data) {
|
|
|
|
const clients = this.getClientsForUser(userId)
|
2022-11-24 22:53:58 +01:00
|
|
|
if (!clients.length) {
|
2023-08-01 23:34:01 +02:00
|
|
|
return Logger.debug(`[SocketAuthority] clientEmitter - no clients found for user ${userId}`)
|
2022-11-24 22:53:58 +01:00
|
|
|
}
|
|
|
|
clients.forEach((client) => {
|
|
|
|
if (client.socket) {
|
2022-11-24 23:35:26 +01:00
|
|
|
client.socket.emit(evt, data)
|
2022-11-24 22:53:58 +01:00
|
|
|
}
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
2022-11-24 23:35:26 +01:00
|
|
|
// Emits event to all admin user clients
|
|
|
|
adminEmitter(evt, data) {
|
|
|
|
for (const socketId in this.clients) {
|
2024-08-10 22:46:04 +02:00
|
|
|
if (this.clients[socketId].user?.isAdminOrUp) {
|
2022-11-24 23:35:26 +01:00
|
|
|
this.clients[socketId].socket.emit(evt, data)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-12-28 23:32:21 +01:00
|
|
|
/**
|
|
|
|
* Closes the Socket.IO server and disconnect all clients
|
2024-08-10 22:46:04 +02:00
|
|
|
*
|
|
|
|
* @param {Function} callback
|
2023-12-28 23:32:21 +01:00
|
|
|
*/
|
2023-12-27 14:33:33 +01:00
|
|
|
close(callback) {
|
|
|
|
Logger.info('[SocketAuthority] Shutting down')
|
|
|
|
// This will close all open socket connections, and also close the underlying http server
|
2024-08-10 22:46:04 +02:00
|
|
|
if (this.io) this.io.close(callback)
|
|
|
|
else callback()
|
2023-12-27 14:33:33 +01:00
|
|
|
}
|
|
|
|
|
2022-11-24 22:53:58 +01:00
|
|
|
initialize(Server) {
|
|
|
|
this.Server = Server
|
|
|
|
|
|
|
|
this.io = new SocketIO.Server(this.Server.server, {
|
|
|
|
cors: {
|
|
|
|
origin: '*',
|
2024-08-10 22:46:04 +02:00
|
|
|
methods: ['GET', 'POST']
|
2022-11-24 22:53:58 +01:00
|
|
|
}
|
|
|
|
})
|
2023-11-22 18:00:11 +01:00
|
|
|
|
2022-11-24 22:53:58 +01:00
|
|
|
this.io.on('connection', (socket) => {
|
|
|
|
this.clients[socket.id] = {
|
|
|
|
id: socket.id,
|
|
|
|
socket,
|
|
|
|
connected_at: Date.now()
|
|
|
|
}
|
|
|
|
socket.sheepClient = this.clients[socket.id]
|
|
|
|
|
2023-08-01 23:34:01 +02:00
|
|
|
Logger.info('[SocketAuthority] Socket Connected', socket.id)
|
2022-11-24 22:53:58 +01:00
|
|
|
|
|
|
|
// Required for associating a User with a socket
|
|
|
|
socket.on('auth', (token) => this.authenticateSocket(socket, token))
|
|
|
|
|
|
|
|
// Scanning
|
2023-09-04 18:50:55 +02:00
|
|
|
socket.on('cancel_scan', (libraryId) => this.cancelScan(libraryId))
|
2022-11-24 22:53:58 +01:00
|
|
|
|
|
|
|
// Logs
|
|
|
|
socket.on('set_log_listener', (level) => Logger.addSocketListener(socket, level))
|
|
|
|
socket.on('remove_log_listener', () => Logger.removeSocketListener(socket.id))
|
|
|
|
|
|
|
|
// Sent automatically from socket.io clients
|
|
|
|
socket.on('disconnect', (reason) => {
|
|
|
|
Logger.removeSocketListener(socket.id)
|
|
|
|
|
|
|
|
const _client = this.clients[socket.id]
|
|
|
|
if (!_client) {
|
2023-08-01 23:34:01 +02:00
|
|
|
Logger.warn(`[SocketAuthority] Socket ${socket.id} disconnect, no client (Reason: ${reason})`)
|
2022-11-24 22:53:58 +01:00
|
|
|
} else if (!_client.user) {
|
2023-08-01 23:34:01 +02:00
|
|
|
Logger.info(`[SocketAuthority] Unauth socket ${socket.id} disconnected (Reason: ${reason})`)
|
2022-11-24 22:53:58 +01:00
|
|
|
delete this.clients[socket.id]
|
|
|
|
} else {
|
2023-08-01 23:34:01 +02:00
|
|
|
Logger.debug('[SocketAuthority] User Offline ' + _client.user.username)
|
2023-08-12 23:11:58 +02:00
|
|
|
this.adminEmitter('user_offline', _client.user.toJSONForPublic(this.Server.playbackSessionManager.sessions))
|
2022-11-24 22:53:58 +01:00
|
|
|
|
|
|
|
const disconnectTime = Date.now() - _client.connected_at
|
2023-08-01 23:34:01 +02:00
|
|
|
Logger.info(`[SocketAuthority] Socket ${socket.id} disconnected from client "${_client.user.username}" after ${disconnectTime}ms (Reason: ${reason})`)
|
2022-11-24 22:53:58 +01:00
|
|
|
delete this.clients[socket.id]
|
|
|
|
}
|
|
|
|
})
|
2022-11-24 23:35:26 +01:00
|
|
|
|
|
|
|
//
|
|
|
|
// Events for testing
|
|
|
|
//
|
|
|
|
socket.on('message_all_users', (payload) => {
|
|
|
|
// admin user can send a message to all authenticated users
|
|
|
|
// displays on the web app as a toast
|
|
|
|
const client = this.clients[socket.id] || {}
|
2024-08-10 22:46:04 +02:00
|
|
|
if (client.user?.isAdminOrUp) {
|
2022-11-24 23:35:26 +01:00
|
|
|
this.emitter('admin_message', payload.message || '')
|
|
|
|
} else {
|
2023-08-01 23:34:01 +02:00
|
|
|
Logger.error(`[SocketAuthority] Non-admin user sent the message_all_users event`)
|
2022-11-24 23:35:26 +01:00
|
|
|
}
|
|
|
|
})
|
|
|
|
socket.on('ping', () => {
|
|
|
|
const client = this.clients[socket.id] || {}
|
|
|
|
const user = client.user || {}
|
2023-08-01 23:34:01 +02:00
|
|
|
Logger.debug(`[SocketAuthority] Received ping from socket ${user.username || 'No User'}`)
|
2022-11-24 23:35:26 +01:00
|
|
|
socket.emit('pong')
|
|
|
|
})
|
2022-11-24 22:53:58 +01:00
|
|
|
})
|
|
|
|
}
|
|
|
|
|
2023-11-22 18:00:11 +01:00
|
|
|
/**
|
|
|
|
* When setting up a socket connection the user needs to be associated with a socket id
|
|
|
|
* for this the client will send a 'auth' event that includes the users API token
|
2024-08-10 22:46:04 +02:00
|
|
|
*
|
|
|
|
* @param {SocketIO.Socket} socket
|
2023-11-22 18:00:11 +01:00
|
|
|
* @param {string} token JWT
|
|
|
|
*/
|
2022-11-24 22:53:58 +01:00
|
|
|
async authenticateSocket(socket, token) {
|
2023-11-22 18:00:11 +01:00
|
|
|
// we don't use passport to authenticate the jwt we get over the socket connection.
|
|
|
|
// it's easier to directly verify/decode it.
|
|
|
|
const token_data = Auth.validateAccessToken(token)
|
|
|
|
|
|
|
|
if (!token_data?.userId) {
|
|
|
|
// Token invalid
|
|
|
|
Logger.error('Cannot validate socket - invalid token')
|
|
|
|
return socket.emit('invalid_token')
|
|
|
|
}
|
2024-08-10 22:46:04 +02:00
|
|
|
|
2023-11-22 18:00:11 +01:00
|
|
|
// get the user via the id from the decoded jwt.
|
|
|
|
const user = await Database.userModel.getUserByIdOrOldId(token_data.userId)
|
2022-11-24 22:53:58 +01:00
|
|
|
if (!user) {
|
2023-11-22 18:00:11 +01:00
|
|
|
// user not found
|
2022-11-24 22:53:58 +01:00
|
|
|
Logger.error('Cannot validate socket - invalid token')
|
|
|
|
return socket.emit('invalid_token')
|
|
|
|
}
|
2023-11-22 18:00:11 +01:00
|
|
|
|
2022-11-24 22:53:58 +01:00
|
|
|
const client = this.clients[socket.id]
|
2023-08-01 23:34:01 +02:00
|
|
|
if (!client) {
|
|
|
|
Logger.error(`[SocketAuthority] Socket for user ${user.username} has no client`)
|
|
|
|
return
|
|
|
|
}
|
2022-11-24 22:53:58 +01:00
|
|
|
|
|
|
|
if (client.user !== undefined) {
|
2023-08-01 23:34:01 +02:00
|
|
|
Logger.debug(`[SocketAuthority] Authenticating socket client already has user`, client.user.username)
|
2022-11-24 22:53:58 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
client.user = user
|
|
|
|
|
2023-08-01 23:34:01 +02:00
|
|
|
Logger.debug(`[SocketAuthority] User Online ${client.user.username}`)
|
2022-11-24 22:53:58 +01:00
|
|
|
|
2023-08-12 23:11:58 +02:00
|
|
|
this.adminEmitter('user_online', client.user.toJSONForPublic(this.Server.playbackSessionManager.sessions))
|
2022-11-24 22:53:58 +01:00
|
|
|
|
2023-11-24 21:27:32 +01:00
|
|
|
// Update user lastSeen without firing sequelize bulk update hooks
|
2022-11-24 22:53:58 +01:00
|
|
|
user.lastSeen = Date.now()
|
2024-08-10 22:46:04 +02:00
|
|
|
await user.save({ hooks: false })
|
2022-11-24 22:53:58 +01:00
|
|
|
|
|
|
|
const initialPayload = {
|
|
|
|
userId: client.user.id,
|
2023-10-21 19:56:35 +02:00
|
|
|
username: client.user.username
|
2022-11-24 22:53:58 +01:00
|
|
|
}
|
|
|
|
if (user.isAdminOrUp) {
|
|
|
|
initialPayload.usersOnline = this.getUsersOnline()
|
|
|
|
}
|
|
|
|
client.socket.emit('init', initialPayload)
|
|
|
|
}
|
|
|
|
|
|
|
|
cancelScan(id) {
|
2023-08-01 23:34:01 +02:00
|
|
|
Logger.debug('[SocketAuthority] Cancel scan', id)
|
2023-09-04 18:50:55 +02:00
|
|
|
this.Server.cancelLibraryScan(id)
|
2022-11-24 22:53:58 +01:00
|
|
|
}
|
|
|
|
}
|
2024-08-10 22:46:04 +02:00
|
|
|
module.exports = new SocketAuthority()
|