supervisor.js 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. import bancho from './bancho.js';
  2. import db from './database.js';
  3. import {init_lobby} from './ranked.js';
  4. // Create a new bancho match, and copy existing lobby settings
  5. async function reopen_lobby(match) {
  6. console.info(`Recreating lobby #${match.match_id}`);
  7. const new_lobby = await bancho.make('New o!RL lobby');
  8. await init_lobby(new_lobby, JSON.parse(match.data), true);
  9. db.prepare(`UPDATE match SET reopened_as = ? WHERE match_id = ?`).run(new_lobby.id, match.match_id);
  10. return new_lobby;
  11. }
  12. // Join an existing bancho match, or recreate it if it no longer exists
  13. async function rejoin_lobby(match) {
  14. console.info(`Rejoining lobby #${match.match_id}`);
  15. let new_lobby = null;
  16. try {
  17. const bancho_lobby = await bancho.join('#mp_' + match.match_id);
  18. new_lobby = await init_lobby(bancho_lobby, JSON.parse(match.data), false);
  19. } catch (err) {
  20. console.error(`Failed to rejoin lobby #${match.match_id}: ${err}`);
  21. db.prepare(`UPDATE match SET end_time = ? WHERE match_id = ?`).run(Date.now(), match.match_id);
  22. try {
  23. new_lobby = await reopen_lobby(match);
  24. } catch (err) {
  25. console.error(`Failed to reopen lobby #${match.match_id}: ${err}`);
  26. }
  27. }
  28. return new_lobby;
  29. }
  30. // Rejoin lobbies if none are open
  31. async function auto_rejoin_lobbies() {
  32. if (bancho.joined_lobbies.length > 0) return;
  33. const lobbies = db.prepare(`SELECT * FROM match WHERE end_time IS NULL`).all();
  34. if (lobbies.length > 0) {
  35. // Bancho restarted, we need to recreate all the lobbies that got closed just now
  36. const promises = [];
  37. for (const lobby of lobbies) {
  38. promises.push(rejoin_lobby(lobby));
  39. }
  40. await Promise.all(promises);
  41. } else {
  42. // All lobbies got closed, we need to reopen at least one lobby for convenience
  43. try {
  44. const last_lobby = db.prepare(`SELECT * FROM match WHERE reopened_as IS NULL ORDER BY end_time DESC LIMIT 1`).get();
  45. if (!last_lobby) throw new Error('You need to create the first lobby manually');
  46. await reopen_lobby(last_lobby);
  47. } catch (err) {
  48. console.error(`Failed to create default lobby: ${err}`);
  49. }
  50. }
  51. }
  52. export {auto_rejoin_lobbies};