Fix #72: Link actor with a discord user #78
@@ -85,7 +85,7 @@ campaign, and handlers check ownership with a `userOwnsCampaign(campaignId, user
|
||||
- `Campaign` — `name*`, `createdBy*`→User, `description`, `color`, `settings`, `foundryWorldId`/`foundryWorldTitle`/`foundrySystem`, `foundrySyncTokenHash` (`select: false`), `discordGuildId`
|
||||
- `Note` — `title`, `content` (markdown source), `campaign*`, `folder` (null = root), `color`
|
||||
- `Folder` — `name*`, `campaign*`, `parentFolder` (null = root, self-ref), `color`
|
||||
- `Actor` — `name*`, `campaign*`, `foundryActorId` (unique per campaign), plus free-form sheet fields (`type`, `species`, `className`, `level`, `abilityScores`, `armorClass`, `speed`, `proficiencies`, `traits`, `spells`, `image`) and `inventory[{name,quantity,weight}]` (flattened Foundry items, **not** `Item` docs)
|
||||
- `Actor` — `name*`, `campaign*`, `foundryActorId` (unique per campaign), `discordUserId` (the Discord player holding the character, unique per campaign — set only by `routes/discord.js`), plus free-form sheet fields (`type`, `species`, `className`, `level`, `abilityScores`, `armorClass`, `speed`, `proficiencies`, `traits`, `spells`, `image`) and `inventory[{name,quantity,weight}]` (flattened Foundry items, **not** `Item` docs)
|
||||
- `Item` — `name*`, `campaign*`, `foundryItemId` (unique per campaign), `foundryNames`, `category`, `rarity`, `quantity`, `weight`, `properties`, `description`
|
||||
- `Map` — `name*`, `campaign*`, `image` (filename in `src/uploads`), `gridSize`/`offsetX`/`offsetY`/`scale` (image px), `pins[{note→Note, x, y}]` (addressed by the pin's own `_id`), `tokens[{actor→Actor, x, y}]` (the centre of the grid cell the token stands in, also addressed by its own `_id`)
|
||||
- `ServiceLinkRequest` — the pending/completed service pairings of §4; `DiscordGuildLink` maps a Discord guild to the Dragonroll user who claimed it
|
||||
|
||||
@@ -54,6 +54,10 @@ const ActorSchema = new Schema({
|
||||
default: null
|
||||
},
|
||||
foundryActorId: { type: String },
|
||||
// The Discord player this character belongs to (Syndria98/dragonroll#72): each player
|
||||
// of the server a campaign is linked to holds one character of it. Only
|
||||
// routes/discord.js writes it, so the campaign keeps owning it whichever guild claimed it.
|
||||
discordUserId: { type: String, default: null },
|
||||
date: { type: Date, default: Date.now }
|
||||
});
|
||||
|
||||
@@ -62,4 +66,10 @@ ActorSchema.index(
|
||||
{ unique: true, partialFilterExpression: { foundryActorId: { $type: 'string' } } }
|
||||
);
|
||||
|
||||
// A player holds at most one character of a campaign: the id is unique within it.
|
||||
ActorSchema.index(
|
||||
{ campaign: 1, discordUserId: 1 },
|
||||
{ unique: true, partialFilterExpression: { discordUserId: { $type: 'string' } } }
|
||||
);
|
||||
|
||||
module.exports = mongoose.model('Actor', ActorSchema);
|
||||
|
||||
@@ -16,6 +16,11 @@ 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
|
||||
@@ -179,4 +184,92 @@ router.get('/bot/guild/:guildId/actors', requireBot, async (req, res) => {
|
||||
}
|
||||
});
|
||||
|
||||
// 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;
|
||||
|
||||
@@ -13,12 +13,14 @@ Discord server B ──link──▶ Dragonroll campaign "Silang" (account g
|
||||
|
||||
## Commands
|
||||
|
||||
- `/characters [type]` lists the linked campaign's actors, optionally filtered to characters, NPCs, or creatures.
|
||||
- `/characters [type]` lists the linked campaign's actors, optionally filtered to characters, NPCs, or creatures. Each one that a player has claimed with `/dragonroll assign` shows that player next to it.
|
||||
- `/character name public:true` shows the matching actor's portrait (when one has been uploaded), profile, ability scores, combat stats, proficiencies, traits, spells, and inventory. Type part of a name to pick it from the campaign's current roster. Set `public` to `true` to show the reply to everyone in the channel.
|
||||
- `/dragonroll connect` starts a short-lived Dragonroll sign-in and authorization link, and confirms here once somebody authorizes the server.
|
||||
- `/dragonroll link` lets a server administrator choose a campaign owned by the connected Dragonroll account. Type part of a campaign name to filter the choices.
|
||||
- `/dragonroll unlink` removes this server’s campaign link.
|
||||
- `/dragonroll status` shows the campaign linked to this server.
|
||||
- `/dragonroll status` shows the campaign linked to this server, and the character linked to your Discord account on it.
|
||||
- `/dragonroll assign character` links that character of the campaign to your Discord account: each player holds one character, so claiming a second one frees the first. Anyone can take a free character; only a server administrator can take a character another player already holds.
|
||||
- `/dragonroll unassign [character]` removes a character link. Without the option you give up your own character; naming somebody else’s character takes it off them, which only a server administrator can do.
|
||||
- `/dragonroll refresh` rechecks the current connection and campaign in Dragonroll.
|
||||
|
||||
Replies are private by default. `/character` can be made public with its `public` option, so everyone in the channel can see the character sheet.
|
||||
|
||||
@@ -51,7 +51,24 @@ const commands = [
|
||||
.setDescription('Show the campaign linked to this server.'))
|
||||
.addSubcommand((subcommand) => subcommand
|
||||
.setName('refresh')
|
||||
.setDescription('Refresh this server’s Dragonroll connection status.')))
|
||||
.setDescription('Refresh this server’s Dragonroll connection status.'))
|
||||
.addSubcommand((subcommand) => subcommand
|
||||
.setName('assign')
|
||||
.setDescription('Link one character of the campaign to your Discord account.')
|
||||
.addStringOption((option) => option
|
||||
.setName('character')
|
||||
.setDescription('Character to play (pick it from the campaign roster).')
|
||||
.setRequired(true)
|
||||
.setMaxLength(100)
|
||||
.setAutocomplete(true)))
|
||||
.addSubcommand((subcommand) => subcommand
|
||||
.setName('unassign')
|
||||
.setDescription('Remove the link between a character and a Discord player.')
|
||||
.addStringOption((option) => option
|
||||
.setName('character')
|
||||
.setDescription('Character to free (yours by default, anyone’s as a server administrator).')
|
||||
.setMaxLength(100)
|
||||
.setAutocomplete(true))))
|
||||
];
|
||||
|
||||
module.exports = commands;
|
||||
|
||||
@@ -123,7 +123,32 @@ function createDragonrollApi(config) {
|
||||
return { campaign, actors: payload.actors };
|
||||
}
|
||||
|
||||
return { startAuthorization, claimLinkNotifications, getStatus, getCampaign, listCampaigns, linkCampaign, unlinkCampaign, listActors };
|
||||
// Linking players to characters (Syndria98/dragonroll#72). `admin` says
|
||||
// whether the Discord side already checked the person is a server
|
||||
// administrator, who may move a character somebody else holds.
|
||||
async function assignActor(guildId, { actorId, discordUserId, admin = false }) {
|
||||
const payload = await request(`/discord/bot/guild/${encodeURIComponent(guildId)}/actors/assign`, {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ actorId, discordUserId: String(discordUserId), admin })
|
||||
});
|
||||
if (!payload.actor) throw new Error('Dragonroll returned an invalid character link.');
|
||||
return { actor: payload.actor, previous: payload.previous ?? null };
|
||||
}
|
||||
|
||||
async function unassignActor(guildId, { actorId, discordUserId, admin = false }) {
|
||||
const payload = await request(`/discord/bot/guild/${encodeURIComponent(guildId)}/actors/unassign`, {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({
|
||||
discordUserId: String(discordUserId),
|
||||
...(actorId ? { actorId } : {}),
|
||||
admin
|
||||
})
|
||||
});
|
||||
if (!payload.actor) throw new Error('Dragonroll returned an invalid character link.');
|
||||
return { actor: payload.actor, wasYours: payload.wasYours === true };
|
||||
}
|
||||
|
||||
return { startAuthorization, claimLinkNotifications, getStatus, getCampaign, listCampaigns, linkCampaign, unlinkCampaign, listActors, assignActor, unassignActor };
|
||||
}
|
||||
|
||||
module.exports = { createDragonrollApi, CampaignNotLinkedError, DragonrollNotConnectedError };
|
||||
|
||||
@@ -234,6 +234,20 @@ async function main() {
|
||||
: 'Not linked yet.' }
|
||||
);
|
||||
|
||||
// The campaign's character linked to this Discord account (#72), when there is one.
|
||||
if (status.campaign) {
|
||||
try {
|
||||
const { actors } = await dragonroll.listActors(guildId);
|
||||
const yours = actors.find((actor) => String(actor.discordUserId ?? '') === interaction.user.id);
|
||||
embed.addFields({
|
||||
name: 'Your character',
|
||||
value: yours ? safeField(yours.name, 100) : 'None. Run /dragonroll assign to link one to your Discord account.'
|
||||
});
|
||||
} catch {
|
||||
// The roster is a bonus of this card, which stays useful without it.
|
||||
}
|
||||
}
|
||||
|
||||
if (!status.connected) {
|
||||
embed.setDescription('A server administrator can run /dragonroll connect to connect a Dragonroll account.');
|
||||
} else if (!status.campaign) {
|
||||
@@ -243,6 +257,78 @@ async function main() {
|
||||
await respond(interaction, { embeds: [embed] });
|
||||
}
|
||||
|
||||
// /dragonroll assign and unassign (Syndria98/dragonroll#72): each player of the
|
||||
// server holds one character of the linked campaign. Anyone claims a free
|
||||
// character for themselves; server administrators also move and free the ones
|
||||
// somebody else holds.
|
||||
async function handleActorAssignment(interaction, guildId, subcommand) {
|
||||
const isAdmin = interaction.memberPermissions?.has(PermissionFlagsBits.Administrator) === true;
|
||||
const name = interaction.options.getString('character');
|
||||
const { actors } = await dragonroll.listActors(guildId);
|
||||
|
||||
// Unassign without a character gives up the one linked to you.
|
||||
if (subcommand === 'unassign' && !name) {
|
||||
const mine = actors.find((actor) => String(actor.discordUserId ?? '') === interaction.user.id);
|
||||
if (!mine) {
|
||||
await respond(interaction, { content: 'You do not have a character linked to your Discord account here. Run `/dragonroll assign` to claim one.' });
|
||||
return;
|
||||
}
|
||||
await dragonroll.unassignActor(guildId, { discordUserId: interaction.user.id });
|
||||
await respond(interaction, { content: `You are no longer linked to **${safeField(mine.name, 100)}**.` });
|
||||
return;
|
||||
}
|
||||
|
||||
const result = findActor(actors, name);
|
||||
if (!result.actor) {
|
||||
await respond(interaction, {
|
||||
content: result.matches?.length
|
||||
? safeField(`Several characters match **${name}**: ${result.matches.slice(0, 15).map((actor) => actor.name).join(', ')}. Try a more specific name.`, 1800)
|
||||
: safeField(`I couldn't find a character named **${name}**. Try \`/characters\` to see the campaign roster.`, 1800)
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
const actor = result.actor;
|
||||
const holder = String(actor.discordUserId ?? '');
|
||||
|
||||
if (subcommand === 'assign') {
|
||||
if (holder === interaction.user.id) {
|
||||
await respond(interaction, { content: `You are already linked to **${safeField(actor.name, 100)}**.` });
|
||||
return;
|
||||
}
|
||||
if (holder && !isAdmin) {
|
||||
await respond(interaction, { content: `**${safeField(actor.name, 100)}** is already linked to <@${holder}>. A server administrator can give it away and take it with the same command.` });
|
||||
return;
|
||||
}
|
||||
const { previous } = await dragonroll.assignActor(guildId, {
|
||||
actorId: String(actor._id),
|
||||
discordUserId: interaction.user.id,
|
||||
admin: isAdmin
|
||||
});
|
||||
const lines = [`You are now linked to **${safeField(actor.name, 100)}**.`];
|
||||
if (holder) lines.push(`That character was linked to <@${holder}>; the link is removed.`);
|
||||
if (previous) lines.push(`Your previous character, **${safeField(previous.name, 100)}**, is free again.`);
|
||||
await respond(interaction, { content: safeField(lines.join('\n'), 1800) });
|
||||
return;
|
||||
}
|
||||
|
||||
// Unassign with a character named: your own, or anybody's as an administrator.
|
||||
if (!holder) {
|
||||
await respond(interaction, { content: `**${safeField(actor.name, 100)}** does not have a linked Discord player.` });
|
||||
return;
|
||||
}
|
||||
if (holder !== interaction.user.id && !isAdmin) {
|
||||
await respond(interaction, { content: `**${safeField(actor.name, 100)}** is linked to <@${holder}>. Only a server administrator can unlink it.` });
|
||||
return;
|
||||
}
|
||||
await dragonroll.unassignActor(guildId, { actorId: String(actor._id), discordUserId: interaction.user.id, admin: isAdmin });
|
||||
await respond(interaction, {
|
||||
content: holder === interaction.user.id
|
||||
? `You are no longer linked to **${safeField(actor.name, 100)}**.`
|
||||
: `**${safeField(actor.name, 100)}** is no longer linked to <@${holder}>.`
|
||||
});
|
||||
}
|
||||
|
||||
client.once(Events.ClientReady, (readyClient) => {
|
||||
console.log(`Dragonroll character bot is online as ${readyClient.user.tag}, in ${readyClient.guilds.cache.size} servers.`);
|
||||
// Guild commands registered when the bot joined shadow global ones and
|
||||
@@ -331,9 +417,16 @@ async function main() {
|
||||
await respondActorChoices(interaction, guildId);
|
||||
return;
|
||||
}
|
||||
if (interaction.commandName === 'dragonroll' && interaction.options.getSubcommand() === 'link') {
|
||||
await respondCampaignChoices(interaction, guildId);
|
||||
return;
|
||||
if (interaction.commandName === 'dragonroll') {
|
||||
const subcommand = interaction.options.getSubcommand();
|
||||
if (subcommand === 'link') {
|
||||
await respondCampaignChoices(interaction, guildId);
|
||||
return;
|
||||
}
|
||||
if (['assign', 'unassign'].includes(subcommand)) {
|
||||
await respondActorChoices(interaction, guildId);
|
||||
return;
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
@@ -412,6 +505,34 @@ async function main() {
|
||||
return;
|
||||
}
|
||||
|
||||
// Players link themselves to a character of the campaign (Syndria98/dragonroll#72).
|
||||
if (['assign', 'unassign'].includes(subcommand)) {
|
||||
await interaction.deferReply({ flags: MessageFlags.Ephemeral });
|
||||
try {
|
||||
await handleActorAssignment(interaction, guildId, subcommand);
|
||||
} catch (error) {
|
||||
if (error instanceof DragonrollNotConnectedError) {
|
||||
await explainNotConnected(interaction, guildId);
|
||||
return;
|
||||
}
|
||||
if (error instanceof CampaignNotLinkedError) {
|
||||
await explainMissingCampaign(interaction, guildId);
|
||||
return;
|
||||
}
|
||||
if (error.code === 'discord.errors.actor-held') {
|
||||
await respond(interaction, { content: 'That character is already linked to another player. A server administrator can give it away and take it with the same command.' });
|
||||
return;
|
||||
}
|
||||
if (error.status === 401 || error.message.includes('DRAGONROLL_DISCORD_BOT_SECRET')) {
|
||||
await respond(interaction, { content: 'The bot API secret is missing or does not match the backend. Contact the bot operator.' });
|
||||
return;
|
||||
}
|
||||
console.error(`Could not ${subcommand} a character link in Discord server ${guildId}:`, error.message);
|
||||
await respond(interaction, { content: 'I could not change that character link right now. Please try again.' });
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
await interaction.deferReply({ flags: MessageFlags.Ephemeral });
|
||||
await showStatus(interaction, guildId);
|
||||
return;
|
||||
@@ -442,7 +563,10 @@ async function main() {
|
||||
const details = [actor.species, actor.className, actor.level ? `Lv. ${actor.level}` : null]
|
||||
.filter(Boolean)
|
||||
.join(' · ');
|
||||
return `• **${actor.name}**${details ? ` — ${details}` : ''}`;
|
||||
// The player a character is linked to (#72); mentions never ping
|
||||
// here, the replies parse no mentions.
|
||||
const player = actor.discordUserId ? ` 🎮 <@${actor.discordUserId}>` : '';
|
||||
return `• **${actor.name}**${details ? ` — ${details}` : ''}${player}`;
|
||||
});
|
||||
const embed = new EmbedBuilder()
|
||||
.setTitle(`Characters of ${campaign.name}`)
|
||||
|
||||
290
tests/discord-actor-links.test.js
Normal file
290
tests/discord-actor-links.test.js
Normal file
@@ -0,0 +1,290 @@
|
||||
// Tests for linking the characters of a campaign to the Discord players of the server it is
|
||||
// linked to (Syndria98/dragonroll#72): each player holds one character, anybody claims a free
|
||||
// one for themselves, and only a server administrator moves or frees one somebody else holds.
|
||||
//
|
||||
// Same set-up as tests/map-tokens.test.js, which the repository root runs without installing
|
||||
// anything: the express router of routes/discord.js is loaded into `node:vm` with its models
|
||||
// stubbed, and the last checks read the sources of the bot, whose command wiring is what has
|
||||
// to stay right.
|
||||
//
|
||||
// Run with `npm test` from the repository root, or `node --test tests/`.
|
||||
|
||||
const { test } = require("node:test");
|
||||
const assert = require("node:assert/strict");
|
||||
const fs = require("node:fs");
|
||||
const path = require("node:path");
|
||||
const vm = require("node:vm");
|
||||
|
||||
function readRepoFile(...parts) {
|
||||
return fs.readFileSync(path.join(__dirname, "..", ...parts), "utf8");
|
||||
}
|
||||
|
||||
// A mongoose query answers whatever `await query` and `query.lean()` answer with, and lets `select()`
|
||||
// and `sort()` sit in between.
|
||||
function mongooseQuery(value) {
|
||||
const result = {
|
||||
select: () => result,
|
||||
sort: () => result,
|
||||
lean: () => Promise.resolve(value),
|
||||
then: (onFulfilled, onRejected) => Promise.resolve(value).then(onFulfilled, onRejected),
|
||||
};
|
||||
return result;
|
||||
}
|
||||
|
||||
const GUILD_ID = "12345678901234567";
|
||||
const PLAYER = "1111111111111111111";
|
||||
const OTHER_PLAYER = "2222222222222222222";
|
||||
|
||||
// The pieces of a filter the routes build against actors: the campaign, the player holding the
|
||||
// character, and plain or `$ne` ids.
|
||||
function actorMatches(actor, filter = {}) {
|
||||
if (filter.campaign !== undefined && String(actor.campaign) !== String(filter.campaign)) return false;
|
||||
if (filter.discordUserId !== undefined && String(actor.discordUserId ?? null) !== String(filter.discordUserId ?? null)) return false;
|
||||
if (filter._id !== undefined) {
|
||||
if (filter._id && typeof filter._id === "object" && filter._id.$ne !== undefined) {
|
||||
if (String(actor._id) === String(filter._id.$ne)) return false;
|
||||
} else if (String(actor._id) !== String(filter._id)) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
// Loads routes/discord.js over a store of actors, a guild link and the campaign that guild holds.
|
||||
function loadDiscordRoutes({ guildLink = { guildId: GUILD_ID, dragonrollUser: "user-1" }, campaign = { _id: "campaign-1", name: "Katlum" }, actors = [] } = {}) {
|
||||
const store = actors.map((actor) => ({ campaign: "campaign-1", discordUserId: null, save: async () => {}, ...actor }));
|
||||
|
||||
const routes = new Map();
|
||||
const router = {
|
||||
get: (route, ...handlers) => routes.set(`GET ${route}`, handlers),
|
||||
post: (route, ...handlers) => routes.set(`POST ${route}`, handlers),
|
||||
delete: () => {},
|
||||
};
|
||||
|
||||
const requireStub = (id) => {
|
||||
if (id === "express") return { Router: () => router };
|
||||
if (id === "../models/Actor") return {
|
||||
findOne: (filter) => {
|
||||
const actor = store.find((candidate) => actorMatches(candidate, filter));
|
||||
return mongooseQuery(actor ?? null);
|
||||
},
|
||||
find: (filter) => mongooseQuery(store.filter((candidate) => actorMatches(candidate, filter))
|
||||
.slice()
|
||||
.sort((a, b) => String(a.name).localeCompare(String(b.name)))),
|
||||
updateMany: async (filter, update) => {
|
||||
let modifiedCount = 0;
|
||||
for (const actor of store) {
|
||||
if (!actorMatches(actor, filter)) continue;
|
||||
if (update.$set && "discordUserId" in update.$set) actor.discordUserId = update.$set.discordUserId;
|
||||
modifiedCount += 1;
|
||||
}
|
||||
return { modifiedCount };
|
||||
},
|
||||
};
|
||||
if (id === "../models/Campaign") return { findOne: () => mongooseQuery(campaign) };
|
||||
if (id === "../models/DiscordGuildLink") return { findOne: () => mongooseQuery(guildLink) };
|
||||
if (id === "../models/ServiceLinkRequest") return {};
|
||||
if (id === "../models/User") return {};
|
||||
if (id === "../services/service-links") return { requireDiscordBot: (req, res, next) => next(), NOTIFICATION_WINDOW_MS: 1 };
|
||||
throw new Error(`require("${id}") is not stubbed`);
|
||||
};
|
||||
|
||||
const moduleStub = { exports: {} };
|
||||
vm.compileFunction(readRepoFile("backend", "src", "routes", "discord.js"), ["require", "module", "exports"])(
|
||||
requireStub, moduleStub, moduleStub.exports
|
||||
);
|
||||
|
||||
async function call(route, { body = {}, params = {} } = {}) {
|
||||
const handlers = routes.get(route);
|
||||
assert.ok(handlers, `${route} is not mounted`);
|
||||
const res = { payload: null, json(payload) { this.payload = payload; } };
|
||||
// The last handler of the chain, skipping the bot-secret gate the harness stands behind.
|
||||
await handlers[handlers.length - 1]({ body, params: { guildId: GUILD_ID, ...params } }, res);
|
||||
return res.payload;
|
||||
}
|
||||
|
||||
function actor(id) {
|
||||
return store.find((candidate) => candidate._id === id);
|
||||
}
|
||||
|
||||
return { call, actor };
|
||||
}
|
||||
|
||||
const ASSIGN = "POST /bot/guild/:guildId/actors/assign";
|
||||
const UNASSIGN = "POST /bot/guild/:guildId/actors/unassign";
|
||||
|
||||
function assignmentRouteTests() {
|
||||
test("assigning links one campaign character to a Discord player", async () => {
|
||||
const api = loadDiscordRoutes({ actors: [{ _id: "actor-1", name: "Katlum" }] });
|
||||
|
||||
const response = await api.call(ASSIGN, { body: { actorId: "actor-1", discordUserId: PLAYER } });
|
||||
|
||||
assert.equal(response.status, "ok");
|
||||
assert.deepEqual(response.actor, { id: "actor-1", name: "Katlum", discordUserId: PLAYER });
|
||||
assert.equal(api.actor("actor-1").discordUserId, PLAYER);
|
||||
assert.equal(response.previous, null);
|
||||
});
|
||||
|
||||
test("a player never holds two characters: taking a second one frees the first", async () => {
|
||||
const api = loadDiscordRoutes({
|
||||
actors: [
|
||||
{ _id: "actor-1", name: "Katlum", discordUserId: PLAYER },
|
||||
{ _id: "actor-2", name: "Solus" }
|
||||
]
|
||||
});
|
||||
|
||||
const response = await api.call(ASSIGN, { body: { actorId: "actor-2", discordUserId: PLAYER } });
|
||||
|
||||
assert.equal(response.status, "ok");
|
||||
assert.equal(api.actor("actor-1").discordUserId, null);
|
||||
assert.equal(api.actor("actor-2").discordUserId, PLAYER);
|
||||
assert.deepEqual(response.previous, { id: "actor-1", name: "Katlum" });
|
||||
});
|
||||
|
||||
test("a player cannot take a character another player already holds", async () => {
|
||||
const api = loadDiscordRoutes({
|
||||
actors: [{ _id: "actor-1", name: "Katlum", discordUserId: OTHER_PLAYER }]
|
||||
});
|
||||
|
||||
const response = await api.call(ASSIGN, { body: { actorId: "actor-1", discordUserId: PLAYER } });
|
||||
|
||||
assert.equal(response.msg, "discord.errors.actor-held");
|
||||
assert.equal(api.actor("actor-1").discordUserId, OTHER_PLAYER);
|
||||
});
|
||||
|
||||
test("a server administrator moves a held character to themselves", async () => {
|
||||
const api = loadDiscordRoutes({
|
||||
actors: [
|
||||
{ _id: "actor-1", name: "Katlum", discordUserId: OTHER_PLAYER },
|
||||
{ _id: "actor-2", name: "Solus", discordUserId: PLAYER }
|
||||
]
|
||||
});
|
||||
|
||||
const response = await api.call(ASSIGN, { body: { actorId: "actor-1", discordUserId: PLAYER, admin: true } });
|
||||
|
||||
assert.equal(response.status, "ok");
|
||||
assert.equal(api.actor("actor-1").discordUserId, PLAYER);
|
||||
assert.equal(api.actor("actor-2").discordUserId, null);
|
||||
});
|
||||
|
||||
test("unassigning without a character frees the one linked to the player", async () => {
|
||||
const api = loadDiscordRoutes({
|
||||
actors: [
|
||||
{ _id: "actor-1", name: "Katlum", discordUserId: PLAYER },
|
||||
{ _id: "actor-2", name: "Silang", discordUserId: OTHER_PLAYER }
|
||||
]
|
||||
});
|
||||
|
||||
const response = await api.call(UNASSIGN, { body: { discordUserId: PLAYER } });
|
||||
|
||||
assert.equal(response.status, "ok");
|
||||
assert.deepEqual(response.actor, { id: "actor-1", name: "Katlum" });
|
||||
assert.equal(response.wasYours, true);
|
||||
assert.equal(api.actor("actor-1").discordUserId, null);
|
||||
assert.equal(api.actor("actor-2").discordUserId, OTHER_PLAYER);
|
||||
});
|
||||
|
||||
test("a player cannot unassign a character held by somebody else", async () => {
|
||||
const api = loadDiscordRoutes({
|
||||
actors: [{ _id: "actor-1", name: "Katlum", discordUserId: OTHER_PLAYER }]
|
||||
});
|
||||
|
||||
const response = await api.call(UNASSIGN, { body: { actorId: "actor-1", discordUserId: PLAYER } });
|
||||
|
||||
assert.equal(response.msg, "discord.errors.actor-held");
|
||||
assert.equal(api.actor("actor-1").discordUserId, OTHER_PLAYER);
|
||||
});
|
||||
|
||||
test("a server administrator frees anybody's character", async () => {
|
||||
const api = loadDiscordRoutes({
|
||||
actors: [{ _id: "actor-1", name: "Katlum", discordUserId: OTHER_PLAYER }]
|
||||
});
|
||||
|
||||
const response = await api.call(UNASSIGN, { body: { actorId: "actor-1", discordUserId: PLAYER, admin: true } });
|
||||
|
||||
assert.equal(response.status, "ok");
|
||||
assert.equal(response.wasYours, false);
|
||||
assert.equal(api.actor("actor-1").discordUserId, null);
|
||||
});
|
||||
}
|
||||
|
||||
function assignmentGuardTests() {
|
||||
test("linking needs a guild with a connected account and a linked campaign", async () => {
|
||||
const connected = loadDiscordRoutes({ actors: [{ _id: "actor-1", name: "Katlum" }] });
|
||||
assert.equal((await connected.call(ASSIGN, { body: { actorId: "actor-1", discordUserId: PLAYER } })).status, "ok");
|
||||
|
||||
const notLinked = loadDiscordRoutes({ guildLink: null });
|
||||
assert.equal((await notLinked.call(ASSIGN, { body: { actorId: "actor-1", discordUserId: PLAYER } })).msg, "discord.errors.not-connected");
|
||||
assert.equal((await notLinked.call(UNASSIGN, { body: { discordUserId: PLAYER } })).msg, "discord.errors.not-connected");
|
||||
|
||||
const noCampaign = loadDiscordRoutes({ campaign: null });
|
||||
assert.equal((await noCampaign.call(ASSIGN, { body: { actorId: "actor-1", discordUserId: PLAYER } })).msg, "errors.notfound");
|
||||
});
|
||||
|
||||
test("linking needs a whole player and one of the campaign's own characters", async () => {
|
||||
const api = loadDiscordRoutes({ actors: [{ _id: "actor-1", name: "Katlum", campaign: "campaign-1" }] });
|
||||
|
||||
assert.equal((await api.call(ASSIGN, { body: { discordUserId: PLAYER } })).msg, "errors.missing-data");
|
||||
assert.equal((await api.call(ASSIGN, { body: { actorId: "actor-1" } })).msg, "errors.missing-data");
|
||||
assert.equal((await api.call(ASSIGN, { body: { actorId: "actor-1", discordUserId: "bob" } })).msg, "errors.missing-data");
|
||||
assert.equal((await api.call(UNASSIGN, { body: {} })).msg, "errors.missing-data");
|
||||
|
||||
const otherCampaign = loadDiscordRoutes({ actors: [{ _id: "actor-9", name: "Stranger", campaign: "campaign-2" }] });
|
||||
assert.equal((await otherCampaign.call(ASSIGN, { body: { actorId: "actor-9", discordUserId: PLAYER } })).msg, "errors.notfound");
|
||||
});
|
||||
|
||||
test("the bot roster carries the player linked to each character", async () => {
|
||||
const api = loadDiscordRoutes({
|
||||
actors: [
|
||||
{ _id: "actor-1", name: "Katlum", discordUserId: PLAYER },
|
||||
{ _id: "actor-2", name: "Solus" }
|
||||
]
|
||||
});
|
||||
|
||||
const response = await api.call("GET /bot/guild/:guildId/actors");
|
||||
|
||||
assert.equal(response.status, "ok");
|
||||
assert.deepEqual(response.actors.map((actor) => actor.discordUserId), [PLAYER, null]);
|
||||
});
|
||||
}
|
||||
|
||||
function botWiringTests() {
|
||||
const commands = readRepoFile("discord-bot", "src", "commands.js");
|
||||
const api = readRepoFile("discord-bot", "src", "dragonroll-api.js");
|
||||
const bot = readRepoFile("discord-bot", "src", "index.js");
|
||||
|
||||
test("the dragonroll command carries assign and unassign with a character choice", () => {
|
||||
assert.match(commands, /setName\('assign'\)[\s\S]*setName\('character'\)[\s\S]*setRequired\(true\)[\s\S]*setAutocomplete\(true\)/);
|
||||
assert.match(commands, /setName\('unassign'\)[\s\S]*setName\('character'\)[\s\S]*setAutocomplete\(true\)/);
|
||||
// The unassign character is optional, so a player can free their own without naming it.
|
||||
const unassign = /setName\('unassign'\)([\s\S]*)$/.exec(commands)?.[1] ?? "";
|
||||
assert.doesNotMatch(unassign, /setRequired\(true\)/);
|
||||
});
|
||||
|
||||
test("the bot client calls the new routes and answers the new subcommands", () => {
|
||||
assert.match(api, /\/actors\/assign/);
|
||||
assert.match(api, /\/actors\/unassign/);
|
||||
assert.match(bot, /\['assign', 'unassign'\]\.includes\(subcommand\)/);
|
||||
assert.match(bot, /dragonroll\.assignActor\(guildId/);
|
||||
assert.match(bot, /dragonroll\.unassignActor\(guildId/);
|
||||
});
|
||||
|
||||
test("the character choices autocomplete both new subcommands", () => {
|
||||
const autocomplete = /if \(interaction\.commandName === 'dragonroll'\) \{([\s\S]*?)\n \}\n/.exec(bot)?.[1] ?? "";
|
||||
assert.match(autocomplete, /\['assign', 'unassign'\]\.includes\(subcommand\)/);
|
||||
assert.match(autocomplete, /respondActorChoices\(interaction, guildId\)/);
|
||||
});
|
||||
|
||||
test("the roster shows the player and the status card shows your character", () => {
|
||||
assert.match(bot, /actor\.discordUserId \? ` 🎮 <@\$\{actor\.discordUserId\}>`/);
|
||||
assert.match(bot, /name: 'Your character'/);
|
||||
});
|
||||
|
||||
test("the actor model holds one Discord player per character and per campaign", () => {
|
||||
const model = readRepoFile("backend", "src", "models", "Actor.js");
|
||||
assert.match(model, /discordUserId: \{ type: String, default: null \}/);
|
||||
assert.match(model, /\{ campaign: 1, discordUserId: 1 \},\s*\{ unique: true, partialFilterExpression: \{ discordUserId: \{ \$type: 'string' \} \} \}/);
|
||||
});
|
||||
}
|
||||
|
||||
assignmentRouteTests();
|
||||
assignmentGuardTests();
|
||||
botWiringTests();
|
||||
Reference in New Issue
Block a user