Foundry and discord bot
All checks were successful
Build and Deploy Nuxt / build (push) Successful in 1m51s
All checks were successful
Build and Deploy Nuxt / build (push) Successful in 1m51s
This commit is contained in:
@@ -40,13 +40,34 @@ require('./services/passport')(passport);
|
||||
// CORS
|
||||
app.use(cookieParser());
|
||||
|
||||
app.use(cors({
|
||||
const foundryCorsPaths = [
|
||||
'/api/foundry/link/complete', '/foundry/link/complete',
|
||||
'/api/foundry/sync', '/foundry/sync',
|
||||
];
|
||||
const foundryCors = cors({
|
||||
origin: true,
|
||||
methods: ['GET', 'POST', 'OPTIONS'],
|
||||
allowedHeaders: ['Authorization', 'Content-Type'],
|
||||
});
|
||||
app.use('/api/foundry/link/complete', foundryCors);
|
||||
app.use('/foundry/link/complete', foundryCors);
|
||||
app.use('/api/foundry/sync', foundryCors);
|
||||
app.use('/foundry/sync', foundryCors);
|
||||
|
||||
const appCors = cors({
|
||||
origin: 'http://localhost:3000',
|
||||
credentials: true, // if using cookies/auth
|
||||
}));
|
||||
});
|
||||
app.use((req, res, next) => {
|
||||
if (foundryCorsPaths.some((path) => req.path === path || req.path.startsWith(`${path}/`))) return next();
|
||||
appCors(req, res, next);
|
||||
});
|
||||
|
||||
// ROUTES (NO AUTH)
|
||||
app.use('/api/user', require('./routes/user'));
|
||||
app.use('/api/discord', require('./routes/discord'));
|
||||
app.use('/api/foundry', require('./routes/foundry-link'));
|
||||
app.use('/foundry', require('./routes/foundry-link'));
|
||||
|
||||
// AUTH
|
||||
checkAuth = passport.authenticate('jwt', { session: false });
|
||||
@@ -56,6 +77,9 @@ app.use(checkAuth);
|
||||
app.use('/api/campaign', require('./routes/campaign'));
|
||||
app.use('/api/note', require('./routes/note'));
|
||||
app.use('/api/folder', require('./routes/folder'));
|
||||
app.use('/api/actor', require('./routes/actor'));
|
||||
app.use('/api/item', require('./routes/item'));
|
||||
app.use('/api/foundry', require('./routes/foundry'));
|
||||
/*
|
||||
app.use('/campaign', require('./routes/campaign'));
|
||||
app.use('/maps', require('./routes/map'));
|
||||
@@ -70,4 +94,4 @@ app.get("/api/test", (req, res) => {
|
||||
|
||||
app.listen(5000, () => {
|
||||
console.log("Server running on port 5000");
|
||||
});
|
||||
});
|
||||
|
||||
47
backend/src/models/Actor.js
Normal file
47
backend/src/models/Actor.js
Normal file
@@ -0,0 +1,47 @@
|
||||
const mongoose = require('mongoose');
|
||||
const Schema = mongoose.Schema;
|
||||
|
||||
const ActorSchema = new Schema({
|
||||
name: { type: String, required: true, trim: true },
|
||||
type: { type: String, enum: ['character', 'npc', 'creature'], default: 'character' },
|
||||
species: { type: String, default: '' },
|
||||
className: { type: String, default: '' },
|
||||
subclass: { type: String, default: '' },
|
||||
level: { type: Number, min: 1, max: 20, default: 1 },
|
||||
background: { type: String, default: '' },
|
||||
challengeRating: { type: String, default: '' },
|
||||
description: { type: String, default: '' },
|
||||
image: { type: String, default: '' },
|
||||
abilityScores: {
|
||||
str: { type: Number, min: 1, max: 30, default: 10 },
|
||||
dex: { type: Number, min: 1, max: 30, default: 10 },
|
||||
con: { type: Number, min: 1, max: 30, default: 10 },
|
||||
int: { type: Number, min: 1, max: 30, default: 10 },
|
||||
wis: { type: Number, min: 1, max: 30, default: 10 },
|
||||
cha: { type: Number, min: 1, max: 30, default: 10 }
|
||||
},
|
||||
armorClass: { type: Number, min: 0, default: 10 },
|
||||
speed: { type: Number, min: 0, default: 30 },
|
||||
proficiencies: { type: String, default: '' },
|
||||
inventory: [{
|
||||
name: { type: String, trim: true, default: '' },
|
||||
quantity: { type: Number, min: 1, default: 1 },
|
||||
weight: { type: Number, min: 0, default: 0 }
|
||||
}],
|
||||
traits: { type: String, default: '' },
|
||||
spells: { type: String, default: '' },
|
||||
campaign: {
|
||||
type: Schema.Types.ObjectId,
|
||||
ref: 'Campaign',
|
||||
required: true
|
||||
},
|
||||
foundryActorId: { type: String },
|
||||
date: { type: Date, default: Date.now }
|
||||
});
|
||||
|
||||
ActorSchema.index(
|
||||
{ campaign: 1, foundryActorId: 1 },
|
||||
{ unique: true, partialFilterExpression: { foundryActorId: { $type: 'string' } } }
|
||||
);
|
||||
|
||||
module.exports = mongoose.model('Actor', ActorSchema);
|
||||
@@ -11,7 +11,14 @@ const CampaignSchema = new Schema({
|
||||
required: true
|
||||
},
|
||||
date: { type: Date, default: Date.now},
|
||||
settings: { type: Object }
|
||||
settings: { type: Object },
|
||||
foundryWorldId: { type: String, unique: true, sparse: true },
|
||||
foundryWorldTitle: { type: String },
|
||||
foundrySystem: { type: String },
|
||||
foundrySyncTokenHash: { type: String, select: false },
|
||||
// Discord server ("guild") this campaign is linked to. A campaign serves
|
||||
// at most one guild, and a guild selects one campaign.
|
||||
discordGuildId: { type: String, index: true }
|
||||
});
|
||||
|
||||
module.exports = mongoose.model('Campaign', CampaignSchema);
|
||||
module.exports = mongoose.model('Campaign', CampaignSchema);
|
||||
|
||||
11
backend/src/models/DiscordGuildLink.js
Normal file
11
backend/src/models/DiscordGuildLink.js
Normal file
@@ -0,0 +1,11 @@
|
||||
const mongoose = require('mongoose');
|
||||
const Schema = mongoose.Schema;
|
||||
|
||||
const DiscordGuildLinkSchema = new Schema({
|
||||
guildId: { type: String, required: true, unique: true, index: true },
|
||||
discordUserId: { type: String, required: true },
|
||||
dragonrollUser: { type: Schema.Types.ObjectId, ref: 'User', required: true },
|
||||
connectedAt: { type: Date, default: Date.now }
|
||||
});
|
||||
|
||||
module.exports = mongoose.model('DiscordGuildLink', DiscordGuildLinkSchema);
|
||||
20
backend/src/models/DiscordLinkRequest.js
Normal file
20
backend/src/models/DiscordLinkRequest.js
Normal file
@@ -0,0 +1,20 @@
|
||||
const mongoose = require('mongoose');
|
||||
const Schema = mongoose.Schema;
|
||||
|
||||
const DiscordLinkRequestSchema = new Schema({
|
||||
codeHash: { type: String, required: true, unique: true },
|
||||
guildId: { type: String, required: true },
|
||||
guildName: { type: String, required: true },
|
||||
discordUserId: { type: String, required: true },
|
||||
discordUserName: { type: String, required: true },
|
||||
dragonrollUser: { type: Schema.Types.ObjectId, ref: 'User' },
|
||||
createdAt: { type: Date, default: Date.now },
|
||||
expiresAt: { type: Date, required: true },
|
||||
completedAt: { type: Date },
|
||||
// Quan el bot ja ha confirmat a Discord que aquesta autoritzacio s'ha fet.
|
||||
notifiedAt: { type: Date }
|
||||
});
|
||||
|
||||
DiscordLinkRequestSchema.index({ expiresAt: 1 }, { expireAfterSeconds: 0 });
|
||||
|
||||
module.exports = mongoose.model('DiscordLinkRequest', DiscordLinkRequestSchema);
|
||||
24
backend/src/models/FoundryLinkRequest.js
Normal file
24
backend/src/models/FoundryLinkRequest.js
Normal file
@@ -0,0 +1,24 @@
|
||||
const mongoose = require('mongoose');
|
||||
const Schema = mongoose.Schema;
|
||||
|
||||
const FoundryLinkRequestSchema = new Schema({
|
||||
codeHash: { type: String, required: true, unique: true },
|
||||
// Kept in clear text so the campaign settings screen can re-display a pending
|
||||
// pairing code after a reload or a backend restart. It is only ever returned
|
||||
// to the user who created the request and is cleared once the link completes.
|
||||
code: { type: String },
|
||||
source: { type: String, enum: ['dragonroll'], required: true },
|
||||
campaign: { type: Schema.Types.ObjectId, ref: 'Campaign' },
|
||||
createdBy: { type: Schema.Types.ObjectId, ref: 'User' },
|
||||
worldId: { type: String },
|
||||
worldTitle: { type: String },
|
||||
system: { type: String },
|
||||
foundryUrl: { type: String },
|
||||
createdAt: { type: Date, default: Date.now },
|
||||
expiresAt: { type: Date, required: true },
|
||||
completedAt: { type: Date }
|
||||
});
|
||||
|
||||
FoundryLinkRequestSchema.index({ expiresAt: 1 }, { expireAfterSeconds: 0 });
|
||||
|
||||
module.exports = mongoose.model('FoundryLinkRequest', FoundryLinkRequestSchema);
|
||||
28
backend/src/models/Item.js
Normal file
28
backend/src/models/Item.js
Normal file
@@ -0,0 +1,28 @@
|
||||
const mongoose = require('mongoose');
|
||||
const Schema = mongoose.Schema;
|
||||
|
||||
const ItemSchema = new Schema({
|
||||
name: { type: String, required: true, trim: true },
|
||||
category: {
|
||||
type: String,
|
||||
enum: ['weapon', 'armor', 'shield', 'adventuring-gear', 'magic-item', 'consumable', 'tool', 'treasure', 'other'],
|
||||
default: 'adventuring-gear'
|
||||
},
|
||||
rarity: {
|
||||
type: String,
|
||||
enum: ['common', 'uncommon', 'rare', 'very-rare', 'legendary', 'artifact'],
|
||||
default: 'common'
|
||||
},
|
||||
quantity: { type: Number, min: 1, default: 1 },
|
||||
weight: { type: Number, min: 0 },
|
||||
properties: { type: String, default: '' },
|
||||
description: { type: String, default: '' },
|
||||
campaign: {
|
||||
type: Schema.Types.ObjectId,
|
||||
ref: 'Campaign',
|
||||
required: true
|
||||
},
|
||||
date: { type: Date, default: Date.now }
|
||||
});
|
||||
|
||||
module.exports = mongoose.model('Item', ItemSchema);
|
||||
111
backend/src/routes/actor.js
Normal file
111
backend/src/routes/actor.js
Normal file
@@ -0,0 +1,111 @@
|
||||
const express = require('express');
|
||||
const router = express.Router();
|
||||
|
||||
const upload = require('../services/storage');
|
||||
|
||||
const Campaign = require('../models/Campaign');
|
||||
const Actor = require('../models/Actor');
|
||||
|
||||
async function userOwnsCampaign(campaignId, userId) {
|
||||
const campaign = await Campaign.findOne({ _id: campaignId, createdBy: userId }).lean();
|
||||
return Boolean(campaign);
|
||||
}
|
||||
|
||||
router.get('/list', async (req, res) => {
|
||||
try {
|
||||
const { campaign } = req.query;
|
||||
if (!campaign) return res.json({ status: 'error', msg: 'errors.missing-data' });
|
||||
if (!(await userOwnsCampaign(campaign, req.user.id))) return res.json({ status: 'error', msg: 'unauthorized' });
|
||||
|
||||
const actors = await Actor.find({ campaign }).sort({ name: 1 }).lean();
|
||||
res.json({ status: 'ok', actors });
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
res.json({ status: 'error', msg: 'errors.internal' });
|
||||
}
|
||||
});
|
||||
|
||||
router.post('/create', async (req, res) => {
|
||||
try {
|
||||
const { name, campaign, type, species, className, subclass, level, background, challengeRating, description } = req.body;
|
||||
if (!name?.trim() || !campaign) return res.json({ status: 'error', msg: 'errors.missing-data' });
|
||||
if (!(await userOwnsCampaign(campaign, req.user.id))) return res.json({ status: 'error', msg: 'unauthorized' });
|
||||
|
||||
const actor = await Actor.create({
|
||||
name: name.trim(), campaign, type, species, className, subclass,
|
||||
level: level === '' || level === undefined ? undefined : Number(level),
|
||||
background, challengeRating, description
|
||||
});
|
||||
res.json({ status: 'ok', actor });
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
res.json({ status: 'error', msg: 'errors.internal' });
|
||||
}
|
||||
});
|
||||
|
||||
router.post('/update', async (req, res) => {
|
||||
try {
|
||||
const { id, name, species, className, subclass, level, abilityScores, armorClass, speed, proficiencies, inventory, traits, spells, image } = req.body;
|
||||
if (!id) return res.json({ status: 'error', msg: 'errors.missing-data' });
|
||||
|
||||
const actor = await Actor.findById(id);
|
||||
if (!actor) return res.json({ status: 'error', msg: 'errors.notfound' });
|
||||
if (!(await userOwnsCampaign(actor.campaign, req.user.id))) return res.json({ status: 'error', msg: 'unauthorized' });
|
||||
|
||||
if (name !== undefined) actor.name = String(name).trim();
|
||||
if (species !== undefined) actor.species = species;
|
||||
if (className !== undefined) actor.className = className;
|
||||
if (subclass !== undefined) actor.subclass = subclass;
|
||||
if (level !== undefined) actor.level = Number(level);
|
||||
if (abilityScores !== undefined) actor.abilityScores = abilityScores;
|
||||
if (armorClass !== undefined) actor.armorClass = Number(armorClass);
|
||||
if (speed !== undefined) actor.speed = Number(speed);
|
||||
if (proficiencies !== undefined) actor.proficiencies = proficiencies;
|
||||
if (inventory !== undefined) actor.inventory = inventory;
|
||||
if (traits !== undefined) actor.traits = traits;
|
||||
if (spells !== undefined) actor.spells = spells;
|
||||
if (image !== undefined) actor.image = String(image);
|
||||
|
||||
await actor.save();
|
||||
res.json({ status: 'ok', actor });
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
res.json({ status: 'error', msg: 'errors.internal' });
|
||||
}
|
||||
});
|
||||
|
||||
// Upload actor image post
|
||||
router.post("/upload-image", upload.single("image"), async (req, res) => {
|
||||
try {
|
||||
const actorId = req.query.actor || req.body.actor;
|
||||
if (!actorId || !req.file) return res.json({ status: 'error', msg: 'errors.missing-data' });
|
||||
|
||||
const actor = await Actor.findById(actorId);
|
||||
if (!actor) return res.json({ status: 'error', msg: 'errors.notfound' });
|
||||
if (!(await userOwnsCampaign(actor.campaign, req.user.id))) return res.json({ status: 'error', msg: 'unauthorized' });
|
||||
|
||||
actor.image = req.file.filename;
|
||||
await actor.save();
|
||||
res.json({ status: "ok", msg: "uploaded", actor });
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
res.json({ status: "error", msg: "internal" });
|
||||
}
|
||||
});
|
||||
|
||||
router.post('/delete', async (req, res) => {
|
||||
try {
|
||||
const { id } = req.body;
|
||||
if (!id) return res.json({ status: 'error', msg: 'errors.missing-data' });
|
||||
const actor = await Actor.findById(id);
|
||||
if (!actor) return res.json({ status: 'error', msg: 'errors.notfound' });
|
||||
if (!(await userOwnsCampaign(actor.campaign, req.user.id))) return res.json({ status: 'error', msg: 'unauthorized' });
|
||||
await actor.deleteOne();
|
||||
res.json({ status: 'ok' });
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
res.json({ status: 'error', msg: 'errors.internal' });
|
||||
}
|
||||
});
|
||||
|
||||
module.exports = router;
|
||||
@@ -1,7 +1,25 @@
|
||||
const express = require('express')
|
||||
const router = express.Router();
|
||||
const crypto = require('node:crypto');
|
||||
|
||||
const Campaign = require("../models/Campaign");
|
||||
const FoundryLinkRequest = require('../models/FoundryLinkRequest');
|
||||
|
||||
const FOUNDRY_LINK_TTL_MS = 10 * 60 * 1000;
|
||||
|
||||
function foundryCodeHash(code) {
|
||||
return crypto.createHash('sha256').update(String(code ?? '').trim()).digest('hex');
|
||||
}
|
||||
|
||||
async function expirePendingFoundryLinks(campaignId, userId) {
|
||||
const filter = {
|
||||
source: 'dragonroll',
|
||||
campaign: campaignId,
|
||||
createdBy: userId,
|
||||
completedAt: null
|
||||
};
|
||||
await FoundryLinkRequest.updateMany(filter, { $set: { expiresAt: new Date() } });
|
||||
}
|
||||
|
||||
router.post('/create', async (req, res) => {
|
||||
try {
|
||||
@@ -21,6 +39,133 @@ router.post('/create', async (req, res) => {
|
||||
}
|
||||
});
|
||||
|
||||
router.post('/update', async (req, res) => {
|
||||
try {
|
||||
const { id, name, color, settings } = req.body;
|
||||
if (!id) return res.json({ status: "error", msg: "errors.missing-data" });
|
||||
|
||||
const campaign = await Campaign.findOne({ _id: id, createdBy: req.user.id });
|
||||
if (!campaign) return res.json({ status: "error", msg: "errors.notfound" });
|
||||
|
||||
if (name !== undefined) {
|
||||
if (typeof name !== 'string' || !name.trim()) {
|
||||
return res.json({ status: "error", msg: "errors.missing-data" });
|
||||
}
|
||||
campaign.name = name.trim();
|
||||
}
|
||||
|
||||
if (color !== undefined) {
|
||||
if (typeof color !== 'string') return res.json({ status: "error", msg: "errors.missing-data" });
|
||||
campaign.color = color;
|
||||
}
|
||||
|
||||
if (settings !== undefined) {
|
||||
if (!settings || typeof settings !== 'object' || Array.isArray(settings)) {
|
||||
return res.json({ status: "error", msg: "errors.missing-data" });
|
||||
}
|
||||
campaign.settings = settings;
|
||||
}
|
||||
|
||||
await campaign.save();
|
||||
res.json({ status: "ok", campaign });
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
res.json({ status: "error", msg: "errors.internal" });
|
||||
}
|
||||
});
|
||||
|
||||
router.post('/foundry-link/start', async (req, res) => {
|
||||
try {
|
||||
const campaign = await Campaign.findOne({ _id: req.body.campaignId, createdBy: req.user.id });
|
||||
if (!campaign) return res.json({ status: 'error', msg: 'errors.notfound' });
|
||||
|
||||
await expirePendingFoundryLinks(campaign._id, req.user.id);
|
||||
const code = crypto.randomBytes(24).toString('base64url');
|
||||
const expiresAt = new Date(Date.now() + FOUNDRY_LINK_TTL_MS);
|
||||
const request = await FoundryLinkRequest.create({
|
||||
codeHash: foundryCodeHash(code),
|
||||
code,
|
||||
source: 'dragonroll',
|
||||
campaign: campaign._id,
|
||||
createdBy: req.user.id,
|
||||
expiresAt
|
||||
});
|
||||
|
||||
res.set('Cache-Control', 'no-store');
|
||||
res.json({ status: 'ok', code, requestId: request.id, expiresAt });
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
res.json({ status: 'error', msg: 'errors.internal' });
|
||||
}
|
||||
});
|
||||
|
||||
router.get('/foundry-link/status/:requestId', async (req, res) => {
|
||||
try {
|
||||
const request = await FoundryLinkRequest.findOne({
|
||||
_id: req.params.requestId,
|
||||
source: 'dragonroll',
|
||||
createdBy: req.user.id
|
||||
});
|
||||
if (!request) return res.json({ status: 'ok', state: 'expired' });
|
||||
if (!request.completedAt && request.expiresAt <= new Date()) {
|
||||
return res.json({ status: 'ok', state: 'expired' });
|
||||
}
|
||||
if (!request.completedAt) return res.json({ status: 'ok', state: 'pending' });
|
||||
|
||||
const campaign = await Campaign.findOne({ _id: request.campaign, createdBy: req.user.id });
|
||||
if (!campaign) return res.json({ status: 'error', msg: 'errors.notfound' });
|
||||
res.json({ status: 'ok', state: 'complete', campaign });
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
res.json({ status: 'error', msg: 'errors.internal' });
|
||||
}
|
||||
});
|
||||
|
||||
// Returns the still-valid pending pairing request for a campaign, so the
|
||||
// settings window can restore its pairing code across reloads and restarts.
|
||||
router.get('/foundry-link/pending', async (req, res) => {
|
||||
try {
|
||||
const campaign = await Campaign.findOne({ _id: req.query.campaignId, createdBy: req.user.id });
|
||||
if (!campaign) return res.json({ status: 'error', msg: 'errors.notfound' });
|
||||
|
||||
const request = await FoundryLinkRequest.findOne({
|
||||
source: 'dragonroll',
|
||||
campaign: campaign._id,
|
||||
createdBy: req.user.id,
|
||||
completedAt: null,
|
||||
expiresAt: { $gt: new Date() }
|
||||
}).sort({ createdAt: -1 });
|
||||
if (!request) return res.json({ status: 'ok', request: null });
|
||||
|
||||
res.set('Cache-Control', 'no-store');
|
||||
res.json({
|
||||
status: 'ok',
|
||||
request: { requestId: request.id, code: request.code, expiresAt: request.expiresAt }
|
||||
});
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
res.json({ status: 'error', msg: 'errors.internal' });
|
||||
}
|
||||
});
|
||||
|
||||
router.post('/foundry-unlink', async (req, res) => {
|
||||
try {
|
||||
const campaign = await Campaign.findOne({ _id: req.body.campaignId, createdBy: req.user.id });
|
||||
if (!campaign) return res.json({ status: 'error', msg: 'errors.notfound' });
|
||||
|
||||
campaign.foundryWorldId = undefined;
|
||||
campaign.foundryWorldTitle = undefined;
|
||||
campaign.foundrySystem = undefined;
|
||||
campaign.set('foundrySyncTokenHash', undefined);
|
||||
await campaign.save();
|
||||
await expirePendingFoundryLinks(campaign._id, req.user.id);
|
||||
res.json({ status: 'ok', campaign });
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
res.json({ status: 'error', msg: 'errors.internal' });
|
||||
}
|
||||
});
|
||||
|
||||
router.get('/list', async (req, res) => {
|
||||
try {
|
||||
const campaigns = await Campaign.find({ createdBy: req.user.id });
|
||||
|
||||
272
backend/src/routes/discord.js
Normal file
272
backend/src/routes/discord.js
Normal file
@@ -0,0 +1,272 @@
|
||||
const crypto = require('node:crypto');
|
||||
const express = require('express');
|
||||
const passport = require('passport');
|
||||
const router = express.Router();
|
||||
|
||||
const Actor = require('../models/Actor');
|
||||
const Campaign = require('../models/Campaign');
|
||||
const DiscordGuildLink = require('../models/DiscordGuildLink');
|
||||
const DiscordLinkRequest = require('../models/DiscordLinkRequest');
|
||||
const User = require('../models/User');
|
||||
|
||||
const LINK_TTL_MS = 10 * 60 * 1000;
|
||||
const NOTIFICATION_WINDOW_MS = 15 * 60 * 1000;
|
||||
const NOTIFICATION_LIMIT = 10;
|
||||
|
||||
function validGuildId(value) {
|
||||
return /^\d{5,25}$/.test(String(value ?? ''));
|
||||
}
|
||||
|
||||
function codeHash(code) {
|
||||
return crypto.createHash('sha256').update(String(code ?? '')).digest('hex');
|
||||
}
|
||||
|
||||
function requireBot(req, res, next) {
|
||||
const configuredSecret = process.env.DRAGONROLL_DISCORD_BOT_SECRET?.trim() || '';
|
||||
const suppliedSecret = req.get('x-dragonroll-discord-bot-secret') || '';
|
||||
const expected = Buffer.from(configuredSecret);
|
||||
const supplied = Buffer.from(suppliedSecret);
|
||||
|
||||
if (!expected.length || expected.length !== supplied.length || !crypto.timingSafeEqual(expected, supplied)) {
|
||||
return res.status(401).json({ status: 'error', msg: 'errors.unauthorized' });
|
||||
}
|
||||
return next();
|
||||
}
|
||||
|
||||
function frontendAuthorizeUrl() {
|
||||
const frontendUrl = (process.env.DRAGONROLL_FRONTEND_URL || 'http://localhost:3000').trim().replace(/\/+$/, '');
|
||||
return `${frontendUrl}/discord/authorize`;
|
||||
}
|
||||
|
||||
// La pantalla d'autorització l'serveix el frontend. El codi viatja al fragment de la URL i el
|
||||
// navegador no l'envia mai al servidor, així que els enllaços antics del bot arriben a la
|
||||
// pantalla sense codi i demanen de tornar a executar /dragonroll connect.
|
||||
router.get('/authorize', (req, res) => {
|
||||
res.set('Cache-Control', 'no-store');
|
||||
res.set('Referrer-Policy', 'no-referrer');
|
||||
res.set('X-Content-Type-Options', 'nosniff');
|
||||
res.redirect(302, frontendAuthorizeUrl());
|
||||
});
|
||||
|
||||
router.post('/link/start', requireBot, async (req, res) => {
|
||||
try {
|
||||
const { guildId, guildName, discordUserId, discordUserName } = req.body;
|
||||
if (!validGuildId(guildId) || !/^\d{5,25}$/.test(String(discordUserId ?? '')) || !guildName || !discordUserName) {
|
||||
return res.json({ status: 'error', msg: 'errors.missing-data' });
|
||||
}
|
||||
|
||||
const code = crypto.randomBytes(32).toString('base64url');
|
||||
await DiscordLinkRequest.create({
|
||||
codeHash: codeHash(code),
|
||||
guildId: String(guildId),
|
||||
guildName: String(guildName).slice(0, 100),
|
||||
discordUserId: String(discordUserId),
|
||||
discordUserName: String(discordUserName).slice(0, 100),
|
||||
expiresAt: new Date(Date.now() + LINK_TTL_MS)
|
||||
});
|
||||
|
||||
res.json({ status: 'ok', code, expiresAt: new Date(Date.now() + LINK_TTL_MS) });
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
res.json({ status: 'error', msg: 'errors.internal' });
|
||||
}
|
||||
});
|
||||
|
||||
router.post('/link/details', async (req, res) => {
|
||||
try {
|
||||
res.set('Cache-Control', 'no-store');
|
||||
const request = await DiscordLinkRequest.findOne({
|
||||
codeHash: codeHash(req.body.code),
|
||||
expiresAt: { $gt: new Date() },
|
||||
completedAt: null
|
||||
}).lean();
|
||||
if (!request) return res.json({ status: 'error', msg: 'discord.errors.link-expired' });
|
||||
|
||||
res.json({ status: 'ok', guildName: request.guildName, discordUserName: request.discordUserName });
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
res.json({ status: 'error', msg: 'errors.internal' });
|
||||
}
|
||||
});
|
||||
|
||||
router.post('/link/complete', passport.authenticate('jwt', { session: false }), async (req, res) => {
|
||||
try {
|
||||
const request = await DiscordLinkRequest.findOneAndUpdate({
|
||||
codeHash: codeHash(req.body.code),
|
||||
expiresAt: { $gt: new Date() },
|
||||
completedAt: null
|
||||
}, {
|
||||
$set: { completedAt: new Date(), dragonrollUser: req.user.id }
|
||||
}, { new: true });
|
||||
if (!request) return res.json({ status: 'error', msg: 'discord.errors.link-expired' });
|
||||
|
||||
await Campaign.updateMany(
|
||||
{ discordGuildId: request.guildId, createdBy: { $ne: req.user.id } },
|
||||
{ $unset: { discordGuildId: 1 } }
|
||||
);
|
||||
|
||||
await DiscordGuildLink.findOneAndUpdate({ guildId: request.guildId }, {
|
||||
$set: {
|
||||
discordUserId: request.discordUserId,
|
||||
dragonrollUser: req.user.id,
|
||||
connectedAt: new Date()
|
||||
}
|
||||
}, { new: true, upsert: true, setDefaultsOnInsert: true });
|
||||
|
||||
res.json({ status: 'ok', guildName: request.guildName });
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
res.json({ status: 'error', msg: 'errors.internal' });
|
||||
}
|
||||
});
|
||||
|
||||
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 DiscordLinkRequest.find({
|
||||
completedAt: { $gte: new Date(Date.now() - NOTIFICATION_WINDOW_MS) },
|
||||
notifiedAt: null
|
||||
}).select('_id guildId guildName discordUserId discordUserName dragonrollUser')
|
||||
.limit(NOTIFICATION_LIMIT)
|
||||
.lean();
|
||||
|
||||
const claimed = [];
|
||||
for (const request of pending) {
|
||||
const taken = await DiscordLinkRequest.findOneAndUpdate(
|
||||
{ _id: request._id, notifiedAt: null },
|
||||
{ $set: { notifiedAt: new Date() } },
|
||||
{ new: true }
|
||||
).lean();
|
||||
if (taken) claimed.push(request);
|
||||
}
|
||||
|
||||
const names = await dragonrollUserNames(claimed);
|
||||
res.json({
|
||||
status: 'ok',
|
||||
notifications: claimed.map((request) => ({
|
||||
id: String(request._id),
|
||||
guildId: request.guildId,
|
||||
guildName: request.guildName,
|
||||
discordUserId: request.discordUserId,
|
||||
discordUserName: request.discordUserName,
|
||||
dragonrollUserName: names.get(String(request.dragonrollUser ?? '')) || 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' });
|
||||
}
|
||||
});
|
||||
|
||||
module.exports = router;
|
||||
258
backend/src/routes/foundry-link.js
Normal file
258
backend/src/routes/foundry-link.js
Normal file
@@ -0,0 +1,258 @@
|
||||
const crypto = require('node:crypto');
|
||||
const express = require('express');
|
||||
const rateLimit = require('express-rate-limit');
|
||||
const mongoose = require('mongoose');
|
||||
const router = express.Router();
|
||||
|
||||
const Campaign = require('../models/Campaign');
|
||||
const Actor = require('../models/Actor');
|
||||
const FoundryLinkRequest = require('../models/FoundryLinkRequest');
|
||||
const { foundryActorToCharacter } = require('../services/actor-foundry');
|
||||
|
||||
const linkRateLimit = rateLimit({ windowMs: 15 * 60 * 1000, max: 20 });
|
||||
|
||||
function codeHash(code) {
|
||||
return crypto.createHash('sha256').update(String(code ?? '').trim()).digest('hex');
|
||||
}
|
||||
|
||||
function readSyncToken(req) {
|
||||
const match = /^Bearer\s+(.+)$/i.exec(req.get('authorization') || '');
|
||||
return match?.[1] || '';
|
||||
}
|
||||
|
||||
async function syncCampaign(req, res) {
|
||||
const token = readSyncToken(req);
|
||||
if (!token) {
|
||||
res.json({ status: 'error', msg: 'unauthorized' });
|
||||
return null;
|
||||
}
|
||||
|
||||
const campaign = await Campaign.findOne({ foundrySyncTokenHash: codeHash(token) });
|
||||
if (!campaign?.foundryWorldId) {
|
||||
res.json({ status: 'error', msg: 'unauthorized' });
|
||||
return null;
|
||||
}
|
||||
return campaign;
|
||||
}
|
||||
|
||||
function requestMatchesWorld(campaign, worldId) {
|
||||
return typeof worldId === 'string' && worldId === campaign.foundryWorldId;
|
||||
}
|
||||
|
||||
async function saveFoundryActor(campaign, source, fullSync = false) {
|
||||
const foundryActorId = String(source?._id || source?.id || '').trim().slice(0, 120);
|
||||
const fields = foundryActorToCharacter(source || {});
|
||||
if (!foundryActorId || !fields.name) return null;
|
||||
|
||||
let actor = await Actor.findOne({ campaign: campaign._id, foundryActorId });
|
||||
const dragonrollActorId = source?.flags?.['dragonroll-foundry']?.actorId;
|
||||
if (!actor && mongoose.isValidObjectId(dragonrollActorId)) {
|
||||
actor = await Actor.findOne({ _id: dragonrollActorId, campaign: campaign._id });
|
||||
}
|
||||
if (!actor) {
|
||||
const possibleMatches = await Actor.find({
|
||||
campaign: campaign._id,
|
||||
name: fields.name,
|
||||
foundryActorId: { $exists: false }
|
||||
}).limit(2);
|
||||
actor = possibleMatches.length === 1
|
||||
? possibleMatches[0]
|
||||
: new Actor({ campaign: campaign._id });
|
||||
}
|
||||
actor.foundryActorId = foundryActorId;
|
||||
// A full snapshot runs when a GM reconnects. Preserve existing Dragonroll
|
||||
// edits then; live Foundry change events continue to overwrite normally.
|
||||
if (!fullSync || actor.isNew) Object.assign(actor, fields);
|
||||
await actor.save();
|
||||
return { foundryActorId, actorId: actor.id };
|
||||
}
|
||||
|
||||
function readWorld(body) {
|
||||
const world = body?.world;
|
||||
if (!world || typeof world.id !== 'string' || !world.id.trim()) return null;
|
||||
|
||||
let foundryUrl = '';
|
||||
if (typeof world.url === 'string') {
|
||||
try {
|
||||
const url = new URL(world.url);
|
||||
if (url.protocol === 'http:' || url.protocol === 'https:') foundryUrl = url.origin;
|
||||
} catch {}
|
||||
}
|
||||
|
||||
return {
|
||||
worldId: world.id.trim().slice(0, 120),
|
||||
worldTitle: typeof world.title === 'string' ? world.title.trim().slice(0, 200) : '',
|
||||
system: typeof world.system === 'string' ? world.system.trim().slice(0, 120) : '',
|
||||
foundryUrl
|
||||
};
|
||||
}
|
||||
|
||||
async function attachWorldToCampaign(campaign, world) {
|
||||
const linkedElsewhere = await Campaign.findOne({
|
||||
foundryWorldId: world.worldId,
|
||||
_id: { $ne: campaign._id }
|
||||
}).select('_id');
|
||||
if (linkedElsewhere) return false;
|
||||
|
||||
campaign.foundryWorldId = world.worldId;
|
||||
campaign.foundryWorldTitle = world.worldTitle;
|
||||
campaign.foundrySystem = world.system;
|
||||
if (world.foundryUrl) {
|
||||
const settings = campaign.settings && typeof campaign.settings === 'object' ? campaign.settings : {};
|
||||
const integrations = settings.integrations && typeof settings.integrations === 'object'
|
||||
? settings.integrations
|
||||
: {};
|
||||
campaign.settings = {
|
||||
...settings,
|
||||
integrations: {
|
||||
...integrations,
|
||||
foundryUrl: integrations.foundryUrl || world.foundryUrl
|
||||
}
|
||||
};
|
||||
}
|
||||
await campaign.save();
|
||||
return true;
|
||||
}
|
||||
|
||||
async function expireOtherPendingLinks(campaignId, userId, requestId) {
|
||||
await FoundryLinkRequest.updateMany({
|
||||
source: 'dragonroll',
|
||||
campaign: campaignId,
|
||||
createdBy: userId,
|
||||
completedAt: null,
|
||||
_id: { $ne: requestId }
|
||||
}, { $set: { expiresAt: new Date() } });
|
||||
}
|
||||
|
||||
router.post('/link/complete', linkRateLimit, async (req, res) => {
|
||||
try {
|
||||
const world = readWorld(req.body);
|
||||
if (!world || typeof req.body.code !== 'string' || !req.body.code.trim()) {
|
||||
return res.json({ status: 'error', msg: 'errors.missing-data' });
|
||||
}
|
||||
|
||||
const request = await FoundryLinkRequest.findOne({
|
||||
codeHash: codeHash(req.body.code),
|
||||
source: 'dragonroll',
|
||||
expiresAt: { $gt: new Date() },
|
||||
completedAt: null
|
||||
});
|
||||
if (!request) return res.json({ status: 'error', msg: 'foundry.errors.link-expired' });
|
||||
|
||||
const campaign = await Campaign.findOne({ _id: request.campaign, createdBy: request.createdBy });
|
||||
if (!campaign) return res.json({ status: 'error', msg: 'errors.notfound' });
|
||||
|
||||
const attached = await attachWorldToCampaign(campaign, world);
|
||||
if (!attached) return res.json({ status: 'error', msg: 'foundry.errors.world-already-linked' });
|
||||
|
||||
const syncToken = crypto.randomBytes(32).toString('base64url');
|
||||
campaign.foundrySyncTokenHash = codeHash(syncToken);
|
||||
await campaign.save();
|
||||
|
||||
request.worldId = world.worldId;
|
||||
request.worldTitle = world.worldTitle;
|
||||
request.system = world.system;
|
||||
request.foundryUrl = world.foundryUrl;
|
||||
request.completedAt = new Date();
|
||||
request.code = undefined; // Redeemed: keep only the hash from now on.
|
||||
await request.save();
|
||||
await expireOtherPendingLinks(campaign._id, request.createdBy, request._id);
|
||||
|
||||
const bridgeUrl = process.env.FOUNDRY_API_CLIENT_URL || process.env.FOUNDRY_API_URL;
|
||||
const pushToken = process.env.FOUNDRY_API_PUSH_TOKEN;
|
||||
res.set('Cache-Control', 'no-store');
|
||||
res.json({
|
||||
status: 'ok',
|
||||
world: { id: world.worldId, title: world.worldTitle, system: world.system },
|
||||
syncToken,
|
||||
bridgeConfig: bridgeUrl && pushToken ? { url: bridgeUrl, pushToken } : null
|
||||
});
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
if (err.code === 11000) return res.json({ status: 'error', msg: 'foundry.errors.world-already-linked' });
|
||||
res.json({ status: 'error', msg: 'errors.internal' });
|
||||
}
|
||||
});
|
||||
|
||||
router.post('/sync/snapshot', async (req, res) => {
|
||||
try {
|
||||
const campaign = await syncCampaign(req, res);
|
||||
if (!campaign) return;
|
||||
if (!requestMatchesWorld(campaign, req.body.worldId) || !Array.isArray(req.body.actors)) {
|
||||
return res.json({ status: 'error', msg: 'errors.missing-data' });
|
||||
}
|
||||
|
||||
const actors = [];
|
||||
for (const source of req.body.actors) {
|
||||
const mapping = await saveFoundryActor(campaign, source, req.body.fullSync === true);
|
||||
if (mapping) actors.push(mapping);
|
||||
}
|
||||
if (req.body.fullSync === true) {
|
||||
const currentIds = req.body.actors
|
||||
.map((source) => String(source?._id || source?.id || '').trim())
|
||||
.filter(Boolean);
|
||||
await Actor.deleteMany({
|
||||
campaign: campaign._id,
|
||||
foundryActorId: { $exists: true, $nin: currentIds }
|
||||
});
|
||||
}
|
||||
res.json({ status: 'ok', actors });
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
res.json({ status: 'error', msg: 'errors.internal' });
|
||||
}
|
||||
});
|
||||
|
||||
router.post('/sync/delete', async (req, res) => {
|
||||
try {
|
||||
const campaign = await syncCampaign(req, res);
|
||||
if (!campaign) return;
|
||||
const foundryActorId = String(req.body.foundryActorId || '').trim();
|
||||
if (!requestMatchesWorld(campaign, req.body.worldId) || !foundryActorId) {
|
||||
return res.json({ status: 'error', msg: 'errors.missing-data' });
|
||||
}
|
||||
|
||||
await Actor.deleteOne({ campaign: campaign._id, foundryActorId });
|
||||
res.json({ status: 'ok' });
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
res.json({ status: 'error', msg: 'errors.internal' });
|
||||
}
|
||||
});
|
||||
|
||||
router.get('/sync/characters', async (req, res) => {
|
||||
try {
|
||||
const campaign = await syncCampaign(req, res);
|
||||
if (!campaign) return;
|
||||
const actors = await Actor.find({ campaign: campaign._id }).sort({ name: 1 }).lean();
|
||||
res.json({ status: 'ok', actors });
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
res.json({ status: 'error', msg: 'errors.internal' });
|
||||
}
|
||||
});
|
||||
|
||||
router.post('/sync/map', async (req, res) => {
|
||||
try {
|
||||
const campaign = await syncCampaign(req, res);
|
||||
if (!campaign) return;
|
||||
const { actorId, foundryActorId, worldId } = req.body;
|
||||
if (!requestMatchesWorld(campaign, worldId) || !actorId || !foundryActorId) {
|
||||
return res.json({ status: 'error', msg: 'errors.missing-data' });
|
||||
}
|
||||
|
||||
const actor = await Actor.findOne({ _id: actorId, campaign: campaign._id });
|
||||
if (!actor) return res.json({ status: 'error', msg: 'errors.notfound' });
|
||||
const existing = await Actor.findOne({ campaign: campaign._id, foundryActorId, _id: { $ne: actor._id } });
|
||||
if (existing) return res.json({ status: 'error', msg: 'foundry.errors.actor-already-synced' });
|
||||
|
||||
actor.foundryActorId = String(foundryActorId).trim().slice(0, 120);
|
||||
await actor.save();
|
||||
res.json({ status: 'ok', actor });
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
res.json({ status: 'error', msg: 'errors.internal' });
|
||||
}
|
||||
});
|
||||
|
||||
module.exports = router;
|
||||
27
backend/src/routes/foundry.js
Normal file
27
backend/src/routes/foundry.js
Normal file
@@ -0,0 +1,27 @@
|
||||
const express = require('express');
|
||||
const router = express.Router();
|
||||
const { requestFoundry } = require('../services/foundry');
|
||||
|
||||
async function proxy(path, res) {
|
||||
try {
|
||||
const result = await requestFoundry(path);
|
||||
res.status(result.status).json(result.data);
|
||||
} catch (err) {
|
||||
if (err.code === 'FOUNDRY_NOT_CONFIGURED') {
|
||||
return res.status(503).json({ status: 'error', msg: 'foundry.not-configured' });
|
||||
}
|
||||
|
||||
console.error(err);
|
||||
res.status(502).json({ status: 'error', msg: 'foundry.unavailable' });
|
||||
}
|
||||
}
|
||||
|
||||
router.get('/world', (req, res) => proxy('api/world', res));
|
||||
router.get('/actors', (req, res) => proxy('api/actors', res));
|
||||
router.get('/characters', (req, res) => proxy('api/characters', res));
|
||||
router.get('/items', (req, res) => proxy('api/items', res));
|
||||
router.get('/actors/:id/items', (req, res) => proxy(`api/actors/${encodeURIComponent(req.params.id)}/items`, res));
|
||||
router.get('/actors/:id', (req, res) => proxy(`api/actors/${encodeURIComponent(req.params.id)}`, res));
|
||||
router.get('/items/:id', (req, res) => proxy(`api/items/${encodeURIComponent(req.params.id)}`, res));
|
||||
|
||||
module.exports = router;
|
||||
60
backend/src/routes/item.js
Normal file
60
backend/src/routes/item.js
Normal file
@@ -0,0 +1,60 @@
|
||||
const express = require('express');
|
||||
const router = express.Router();
|
||||
|
||||
const Campaign = require('../models/Campaign');
|
||||
const Item = require('../models/Item');
|
||||
|
||||
async function userOwnsCampaign(campaignId, userId) {
|
||||
const campaign = await Campaign.findOne({ _id: campaignId, createdBy: userId }).lean();
|
||||
return Boolean(campaign);
|
||||
}
|
||||
|
||||
router.get('/list', async (req, res) => {
|
||||
try {
|
||||
const { campaign } = req.query;
|
||||
if (!campaign) return res.json({ status: 'error', msg: 'errors.missing-data' });
|
||||
if (!(await userOwnsCampaign(campaign, req.user.id))) return res.json({ status: 'error', msg: 'unauthorized' });
|
||||
|
||||
const items = await Item.find({ campaign }).sort({ name: 1 }).lean();
|
||||
res.json({ status: 'ok', items });
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
res.json({ status: 'error', msg: 'errors.internal' });
|
||||
}
|
||||
});
|
||||
|
||||
router.post('/create', async (req, res) => {
|
||||
try {
|
||||
const { name, campaign, category, rarity, quantity, weight, properties, description } = req.body;
|
||||
if (!name?.trim() || !campaign) return res.json({ status: 'error', msg: 'errors.missing-data' });
|
||||
if (!(await userOwnsCampaign(campaign, req.user.id))) return res.json({ status: 'error', msg: 'unauthorized' });
|
||||
|
||||
const item = await Item.create({
|
||||
name: name.trim(), campaign, category, rarity,
|
||||
quantity: quantity === '' || quantity === undefined ? 1 : Number(quantity),
|
||||
weight: weight === '' || weight === undefined ? undefined : Number(weight),
|
||||
properties, description
|
||||
});
|
||||
res.json({ status: 'ok', item });
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
res.json({ status: 'error', msg: 'errors.internal' });
|
||||
}
|
||||
});
|
||||
|
||||
router.post('/delete', async (req, res) => {
|
||||
try {
|
||||
const { id } = req.body;
|
||||
if (!id) return res.json({ status: 'error', msg: 'errors.missing-data' });
|
||||
const item = await Item.findById(id);
|
||||
if (!item) return res.json({ status: 'error', msg: 'errors.notfound' });
|
||||
if (!(await userOwnsCampaign(item.campaign, req.user.id))) return res.json({ status: 'error', msg: 'unauthorized' });
|
||||
await item.deleteOne();
|
||||
res.json({ status: 'ok' });
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
res.json({ status: 'error', msg: 'errors.internal' });
|
||||
}
|
||||
});
|
||||
|
||||
module.exports = router;
|
||||
82
backend/src/services/actor-foundry.js
Normal file
82
backend/src/services/actor-foundry.js
Normal file
@@ -0,0 +1,82 @@
|
||||
function numberOr(value, fallback) {
|
||||
const number = Number(value);
|
||||
return Number.isFinite(number) ? number : fallback;
|
||||
}
|
||||
|
||||
function asText(value) {
|
||||
return typeof value === 'string' ? value : '';
|
||||
}
|
||||
|
||||
function plainText(value) {
|
||||
return asText(value)
|
||||
.replace(/<br\s*\/?>/gi, '\n')
|
||||
.replace(/<\/p\s*>/gi, '\n')
|
||||
.replace(/<[^>]*>/g, ' ')
|
||||
.replace(/ /gi, ' ')
|
||||
.replace(/&/gi, '&')
|
||||
.replace(/</gi, '<')
|
||||
.replace(/>/gi, '>')
|
||||
.replace(/\s+\n/g, '\n')
|
||||
.trim();
|
||||
}
|
||||
|
||||
function traitList(value) {
|
||||
if (Array.isArray(value)) return value.map(asText).filter(Boolean);
|
||||
if (typeof value === 'string') return [value];
|
||||
return [];
|
||||
}
|
||||
|
||||
function foundryActorToCharacter(foundryActor) {
|
||||
const system = foundryActor.system || {};
|
||||
const details = system.details || {};
|
||||
const abilities = system.abilities || {};
|
||||
const attributes = system.attributes || {};
|
||||
const movement = attributes.movement || {};
|
||||
const items = Array.isArray(foundryActor.items) ? foundryActor.items : [];
|
||||
const classItem = items.find((item) => item.type === 'class');
|
||||
const subclassItem = items.find((item) => item.type === 'subclass');
|
||||
const backgroundItem = items.find((item) => item.type === 'background');
|
||||
const traits = system.traits || {};
|
||||
const savedDragonrollFields = foundryActor.flags?.['dragonroll-foundry'] || {};
|
||||
const savedDragonrollType = savedDragonrollFields.actorType;
|
||||
const foundryProficiencies = [
|
||||
...traitList(traits.languages?.value),
|
||||
...traitList(traits.armor?.value),
|
||||
...traitList(traits.weapon?.value),
|
||||
...traitList(traits.tool?.value)
|
||||
].join(', ');
|
||||
|
||||
return {
|
||||
name: asText(foundryActor.name).trim(),
|
||||
type: ['character', 'npc', 'creature'].includes(savedDragonrollType)
|
||||
? savedDragonrollType
|
||||
: (['character', 'npc', 'creature'].includes(foundryActor.type) ? foundryActor.type : 'character'),
|
||||
species: asText(details.race || details.species),
|
||||
className: asText(details.class || classItem?.name),
|
||||
subclass: asText(details.subclass || subclassItem?.name),
|
||||
level: numberOr(details.level ?? classItem?.system?.levels, 1),
|
||||
background: asText(details.background || backgroundItem?.name),
|
||||
challengeRating: String(details.cr ?? ''),
|
||||
description: plainText(details.biography?.value || details.biography),
|
||||
image: asText(foundryActor.img || foundryActor.image),
|
||||
abilityScores: Object.fromEntries(['str', 'dex', 'con', 'int', 'wis', 'cha'].map((key) => [
|
||||
key,
|
||||
numberOr(abilities[key]?.value, 10)
|
||||
])),
|
||||
armorClass: numberOr(attributes.ac?.value ?? attributes.ac, 10),
|
||||
speed: numberOr(movement.walk ?? movement.value, 30),
|
||||
proficiencies: foundryProficiencies || asText(savedDragonrollFields.proficiencies),
|
||||
traits: asText(savedDragonrollFields.traits),
|
||||
inventory: items
|
||||
.filter((item) => !['class', 'subclass', 'background', 'spell'].includes(item.type))
|
||||
.map((item) => ({
|
||||
name: asText(item.name).trim(),
|
||||
quantity: numberOr(item.system?.quantity, 1),
|
||||
weight: numberOr(item.system?.weight?.value ?? item.system?.weight, 0)
|
||||
}))
|
||||
.filter((item) => item.name),
|
||||
spells: items.filter((item) => item.type === 'spell').map((item) => asText(item.name)).filter(Boolean).join('\n')
|
||||
};
|
||||
}
|
||||
|
||||
module.exports = { foundryActorToCharacter };
|
||||
34
backend/src/services/foundry.js
Normal file
34
backend/src/services/foundry.js
Normal file
@@ -0,0 +1,34 @@
|
||||
async function requestFoundry(path) {
|
||||
const baseUrl = process.env.FOUNDRY_API_URL;
|
||||
const token = process.env.FOUNDRY_API_TOKEN;
|
||||
|
||||
if (!baseUrl || !token) {
|
||||
const error = new Error('Foundry API is not configured.');
|
||||
error.code = 'FOUNDRY_NOT_CONFIGURED';
|
||||
throw error;
|
||||
}
|
||||
|
||||
const normalizedBase = baseUrl.endsWith('/') ? baseUrl : `${baseUrl}/`;
|
||||
const url = new URL(path.replace(/^\/+/, ''), normalizedBase);
|
||||
const response = await fetch(url, {
|
||||
headers: {
|
||||
'Accept': 'application/json',
|
||||
'Authorization': `Bearer ${token}`
|
||||
},
|
||||
signal: AbortSignal.timeout(10000)
|
||||
});
|
||||
|
||||
const body = await response.text();
|
||||
let data;
|
||||
try {
|
||||
data = JSON.parse(body);
|
||||
} catch {
|
||||
const error = new Error('Foundry API returned an invalid response.');
|
||||
error.code = 'FOUNDRY_INVALID_RESPONSE';
|
||||
throw error;
|
||||
}
|
||||
|
||||
return { status: response.status, data };
|
||||
}
|
||||
|
||||
module.exports = { requestFoundry };
|
||||
Reference in New Issue
Block a user