1 import { Transaction } from 'sequelize/types'
2 import { logger } from '@server/helpers/logger'
3 import { ActorImageModel } from '@server/models/actor/actor-image'
4 import { MActorImage, MActorImages } from '@server/types/models'
5 import { ActorImageType } from '@shared/models'
15 async function updateActorImages (actor: MActorImages, type: ActorImageType, imagesInfo: ImageInfo[], t: Transaction) {
16 const avatarsOrBanners = type === ActorImageType.AVATAR
20 if (imagesInfo.length === 0) {
21 await deleteActorImages(actor, type, t)
24 for (const imageInfo of imagesInfo) {
25 const oldImageModel = (avatarsOrBanners || []).find(i => i.width === imageInfo.width)
28 // Don't update the avatar if the file URL did not change
29 if (imageInfo?.fileUrl && oldImageModel.fileUrl === imageInfo.fileUrl) {
33 await safeDeleteActorImage(actor, oldImageModel, type, t)
36 const imageModel = await ActorImageModel.create({
37 filename: imageInfo.name,
38 onDisk: imageInfo.onDisk ?? false,
39 fileUrl: imageInfo.fileUrl,
40 height: imageInfo.height,
41 width: imageInfo.width,
44 }, { transaction: t })
46 addActorImage(actor, type, imageModel)
52 async function deleteActorImages (actor: MActorImages, type: ActorImageType, t: Transaction) {
54 const association = buildAssociationName(type)
56 for (const image of actor[association]) {
57 await image.destroy({ transaction: t })
60 actor[association] = []
62 logger.error('Cannot remove old image of actor %s.', actor.url, { err })
68 async function safeDeleteActorImage (actor: MActorImages, toDelete: MActorImage, type: ActorImageType, t: Transaction) {
70 await toDelete.destroy({ transaction: t })
72 const association = buildAssociationName(type)
73 actor[association] = actor[association].filter(image => image.id !== toDelete.id)
75 logger.error('Cannot remove old actor image of actor %s.', actor.url, { err })
79 // ---------------------------------------------------------------------------
88 // ---------------------------------------------------------------------------
90 function addActorImage (actor: MActorImages, type: ActorImageType, imageModel: MActorImage) {
91 const association = buildAssociationName(type)
92 if (!actor[association]) actor[association] = []
94 actor[association].push(imageModel)
97 function buildAssociationName (type: ActorImageType) {
98 return type === ActorImageType.AVATAR