'use strict'; /* * Alliance data helpers shared by commands, events, queries and (later) the military stage. * * Other modules use the lookups at the bottom: * relationBetween(db, allianceA, allianceB) -> 'war' | 'neutral' | 'nap' | 'confed' * operatorRelation(db, opA, opB) -> 'self' | 'same_alliance' | 'war' | 'neutral' | 'nap' | 'confed' * atWar(db, opA, opB), confederated(db, opA, opB), pactPartners(db, opA, opB) * * Membership is kept in alliance_members (role) and operators.alliance_id (quick lookup). addMember / removeMember * are the only writers of both. */ const R = require('../public/js/rules.js'); const D = require('../public/js/data.js'); const { GameError } = require('./errors'); const S = D.SOCIAL; const HOUR = D.HOUR_MS; // ------------------------------------------------------------------ operators and membership // The caller's operator. With worldId: the one in that world; without: their oldest. not_found when there is none. function operatorOf(db, userId, worldId) { const row = worldId !== undefined && worldId !== null ? db.get('SELECT * FROM operators WHERE user_id = ? AND world_id = ?', userId, worldId) : db.get('SELECT * FROM operators WHERE user_id = ? ORDER BY id LIMIT 1', userId); if (!row) throw new GameError('not_found', { what: 'operator' }); return row; } // Best (highest) completed Peering office level over all POPs of an operator. function peeringLevel(db, operatorId) { const r = db.get(`SELECT MAX(b.level) AS lvl FROM buildings b JOIN towns t ON t.id = b.town_id WHERE t.owner_id = ? AND b.type = 'peering_office'`, operatorId); return r && r.lvl ? r.lvl : 0; } const membership = (db, operatorId) => db.get('SELECT operator_id, alliance_id, role, joined_at FROM alliance_members WHERE operator_id = ?', operatorId) || null; const getAlliance = (db, id) => db.get('SELECT * FROM alliances WHERE id = ?', id) || null; const memberCount = (db, allianceId) => db.get('SELECT COUNT(*) AS n FROM alliance_members WHERE alliance_id = ?', allianceId).n; const leaderOf = (db, allianceId) => db.get("SELECT operator_id FROM alliance_members WHERE alliance_id = ? AND role = 'leader'", allianceId); // { id, tag, name } or null, for embedding in other views (/me, /map). function allianceBrief(db, id) { if (id === null || id === undefined) return null; const a = db.get('SELECT id, tag, name FROM alliances WHERE id = ?', id); return a || null; } // The cap that applies now: the stored one, raised if the current leader's best Peering office would give more. // Never lowered (a lost building must not kick anyone). Pure read; `refreshCap` persists a raise. function effectiveCap(db, alliance) { const lead = leaderOf(db, alliance.id); const fromLeader = lead ? R.allianceCap(peeringLevel(db, lead.operator_id)) : 0; return Math.max(alliance.size_cap, fromLeader); } function refreshCap(db, alliance) { const cap = effectiveCap(db, alliance); if (cap > alliance.size_cap) { db.run('UPDATE alliances SET size_cap = ? WHERE id = ?', cap, alliance.id); alliance.size_cap = cap; } return cap; } function addMember(db, allianceId, operatorId, role, now) { db.run('INSERT INTO alliance_members (operator_id, alliance_id, role, joined_at) VALUES (?, ?, ?, ?)', operatorId, allianceId, role, now); db.run('UPDATE operators SET alliance_id = ? WHERE id = ?', allianceId, operatorId); // Any other open invites of this operator are moot now. db.run("UPDATE alliance_invites SET status = 'cancelled', answered_at = ? WHERE operator_id = ? AND status = 'pending' AND alliance_id <> ?", now, operatorId, allianceId); } function removeMember(db, operatorId) { db.run('DELETE FROM alliance_members WHERE operator_id = ?', operatorId); db.run('UPDATE operators SET alliance_id = NULL WHERE id = ?', operatorId); } // Authorise an alliance action. Returns { op, alliance, member }. not_found: no such alliance (or the caller has no // operator in its world); forbidden: not a member, or the role may not do `action`. function requireRole(db, userId, allianceId, action) { const alliance = getAlliance(db, allianceId); if (!alliance) throw new GameError('not_found', { what: 'alliance' }); const op = db.get('SELECT * FROM operators WHERE user_id = ? AND world_id = ?', userId, alliance.world_id); if (!op) throw new GameError('not_found', { what: 'alliance' }); const member = membership(db, op.id); if (!member || member.alliance_id !== alliance.id) throw new GameError('forbidden', { need: 'member' }); if (action && !R.allianceCan(member.role, action)) throw new GameError('forbidden', { need: action, role: member.role }); return { op, alliance, member }; } // ------------------------------------------------------------------ notifications (rows in `notifications`) const userOfOperator = (db, operatorId) => { const r = db.get('SELECT user_id FROM operators WHERE id = ?', operatorId); return r ? r.user_id : null; }; function notifyOperator(ctx, operatorId, type, payload) { const o = ctx.db.get('SELECT user_id, world_id FROM operators WHERE id = ?', operatorId); if (o) ctx.scheduler.notify(o.user_id, o.world_id, type, payload); } // All members of an alliance, optionally only some roles, optionally skipping one operator. function notifyAlliance(ctx, allianceId, type, payload, o) { o = o || {}; const rows = ctx.db.all(`SELECT m.operator_id AS oid, m.role AS role, op.user_id AS uid, op.world_id AS wid FROM alliance_members m JOIN operators op ON op.id = m.operator_id WHERE m.alliance_id = ?`, allianceId); for (const r of rows) { if (o.except && r.oid === o.except) continue; if (o.roles && o.roles.indexOf(r.role) < 0) continue; ctx.scheduler.notify(r.uid, r.wid, type, payload); } } // ------------------------------------------------------------------ dissolving // Remove an alliance and everything hanging off it. Counterparts of non-neutral relations are told it is neutral now. function dissolve(ctx, allianceId, reason) { const { db, now } = ctx; const a = getAlliance(db, allianceId); if (!a) return; const brief = { allianceId: a.id, tag: a.tag, name: a.name }; notifyAlliance(ctx, a.id, 'alliance_disbanded', Object.assign({ reason }, brief)); const rels = db.all('SELECT * FROM alliance_relations WHERE a_id = ? OR b_id = ?', a.id, a.id); for (const r of rels) { const other = r.a_id === a.id ? r.b_id : r.a_id; if (r.pending_event) db.run("UPDATE events SET status = 'cancelled', done_at = ? WHERE id = ? AND status = 'pending'", now, r.pending_event); if (r.state !== 'neutral') notifyAlliance(ctx, other, 'diplomacy_changed', { allianceId: other, otherId: a.id, otherTag: a.tag, from: r.state, to: 'neutral', reason: 'disbanded' }); } db.run('DELETE FROM alliance_relations WHERE a_id = ? OR b_id = ?', a.id, a.id); db.run('DELETE FROM alliance_proposals WHERE from_id = ? OR to_id = ?', a.id, a.id); db.run('DELETE FROM alliance_invites WHERE alliance_id = ?', a.id); db.run('DELETE FROM alliance_notes WHERE alliance_id = ?', a.id); const ids = db.all('SELECT operator_id FROM alliance_members WHERE alliance_id = ?', a.id); for (const m of ids) removeMember(db, m.operator_id); db.run('DELETE FROM alliances WHERE id = ?', a.id); } // ------------------------------------------------------------------ relations const pairOf = (x, y) => (x < y ? [x, y] : [y, x]); const getRelation = (db, x, y) => { const [a, b] = pairOf(x, y); return db.get('SELECT * FROM alliance_relations WHERE a_id = ? AND b_id = ?', a, b) || null; }; // Set the current state of a pair, clearing any pending change. neutral with nothing pending = no row. function setRelation(db, worldId, x, y, state, now) { const [a, b] = pairOf(x, y); if (state === 'neutral') { db.run('DELETE FROM alliance_relations WHERE a_id = ? AND b_id = ?', a, b); return; } db.run(`INSERT INTO alliance_relations (a_id, b_id, world_id, state, since) VALUES (?, ?, ?, ?, ?) ON CONFLICT (a_id, b_id) DO UPDATE SET state = excluded.state, since = excluded.since, pending_to = NULL, pending_at = NULL, pending_by = NULL, pending_event = NULL`, a, b, worldId, state, now); } // Mark every open proposal between two alliances (either direction) as withdrawn: the state moved on under them. function withdrawProposals(db, x, y, now) { db.run("UPDATE alliance_proposals SET status = 'withdrawn', answered_at = ? WHERE status = 'pending' AND ((from_id = ? AND to_id = ?) OR (from_id = ? AND to_id = ?))", now, x, y, y, x); } // ------------------------------------------------------------------ lookups for other modules function relationBetween(db, allianceA, allianceB) { if (!allianceA || !allianceB || allianceA === allianceB) return 'neutral'; const r = getRelation(db, allianceA, allianceB); return r ? r.state : 'neutral'; } function operatorRelation(db, opA, opB) { if (opA === opB) return 'self'; const rows = db.all('SELECT id, alliance_id FROM operators WHERE id IN (?, ?)', opA, opB); const a = rows.find((r) => r.id === opA), b = rows.find((r) => r.id === opB); if (!a || !b || !a.alliance_id || !b.alliance_id) return 'neutral'; if (a.alliance_id === b.alliance_id) return 'same_alliance'; return relationBetween(db, a.alliance_id, b.alliance_id); } const atWar = (db, opA, opB) => operatorRelation(db, opA, opB) === 'war'; // Can reinforce each other and see each other's incoming: same alliance or confederation. const confederated = (db, opA, opB) => { const r = operatorRelation(db, opA, opB); return r === 'confed' || r === 'same_alliance'; }; // May not attack each other: same alliance, NAP or confederation. const pactPartners = (db, opA, opB) => { const r = operatorRelation(db, opA, opB); return r === 'nap' || r === 'confed' || r === 'same_alliance'; }; module.exports = { S, HOUR, operatorOf, peeringLevel, membership, getAlliance, memberCount, leaderOf, allianceBrief, effectiveCap, refreshCap, addMember, removeMember, requireRole, userOfOperator, notifyOperator, notifyAlliance, dissolve, pairOf, getRelation, setRelation, withdrawProposals, relationBetween, operatorRelation, atWar, confederated, pactPartners, };