const database = require('../database/database') const {get_webrtc_port, get_app_port, get_sfu_port} = require('../modules/port_alloc') const {get_app_path} = require('../modules/titles') const not_found_error = require('../../lib/src/http/errors/not_found_error') const server_error = require('../../lib/src/http/errors/server_error') const {run_webrtc, run_app, run_sfu, kill_proc} = require('../modules/run_process') const {create_websocket_url} = require('../modules/links') const {port} = require('../../config') const run_session = async (req, res, next) => { const {title, session_id} = req.body let app_path = get_app_path(title) if (!app_path) { next(new not_found_error('title or path does not exist')) return } let webrtc_port = await get_webrtc_port() let app_port = await get_app_port() let sfu_port = 8889//await get_sfu_port() if (!app_port) { next(new server_error('all app ports busy')) return } else if (!webrtc_port) { next(new server_error('all webrtc ports busy')) return } // else if (!sfu_port) { // next(new server_error('all sfu ports busy')) // return // } let app_pid = await run_app(app_path, app_port) if (!app_pid) { next(new server_error('can not run app')) return } const this_server_url = `http://127.0.0.1:${port}` let webrtc_pid = await run_webrtc(webrtc_port, app_port, sfu_port, this_server_url, session_id) if (!webrtc_pid) { kill_proc(app_pid) next(new server_error('can not run webrtc')) return } let sfu_pid = null //await run_sfu(sfu_port) // if (!sfu_pid) { // kill_proc(app_pid) // kill_proc(webrtc_pid) // next(new server_error('can not run sfu')) // return // } let add_runnning_session_result = await database.add_running_session(session_id, title, app_pid, webrtc_pid, sfu_pid, app_port, webrtc_port, sfu_port) if(!add_runnning_session_result) { next(new server_error('can not add session to database')) return } res.json({websocket_url:create_websocket_url(webrtc_port)}) } module.exports = { run_session }