feat: stop single session and auto start all sessions

This commit is contained in:
Anton Voylenko 2025-07-11 20:14:24 +03:00
commit 19797f4268
8 changed files with 162 additions and 7 deletions

View file

@ -1,6 +1,5 @@
require('./routes')
const express = require('express')
const { restoreSessions } = require('./sessions')
const { routes } = require('./routes')
const { maxAttachmentSize } = require('./config')
@ -12,6 +11,4 @@ app.use(express.json({ limit: maxAttachmentSize + 1000000 }))
app.use(express.urlencoded({ limit: maxAttachmentSize + 1000000, extended: true }))
app.use('/', routes)
restoreSessions()
module.exports = app

View file

@ -21,6 +21,7 @@ const releaseBrowserLock = process.env.RELEASE_BROWSER_LOCK ? (process.env.RELEA
const logLevel = process.env.LOG_LEVEL || 'info'
const enableWebHook = process.env.ENABLE_WEBHOOK ? (process.env.ENABLE_WEBHOOK).toLowerCase() === 'true' : true
const enableWebSocket = process.env.ENABLE_WEBSOCKET ? (process.env.ENABLE_WEBSOCKET).toLowerCase() === 'true' : false
const autoStartSessions = process.env.AUTO_START_SESSIONS ? (process.env.AUTO_START_SESSIONS).toLowerCase() === 'true' : true
module.exports = {
sessionFolderPath,
@ -41,5 +42,6 @@ module.exports = {
releaseBrowserLock,
logLevel,
enableWebHook,
enableWebSocket
enableWebSocket,
autoStartSessions
}

View file

@ -1,5 +1,5 @@
const qr = require('qr-image')
const { setupSession, deleteSession, reloadSession, validateSession, flushSessions, sessions } = require('../sessions')
const { setupSession, deleteSession, reloadSession, validateSession, flushSessions, destroySession, sessions } = require('../sessions')
const { sendErrorResponse, waitForNestedObject } = require('../utils')
const { logger } = require('../logger')
@ -51,6 +51,39 @@ const startSession = async (req, res) => {
}
}
/**
* Stops a session for the given session ID.
*
* @function
* @async
* @param {Object} req - The HTTP request object.
* @param {Object} res - The HTTP response object.
* @param {string} req.params.sessionId - The session ID to stop.
* @returns {Promise<void>}
* @throws {Error} If there was an error stopping the session.
*/
const stopSession = async (req, res) => {
// #swagger.summary = 'Stop session'
// #swagger.description = 'Stops a session for the given session ID.'
const sessionId = req.params.sessionId
try {
await destroySession(sessionId)
/* #swagger.responses[200] = {
description: "Status of the stopped session.",
content: {
"application/json": {
schema: { "$ref": "#/definitions/StopSessionResponse" }
}
}
}
*/
res.json({ success: true, message: 'Session stopped successfully' })
} catch (error) {
logger.error({ sessionId, err: error }, 'Failed to stop session')
sendErrorResponse(res, 500, error.message)
}
}
/**
* Status of the session with the given session ID.
*
@ -417,6 +450,7 @@ const getPageScreenshot = async (req, res) => {
module.exports = {
startSession,
stopSession,
statusSession,
sessionQrCode,
sessionQrCodeImage,

View file

@ -38,6 +38,7 @@ routes.use('/session', sessionRouter)
sessionRouter.get('/getSessions', sessionController.getSessions)
sessionRouter.get('/start/:sessionId', middleware.sessionNameValidation, sessionController.startSession)
sessionRouter.get('/stop/:sessionId', middleware.sessionNameValidation, sessionController.stopSession)
sessionRouter.get('/status/:sessionId', middleware.sessionNameValidation, sessionController.statusSession)
sessionRouter.get('/qr/:sessionId', middleware.sessionNameValidation, sessionController.sessionQrCode)
sessionRouter.get('/qr/:sessionId/image', middleware.sessionNameValidation, sessionController.sessionQrCodeImage)

View file

@ -488,6 +488,33 @@ const reloadSession = async (sessionId) => {
}
}
const destroySession = async (sessionId) => {
try {
const client = sessions.get(sessionId)
if (!client) {
return
}
client.pupPage?.removeAllListeners('close')
client.pupPage?.removeAllListeners('error')
try {
await terminateWebSocketServer(sessionId)
} catch (error) {
logger.error({ sessionId, err: error }, 'Failed to terminate WebSocket server')
}
await client.destroy()
// Wait 10 secs for client.pupBrowser to be disconnected
let maxDelay = 0
while (client.pupBrowser?.isConnected() && (maxDelay < 10)) {
await new Promise(resolve => setTimeout(resolve, 1000))
maxDelay++
}
sessions.delete(sessionId)
} catch (error) {
logger.error({ sessionId, err: error }, 'Failed to stop session')
throw error
}
}
const deleteSession = async (sessionId, validation) => {
try {
const client = sessions.get(sessionId)
@ -554,5 +581,6 @@ module.exports = {
validateSession,
deleteSession,
reloadSession,
flushSessions
flushSessions,
destroySession
}