| const fs = require('fs'); |
| const path = require('path'); |
| const sharp = require('sharp'); |
| const { logger } = require('@librechat/data-schemas'); |
| const { resizeImageBuffer } = require('../images/resize'); |
| const { updateUser, updateFile } = require('~/models'); |
| const { saveBufferToFirebase } = require('./crud'); |
|
|
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| async function uploadImageToFirebase({ req, file, file_id, endpoint, resolution = 'high' }) { |
| const appConfig = req.config; |
| const inputFilePath = file.path; |
| const inputBuffer = await fs.promises.readFile(inputFilePath); |
| const { |
| buffer: resizedBuffer, |
| width, |
| height, |
| } = await resizeImageBuffer(inputBuffer, resolution, endpoint); |
| const extension = path.extname(inputFilePath); |
| const userId = req.user.id; |
|
|
| let webPBuffer; |
| let fileName = `${file_id}__${path.basename(inputFilePath)}`; |
| const targetExtension = `.${appConfig.imageOutputType}`; |
| if (extension.toLowerCase() === targetExtension) { |
| webPBuffer = resizedBuffer; |
| } else { |
| webPBuffer = await sharp(resizedBuffer).toFormat(appConfig.imageOutputType).toBuffer(); |
| |
| const extRegExp = new RegExp(path.extname(fileName) + '$'); |
| fileName = fileName.replace(extRegExp, targetExtension); |
| if (!path.extname(fileName)) { |
| fileName += targetExtension; |
| } |
| } |
|
|
| const downloadURL = await saveBufferToFirebase({ userId, buffer: webPBuffer, fileName }); |
|
|
| await fs.promises.unlink(inputFilePath); |
|
|
| const bytes = Buffer.byteLength(webPBuffer); |
| return { filepath: downloadURL, bytes, width, height }; |
| } |
|
|
| |
| |
| |
| |
| |
| |
| |
| async function prepareImageURL(req, file) { |
| const { filepath } = file; |
| const promises = []; |
| promises.push(updateFile({ file_id: file.file_id })); |
| promises.push(filepath); |
| return await Promise.all(promises); |
| } |
|
|
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| async function processFirebaseAvatar({ buffer, userId, manual, agentId }) { |
| try { |
| const metadata = await sharp(buffer).metadata(); |
| const extension = metadata.format === 'gif' ? 'gif' : 'png'; |
| const timestamp = new Date().getTime(); |
|
|
| |
| const fileName = agentId |
| ? `agent-${agentId}-avatar-${timestamp}.${extension}` |
| : `avatar-${timestamp}.${extension}`; |
|
|
| const downloadURL = await saveBufferToFirebase({ |
| userId, |
| buffer, |
| fileName, |
| }); |
|
|
| const isManual = manual === 'true'; |
| const url = `${downloadURL}?manual=${isManual}`; |
|
|
| |
| if (isManual && !agentId) { |
| await updateUser(userId, { avatar: url }); |
| } |
|
|
| return url; |
| } catch (error) { |
| logger.error('Error uploading profile picture:', error); |
| throw error; |
| } |
| } |
|
|
| module.exports = { uploadImageToFirebase, prepareImageURL, processFirebaseAvatar }; |
|
|