Added revision import tool.

This commit is contained in:
2026-11-21 05:59:32 +01:00
parent 2f14c6f920
commit b814f3dcf1
3 changed files with 250 additions and 9 deletions
+27 -7
View File
@@ -527,7 +527,7 @@ function diffRelations(baseRelations, deltaRelations) {
}; };
} }
async function fetchRevisionRelations(sceneId, trx) { export async function fetchRevisionRelations(sceneId, trx) {
const relations = await queryRelations(knexOwner, sceneId) const relations = await queryRelations(knexOwner, sceneId)
.modify((builder) => { .modify((builder) => {
if (trx) { if (trx) {
@@ -1264,7 +1264,8 @@ async function applySceneDeleteDelta(sceneId, _delta, trx, reqUser) {
.transacting(trx); .transacting(trx);
} }
async function applySceneRevision(revisionIds, reqUser) { // sync: false leaves syncing to the caller, i.e. to sync once after applying revisions in bulk
async function applySceneRevision(revisionIds, reqUser, { sync = true } = {}) {
const revisions = await knexOwner('scenes_revisions') const revisions = await knexOwner('scenes_revisions')
.whereIn('id', revisionIds) .whereIn('id', revisionIds)
.whereNull('applied_at'); // should not re-apply revision that was already applied .whereNull('applied_at'); // should not re-apply revision that was already applied
@@ -1324,12 +1325,14 @@ async function applySceneRevision(revisionIds, reqUser) {
}); });
}, Promise.resolve()); }, Promise.resolve());
const sceneIds = Array.from(new Set(revisions.map((revision) => revision.scene_id))); if (sync) {
const sceneIds = Array.from(new Set(revisions.map((revision) => revision.scene_id)));
await syncScenes(sceneIds); await syncScenes(sceneIds);
}
} }
export async function reviewSceneRevision(revisionId, isApproved, { feedback }, reqUser) { export async function reviewSceneRevision(revisionId, isApproved, { feedback }, reqUser, options = {}) {
if (!reqUser || reqUser.role === 'user') { if (!reqUser || reqUser.role === 'user') {
throw new HttpError('You are not permitted to approve revisions', 403); throw new HttpError('You are not permitted to approve revisions', 403);
} }
@@ -1355,7 +1358,7 @@ export async function reviewSceneRevision(revisionId, isApproved, { feedback },
if (isApproved) { if (isApproved) {
try { try {
await applySceneRevision([revisionId], reqUser); await applySceneRevision([revisionId], reqUser, options);
} }
catch (error) { catch (error) {
await knexOwner('scenes_revisions') await knexOwner('scenes_revisions')
@@ -1371,7 +1374,8 @@ export async function reviewSceneRevision(revisionId, isApproved, { feedback },
} }
} }
export async function createSceneRevision(sceneId, { edits, comment, apply }, reqUser) { // dryRun validates the edits and returns the deltas without storing a revision
export async function createSceneRevision(sceneId, { edits, comment, apply }, reqUser, { dryRun = false } = {}) {
if (!reqUser) { if (!reqUser) {
throw new HttpError('Must be authenticated to create scene revision', 401); throw new HttpError('Must be authenticated to create scene revision', 401);
} }
@@ -1500,6 +1504,15 @@ export async function createSceneRevision(sceneId, { edits, comment, apply }, re
const affectedSceneIds = getAffectedSceneIds(baseScene, deltas); const affectedSceneIds = getAffectedSceneIds(baseScene, deltas);
if (dryRun) {
return {
id: null,
sceneId: scene.id,
deltas,
affectedSceneIds,
};
}
const [revisionEntry] = await knexOwner('scenes_revisions') const [revisionEntry] = await knexOwner('scenes_revisions')
.insert({ .insert({
user_id: reqUser.id, user_id: reqUser.id,
@@ -1519,4 +1532,11 @@ export async function createSceneRevision(sceneId, { edits, comment, apply }, re
// don't keep the editor waiting for the revision to apply // don't keep the editor waiting for the revision to apply
reviewSceneRevision(revisionEntry.id, true, {}, reqUser).catch(() => {}); reviewSceneRevision(revisionEntry.id, true, {}, reqUser).catch(() => {});
} }
return {
id: revisionEntry.id,
sceneId: scene.id,
deltas,
affectedSceneIds,
};
} }
+6 -2
View File
@@ -286,11 +286,15 @@ export async function syncManticoreScenes(sceneIds) {
return manticoreResult; return manticoreResult;
} }
export async function syncScenes(releaseIds) { // notify: false for bulk curation that shouldn't send alerts
export async function syncScenes(releaseIds, { notify: shouldNotify = true } = {}) {
await knex.raw('REFRESH MATERIALIZED VIEW scenes_meta;'); await knex.raw('REFRESH MATERIALIZED VIEW scenes_meta;');
await syncManticoreScenes(releaseIds); await syncManticoreScenes(releaseIds);
await notify(releaseIds);
if (shouldNotify) {
await notify(releaseIds);
}
} }
export async function syncManticoreMovies(movieIds) { export async function syncManticoreMovies(movieIds) {
+217
View File
@@ -0,0 +1,217 @@
import fs from 'node:fs/promises';
import process from 'node:process';
import yargs from 'yargs';
import { knexOwner as knex } from '../src/knex.js';
import { createSceneRevision, fetchRevisionRelations, reviewSceneRevision } from '../src/scenes.js';
import { syncScenes } from '../src/sync.js';
import { fetchUser } from '../src/users.js';
import runTool from './run-tool.js';
// bulk scene curation, i.e. seeding relations, as revisions so each change is attributed and shows in the scene history
// the file holds an array of { sceneId, edits, comment, addRelations }, edits as submitted by the scene edit page
// addRelations: [{ sceneId, type, direction, comment }] are added to the scene's current relations, rather than replacing them like edits.relations
// validates every entry without storing anything unless --write or --apply is given
const { argv } = yargs(process.argv.slice(2))
.command('$0 <file>', 'import scene revisions from a JSON file')
.option('user', {
describe: 'ID or username of the admin or editor the revisions are attributed to',
type: 'string',
demandOption: true,
})
.option('write', {
describe: 'store the revisions for review',
type: 'boolean',
default: false,
})
.option('apply', {
describe: 'store, approve and apply the revisions, without sending alerts',
type: 'boolean',
default: false,
})
.option('comment', {
describe: 'revision comment for entries without their own',
type: 'string',
})
.option('skip-missing', {
describe: 'skip entries for scenes that don\'t exist, and leave out relations to them, i.e. on a database that is behind the one the file was made for',
type: 'boolean',
default: false,
});
function isNoChange(error) {
return /No effective changes/.test(error.message);
}
async function readEntries(file) {
const entries = JSON.parse(await fs.readFile(file, 'utf8'));
if (!Array.isArray(entries)) {
throw new TypeError('The file must contain an array of revisions');
}
const invalidIndex = entries.findIndex((entry) => !Number.isInteger(entry?.sceneId)
|| (entry.edits !== undefined && (typeof entry.edits !== 'object' || Array.isArray(entry.edits)))
|| (entry.addRelations !== undefined && !Array.isArray(entry.addRelations))
|| (!entry.edits && !entry.addRelations));
if (invalidIndex > -1) {
throw new Error(`Entry ${invalidIndex} needs a numeric sceneId, and edits or addRelations: ${JSON.stringify(entries[invalidIndex])}`);
}
if (entries.some((entry) => entry.addRelations && entry.edits?.relations)) {
throw new Error('An entry can have addRelations or edits.relations, not both');
}
// a second revision would be based on the scene before the first applies, merge them instead
const sceneIds = entries.map((entry) => entry.sceneId);
const duplicateIds = Array.from(new Set(sceneIds.filter((sceneId, index) => sceneIds.indexOf(sceneId) !== index)));
if (duplicateIds.length > 0) {
throw new Error(`Scenes listed more than once, merge their edits into one entry: ${duplicateIds.join(', ')}`);
}
return entries;
}
// relations to missing scenes are left out of addRelations, an entry is skipped if its scene is missing or nothing is left to change
// edits.relations replaces the scene's relations, leaving one out would remove it, so such an entry is skipped entirely
async function skipMissing(entries) {
const sceneIds = Array.from(new Set(entries.flatMap((entry) => [
entry.sceneId,
...(entry.addRelations || []).map((relation) => relation?.sceneId),
...(entry.edits?.relations || []).map((relation) => relation?.sceneId),
]).filter(Number.isInteger)));
const existingIds = new Set(await knex('releases').whereIn('id', sceneIds).pluck('id'));
const missingIds = sceneIds.filter((sceneId) => !existingIds.has(sceneId));
let skipped = 0;
let omittedRelations = 0;
const curatedEntries = entries.map((entry) => {
if (!existingIds.has(entry.sceneId) || (entry.edits?.relations || []).some((relation) => !existingIds.has(relation?.sceneId))) {
skipped += 1;
return null;
}
if (!entry.addRelations) {
return entry;
}
const addRelations = entry.addRelations.filter((relation) => existingIds.has(relation?.sceneId));
omittedRelations += entry.addRelations.length - addRelations.length;
if (addRelations.length === 0 && Object.keys(entry.edits || {}).length === 0) {
skipped += 1;
return null;
}
return { ...entry, addRelations };
}).filter(Boolean);
console.log(`${missingIds.length} scenes not found, skipped ${skipped} entries and left out ${omittedRelations} other relations`);
return curatedEntries;
}
async function curateEdits(entry) {
if (!entry.addRelations) {
return entry.edits;
}
const currentRelations = await fetchRevisionRelations(entry.sceneId);
return {
...entry.edits,
relations: [
...currentRelations.map((relation) => ({
sceneId: relation.sceneId,
type: relation.type,
direction: relation.direction,
comment: relation.comment,
})),
...entry.addRelations,
],
};
}
async function importRevisions() {
const reqUser = await fetchUser(/^\d+$/.test(argv.user) ? Number(argv.user) : argv.user);
if (!['admin', 'editor'].includes(reqUser.role)) {
throw new Error(`User ${reqUser.username} must be an admin or editor to import revisions`);
}
const fileEntries = await readEntries(argv.file);
const entries = argv.skipMissing ? await skipMissing(fileEntries) : fileEntries;
const write = argv.write || argv.apply;
// validate everything first, so a bad entry doesn't leave the import half done
const checked = await entries.reduce(async (chain, entry, index) => {
const acc = await chain;
try {
const revision = await createSceneRevision(entry.sceneId, {
edits: await curateEdits(entry),
comment: entry.comment || argv.comment,
}, reqUser, { dryRun: true });
return { ...acc, valid: acc.valid.concat({ entry, revision }) };
}
catch (error) {
if (isNoChange(error)) {
return { ...acc, unchanged: acc.unchanged.concat(entry) };
}
return { ...acc, invalid: acc.invalid.concat({ index, entry, error }) };
}
}, Promise.resolve({ valid: [], unchanged: [], invalid: [] }));
checked.invalid.forEach(({ index, entry, error }) => console.error(`Entry ${index}, scene ${entry.sceneId}: ${error.message}`));
console.log(`${checked.valid.length} revisions to create, ${checked.unchanged.length} without changes, ${checked.invalid.length} invalid`);
if (checked.invalid.length > 0) {
throw new Error('Not importing, fix the invalid entries first');
}
if (!write) {
checked.valid.forEach(({ revision }) => console.log(`Scene ${revision.sceneId}: ${revision.deltas.map((delta) => delta.key).join(', ')}${revision.affectedSceneIds.length > 0 ? `, affects ${revision.affectedSceneIds.join(', ')}` : ''}`));
console.log('Dry run, use --write to store the revisions for review, or --apply to also apply them');
return;
}
// one at a time, each revision is based on the scene as it is when created
const created = await checked.valid.reduce(async (chain, { entry }) => {
const acc = await chain;
const revision = await createSceneRevision(entry.sceneId, {
edits: await curateEdits(entry),
comment: entry.comment || argv.comment,
}, reqUser);
if (argv.apply) {
await reviewSceneRevision(revision.id, true, {}, reqUser, { sync: false });
}
return acc.concat(revision);
}, Promise.resolve([]));
if (created.length === 0) {
console.log('Nothing to import');
return;
}
console.log(`${argv.apply ? 'Applied' : 'Stored'} ${created.length} revisions: ${created.map((revision) => revision.id).join(', ')}`);
if (argv.apply) {
// once for all, and without alerts, the scenes aren't new
await syncScenes(Array.from(new Set(created.flatMap((revision) => [revision.sceneId, ...revision.affectedSceneIds]))), { notify: false });
}
}
runTool(importRevisions);