134 lines
6.6 KiB
JavaScript
134 lines
6.6 KiB
JavaScript
const express = require('express');
|
|
const router = express.Router();
|
|
const { requestFoundry } = require('../services/foundry');
|
|
const { normalizeIconDirectory, readIconListingPage, shapeIconListing } = require('../services/foundry-icons');
|
|
|
|
const Campaign = require('../models/Campaign');
|
|
// The writers a Foundry document is stored through, shared with the sync pushes the
|
|
// linked module sends (routes/foundry-link.js) so both write a world's rows by the
|
|
// same rules.
|
|
const { saveFoundryActor, saveFoundryItem } = require('./foundry-link');
|
|
|
|
// The world address the icons are loaded from is kept on the campaign, so an icon
|
|
// listing is always asked for one of the caller's own campaigns. The linked world's
|
|
// id travels along: an import has to know whose data it is pulling over.
|
|
async function findOwnedCampaign(campaignId, userId) {
|
|
if (!campaignId) return null;
|
|
return Campaign.findOne({ _id: campaignId, createdBy: userId }).select('settings foundryWorldId').lean();
|
|
}
|
|
|
|
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));
|
|
|
|
// Force import (Syndria98/dragonroll#77): the sidebar's "force import from Foundry"
|
|
// pulls the whole actor list or item directory of the world the bridge is showing
|
|
// right now. The documents go through the writers the module's own snapshot push
|
|
// uses, so a world document lands on the row it owns: what the campaign already has
|
|
// is written over, not imported a second time. Nothing is pruned here — only a full
|
|
// snapshot from the module sees the whole world, so dropping rows the world let go of
|
|
// stays that snapshot's job.
|
|
router.post('/import', async (req, res) => {
|
|
try {
|
|
const kind = ['actors', 'items'].includes(req.body?.kind) ? req.body.kind : null;
|
|
if (!kind) return res.json({ status: 'error', msg: 'errors.missing-data' });
|
|
|
|
const campaign = await findOwnedCampaign(req.body.campaign, req.user.id);
|
|
if (!campaign) return res.json({ status: 'error', msg: 'errors.notfound' });
|
|
if (!campaign.foundryWorldId) {
|
|
return res.json({ status: 'error', msg: 'foundry.errors.import-not-linked' });
|
|
}
|
|
|
|
// The bridge answers `{status, data, world}`: `data` holds the world's actors
|
|
// or its world-level items, in the shape the module published them in.
|
|
let snapshot;
|
|
try {
|
|
snapshot = await requestFoundry(`api/${kind}`);
|
|
} catch (err) {
|
|
if (err.code !== 'FOUNDRY_NOT_CONFIGURED') console.error(err);
|
|
return res.json({ status: 'error', msg: 'foundry.errors.import-unavailable' });
|
|
}
|
|
if (snapshot.status !== 200 || snapshot.data?.status !== 'ok' || !Array.isArray(snapshot.data.data)) {
|
|
return res.json({ status: 'error', msg: 'foundry.errors.import-unavailable' });
|
|
}
|
|
// The bridge keeps one world's snapshot at a time, so a campaign linked to
|
|
// another world must not be filled with it. A bridge that does not say whose
|
|
// world it holds is taken at its word: only a known mismatch stops the import.
|
|
if (snapshot.data.world?.id && snapshot.data.world.id !== campaign.foundryWorldId) {
|
|
return res.json({ status: 'error', msg: 'foundry.errors.import-world-mismatch' });
|
|
}
|
|
|
|
let imported = 0;
|
|
let updated = 0;
|
|
for (const source of snapshot.data.data) {
|
|
// An actor without a name, or a world document that is not gear, maps to
|
|
// nothing and is skipped exactly like a sync push skips it.
|
|
const mapping = kind === 'actors'
|
|
? await saveFoundryActor(campaign, source)
|
|
: await saveFoundryItem(campaign, source);
|
|
if (!mapping) continue;
|
|
if (mapping.created) imported += 1;
|
|
else updated += 1;
|
|
}
|
|
|
|
res.json({ status: 'ok', kind, imported, updated });
|
|
} catch (err) {
|
|
console.error(err);
|
|
res.json({ status: 'error', msg: 'errors.internal' });
|
|
}
|
|
});
|
|
|
|
// Foundry's core icon library: the `icons/` folder of the world's data directory.
|
|
// One folder per request, and the icons inside it paged, because that library runs
|
|
// into the thousands and the window only ever shows where the user is standing.
|
|
// The bridge reads it on the Foundry host; the images themselves are loaded by the
|
|
// browser from the campaign's world address, the same way a synced item's icon is.
|
|
router.get('/icons', async (req, res) => {
|
|
try {
|
|
const campaign = await findOwnedCampaign(req.query.campaign, req.user.id);
|
|
if (!campaign) return res.status(404).json({ status: 'error', msg: 'errors.notfound' });
|
|
|
|
const base = campaign.settings?.integrations?.foundryUrl || '';
|
|
if (!base) return res.status(400).json({ status: 'error', msg: 'foundry.errors.icons-no-world-url' });
|
|
|
|
const dir = normalizeIconDirectory(req.query.dir);
|
|
if (!dir) return res.status(400).json({ status: 'error', msg: 'errors.missing-data' });
|
|
|
|
const { limit, offset } = readIconListingPage(req.query);
|
|
const query = new URLSearchParams({ dir, offset: String(offset), limit: String(limit) });
|
|
const result = await requestFoundry(`api/icons?${query}`);
|
|
if (result.status !== 200 || result.data?.status !== 'ok') {
|
|
return res.status(502).json({ status: 'error', msg: 'foundry.errors.icons-unavailable' });
|
|
}
|
|
|
|
res.json({ status: 'ok', ...shapeIconListing({ base, dir, listing: result.data }) });
|
|
} catch (err) {
|
|
if (err.code === 'FOUNDRY_NOT_CONFIGURED') {
|
|
return res.status(503).json({ status: 'error', msg: 'foundry.errors.icons-unavailable' });
|
|
}
|
|
|
|
console.error(err);
|
|
res.status(502).json({ status: 'error', msg: 'foundry.errors.icons-unavailable' });
|
|
}
|
|
});
|
|
|
|
module.exports = router;
|