From 9c5f4fe2f0ef13f5f9142836817f0d284fcccebc Mon Sep 17 00:00:00 2001 From: JoaquinOlivero Date: Thu, 1 Aug 2024 08:34:06 +0000 Subject: [PATCH] fix: remove unexpired unused image when a user changes their avatar --- server/lib/imageproxy.ts | 15 +++++++++++++++ server/routes/auth.ts | 16 ++++++++++++++-- 2 files changed, 29 insertions(+), 2 deletions(-) diff --git a/server/lib/imageproxy.ts b/server/lib/imageproxy.ts index 4ea69fcc..3a3098f8 100644 --- a/server/lib/imageproxy.ts +++ b/server/lib/imageproxy.ts @@ -171,6 +171,21 @@ class ImageProxy { return imageResponse; } + public async clearCachedImage(path: string) { + // find cacheKey + const cacheKey = this.getCacheKey(path); + + try { + const directory = join(this.getCacheDirectory(), cacheKey); + await promises.rm(directory, { recursive: true }); + logger.info(`Cleared ${path} image from cache 'avatar'`, { + label: 'Image Cache', + }); + } catch (e) { + logger.error(e.message, { label: 'Image Cache' }); + } + } + private async get(cacheKey: string): Promise { try { const directory = join(this.getCacheDirectory(), cacheKey); diff --git a/server/routes/auth.ts b/server/routes/auth.ts index cd931c25..395c987d 100644 --- a/server/routes/auth.ts +++ b/server/routes/auth.ts @@ -6,6 +6,7 @@ import { UserType } from '@server/constants/user'; import { getRepository } from '@server/datasource'; import { User } from '@server/entity/User'; import { startJobs } from '@server/job/schedule'; +import ImageProxy from '@server/lib/imageproxy'; import { Permission } from '@server/lib/permissions'; import { getSettings } from '@server/lib/settings'; import logger from '@server/logger'; @@ -407,12 +408,23 @@ authRoutes.post('/jellyfin', async (req, res, next) => { ); // Update the users avatar with their jellyfin profile pic (incase it changed) if (account.User.PrimaryImageTag) { - user.avatar = `${jellyfinHost}/Users/${account.User.Id}/Images/Primary/?tag=${account.User.PrimaryImageTag}&quality=90`; + const avatar = `${jellyfinHost}/Users/${account.User.Id}/Images/Primary/?tag=${account.User.PrimaryImageTag}&quality=90`; + if (avatar !== user.avatar) { + const avatarProxy = new ImageProxy('avatar', ''); + avatarProxy.clearCachedImage(user.avatar); + } + user.avatar = avatar; } else { - user.avatar = gravatarUrl(user.email || account.User.Name, { + const avatar = gravatarUrl(user.email || account.User.Name, { default: 'mm', size: 200, }); + + if (avatar !== user.avatar) { + const avatarProxy = new ImageProxy('avatar', ''); + avatarProxy.clearCachedImage(user.avatar); + } + user.avatar = avatar; } user.jellyfinUsername = account.User.Name;