276 lines
12 KiB
JavaScript
276 lines
12 KiB
JavaScript
const express = require('express');
|
|
const router = express.Router();
|
|
|
|
const Actor = require('../models/Actor');
|
|
const Campaign = require('../models/Campaign');
|
|
const DiscordGuildLink = require('../models/DiscordGuildLink');
|
|
const ServiceLinkRequest = require('../models/ServiceLinkRequest');
|
|
const User = require('../models/User');
|
|
const serviceLinks = require('../services/service-links');
|
|
|
|
const NOTIFICATION_LIMIT = 10;
|
|
|
|
const requireBot = serviceLinks.requireDiscordBot;
|
|
|
|
function validGuildId(value) {
|
|
return /^\d{5,25}$/.test(String(value ?? ''));
|
|
}
|
|
|
|
// Discord ids are snowflakes the same shape as guild ids.
|
|
function validUserId(value) {
|
|
return /^\d{5,25}$/.test(String(value ?? ''));
|
|
}
|
|
|
|
// Connecting a Discord server is the service link of issue: the bot asks
|
|
// /api/link/start for a sign-up link, and whoever opens it signs in and picks the
|
|
// campaign this server may read. What is left here is what the bot needs once
|
|
// that link exists: confirming it in Discord and working with its campaign.
|
|
|
|
async function dragonrollUserNames(requests) {
|
|
const userIds = [...new Set(requests.map((request) => String(request.dragonrollUser ?? '')).filter(Boolean))];
|
|
if (!userIds.length) return new Map();
|
|
|
|
const users = await User.find({ _id: { $in: userIds } }).select('username name').lean();
|
|
return new Map(users.map((user) => [String(user._id), user.username || user.name]));
|
|
}
|
|
|
|
// El bot reclama les autoritzacions ja fetes per confirmar-les a Discord. Marcar-les aqui
|
|
// mateix evita que dos processos del bot confirmïn la mateixa vegada.
|
|
router.post('/bot/link-requests/notifications', requireBot, async (req, res) => {
|
|
try {
|
|
const pending = await ServiceLinkRequest.find({
|
|
service: 'discord',
|
|
state: 'linked',
|
|
linkedAt: { $gte: new Date(Date.now() - serviceLinks.NOTIFICATION_WINDOW_MS) },
|
|
notifiedAt: null
|
|
}).select('_id targetId targetName targetUser targetMeta dragonrollUser campaign')
|
|
.limit(NOTIFICATION_LIMIT)
|
|
.lean();
|
|
|
|
const claimed = [];
|
|
for (const request of pending) {
|
|
const taken = await ServiceLinkRequest.findOneAndUpdate(
|
|
{ _id: request._id, notifiedAt: null },
|
|
{ $set: { notifiedAt: new Date() } },
|
|
{ new: true }
|
|
).lean();
|
|
if (taken) claimed.push(request);
|
|
}
|
|
|
|
const names = await dragonrollUserNames(claimed);
|
|
const campaignIds = [...new Set(claimed.map((request) => String(request.campaign ?? '')).filter(Boolean))];
|
|
const campaigns = campaignIds.length
|
|
? await Campaign.find({ _id: { $in: campaignIds } }).select('_id name').lean()
|
|
: [];
|
|
const campaignNames = new Map(campaigns.map((campaign) => [String(campaign._id), campaign.name]));
|
|
|
|
res.json({
|
|
status: 'ok',
|
|
notifications: claimed.map((request) => ({
|
|
id: String(request._id),
|
|
guildId: request.targetId,
|
|
guildName: request.targetName,
|
|
discordUserId: request.targetMeta?.userId || '',
|
|
discordUserName: request.targetUser,
|
|
dragonrollUserName: names.get(String(request.dragonrollUser ?? '')) || null,
|
|
campaignName: campaignNames.get(String(request.campaign ?? '')) || null
|
|
}))
|
|
});
|
|
} catch (err) {
|
|
console.error(err);
|
|
res.json({ status: 'error', msg: 'errors.internal' });
|
|
}
|
|
});
|
|
|
|
router.get('/bot/guild/:guildId/status', requireBot, async (req, res) => {
|
|
try {
|
|
if (!validGuildId(req.params.guildId)) return res.json({ status: 'error', msg: 'errors.missing-data' });
|
|
const link = await DiscordGuildLink.findOne({ guildId: req.params.guildId }).lean();
|
|
if (!link) return res.json({ status: 'ok', connected: false, campaign: null });
|
|
|
|
const campaign = await Campaign.findOne({
|
|
discordGuildId: req.params.guildId,
|
|
createdBy: link.dragonrollUser
|
|
}).select('_id name').lean();
|
|
res.json({ status: 'ok', connected: true, campaign });
|
|
} catch (err) {
|
|
console.error(err);
|
|
res.json({ status: 'error', msg: 'errors.internal' });
|
|
}
|
|
});
|
|
|
|
router.get('/bot/guild/:guildId/campaigns', requireBot, async (req, res) => {
|
|
try {
|
|
if (!validGuildId(req.params.guildId)) return res.json({ status: 'error', msg: 'errors.missing-data' });
|
|
const link = await DiscordGuildLink.findOne({ guildId: req.params.guildId }).lean();
|
|
if (!link) return res.json({ status: 'error', msg: 'discord.errors.not-connected' });
|
|
|
|
const campaigns = await Campaign.find({ createdBy: link.dragonrollUser })
|
|
.select('_id name discordGuildId')
|
|
.sort({ date: -1 })
|
|
.lean();
|
|
res.json({ status: 'ok', campaigns });
|
|
} catch (err) {
|
|
console.error(err);
|
|
res.json({ status: 'error', msg: 'errors.internal' });
|
|
}
|
|
});
|
|
|
|
router.post('/bot/guild/:guildId/campaign', requireBot, async (req, res) => {
|
|
try {
|
|
const guildId = String(req.params.guildId);
|
|
if (!validGuildId(guildId) || !req.body.campaignId) return res.json({ status: 'error', msg: 'errors.missing-data' });
|
|
|
|
const link = await DiscordGuildLink.findOne({ guildId }).lean();
|
|
if (!link) return res.json({ status: 'error', msg: 'discord.errors.not-connected' });
|
|
|
|
const campaign = await Campaign.findOne({ _id: req.body.campaignId, createdBy: link.dragonrollUser });
|
|
if (!campaign) return res.json({ status: 'error', msg: 'errors.notfound' });
|
|
|
|
const conflict = await Campaign.findOne({ discordGuildId: guildId, _id: { $ne: campaign._id } }).lean();
|
|
if (conflict && String(conflict.createdBy) !== String(link.dragonrollUser)) {
|
|
return res.json({ status: 'error', msg: 'campaigns.errors.discord-guild-in-use' });
|
|
}
|
|
if (campaign.discordGuildId && campaign.discordGuildId !== guildId) {
|
|
return res.json({ status: 'error', msg: 'discord.errors.campaign-already-linked' });
|
|
}
|
|
|
|
await Campaign.updateMany(
|
|
{ discordGuildId: guildId, createdBy: link.dragonrollUser, _id: { $ne: campaign._id } },
|
|
{ $unset: { discordGuildId: 1 } }
|
|
);
|
|
campaign.discordGuildId = guildId;
|
|
await campaign.save();
|
|
|
|
res.json({ status: 'ok', campaign: { id: String(campaign._id), name: campaign.name } });
|
|
} catch (err) {
|
|
console.error(err);
|
|
res.json({ status: 'error', msg: 'errors.internal' });
|
|
}
|
|
});
|
|
|
|
router.delete('/bot/guild/:guildId/campaign', requireBot, async (req, res) => {
|
|
try {
|
|
const guildId = String(req.params.guildId);
|
|
if (!validGuildId(guildId)) return res.json({ status: 'error', msg: 'errors.missing-data' });
|
|
const link = await DiscordGuildLink.findOne({ guildId }).lean();
|
|
if (!link) return res.json({ status: 'error', msg: 'discord.errors.not-connected' });
|
|
|
|
const campaign = await Campaign.findOne({ discordGuildId: guildId, createdBy: link.dragonrollUser });
|
|
if (!campaign) return res.json({ status: 'error', msg: 'errors.notfound' });
|
|
campaign.discordGuildId = undefined;
|
|
await campaign.save();
|
|
res.json({ status: 'ok', campaign: { id: String(campaign._id), name: campaign.name } });
|
|
} catch (err) {
|
|
console.error(err);
|
|
res.json({ status: 'error', msg: 'errors.internal' });
|
|
}
|
|
});
|
|
|
|
router.get('/bot/guild/:guildId/actors', requireBot, async (req, res) => {
|
|
try {
|
|
const guildId = String(req.params.guildId);
|
|
if (!validGuildId(guildId)) return res.json({ status: 'error', msg: 'errors.missing-data' });
|
|
const link = await DiscordGuildLink.findOne({ guildId }).lean();
|
|
if (!link) return res.json({ status: 'error', msg: 'discord.errors.not-connected' });
|
|
const campaign = await Campaign.findOne({ discordGuildId: guildId, createdBy: link.dragonrollUser }).select('_id name').lean();
|
|
if (!campaign) return res.json({ status: 'error', msg: 'errors.notfound' });
|
|
|
|
const actors = await Actor.find({ campaign: campaign._id }).sort({ name: 1 }).lean();
|
|
res.json({ status: 'ok', campaign: { id: String(campaign._id), name: campaign.name }, actors });
|
|
} catch (err) {
|
|
console.error(err);
|
|
res.json({ status: 'error', msg: 'errors.internal' });
|
|
}
|
|
});
|
|
|
|
// Who may take a character already held by somebody else is decided in Discord,
|
|
// where the server administrators are: the bot authenticates with the shared
|
|
// secret and says whether the person asking is one (`admin`). Everything else
|
|
// the backend still guards itself: only the guild's own campaign is reachable.
|
|
|
|
// One command per player link (Syndria98/dragonroll#72): assigning takes the
|
|
// character for `discordUserId`, and a player never holds two of them, so a
|
|
// second assign moves the player instead of doubling them up.
|
|
router.post('/bot/guild/:guildId/actors/assign', requireBot, async (req, res) => {
|
|
try {
|
|
const guildId = String(req.params.guildId);
|
|
const discordUserId = String(req.body.discordUserId ?? '');
|
|
if (!validGuildId(guildId) || !validUserId(discordUserId) || !req.body.actorId) {
|
|
return res.json({ status: 'error', msg: 'errors.missing-data' });
|
|
}
|
|
|
|
const link = await DiscordGuildLink.findOne({ guildId }).lean();
|
|
if (!link) return res.json({ status: 'error', msg: 'discord.errors.not-connected' });
|
|
const campaign = await Campaign.findOne({ discordGuildId: guildId, createdBy: link.dragonrollUser }).select('_id name').lean();
|
|
if (!campaign) return res.json({ status: 'error', msg: 'errors.notfound' });
|
|
|
|
const actor = await Actor.findOne({ _id: req.body.actorId, campaign: campaign._id });
|
|
if (!actor) return res.json({ status: 'error', msg: 'errors.notfound' });
|
|
|
|
const holder = String(actor.discordUserId ?? '');
|
|
if (holder && holder !== discordUserId && !req.body.admin) {
|
|
return res.json({ status: 'error', msg: 'discord.errors.actor-held' });
|
|
}
|
|
|
|
// The character this player hands over to take the new one.
|
|
const previous = await Actor.findOne({ campaign: campaign._id, discordUserId, _id: { $ne: actor._id } }).lean();
|
|
if (previous) {
|
|
await Actor.updateMany(
|
|
{ campaign: campaign._id, discordUserId, _id: { $ne: actor._id } },
|
|
{ $set: { discordUserId: null } }
|
|
);
|
|
}
|
|
|
|
actor.discordUserId = discordUserId;
|
|
await actor.save();
|
|
|
|
res.json({
|
|
status: 'ok',
|
|
actor: { id: String(actor._id), name: actor.name, discordUserId },
|
|
previous: previous ? { id: String(previous._id), name: previous.name } : null
|
|
});
|
|
} catch (err) {
|
|
console.error(err);
|
|
res.json({ status: 'error', msg: 'errors.internal' });
|
|
}
|
|
});
|
|
|
|
// Freeing a character: without `actorId` the player gives up their own, with
|
|
// one a server administrator frees anybody's.
|
|
router.post('/bot/guild/:guildId/actors/unassign', requireBot, async (req, res) => {
|
|
try {
|
|
const guildId = String(req.params.guildId);
|
|
const discordUserId = String(req.body.discordUserId ?? '');
|
|
if (!validGuildId(guildId) || !validUserId(discordUserId)) {
|
|
return res.json({ status: 'error', msg: 'errors.missing-data' });
|
|
}
|
|
|
|
const link = await DiscordGuildLink.findOne({ guildId }).lean();
|
|
if (!link) return res.json({ status: 'error', msg: 'discord.errors.not-connected' });
|
|
const campaign = await Campaign.findOne({ discordGuildId: guildId, createdBy: link.dragonrollUser }).select('_id name').lean();
|
|
if (!campaign) return res.json({ status: 'error', msg: 'errors.notfound' });
|
|
|
|
const filter = { campaign: campaign._id };
|
|
if (req.body.actorId) filter._id = req.body.actorId;
|
|
else filter.discordUserId = discordUserId;
|
|
const actor = await Actor.findOne(filter);
|
|
if (!actor || !actor.discordUserId) return res.json({ status: 'error', msg: 'errors.notfound' });
|
|
|
|
const holder = String(actor.discordUserId);
|
|
if (holder !== discordUserId && !req.body.admin) {
|
|
return res.json({ status: 'error', msg: 'discord.errors.actor-held' });
|
|
}
|
|
|
|
actor.discordUserId = null;
|
|
await actor.save();
|
|
|
|
res.json({ status: 'ok', actor: { id: String(actor._id), name: actor.name }, wasYours: holder === discordUserId });
|
|
} catch (err) {
|
|
console.error(err);
|
|
res.json({ status: 'error', msg: 'errors.internal' });
|
|
}
|
|
});
|
|
|
|
module.exports = router;
|