import bancho from './bancho.js'; import db from './database.js'; import {init_lobby} from './ranked.js'; // Create a new bancho match, and copy existing lobby settings async function reopen_lobby(match) { console.info(`Recreating lobby #${match.match_id}`); const new_lobby = await bancho.make('New o!RL lobby'); await init_lobby(new_lobby, JSON.parse(match.data), true); db.prepare(`UPDATE match SET reopened_as = ? WHERE match_id = ?`).run(new_lobby.id, match.match_id); return new_lobby; } // Join an existing bancho match, or recreate it if it no longer exists async function rejoin_lobby(match) { console.info(`Rejoining lobby #${match.match_id}`); let new_lobby = null; try { const bancho_lobby = await bancho.join('#mp_' + match.match_id); new_lobby = await init_lobby(bancho_lobby, JSON.parse(match.data), false); } catch (err) { console.error(`Failed to rejoin lobby #${match.match_id}: ${err}`); db.prepare(`UPDATE match SET end_time = ? WHERE match_id = ?`).run(Date.now(), match.match_id); try { new_lobby = await reopen_lobby(match); } catch (err) { console.error(`Failed to reopen lobby #${match.match_id}: ${err}`); } } return new_lobby; } // Rejoin lobbies if none are open async function auto_rejoin_lobbies() { if (bancho.joined_lobbies.length > 0) return; const lobbies = db.prepare(`SELECT * FROM match WHERE end_time IS NULL`).all(); if (lobbies.length > 0) { // Bancho restarted, we need to recreate all the lobbies that got closed just now const promises = []; for (const lobby of lobbies) { promises.push(rejoin_lobby(lobby)); } await Promise.all(promises); } else { // All lobbies got closed, we need to reopen at least one lobby for convenience try { const last_lobby = db.prepare(`SELECT * FROM match WHERE reopened_as IS NULL ORDER BY end_time DESC LIMIT 1`).get(); if (!last_lobby) throw new Error('You need to create the first lobby manually'); await reopen_lobby(last_lobby); } catch (err) { console.error(`Failed to create default lobby: ${err}`); } } } export {auto_rejoin_lobbies};