Fix issue #19: Add unified campaign sync
This commit is contained in:
@@ -1,24 +1,28 @@
|
||||
const express = require('express')
|
||||
const router = express.Router();
|
||||
const crypto = require('node:crypto');
|
||||
|
||||
const Campaign = require("../models/Campaign");
|
||||
const FoundryLinkRequest = require('../models/FoundryLinkRequest');
|
||||
const User = require('../models/User');
|
||||
const serviceLinks = require('../services/service-links');
|
||||
|
||||
const FOUNDRY_LINK_TTL_MS = 10 * 60 * 1000;
|
||||
// Every service links to a campaign through the same sign-up link
|
||||
// (routes/service-link.js); a campaign only drops one of them again.
|
||||
async function unlinkService(campaign, service) {
|
||||
if (service === 'foundry') {
|
||||
campaign.foundryWorldId = undefined;
|
||||
campaign.foundryWorldTitle = undefined;
|
||||
campaign.foundrySystem = undefined;
|
||||
campaign.set('foundrySyncTokenHash', undefined);
|
||||
} else if (service === 'discord') {
|
||||
// The Discord account the bot answers to stays: the server is simply
|
||||
// left without a campaign until somebody picks one again.
|
||||
campaign.discordGuildId = undefined;
|
||||
}
|
||||
|
||||
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() } });
|
||||
await campaign.save();
|
||||
// A link a service still holds becomes invalid, and it finds that out the
|
||||
// next time it asks where its link stands.
|
||||
await serviceLinks.revokeServiceLink(service, campaign._id);
|
||||
}
|
||||
|
||||
router.post('/create', async (req, res) => {
|
||||
@@ -74,73 +78,26 @@ router.post('/update', async (req, res) => {
|
||||
}
|
||||
});
|
||||
|
||||
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) => {
|
||||
// Which services a campaign has connected, and the account each of them was
|
||||
// authorized with.
|
||||
router.get('/services', 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 });
|
||||
const links = await serviceLinks.listLinkedServices(campaign._id);
|
||||
const userIds = [...new Set(links.map((link) => String(link.dragonrollUser ?? '')).filter(Boolean))];
|
||||
const users = userIds.length
|
||||
? await User.find({ _id: { $in: userIds } }).select('username name').lean()
|
||||
: [];
|
||||
const names = new Map(users.map((user) => [String(user._id), user.username || user.name]));
|
||||
|
||||
res.set('Cache-Control', 'no-store');
|
||||
res.json({
|
||||
status: 'ok',
|
||||
request: { requestId: request.id, code: request.code, expiresAt: request.expiresAt }
|
||||
services: links.map((link) => ({
|
||||
...link,
|
||||
dragonrollUserName: names.get(String(link.dragonrollUser ?? '')) || null
|
||||
}))
|
||||
});
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
@@ -148,18 +105,16 @@ router.get('/foundry-link/pending', async (req, res) => {
|
||||
}
|
||||
});
|
||||
|
||||
router.post('/foundry-unlink', async (req, res) => {
|
||||
router.post('/service-unlink', async (req, res) => {
|
||||
try {
|
||||
const service = String(req.body.service || '').trim();
|
||||
if (!serviceLinks.isService(service)) return res.json({ status: 'error', msg: 'errors.missing-data' });
|
||||
|
||||
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 });
|
||||
await unlinkService(campaign, service);
|
||||
res.json({ status: 'ok', campaign, services: await serviceLinks.listLinkedServices(campaign._id) });
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
res.json({ status: 'error', msg: 'errors.internal' });
|
||||
|
||||
Reference in New Issue
Block a user