Added scene relations.

This commit is contained in:
2026-11-21 02:54:56 +01:00
parent 5ce4c1f63b
commit 78654a62df
12 changed files with 952 additions and 4 deletions
+238
View File
@@ -0,0 +1,238 @@
<script setup>
import { ref, watch } from 'vue';
import RelationDialog from '#/components/scenes/relation.vue';
import { getRelationLabel } from '#/utils/relation-labels.js';
const props = defineProps({
item: {
type: Object,
default: null,
},
scene: {
type: Object,
default: null,
},
edits: {
type: Object,
default: () => {},
},
editing: {
type: Set,
default: null,
},
types: {
type: Array,
default: () => [],
},
});
const emit = defineEmits(['relations']);
const newRelations = ref([]);
const showDialog = ref(false);
function getRelationKey(relation) {
return `${relation.direction}:${relation.type}:${relation.sceneId}`;
}
function getLabel(relation) {
const label = getRelationLabel(relation.type, relation.direction);
return `${label.charAt(0).toLowerCase()}${label.slice(1)}`;
}
function isIncluded(relation) {
return props.edits.relations?.some((editRelation) => getRelationKey(editRelation) === getRelationKey(relation));
}
function toEdit(relation) {
return {
sceneId: relation.sceneId,
type: relation.type,
direction: relation.direction,
};
}
function addRelation(relation) {
showDialog.value = false;
if (isIncluded(relation)) {
return;
}
if (![...props.item.value, ...newRelations.value].some((existingRelation) => getRelationKey(existingRelation) === getRelationKey(relation))) {
newRelations.value = newRelations.value.concat(relation);
}
emit('relations', props.edits.relations.concat(toEdit(relation)));
}
function openDialog() {
if (props.editing.has(props.item.key)) {
showDialog.value = true;
}
}
watch(() => props.scene, () => {
newRelations.value = [];
});
</script>
<template>
<ul
class="relations nolist"
:class="{ disabled: !editing.has(item.key) }"
>
<li
v-for="relation in [...item.value, ...newRelations]"
:key="`relation-${getRelationKey(relation)}`"
class="relation"
:class="{ deleted: edits.relations && !isIncluded(relation) }"
>
<span class="relation-label">
<span class="relation-type">{{ getLabel(relation) }}&nbsp;</span>
<a
:href="`/scene/${relation.sceneId}/${relation.scene?.slug || ''}`"
target="_blank"
class="relation-name link"
>{{ relation.scene?.title || `#${relation.sceneId}` }}</a>
</span>
<Icon
v-if="edits.relations && !isIncluded(relation)"
icon="checkmark"
class="add"
@click="emit('relations', edits.relations.concat(toEdit(relation)))"
/>
<Icon
v-else
icon="cross2"
class="remove"
@click="emit('relations', edits.relations.filter((editRelation) => getRelationKey(editRelation) !== getRelationKey(relation)))"
/>
</li>
<li class="new">
<!-- wrapped like the search dropdown triggers in the movies and tags edits, so the icon sizes the same -->
<div class="trigger">
<Icon
icon="plus3"
class="add"
@click="openDialog"
/>
</div>
</li>
</ul>
<RelationDialog
v-if="showDialog"
:scene="scene"
:types="types"
@relation="addRelation"
@close="showDialog = false"
/>
</template>
<style scoped>
.relations {
display: flex;
flex-wrap: wrap;
gap: .35rem .25rem;
&.disabled {
.relation {
background: var(--glass-weak-50);
color: var(--glass-strong-10);
.remove,
.add {
fill: var(--shadow-weak-30);
background: var(--shadow-weak-50);
}
}
.new .icon {
background: var(--shadow-weak-40);
}
}
.new {
display: flex;
align-items: center;
margin-left: .25rem;
&:hover {
box-shadow: 0 0 3px var(--shadow-weak-20);
}
/* matches the trigger style of the movie and tag search dropdowns */
.trigger {
height: 100%;
overflow: hidden;
}
.icon {
height: 100%;
padding: 0 .5rem;
background: var(--success);
fill: var(--text-light);
}
}
}
.relation {
display: flex;
align-items: stretch;
border-radius: .25rem;
background: var(--background);
box-shadow: 0 0 3px var(--shadow-weak-30);
&.deleted {
color: var(--glass);
text-decoration: line-through;
}
}
.relation,
.new {
.remove,
.add {
height: auto;
padding: .25rem .3rem;
border-radius: .25rem;
fill: var(--highlight-strong-10);
&:hover {
fill: var(--text-light);
cursor: pointer;
}
}
.remove {
fill: var(--error);
&:hover {
background: var(--error);
}
}
.add {
fill: var(--success);
&:hover {
background: var(--success);
}
}
}
.relation-label {
color: var(--text);
padding: .25rem .5rem;
color: inherit;
text-decoration: inherit;
}
</style>
+30
View File
@@ -10,6 +10,7 @@ import Pagination from '#/components/pagination/pagination.vue';
import { get, post } from '#/src/api.js';
import navigate from '#/src/navigate.js';
import { formatDuration } from '#/utils/format.js';
import { getRelationLabel } from '#/utils/relation-labels.js';
defineProps({
context: {
@@ -26,11 +27,28 @@ const actors = ref(pageContext.pageProps.actors);
const tags = ref(pageContext.pageProps.tags);
const movies = ref(pageContext.pageProps.movies);
const avatars = ref(pageContext.pageProps.avatars);
const relationScenes = ref(pageContext.pageProps.relationScenes || []); // not provided for actor revisions
const actorsById = computed(() => Object.fromEntries(actors.value.map((actor) => [actor.id, actor])));
const tagsById = computed(() => Object.fromEntries(tags.value.map((tag) => [tag.id, tag])));
const moviesById = computed(() => Object.fromEntries(movies.value.map((movie) => [movie.id, movie])));
const avatarsById = computed(() => Object.fromEntries(avatars.value.map((avatar) => [avatar.id, avatar])));
const relationScenesById = computed(() => Object.fromEntries(relationScenes.value.map((scene) => [scene.id, scene])));
function getRelationKey(relation) {
return `${relation.direction}:${relation.type}:${relation.sceneId}`;
}
function curateRelation(relation, modified) {
const label = getRelationLabel(relation.type, relation.direction);
const relatedScene = relationScenesById.value[relation.sceneId];
return {
id: getRelationKey(relation),
name: `${label.charAt(0).toLowerCase()}${label.slice(1)} ${relatedScene?.title || `#${relation.sceneId}`}`,
modified,
};
}
const feedbacks = ref({});
const showReviewed = ref(Object.hasOwn(pageContext.urlParsed.search, 'final'));
@@ -90,6 +108,10 @@ const curatedRevisions = computed(() => revisions.value.map((revision) => {
}))];
}
if (key === 'relations') {
return [key, value.map((relation) => curateRelation(relation, revision.deltas.some((delta) => delta.key === key && !delta.value.some((deltaRelation) => getRelationKey(deltaRelation) === getRelationKey(relation)))))];
}
if (key === 'socials') {
// new socials don't have IDs yet, so we need to compare the values
return [key, value.map((item) => ({
@@ -134,6 +156,13 @@ const curatedRevisions = computed(() => revisions.value.map((revision) => {
};
}
if (delta.key === 'relations') {
return {
...delta,
value: delta.value.map((relation) => curateRelation(relation, !(revision.base.relations || []).some((baseRelation) => getRelationKey(baseRelation) === getRelationKey(relation)))),
};
}
if (delta.key === 'socials') {
// new socials don't have IDs yet, so we need to compare the values
return {
@@ -187,6 +216,7 @@ async function reloadRevisions() {
actors.value = updatedRevisions.actors;
tags.value = updatedRevisions.tags;
movies.value = updatedRevisions.movies;
relationScenes.value = updatedRevisions.relationScenes || [];
avatars.value = updatedRevisions.avatars;
revisions.value = updatedRevisions.revisions;
total.value = updatedRevisions.total;
+354
View File
@@ -0,0 +1,354 @@
<script setup>
import { format } from 'date-fns';
import { computed, onMounted, ref, useId } from 'vue';
import Dialog from '#/components/dialog/dialog.vue';
import { get } from '#/src/api.js';
import getPath from '#/src/get-path.js';
import { getRelationLabel } from '#/utils/relation-labels.js';
const props = defineProps({
scene: {
type: Object,
required: true,
},
types: {
type: Array,
required: true,
},
});
const emit = defineEmits(['close', 'relation']);
const searchDelay = 300;
const searchDropdownId = useId();
const query = ref('');
const queryInput = ref(null);
const results = ref([]);
const searching = ref(false);
const selectedScene = ref(null);
const selectedOption = ref(null);
const searchCompleted = ref(false); // only show 'no results' once a search for the current query has finished
let searchTimeout = null;
let searchCount = 0;
// each type can be read from either side, e.g. this scene is a 'Remaster of' or 'Remastered as' the selected scene
const options = computed(() => props.types.flatMap((type) => ['target', 'source'].map((direction) => ({
key: `${type}-${direction}`,
type,
direction,
label: getRelationLabel(type, direction),
}))));
const hasQuery = computed(() => query.value.trim().length > 0);
const showResults = computed(() => results.value.length > 0 || (hasQuery.value && !searching.value && searchCompleted.value));
const canSubmit = computed(() => !!selectedScene.value && !!selectedOption.value);
const hasChanges = computed(() => !!selectedScene.value || !!selectedOption.value);
// accept a pasted scene ID or traxxx scene URL, the search index does not match IDs
function getSceneId(value) {
const id = value.match(/^\s*(\d+)\s*$/)?.[1] || value.match(/\/scene\/(\d+)/)?.[1];
return id ? Number(id) : null;
}
async function search() {
const searchId = ++searchCount;
const sceneId = getSceneId(query.value);
searching.value = true;
searchCompleted.value = false;
try {
const scenes = sceneId
? [await get(`/scenes/${sceneId}`)]
: (await get('/scenes', { q: query.value, limit: 10 })).scenes;
if (searchId === searchCount) {
results.value = scenes.filter((result) => result && result.id !== props.scene.id);
}
}
catch (_error) {
if (searchId === searchCount) {
results.value = [];
}
}
finally {
if (searchId === searchCount) {
searching.value = false;
searchCompleted.value = true;
}
}
}
function queueSearch() {
clearTimeout(searchTimeout);
searchCompleted.value = false;
if (!hasQuery.value) {
searchCount += 1; // discard pending responses
results.value = [];
searching.value = false;
return;
}
searchTimeout = setTimeout(search, searchDelay);
}
function focusInput() {
setTimeout(() => {
queryInput.value?.focus();
}, 100);
}
function selectScene(result) {
selectedScene.value = result;
results.value = [];
query.value = '';
searchCompleted.value = false;
}
function deselectScene() {
selectedScene.value = null;
focusInput();
}
function formatSceneMeta(result) {
return [result.channel.name, result.date && format(result.date, 'yyyy-MM-dd')].filter(Boolean).join(', ');
}
// the relation is only added to the edit, it's stored when the revision is submitted
function addRelation() {
emit('relation', {
sceneId: selectedScene.value.id,
type: selectedOption.value.type,
direction: selectedOption.value.direction,
scene: selectedScene.value,
});
}
onMounted(() => focusInput());
</script>
<template>
<Dialog
title="Add relation"
:confirm-close="hasChanges"
@close="emit('close')"
>
<form
class="dialog-body"
@submit.prevent="addRelation"
>
<div class="scene current">
<img
v-if="scene.poster"
:src="getPath(scene.poster, 'thumbnail')"
class="poster"
>
<span class="info">
<span class="title ellipsis">{{ scene.title || `Scene #${scene.id}` }}</span>
<span class="meta ellipsis">{{ formatSceneMeta(scene) }}</span>
</span>
</div>
<select
v-model="selectedOption"
class="input"
>
<option
:value="null"
disabled
>Select relation</option>
<option
v-for="option in options"
:key="`option-${option.key}`"
:value="option"
>{{ option.label }}</option>
</select>
<div
v-if="selectedScene"
class="scene selected"
>
<img
v-if="selectedScene.poster"
:src="getPath(selectedScene.poster, 'thumbnail')"
class="poster"
>
<span class="info">
<span class="title ellipsis">{{ selectedScene.title || `Scene #${selectedScene.id}` }}</span>
<span class="meta ellipsis">{{ formatSceneMeta(selectedScene) }}</span>
</span>
<Icon
icon="cross2"
title="Choose another scene"
class="deselect"
@click="deselectScene"
/>
</div>
<VDropdown
v-else
:aria-id="searchDropdownId"
:triggers="[]"
:shown="showResults"
:auto-hide="false"
placement="bottom-start"
class="search"
>
<input
ref="queryInput"
v-model="query"
type="search"
enterkeyhint="search"
placeholder="Search scene, or paste an ID or URL"
class="input"
@input="queueSearch"
@keydown.enter.prevent
>
<template #popper>
<ul
v-if="results.length > 0"
class="results nolist"
>
<li
v-for="result in results"
:key="`result-${result.id}`"
v-close-popper
class="scene result"
@click="selectScene(result)"
>
<img
v-if="result.poster"
:src="getPath(result.poster, 'thumbnail')"
loading="lazy"
class="poster"
>
<span class="info">
<span class="title ellipsis">{{ result.title || `Scene #${result.id}` }}</span>
<span class="meta ellipsis">{{ formatSceneMeta(result) }}</span>
</span>
</li>
</ul>
<p
v-else
class="status"
>No scenes found</p>
</template>
</VDropdown>
<div class="dialog-actions">
<button
:disabled="!canSubmit"
class="button button-primary"
>Add relation</button>
</div>
</form>
</Dialog>
</template>
<style scoped>
.dialog-body {
width: 30rem;
max-width: 100%;
box-sizing: border-box;
gap: .75rem;
padding: 1rem;
.input {
width: 100%;
box-sizing: border-box;
}
}
.dialog-actions {
display: flex;
justify-content: center;
margin-top: .5rem;
}
.search {
width: 100%;
}
.results {
width: 28rem;
max-width: calc(100vw - 2rem);
max-height: 18rem;
overflow-y: auto;
padding: .25rem 0;
}
.scene {
display: flex;
align-items: center;
gap: .5rem;
padding: .25rem .5rem;
overflow: hidden;
}
.result:hover {
background: var(--glass-weak-50);
cursor: pointer;
.title {
color: var(--primary);
}
}
.current,
.selected {
border-radius: .25rem;
background: var(--glass-weak-50);
}
.deselect {
flex-shrink: 0;
padding: .5rem;
fill: var(--glass-strong-10);
&:hover {
fill: var(--primary);
cursor: pointer;
}
}
.poster {
width: 5rem;
aspect-ratio: 16 / 9;
flex-shrink: 0;
object-fit: cover;
border-radius: .25rem;
}
.info {
display: flex;
flex-direction: column;
flex-grow: 1;
overflow: hidden;
}
.meta,
.status {
color: var(--glass-strong-10);
font-size: .9rem;
}
.status {
margin: 0;
padding: .5rem;
}
</style>
+29
View File
@@ -11,6 +11,11 @@ const props = defineProps({
type: Object,
default: null,
},
// short context shown over the poster, e.g. how the scene relates to the current page
label: {
type: String,
default: null,
},
});
const pageContext = inject('pageContext');
@@ -53,6 +58,11 @@ const favorited = ref(props.scene.stashes.some((sceneStash) => sceneStash.id ===
/>
</Link>
<span
v-if="label"
class="label"
>{{ label }}</span>
<Heart
domain="scenes"
:item="scene"
@@ -208,6 +218,25 @@ const favorited = ref(props.scene.stashes.some((sceneStash) => sceneStash.id ===
}
}
/* top left, the stash heart sits top right */
.label {
position: absolute;
top: 0;
left: 0;
max-width: calc(100% - 4rem);
box-sizing: border-box;
overflow: hidden;
padding: .2rem .4rem;
border-radius: 0 0 .25rem 0;
background: var(--shadow-strong-10);
color: var(--text-light);
font-size: .8rem;
font-weight: bold;
white-space: nowrap;
text-overflow: ellipsis;
pointer-events: none;
}
.thumbnail {
width: 100%;
height: 100%;
@@ -14,6 +14,7 @@ export async function onBeforeRender(pageContext) {
actors,
tags,
movies,
relationScenes,
} = await fetchSceneRevisions(null, {
isFinalized: Object.hasOwn(pageContext.urlParsed.search, 'final'),
limit: Number(pageContext.urlParsed.search.limit) || 100,
@@ -29,6 +30,7 @@ export async function onBeforeRender(pageContext) {
actors,
tags,
movies,
relationScenes,
},
},
};
+40 -1
View File
@@ -10,6 +10,7 @@ import Banner from '#/components/media/banner.vue';
import MovieTile from '#/components/movies/tile.vue';
import Chapters from '#/components/scenes/chapters.vue';
import SceneTile from '#/components/scenes/tile.vue';
import SerieTile from '#/components/series/tile.vue';
import Heart from '#/components/stashes/heart.vue';
import events from '#/src/events.js';
@@ -17,6 +18,7 @@ import getPath from '#/src/get-path.js';
import { formatDate, formatDuration } from '#/utils/format.js';
import processSummaryTemplate from '#/utils/process-summary-template.js';
import { getRelationLabel } from '#/utils/relation-labels.js';
import verifyAbility from '#/utils/verify-ability.js';
const cookies = Cookies.withConverter({
@@ -31,7 +33,19 @@ const {
env,
} = inject('pageContext');
const { scene } = pageProps;
const { scene, relations } = pageProps;
// one tile per related scene, a scene may be related in more than one way
const relatedScenes = Object.values(relations.reduce((acc, relation) => {
acc[relation.scene.id] ??= {
scene: relation.scene,
labels: [],
};
acc[relation.scene.id].labels.push(getRelationLabel(relation.type, relation.direction));
return acc;
}, {}));
const avatarFrameSize = 36;
const avatarMargin = 2.75;
@@ -571,6 +585,25 @@ function copySummary() {
/>
</div>
<div
v-if="relatedScenes.length > 0"
class="section"
>
<h3 class="heading">Related</h3>
<ul class="related-scenes nolist">
<li
v-for="related in relatedScenes"
:key="`related-${related.scene.id}`"
>
<SceneTile
:scene="related.scene"
:label="related.labels.join(', ')"
/>
</li>
</ul>
</div>
<div class="section details">
<div class="detail">
<h3 class="heading">Added</h3>
@@ -937,6 +970,12 @@ function copySummary() {
grid-template-columns: repeat(auto-fill, minmax(14rem, 1fr));
}
.related-scenes {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(20rem, 1fr));
gap: .5rem;
}
.section {
margin-bottom: 1rem;
}
+11 -2
View File
@@ -1,7 +1,7 @@
import { redirect, render } from 'vike/abort';
import { getIdsBySlug } from '#/src/cache.js';
import { getRandomCampaigns } from '#/src/campaigns.js';
import { fetchScenesById } from '#/src/scenes.js';
import { fetchRelationTypes, fetchSceneRelations, fetchScenesById } from '#/src/scenes.js';
function getTitle(scene) {
if (scene.title) {
@@ -32,7 +32,7 @@ export async function onBeforeRender(pageContext) {
throw render(404, `Cannot find scene '${pageContext.routeParams.sceneId}'.`);
}
const [campaigns, tagIds] = await Promise.all([
const [campaigns, tagIds, relations, relationTypes] = await Promise.all([
getRandomCampaigns([
{
minRatio: 1.5,
@@ -46,6 +46,13 @@ export async function onBeforeRender(pageContext) {
'dp',
'facial',
], 'tags', true),
fetchSceneRelations(scene.id, {
reqUser: pageContext.user,
restriction: pageContext.geo.restriction,
}),
pageContext.user // relations can be proposed through scene revisions
? fetchRelationTypes()
: [],
]);
return {
@@ -54,6 +61,8 @@ export async function onBeforeRender(pageContext) {
pageProps: {
scene,
tagIds,
relations,
relationTypes,
},
campaigns: {
scene: campaigns[0],
+33
View File
@@ -4,6 +4,7 @@ import { computed, inject, ref, useId } from 'vue';
import EditActors from '#/components/edit/actors.vue';
import EditMovies from '#/components/edit/movies.vue';
import EditRelations from '#/components/edit/relations.vue';
import EditTags from '#/components/edit/tags.vue';
import Checkbox from '#/components/form/checkbox.vue';
@@ -14,6 +15,7 @@ const pageContext = inject('pageContext');
const user = pageContext.user;
const scene = ref(pageContext.pageProps.scene);
const relationTypes = pageContext.pageProps.relationTypes;
const applyTooltipId = useId();
const fields = computed(() => [
@@ -80,6 +82,23 @@ const fields = computed(() => [
type: 'movies',
value: scene.value.movies,
},
{
key: 'relations',
type: 'relations',
value: pageContext.pageProps.relations.map((relation) => ({
sceneId: relation.scene.id,
type: relation.type,
direction: relation.direction,
scene: relation.scene,
})),
// only submit what identifies the relation, not the related scene's details
simplify: (relations) => relations.map((relation) => ({
sceneId: relation.sceneId,
type: relation.type,
direction: relation.direction,
})),
note: 'Relations point from a rerelease, remaster or compilation to the original scene. Each relation is shown on both scenes.',
},
{
key: 'comment',
type: 'text',
@@ -97,6 +116,10 @@ const fields = computed(() => [
].filter((field) => field.enabled !== false));
function simplifyArray(field) {
if (typeof field.simplify === 'function') {
return field.simplify(field.value);
}
if (Array.isArray(field.value) && field.simplify !== false) {
return field.value.map((item) => item.hash || item.id);
}
@@ -307,6 +330,16 @@ async function submit() {
@movies="(movies) => { edits.movies = movies; }"
/>
<EditRelations
v-if="item.type === 'relations'"
:scene="scene"
:item="item"
:edits="edits"
:editing="editing"
:types="relationTypes"
@relations="(relations) => { edits.relations = relations; }"
/>
<input
v-if="item.type === 'string'"
v-model="edits[item.key]"
@@ -14,6 +14,7 @@ export async function onBeforeRender(pageContext) {
actors,
tags,
movies,
relationScenes,
} = await fetchSceneRevisions(null, {
sceneId: scene.id,
isFinalized: true,
@@ -31,6 +32,7 @@ export async function onBeforeRender(pageContext) {
actors,
tags,
movies,
relationScenes,
},
},
};
+2
View File
@@ -54,6 +54,7 @@ export async function onBeforeRender(pageContext) {
tags,
movies,
avatars,
relationScenes,
} = userRevisions;
const stashes = await fetchUserStashes(profile.id, pageContext.user);
@@ -72,6 +73,7 @@ export async function onBeforeRender(pageContext) {
tags,
movies,
avatars,
relationScenes,
},
},
};
+191 -1
View File
@@ -438,6 +438,122 @@ export async function fetchScenesById(sceneIds, { reqUser, ...context } = {}) {
}).filter(Boolean);
}
// relations point from the derivation or compilation (source) to the original or compilation part (target)
export async function fetchSceneRelations(sceneId, { reqUser, ...context } = {}) {
const relations = await knex('scenes_relations')
.select('id', 'source_scene_id', 'target_scene_id', 'type')
.where('source_scene_id', sceneId)
.orWhere('target_scene_id', sceneId)
.orderBy('created_at', 'asc');
if (relations.length === 0) {
return [];
}
const relatedSceneIds = Array.from(new Set(relations.map((relation) => (relation.source_scene_id === sceneId
? relation.target_scene_id
: relation.source_scene_id))));
const relatedScenes = await fetchScenesById(relatedSceneIds, { reqUser, ...context });
const relatedScenesById = Object.fromEntries(relatedScenes.map((scene) => [scene.id, scene]));
return relations.map((relation) => {
const isSource = relation.source_scene_id === sceneId;
const relatedScene = relatedScenesById[isSource ? relation.target_scene_id : relation.source_scene_id];
if (!relatedScene) {
return null;
}
return {
id: relation.id,
type: relation.type,
direction: isSource ? 'target' : 'source', // which side of the relation the related scene is on
scene: relatedScene,
};
}).filter(Boolean);
}
export async function fetchRelationTypes() {
return knex('relations_types').orderBy('type').pluck('type');
}
// relations in revisions are stored relative to the revised scene: { sceneId, type, direction }
// sceneId is the related scene, direction is the side of the relation the related scene is on
function getRelationKey(relation) {
return `${relation.direction}:${relation.type}:${relation.sceneId}`;
}
async function fetchRevisionRelations(sceneId, trx) {
const relations = await knexOwner('scenes_relations')
.select('id', 'source_scene_id', 'target_scene_id', 'type')
.where((builder) => {
builder
.where('source_scene_id', sceneId)
.orWhere('target_scene_id', sceneId);
})
.orderBy('created_at', 'asc')
.modify((builder) => {
if (trx) {
builder.transacting(trx);
}
});
return relations.map((relation) => ({
id: relation.id,
sceneId: relation.source_scene_id === sceneId ? relation.target_scene_id : relation.source_scene_id,
type: relation.type,
direction: relation.source_scene_id === sceneId ? 'target' : 'source',
}));
}
async function curateRelationsEdit(sceneId, relations) {
if (!Array.isArray(relations)) {
throw new HttpError('Relations must be a list', 400);
}
const curatedRelations = Object.values(Object.fromEntries(relations.map((relation) => {
const curatedRelation = {
sceneId: Number(relation?.sceneId),
type: relation?.type,
direction: relation?.direction,
};
return [getRelationKey(curatedRelation), curatedRelation];
})));
if (curatedRelations.some((relation) => !Number.isInteger(relation.sceneId) || relation.sceneId === sceneId)) {
throw new HttpError('Relations must refer to a different scene', 400);
}
if (curatedRelations.some((relation) => !['source', 'target'].includes(relation.direction))) {
throw new HttpError('Invalid relation direction', 400);
}
const relatedSceneIds = Array.from(new Set(curatedRelations.map((relation) => relation.sceneId)));
const [types, existingSceneIds] = await Promise.all([
fetchRelationTypes(),
relatedSceneIds.length > 0
? knexOwner('releases').whereIn('id', relatedSceneIds).pluck('id')
: [],
]);
const invalidTypes = curatedRelations.filter((relation) => !types.includes(relation.type)).map((relation) => relation.type);
if (invalidTypes.length > 0) {
throw new HttpError(`Invalid relation types: ${Array.from(new Set(invalidTypes)).join(', ')}`, 400);
}
const missingSceneIds = relatedSceneIds.filter((relatedSceneId) => !existingSceneIds.includes(relatedSceneId));
if (missingSceneIds.length > 0) {
throw new HttpError(`Related scenes do not exist: ${missingSceneIds.join(', ')}`, 404);
}
return curatedRelations;
}
const sqlImplied = ['scenes_stashed'];
function curateOptions(options) {
@@ -919,10 +1035,19 @@ export async function fetchSceneRevisions(revisionId, filters = {}, reqUser) {
const tagIds = Array.from(new Set(revisions.flatMap((revision) => [...revision.base.tags, ...(revision.deltas.find((delta) => delta.key === 'tags')?.value || [])].map((tag) => tag.id))));
const movieIds = Array.from(new Set(revisions.flatMap((revision) => [...revision.base.movies, ...(revision.deltas.find((delta) => delta.key === 'movies')?.value || [])])));
const [actors, tags, movies] = await Promise.all([
// revisions from before relations existed have no base relations
const relationSceneIds = Array.from(new Set(revisions.flatMap((revision) => [
...(revision.base.relations || []),
...(revision.deltas.find((delta) => delta.key === 'relations')?.value || []),
].map((relation) => relation.sceneId))));
const [actors, tags, movies, relationScenes] = await Promise.all([
fetchActorsById(actorIds),
fetchTagsById(tagIds),
fetchMoviesById(movieIds),
relationSceneIds.length > 0
? knexOwner('releases').select('id', 'title', 'slug').whereIn('id', relationSceneIds)
: [],
]);
const curatedRevisions = revisions.map((revision) => curateRevision(revision));
@@ -934,6 +1059,7 @@ export async function fetchSceneRevisions(revisionId, filters = {}, reqUser) {
actors,
tags,
movies,
relationScenes,
};
}
@@ -1016,6 +1142,40 @@ async function applySceneMoviesDelta(sceneId, delta, trx) {
}
}
// apply the difference between the revision's base and delta, so relations added or removed since are left alone
async function applySceneRelationsDelta(revision, delta, trx) {
const baseKeys = new Set((revision.base.relations || []).map((relation) => getRelationKey(relation)));
const deltaKeys = new Set(delta.value.map((relation) => getRelationKey(relation)));
const removedKeys = new Set(Array.from(baseKeys).filter((key) => !deltaKeys.has(key)));
const addedRelations = delta.value.filter((relation) => !baseKeys.has(getRelationKey(relation)));
if (removedKeys.size > 0) {
const currentRelations = await fetchRevisionRelations(revision.scene_id, trx);
const removedIds = currentRelations.filter((relation) => removedKeys.has(getRelationKey(relation))).map((relation) => relation.id);
if (removedIds.length > 0) {
await knexOwner('scenes_relations')
.whereIn('id', removedIds)
.delete()
.transacting(trx);
}
}
if (addedRelations.length > 0) {
await knexOwner('scenes_relations')
.insert(addedRelations.map((relation) => ({
source_scene_id: relation.direction === 'target' ? revision.scene_id : relation.sceneId,
target_scene_id: relation.direction === 'target' ? relation.sceneId : revision.scene_id,
type: relation.type,
created_by: revision.user_id,
})))
.onConflict(['source_scene_id', 'target_scene_id', 'type'])
.ignore()
.transacting(trx);
}
}
async function applySceneDeleteDelta(sceneId, _delta, trx, reqUser) {
if (!reqUser.abilities.some((ability) => ability.subject === 'scene' && ability.action === 'delete')) {
throw new HttpError('You are not privileged to delete scenes', 400);
@@ -1068,6 +1228,10 @@ async function applySceneRevision(revisionIds, reqUser) {
return applySceneMoviesDelta(revision.scene_id, delta, trx);
}
if (delta.key === 'relations') {
return applySceneRelationsDelta(revision, delta, trx);
}
return null;
}));
@@ -1140,6 +1304,7 @@ export async function createSceneRevision(sceneId, { edits, comment, apply }, re
const [
[scene],
openRevisions,
baseRelations,
] = await Promise.all([
fetchScenesById([sceneId], {
reqUser,
@@ -1149,6 +1314,7 @@ export async function createSceneRevision(sceneId, { edits, comment, apply }, re
knexOwner('scenes_revisions')
.where('user_id', reqUser.id)
.whereNull('approved'),
fetchRevisionRelations(sceneId),
]);
if (!scene) {
@@ -1192,11 +1358,35 @@ export async function createSceneRevision(sceneId, { edits, comment, apply }, re
return [key, values];
}).filter(Boolean));
baseScene.relations = baseRelations.map((relation) => ({
sceneId: relation.sceneId,
type: relation.type,
direction: relation.direction,
}));
const curatedRelations = edits.relations
? await curateRelationsEdit(scene.id, edits.relations)
: null;
const deltas = Object.entries(edits).map(([key, value]) => {
if (key === 'delete') {
return { key: 'delete' };
}
if (key === 'relations') {
if (!curatedRelations) {
return null;
}
const baseKeys = new Set(baseScene.relations.map((relation) => getRelationKey(relation)));
if (curatedRelations.length === baseKeys.size && curatedRelations.every((relation) => baseKeys.has(getRelationKey(relation)))) {
return null;
}
return { key, value: curatedRelations };
}
if (baseScene[key] === value || typeof value === 'undefined') {
return null;
}
+20
View File
@@ -0,0 +1,20 @@
// labels per scene relation type, keyed by which side of the relation the related scene is on
// relations point from the derivation or compilation (source) to the original or compilation part (target)
const relationLabels = {
rerelease: { target: 'Rerelease of', source: 'Rereleased as' },
remaster: { target: 'Remaster of', source: 'Remastered as' },
compilation: { target: 'Compilation features', source: 'Featured in compilation' },
};
export function getRelationLabel(type, direction) {
if (relationLabels[type]?.[direction]) {
return relationLabels[type][direction];
}
// fallback for types added later without a label
return direction === 'target'
? `${type.charAt(0).toUpperCase()}${type.slice(1)} of`
: `Has ${type}`;
}
export default relationLabels;