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 getAvatarsOrBanners = () => {
17 const result = type === ActorImageType.AVATAR
24 if (imagesInfo.length === 0) {
25 await deleteActorImages(actor, type, t)
28 // Cleanup old images that did not have a width
29 for (const oldImageModel of getAvatarsOrBanners()) {
30 if (oldImageModel.width) continue
32 await safeDeleteActorImage(actor, oldImageModel, type, t)
35 for (const imageInfo of imagesInfo) {
36 const oldImageModel = getAvatarsOrBanners().find(i => imageInfo.width && i.width === imageInfo.width)
39 // Don't update the avatar if the file URL did not change
40 if (imageInfo.fileUrl && oldImageModel.fileUrl === imageInfo.fileUrl) {
44 await safeDeleteActorImage(actor, oldImageModel, type, t)
47 const imageModel = await ActorImageModel.create({
48 filename: imageInfo.name,
49 onDisk: imageInfo.onDisk ?? false,
50 fileUrl: imageInfo.fileUrl,
51 height: imageInfo.height,
52 width: imageInfo.width,
55 }, { transaction: t })
57 addActorImage(actor, type, imageModel)
63 async function deleteActorImages (actor: MActorImages, type: ActorImageType, t: Transaction) {
65 const association = buildAssociationName(type)
67 for (const image of actor[association]) {
68 await image.destroy({ transaction: t })
71 actor[association] = []
73 logger.error('Cannot remove old image of actor %s.', actor.url, { err })
79 async function safeDeleteActorImage (actor: MActorImages, toDelete: MActorImage, type: ActorImageType, t: Transaction) {
81 await toDelete.destroy({ transaction: t })
83 const association = buildAssociationName(type)
84 actor[association] = actor[association].filter(image => image.id !== toDelete.id)
86 logger.error('Cannot remove old actor image of actor %s.', actor.url, { err })
90 // ---------------------------------------------------------------------------
99 // ---------------------------------------------------------------------------
101 function addActorImage (actor: MActorImages, type: ActorImageType, imageModel: MActorImage) {
102 const association = buildAssociationName(type)
103 if (!actor[association]) actor[association] = []
105 actor[association].push(imageModel)
108 function buildAssociationName (type: ActorImageType) {
109 return type === ActorImageType.AVATAR