Added actor and tag copying to scene relations.
This commit is contained in:
@@ -3,6 +3,7 @@ export function curateRevision(revision) {
|
||||
id: revision.id,
|
||||
sceneId: revision.scene_id,
|
||||
affectedSceneIds: revision.affected_scene_ids || [], // actor revisions have none
|
||||
parentRevisionId: revision.parent_revision_id || null, // generated by sharing a relation, reviewed with the parent
|
||||
actorId: revision.actor_id,
|
||||
base: revision.base,
|
||||
deltas: revision.deltas,
|
||||
|
||||
+429
-69
@@ -492,10 +492,23 @@ export async function fetchSceneRelations(sceneId, { reqUser, ...context } = {})
|
||||
}).filter(Boolean).reverse())).reverse(); // keep the oldest of any duplicates
|
||||
}
|
||||
|
||||
// sharing copies actors, tags or duration between related scenes once, relative to the revised scene:
|
||||
// 'from' the related scene into the revised scene, 'to' the related scene, or 'both' ways
|
||||
const shareFields = (config.revisions.shareFields || []).filter((field) => ['actors', 'tags', 'duration'].includes(field));
|
||||
const shareModes = ['none', 'from', 'to', 'both'];
|
||||
|
||||
export async function fetchRelationTypes() {
|
||||
return knex('relations_types')
|
||||
.select('type', 'symmetric')
|
||||
const types = await knex('relations_types')
|
||||
.select('type', 'symmetric', 'share_defaults')
|
||||
.orderBy('type');
|
||||
|
||||
return types.map((type) => ({
|
||||
type: type.type,
|
||||
symmetric: type.symmetric,
|
||||
// which side receives each field: source, target or both, limited to the fields that can be shared
|
||||
shareDefaults: Object.fromEntries(Object.entries(type.share_defaults || {}).filter(([field]) => shareFields.includes(field))),
|
||||
shareFields,
|
||||
}));
|
||||
}
|
||||
|
||||
// relations in revisions are stored relative to the revised scene: { sceneId, type, direction, comment }
|
||||
@@ -543,6 +556,26 @@ export async function fetchRevisionRelations(sceneId, trx) {
|
||||
}));
|
||||
}
|
||||
|
||||
function curateShare(share) {
|
||||
if (!share) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (typeof share !== 'object' || Array.isArray(share)) {
|
||||
throw new HttpError('Relation share must be an object', 400);
|
||||
}
|
||||
|
||||
const curatedShare = Object.fromEntries(Object.entries(share).filter(([field]) => shareFields.includes(field)).map(([field, mode]) => {
|
||||
if (!shareModes.includes(mode)) {
|
||||
throw new HttpError(`Invalid share mode for ${field}: ${mode}`, 400);
|
||||
}
|
||||
|
||||
return [field, mode];
|
||||
}).filter(([, mode]) => mode !== 'none'));
|
||||
|
||||
return Object.keys(curatedShare).length > 0 ? curatedShare : null;
|
||||
}
|
||||
|
||||
async function curateRelationsEdit(sceneId, relations) {
|
||||
if (!Array.isArray(relations)) {
|
||||
throw new HttpError('Relations must be a list', 400);
|
||||
@@ -565,6 +598,7 @@ async function curateRelationsEdit(sceneId, relations) {
|
||||
comment: typeof relation.comment === 'string' && relation.comment.trim().length > 0
|
||||
? relation.comment.trim()
|
||||
: null,
|
||||
share: curateShare(relation.share), // not part of the relation, stripped from the relations delta
|
||||
};
|
||||
|
||||
return [getRelationKey(curatedRelation), curatedRelation];
|
||||
@@ -597,6 +631,227 @@ async function curateRelationsEdit(sceneId, relations) {
|
||||
return curatedRelations;
|
||||
}
|
||||
|
||||
const getTagKey = (tag) => `${tag.id}:${tag.actorId || null}`;
|
||||
|
||||
// current actors, tags and duration of the scenes involved in sharing, and which tags may never be shared
|
||||
async function fetchShareData(sceneIds) {
|
||||
const [scenes, actors, tags, metaTagIds] = await Promise.all([
|
||||
knexOwner('releases').select('id', 'duration', 'entity_id').whereIn('id', sceneIds),
|
||||
knexOwner('releases_actors').select('id', 'release_id', 'actor_id', 'gender').whereIn('release_id', sceneIds),
|
||||
knexOwner('releases_tags').select('release_id', 'tag_id', 'actor_id', 'source').whereIn('release_id', sceneIds).whereNotNull('tag_id'),
|
||||
knexOwner('tags')
|
||||
.leftJoin('tags_groups', 'tags_groups.id', 'tags.group_id')
|
||||
.where('tags_groups.slug', 'meta') // describe the release rather than the scene, e.g. 4K or compilation
|
||||
.pluck('tags.id'),
|
||||
]);
|
||||
|
||||
// tags every scene of a channel gets, they belong to that channel's scenes
|
||||
const entityTags = await knexOwner('entities_tags')
|
||||
.select('entity_id', 'tag_id')
|
||||
.whereIn('entity_id', Array.from(new Set(scenes.map((scene) => scene.entity_id))));
|
||||
|
||||
return {
|
||||
metaTagIds: new Set(metaTagIds),
|
||||
scenes: Object.fromEntries(scenes.map((scene) => {
|
||||
const entityTagIds = new Set(entityTags.filter((entityTag) => entityTag.entity_id === scene.entity_id).map((entityTag) => entityTag.tag_id));
|
||||
const sceneTags = tags.filter((tag) => tag.release_id === scene.id);
|
||||
const sceneActors = actors.filter((actor) => actor.release_id === scene.id);
|
||||
|
||||
return [scene.id, {
|
||||
id: scene.id,
|
||||
duration: scene.duration,
|
||||
// unidentified actors use the same IDs as for editing, so a child revision keeps them
|
||||
actors: sceneActors.map((actor) => actor.actor_id || `${actor.gender || 'other'}_${actor.id}`),
|
||||
actorIds: sceneActors.map((actor) => actor.actor_id).filter(Boolean), // only identified actors are shared
|
||||
tags: sceneTags.map((tag) => ({ id: tag.tag_id, actorId: tag.actor_id })),
|
||||
// implied tags are derived again on the receiving scene, channel tags only apply to their own channel
|
||||
unshareableTagKeys: new Set(sceneTags
|
||||
.filter((tag) => tag.source === 'implied' || (tag.source !== 'editor' && entityTagIds.has(tag.tag_id)))
|
||||
.map((tag) => getTagKey({ id: tag.tag_id, actorId: tag.actor_id }))),
|
||||
}];
|
||||
})),
|
||||
};
|
||||
}
|
||||
|
||||
function getShareableTags(state, metaTagIds) {
|
||||
return state.tags.filter((tag) => !metaTagIds.has(tag.id) && !state.unshareableTagKeys.has(getTagKey(tag)));
|
||||
}
|
||||
|
||||
// merge what the giving scene has into the receiving scene, never removing or overwriting anything
|
||||
function receiveShare(receiver, giver, fields, metaTagIds) {
|
||||
const received = {};
|
||||
|
||||
if (fields.includes('actors')) {
|
||||
const actorIds = Array.from(new Set([...receiver.actors, ...giver.actorIds]));
|
||||
|
||||
if (actorIds.length > receiver.actors.length) {
|
||||
received.actors = actorIds;
|
||||
}
|
||||
}
|
||||
|
||||
if (fields.includes('tags')) {
|
||||
const finalActorIds = new Set(received.actors || receiver.actors);
|
||||
const tagsByKey = new Map(receiver.tags.map((tag) => [getTagKey(tag), tag]));
|
||||
const receiverTagIds = new Set(receiver.tags.map((tag) => tag.id));
|
||||
|
||||
getShareableTags(giver, metaTagIds).forEach((tag) => {
|
||||
// an actor-specific tag only keeps its actor if the actor is in the receiving scene
|
||||
const keepsActor = !tag.actorId || finalActorIds.has(tag.actorId);
|
||||
const sharedTag = { id: tag.id, actorId: keepsActor ? tag.actorId : null };
|
||||
|
||||
// a tag that lost its actor adds nothing if the receiving scene already has the tag in any form
|
||||
if (!keepsActor && receiverTagIds.has(tag.id)) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!tagsByKey.has(getTagKey(sharedTag))) {
|
||||
tagsByKey.set(getTagKey(sharedTag), sharedTag);
|
||||
receiverTagIds.add(tag.id);
|
||||
}
|
||||
});
|
||||
|
||||
if (tagsByKey.size > receiver.tags.length) {
|
||||
received.tags = Array.from(tagsByKey.values());
|
||||
}
|
||||
}
|
||||
|
||||
// duration can't be merged, only fill it in
|
||||
if (fields.includes('duration') && !receiver.duration && giver.duration) {
|
||||
received.duration = giver.duration;
|
||||
}
|
||||
|
||||
return received;
|
||||
}
|
||||
|
||||
function getShareFields(share, receives) {
|
||||
return Object.entries(share || {})
|
||||
.filter(([, mode]) => mode === 'both' || mode === receives)
|
||||
.map(([field]) => field);
|
||||
}
|
||||
|
||||
// resolve relation shares into edits for the revised scene, and edits for each related scene that become child revisions
|
||||
// shares are resolved against the state before sharing, so what one related scene gives isn't passed on to another
|
||||
async function resolveShares(baseScene, edits, relations) {
|
||||
const sharedRelations = relations.filter((relation) => relation.share);
|
||||
|
||||
if (sharedRelations.length === 0) {
|
||||
return { edits, children: [] };
|
||||
}
|
||||
|
||||
const shareData = await fetchShareData([baseScene.id, ...sharedRelations.map((relation) => relation.sceneId)]);
|
||||
const ownData = shareData.scenes[baseScene.id];
|
||||
|
||||
// the revised scene gives what it will have after this revision's own edits
|
||||
const ownTags = edits.tags?.map((tag) => ({ id: tag.id, actorId: tag.actorId || null })) || ownData.tags;
|
||||
|
||||
const ownGiver = {
|
||||
...ownData,
|
||||
actorIds: (edits.actors || baseScene.actors).filter((actorId) => typeof actorId === 'number'), // unidentified actors aren't shared
|
||||
tags: ownTags,
|
||||
duration: edits.duration ?? baseScene.duration,
|
||||
};
|
||||
|
||||
const ownReceiver = {
|
||||
actors: edits.actors || baseScene.actors,
|
||||
tags: ownTags,
|
||||
duration: edits.duration ?? baseScene.duration,
|
||||
};
|
||||
|
||||
const sharedEdits = { ...edits };
|
||||
const children = [];
|
||||
|
||||
sharedRelations.forEach((relation) => {
|
||||
const related = shareData.scenes[relation.sceneId];
|
||||
|
||||
if (!related) {
|
||||
return;
|
||||
}
|
||||
|
||||
const ownFields = getShareFields(relation.share, 'from');
|
||||
const relatedFields = getShareFields(relation.share, 'to');
|
||||
|
||||
if (ownFields.length > 0) {
|
||||
const received = receiveShare({
|
||||
actors: sharedEdits.actors || ownReceiver.actors,
|
||||
tags: sharedEdits.tags || ownReceiver.tags,
|
||||
duration: sharedEdits.duration ?? ownReceiver.duration,
|
||||
}, related, ownFields, shareData.metaTagIds);
|
||||
|
||||
Object.assign(sharedEdits, received);
|
||||
}
|
||||
|
||||
if (relatedFields.length > 0) {
|
||||
const received = receiveShare({
|
||||
actors: related.actors,
|
||||
tags: related.tags,
|
||||
duration: related.duration,
|
||||
}, ownGiver, relatedFields, shareData.metaTagIds);
|
||||
|
||||
if (Object.keys(received).length > 0) {
|
||||
children.push({
|
||||
sceneId: relation.sceneId,
|
||||
relation,
|
||||
edits: received,
|
||||
});
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
return { edits: sharedEdits, children };
|
||||
}
|
||||
|
||||
// what each of two scenes would get from the other if every shareable field were copied both ways, for the relation dialog
|
||||
// the dialog filters this by the selected share modes, so it doesn't depend on the relation type or the modes
|
||||
export async function previewRelationShare(sceneId, { sceneId: rawRelatedSceneId }, reqUser) {
|
||||
if (!reqUser) {
|
||||
throw new HttpError('Must be authenticated to preview sharing', 401);
|
||||
}
|
||||
|
||||
const relatedSceneId = Number(rawRelatedSceneId);
|
||||
|
||||
if (!Number.isInteger(relatedSceneId) || relatedSceneId === sceneId) {
|
||||
throw new HttpError('Sharing requires a different scene', 400);
|
||||
}
|
||||
|
||||
const { scenes } = await fetchShareData([sceneId, relatedSceneId]);
|
||||
const own = scenes[sceneId];
|
||||
const related = scenes[relatedSceneId];
|
||||
|
||||
if (!own || !related) {
|
||||
throw new HttpError(`No scene with ID ${own ? relatedSceneId : sceneId} found`, 404);
|
||||
}
|
||||
|
||||
const share = Object.fromEntries(shareFields.map((field) => [field, 'both']));
|
||||
const { edits, children: [child] } = await resolveShares({ id: sceneId, actors: own.actors, duration: own.duration }, {}, [{ sceneId: relatedSceneId, type: null, share }]);
|
||||
|
||||
const getAdded = (received = {}, current) => ({
|
||||
actorIds: (received.actors || []).filter((actorId) => typeof actorId === 'number' && !current.actorIds.includes(actorId)),
|
||||
tagIds: Array.from(new Set((received.tags || [])
|
||||
.filter((tag) => !current.tags.some((currentTag) => currentTag.id === tag.id))
|
||||
.map((tag) => tag.id))),
|
||||
duration: received.duration || null,
|
||||
});
|
||||
|
||||
const ownAdded = getAdded(edits, own);
|
||||
const relatedAdded = getAdded(child?.edits, related);
|
||||
|
||||
const [actors, tags] = await Promise.all([
|
||||
knexOwner('actors').select('id', 'name', 'slug').whereIn('id', [...ownAdded.actorIds, ...relatedAdded.actorIds]),
|
||||
knexOwner('tags').select('id', 'name', 'slug').whereIn('id', [...ownAdded.tagIds, ...relatedAdded.tagIds]),
|
||||
]);
|
||||
|
||||
const curateAdded = (added) => ({
|
||||
actors: added.actorIds.map((actorId) => actors.find((actor) => actor.id === actorId)).filter(Boolean),
|
||||
tags: added.tagIds.map((tagId) => tags.find((tag) => tag.id === tagId)).filter(Boolean),
|
||||
duration: added.duration,
|
||||
});
|
||||
|
||||
return {
|
||||
scene: curateAdded(ownAdded),
|
||||
relatedScene: curateAdded(relatedAdded),
|
||||
};
|
||||
}
|
||||
|
||||
const sqlImplied = ['scenes_stashed'];
|
||||
|
||||
function curateOptions(options) {
|
||||
@@ -1098,7 +1353,20 @@ export async function fetchSceneRevisions(revisionId, filters = {}, reqUser) {
|
||||
: [],
|
||||
]);
|
||||
|
||||
const curatedRevisions = revisions.map((revision) => curateRevision(revision));
|
||||
// revisions generated for related scenes by sharing a relation, reviewed and applied with their parent
|
||||
const childRevisions = revisions.length > 0
|
||||
? await knexOwner('scenes_revisions')
|
||||
.select('id', 'scene_id', 'parent_revision_id')
|
||||
.whereIn('parent_revision_id', revisions.map((revision) => revision.id))
|
||||
.orderBy('id')
|
||||
: [];
|
||||
|
||||
const curatedRevisions = revisions.map((revision) => ({
|
||||
...curateRevision(revision),
|
||||
childRevisions: childRevisions
|
||||
.filter((child) => child.parent_revision_id === revision.id)
|
||||
.map((child) => ({ id: child.id, sceneId: child.scene_id })),
|
||||
}));
|
||||
|
||||
return {
|
||||
revisions: curatedRevisions,
|
||||
@@ -1300,61 +1568,77 @@ async function applySceneDeleteDelta(sceneId, _delta, trx, reqUser) {
|
||||
.transacting(trx);
|
||||
}
|
||||
|
||||
async function applySceneRevisionDeltas(revision, trx, reqUser) {
|
||||
await Promise.all(revision.deltas.map(async (delta) => {
|
||||
if (delta.key === 'delete') {
|
||||
return applySceneDeleteDelta(revision.scene_id, delta, trx, reqUser);
|
||||
}
|
||||
|
||||
if ([
|
||||
'title',
|
||||
'description',
|
||||
'date',
|
||||
'url',
|
||||
'datePrecision',
|
||||
'duration',
|
||||
'productionDate',
|
||||
'productionLocation',
|
||||
'productionCity',
|
||||
'productionState',
|
||||
].includes(delta.key)) {
|
||||
return applySceneValueDelta(revision.scene_id, delta, trx);
|
||||
}
|
||||
|
||||
if (delta.key === 'actors') {
|
||||
return applySceneActorsDelta(revision.scene_id, delta, trx);
|
||||
}
|
||||
|
||||
if (delta.key === 'tags') {
|
||||
return applySceneTagsDelta(revision.scene_id, delta, trx);
|
||||
}
|
||||
|
||||
if (delta.key === 'movies') {
|
||||
return applySceneMoviesDelta(revision.scene_id, delta, trx);
|
||||
}
|
||||
|
||||
if (delta.key === 'relations') {
|
||||
return applySceneRelationsDelta(revision, delta, trx);
|
||||
}
|
||||
|
||||
return null;
|
||||
}));
|
||||
|
||||
await knexOwner('scenes_revisions')
|
||||
.where('id', revision.id)
|
||||
.update('applied_at', knexOwner.fn.now())
|
||||
.transacting(trx);
|
||||
}
|
||||
|
||||
// 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')
|
||||
.whereIn('id', revisionIds)
|
||||
.whereNull('applied_at'); // should not re-apply revision that was already applied
|
||||
|
||||
// revisions generated by sharing a relation are applied together with their parent
|
||||
const children = await knexOwner('scenes_revisions')
|
||||
.whereIn('parent_revision_id', revisions.map((revision) => revision.id))
|
||||
.whereNotIn('id', revisions.map((revision) => revision.id))
|
||||
.whereNull('applied_at')
|
||||
.orderBy('id');
|
||||
|
||||
await revisions.reduce(async (chain, revision) => {
|
||||
await chain;
|
||||
|
||||
await knexOwner.transaction(async (trx) => {
|
||||
await Promise.all(revision.deltas.map(async (delta) => {
|
||||
if (delta.key === 'delete') {
|
||||
return applySceneDeleteDelta(revision.scene_id, delta, trx, reqUser);
|
||||
}
|
||||
await applySceneRevisionDeltas(revision, trx, reqUser);
|
||||
|
||||
if ([
|
||||
'title',
|
||||
'description',
|
||||
'date',
|
||||
'url',
|
||||
'datePrecision',
|
||||
'duration',
|
||||
'productionDate',
|
||||
'productionLocation',
|
||||
'productionCity',
|
||||
'productionState',
|
||||
].includes(delta.key)) {
|
||||
return applySceneValueDelta(revision.scene_id, delta, trx);
|
||||
}
|
||||
|
||||
if (delta.key === 'actors') {
|
||||
return applySceneActorsDelta(revision.scene_id, delta, trx);
|
||||
}
|
||||
|
||||
if (delta.key === 'tags') {
|
||||
return applySceneTagsDelta(revision.scene_id, delta, trx);
|
||||
}
|
||||
|
||||
if (delta.key === 'movies') {
|
||||
return applySceneMoviesDelta(revision.scene_id, delta, trx);
|
||||
}
|
||||
|
||||
if (delta.key === 'relations') {
|
||||
return applySceneRelationsDelta(revision, delta, trx);
|
||||
}
|
||||
|
||||
return null;
|
||||
}));
|
||||
|
||||
await knexOwner('scenes_revisions')
|
||||
.where('id', revision.id)
|
||||
.update('applied_at', knexOwner.fn.now())
|
||||
.transacting(trx);
|
||||
|
||||
// await trx.commit();
|
||||
await children
|
||||
.filter((child) => child.parent_revision_id === revision.id)
|
||||
.reduce(async (childChain, child) => {
|
||||
await childChain;
|
||||
await applySceneRevisionDeltas(child, trx, reqUser);
|
||||
}, Promise.resolve());
|
||||
}).catch(async (error) => {
|
||||
logger.error(`Failed to apply revision ${revision.id} on scene ${revision.scene_id}: ${error.message}`);
|
||||
throw error;
|
||||
@@ -1362,7 +1646,7 @@ async function applySceneRevision(revisionIds, reqUser, { sync = true } = {}) {
|
||||
}, Promise.resolve());
|
||||
|
||||
if (sync) {
|
||||
const sceneIds = Array.from(new Set(revisions.map((revision) => revision.scene_id)));
|
||||
const sceneIds = Array.from(new Set([...revisions, ...children].map((revision) => revision.scene_id)));
|
||||
|
||||
await syncScenes(sceneIds);
|
||||
}
|
||||
@@ -1377,6 +1661,15 @@ export async function reviewSceneRevision(revisionId, isApproved, { feedback },
|
||||
throw new HttpError('You must either approve or reject the revision', 400);
|
||||
}
|
||||
|
||||
const revision = await knexOwner('scenes_revisions')
|
||||
.select('id', 'parent_revision_id')
|
||||
.where('id', revisionId)
|
||||
.first();
|
||||
|
||||
if (revision?.parent_revision_id) {
|
||||
throw new HttpError(`This revision was generated by sharing a relation, review revision #${revision.parent_revision_id} instead`, 400);
|
||||
}
|
||||
|
||||
const updated = await knexOwner('scenes_revisions')
|
||||
.where('id', revisionId)
|
||||
.whereNull('approved') // don't rerun reviewed revision, must be forked into new revision instead
|
||||
@@ -1392,6 +1685,16 @@ export async function reviewSceneRevision(revisionId, isApproved, { feedback },
|
||||
throw new HttpError('This revision was already reviewed', 409);
|
||||
}
|
||||
|
||||
// revisions generated by sharing a relation share their parent's review
|
||||
await knexOwner('scenes_revisions')
|
||||
.where('parent_revision_id', revisionId)
|
||||
.whereNull('approved')
|
||||
.update({
|
||||
approved: isApproved,
|
||||
reviewed_at: knex.fn.now(),
|
||||
reviewed_by: reqUser.id,
|
||||
});
|
||||
|
||||
if (isApproved) {
|
||||
try {
|
||||
await applySceneRevision([revisionId], reqUser, options);
|
||||
@@ -1399,6 +1702,7 @@ export async function reviewSceneRevision(revisionId, isApproved, { feedback },
|
||||
catch (error) {
|
||||
await knexOwner('scenes_revisions')
|
||||
.where('id', revisionId)
|
||||
.orWhere('parent_revision_id', revisionId)
|
||||
.update({
|
||||
approved: null,
|
||||
reviewed_at: null,
|
||||
@@ -1411,7 +1715,8 @@ export async function reviewSceneRevision(revisionId, isApproved, { feedback },
|
||||
}
|
||||
|
||||
// dryRun validates the edits and returns the deltas without storing a revision
|
||||
export async function createSceneRevision(sceneId, { edits, comment, apply }, reqUser, { dryRun = false } = {}) {
|
||||
// isChild is used internally for revisions generated by sharing a relation, they return their entry instead of storing it
|
||||
export async function createSceneRevision(sceneId, { edits, comment, apply }, reqUser, { dryRun = false, isChild = false } = {}) {
|
||||
if (!reqUser) {
|
||||
throw new HttpError('Must be authenticated to create scene revision', 401);
|
||||
}
|
||||
@@ -1430,7 +1735,8 @@ export async function createSceneRevision(sceneId, { edits, comment, apply }, re
|
||||
}),
|
||||
knexOwner('scenes_revisions')
|
||||
.where('user_id', reqUser.id)
|
||||
.whereNull('approved'),
|
||||
.whereNull('approved')
|
||||
.whereNull('parent_revision_id'), // revisions generated by sharing are reviewed with their parent
|
||||
fetchRevisionRelations(sceneId),
|
||||
]);
|
||||
|
||||
@@ -1438,7 +1744,7 @@ export async function createSceneRevision(sceneId, { edits, comment, apply }, re
|
||||
throw new HttpError(`No scene with ID ${sceneId} found to update`, 404);
|
||||
}
|
||||
|
||||
if (openRevisions.length >= config.revisions.unapprovedLimit && reqUser.role !== 'admin') {
|
||||
if (!isChild && openRevisions.length >= config.revisions.unapprovedLimit && reqUser.role !== 'admin') {
|
||||
throw new HttpError(`You have ${config.revisions.unapprovedLimit} unapproved revisions, please wait for approval before submitting another revision.`, 429);
|
||||
}
|
||||
|
||||
@@ -1487,7 +1793,27 @@ export async function createSceneRevision(sceneId, { edits, comment, apply }, re
|
||||
? await curateRelationsEdit(scene.id, edits.relations)
|
||||
: null;
|
||||
|
||||
const deltas = Object.entries(edits).map(([key, value]) => {
|
||||
// what this scene receives from related scenes is merged into its own edits, what it gives becomes revisions for the related scenes
|
||||
const { edits: sharedEdits, children: sharedScenes } = curatedRelations && !isChild
|
||||
? await resolveShares(baseScene, edits, curatedRelations)
|
||||
: { edits, children: [] };
|
||||
|
||||
const children = (await Promise.all(sharedScenes.map(async (child) => createSceneRevision(child.sceneId, {
|
||||
edits: child.edits,
|
||||
comment: `Shared ${Object.keys(child.edits).join(', ')} from #${scene.id} through ${child.relation.type} relation`,
|
||||
}, reqUser, {
|
||||
dryRun: true,
|
||||
isChild: true,
|
||||
}).catch((error) => {
|
||||
// the related scene already has everything shared with it
|
||||
if (error instanceof HttpError && error.httpCode === 400 && /No effective changes/.test(error.message)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
throw error;
|
||||
})))).filter(Boolean);
|
||||
|
||||
const deltas = Object.entries(sharedEdits).map(([key, value]) => {
|
||||
if (key === 'delete') {
|
||||
return { key: 'delete' };
|
||||
}
|
||||
@@ -1503,7 +1829,7 @@ export async function createSceneRevision(sceneId, { edits, comment, apply }, re
|
||||
return null;
|
||||
}
|
||||
|
||||
return { key, value: curatedRelations };
|
||||
return { key, value: curatedRelations.map(({ share: _share, ...relation }) => relation) };
|
||||
}
|
||||
|
||||
if (baseScene[key] === value || typeof value === 'undefined') {
|
||||
@@ -1534,11 +1860,35 @@ export async function createSceneRevision(sceneId, { edits, comment, apply }, re
|
||||
return { key, value };
|
||||
}).filter(Boolean);
|
||||
|
||||
if (deltas.length === 0) {
|
||||
// a revision that only shares with related scenes has no deltas of its own
|
||||
if (deltas.length === 0 && children.length === 0) {
|
||||
throw new HttpError('No effective changes provided', 400);
|
||||
}
|
||||
|
||||
const affectedSceneIds = getAffectedSceneIds(baseScene, deltas);
|
||||
const affectedSceneIds = Array.from(new Set([
|
||||
...getAffectedSceneIds(baseScene, deltas),
|
||||
...children.map((child) => child.sceneId),
|
||||
]));
|
||||
|
||||
const entry = {
|
||||
user_id: reqUser.id,
|
||||
scene_id: scene.id,
|
||||
affected_scene_ids: affectedSceneIds,
|
||||
base: JSON.stringify(baseScene),
|
||||
deltas: JSON.stringify(deltas),
|
||||
hash: mj.hash({
|
||||
base: baseScene,
|
||||
deltas,
|
||||
}),
|
||||
comment,
|
||||
};
|
||||
|
||||
const curatedChildren = children.map((child) => ({
|
||||
id: child.id,
|
||||
sceneId: child.sceneId,
|
||||
deltas: child.deltas,
|
||||
comment: child.comment,
|
||||
}));
|
||||
|
||||
if (dryRun) {
|
||||
return {
|
||||
@@ -1546,23 +1896,32 @@ export async function createSceneRevision(sceneId, { edits, comment, apply }, re
|
||||
sceneId: scene.id,
|
||||
deltas,
|
||||
affectedSceneIds,
|
||||
children: curatedChildren,
|
||||
comment,
|
||||
...(isChild && { entry }),
|
||||
};
|
||||
}
|
||||
|
||||
const [revisionEntry] = await knexOwner('scenes_revisions')
|
||||
.insert({
|
||||
user_id: reqUser.id,
|
||||
scene_id: scene.id,
|
||||
affected_scene_ids: affectedSceneIds,
|
||||
base: JSON.stringify(baseScene),
|
||||
deltas: JSON.stringify(deltas),
|
||||
hash: mj.hash({
|
||||
base: baseScene,
|
||||
deltas,
|
||||
}),
|
||||
comment,
|
||||
})
|
||||
.returning('id');
|
||||
const revisionEntry = await knexOwner.transaction(async (trx) => {
|
||||
const [parentEntry] = await trx('scenes_revisions')
|
||||
.insert(entry)
|
||||
.returning('id');
|
||||
|
||||
if (children.length > 0) {
|
||||
const childEntries = await trx('scenes_revisions')
|
||||
.insert(children.map((child) => ({
|
||||
...child.entry,
|
||||
parent_revision_id: parentEntry.id,
|
||||
})))
|
||||
.returning(['id', 'scene_id']);
|
||||
|
||||
children.forEach((child, index) => {
|
||||
curatedChildren[index].id = childEntries[index].id;
|
||||
});
|
||||
}
|
||||
|
||||
return parentEntry;
|
||||
});
|
||||
|
||||
if (['admin', 'editor'].includes(reqUser.role) && apply) {
|
||||
// don't keep the editor waiting for the revision to apply
|
||||
@@ -1574,5 +1933,6 @@ export async function createSceneRevision(sceneId, { edits, comment, apply }, re
|
||||
sceneId: scene.id,
|
||||
deltas,
|
||||
affectedSceneIds,
|
||||
children: curatedChildren,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -13,6 +13,7 @@ import {
|
||||
fetchSceneRevisions,
|
||||
fetchScenes,
|
||||
fetchScenesById,
|
||||
previewRelationShare,
|
||||
reviewSceneRevision,
|
||||
} from '../scenes.js';
|
||||
import { fetchStashByUsernameAndSlug } from '../stashes.js';
|
||||
@@ -311,6 +312,12 @@ async function createSceneRevisionApi(req, res) {
|
||||
res.status(204).send();
|
||||
}
|
||||
|
||||
async function previewRelationShareApi(req, res) {
|
||||
const preview = await previewRelationShare(Number(req.params.sceneId), req.body, req.user);
|
||||
|
||||
res.send(preview);
|
||||
}
|
||||
|
||||
async function reviewSceneRevisionApi(req, res) {
|
||||
await reviewSceneRevision(Number(req.params.revisionId), req.body.isApproved, req.body, req.user);
|
||||
|
||||
@@ -321,6 +328,7 @@ export const scenesRouter = Router();
|
||||
|
||||
scenesRouter.get('/api/scenes', fetchScenesApi);
|
||||
scenesRouter.get('/api/scenes/:sceneId', fetchSceneApi);
|
||||
scenesRouter.post('/api/scenes/:sceneId/relations/share-preview', previewRelationShareApi);
|
||||
|
||||
scenesRouter.get('/api/revisions/scenes', fetchSceneRevisionsApi);
|
||||
scenesRouter.get('/api/revisions/scenes/:revisionId', fetchSceneRevisionsApi);
|
||||
|
||||
Reference in New Issue
Block a user