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, fetchRelationTypes, fetchRevisionRelations, fetchScenesById, 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, addActors }, 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 // addActors: [actorId] are added to the scene's current cast, rather than replacing it like edits.actors // validates every entry without storing anything unless --write or --apply is given const { argv } = yargs(process.argv.slice(2)) .command('$0 ', '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.addActors !== undefined && (!Array.isArray(entry.addActors) || !entry.addActors.every(Number.isInteger))) || (!entry.edits && !entry.addRelations && !entry.addActors)); if (invalidIndex > -1) { throw new Error(`Entry ${invalidIndex} needs a numeric sceneId, and edits, addRelations or numeric addActors: ${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'); } if (entries.some((entry) => entry.addActors && entry.edits?.actors)) { throw new Error('An entry can have addActors or edits.actors, 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 && !entry.addActors && 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; } let symmetricTypes = null; // symmetric types are stored with direction 'both', whatever direction the file gives async function getRelationKey(relation) { symmetricTypes ??= new Set((await fetchRelationTypes()).filter((type) => type.symmetric).map((type) => type.type)); return `${symmetricTypes.has(relation.type) ? 'both' : relation.direction}:${relation.type}:${relation.sceneId}`; } // the cast as the scene edit page submits it, unidentified actors included async function curateActors(entry, reqUser) { if (!entry.addActors) { return {}; } const [scene] = await fetchScenesById([entry.sceneId], { reqUser }); const currentActorIds = scene?.actors.map((actor) => actor.id) || []; return { actors: Array.from(new Set([...currentActorIds, ...entry.addActors])), }; } async function curateEdits(entry, reqUser) { const actorEdits = await curateActors(entry, reqUser); if (!entry.addRelations) { return { ...entry.edits, ...actorEdits }; } const currentRelations = await fetchRevisionRelations(entry.sceneId); const currentKeys = new Set(await Promise.all(currentRelations.map((relation) => getRelationKey(relation)))); // relations that already exist are left as they are, so the file can't clear or overwrite their comments const addRelations = (await Promise.all(entry.addRelations.map(async (relation) => (currentKeys.has(await getRelationKey(relation)) ? null : relation)))).filter(Boolean); return { ...entry.edits, ...actorEdits, relations: [ ...currentRelations.map((relation) => ({ sceneId: relation.sceneId, type: relation.type, direction: relation.direction, comment: relation.comment, })), ...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, reqUser), 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, reqUser), 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);