Я получаю ошибку SignatureDoesNotMatch для ссылок на миниатюры моей галереи.
Это мой Firebase фрагмент функции облака Google ниже, чтобы создать миниатюру, когда пользователь загружает изображение на сервер и получает ссылку с помощью getSignedURL () и, наконец, сохраняет в базе данных.
Для миниатюрных ссылок категории «доска объявлений» никогда не истекает срок действия, но я не знаю, почему для категории «галерея» ссылки истекают через неделю. однако код одинаков для них обоих.
'use strict';
const functions = require('firebase-functions');
const admin = require("firebase-admin");
admin.initializeApp();
const {Storage} = require('@google-cloud/storage');
const projectId = 'myprojectid';
// Instantiates a client
const gcs = new Storage({
projectId: projectId,
});
const path = require('path');
const sharp = require('sharp');
const THUMB_MAX_WIDTH = 300;
const THUMB_MAX_HEIGHT = 300;
exports.thumbnailGen = functions.storage.object().onFinalize(async (object) => {
const fileBucket = object.bucket; // The Storage bucket that contains the file.
const filePath = object.name; // File path in the bucket.
//console.log('filePath',filePath)
console.log('object',object)
const contentType = object.contentType; // File content type.
const fileDir = path.dirname(filePath); //iadd
console.log('fileDir',fileDir)
const lastDir = fileDir.split("/"); //iadd
console.log('lastDir',lastDir);
// Exit if this is triggered on a file that is not an image.
if (!contentType.startsWith('image/')) {
console.log('This is not an image.');
return null;
}
// Get the file name.
const fileName = path.basename(filePath);
// Exit if the image is already a thumbnail.
//console.log('fileName',fileName)
if (fileName.startsWith('thumb_')) {
console.log('Already a Thumbnail.');
return null;
}
/* iadd */
const filenameWithoutExt = fileName.split('.').shift();
//console.log('get filenameWithoutExt: ',filenameWithoutExt);
let exp = /^(.+)_([0-9]+)$/;
let thekey = filenameWithoutExt.replace(exp, '$1');
console.log('thekey',thekey)
// Download file from bucket.
const bucket = gcs.bucket(fileBucket);
const metadata = {
contentType: contentType,
};
// We add a 'thumb_' prefix to thumbnails file name. That's where we'll upload the thumbnail.
const thumbFileName = `thumb_${fileName}`;
const thumbFilePath = path.join(fileDir, thumbFileName);
// Create write stream for uploading thumbnail
const thumbnailUploadStream = bucket.file(thumbFilePath).createWriteStream({metadata});
let theimageindex = filenameWithoutExt.replace(exp, '$2');
//console.log('theimageindex',theimageindex)
/* iadd */
// Create Sharp pipeline for resizing the image and use pipe to read from bucket read stream
const pipeline = sharp();
pipeline
.resize(THUMB_MAX_WIDTH, THUMB_MAX_HEIGHT)
.jpeg({ quality: 100 })
.png({ quality: 100 })
.max()
.pipe(thumbnailUploadStream);
bucket.file(filePath).createReadStream().pipe(pipeline);
const config = {action: 'read', expires: '03-01-2025' }
const streamAsPromise = new Promise((resolve, reject) =>
thumbnailUploadStream.on('finish', resolve).on('error', reject));
let onlyFileName = filenameWithoutExt.split('@'); // returns at 2nd index somthing like -L7QEvCNSEJqJAy9DPu5_0 , image without extension but with _0 or _1 etc.
let createDownloadablepath = thekey.split('@');
let thumbFileUrl
let thumbFile
let updatedatabasepath = {};
if (lastDir[1] === 'noticeboard') {
return streamAsPromise
.then(() => {
console.log('Thumbnail created successfully');
thumbFile = bucket.file(thumbFilePath);
return thumbFile.getSignedUrl(config)
})
.then((results)=>{
thumbFileUrl = results[0];
console.log('Got Signed URLs.',thumbFileUrl);
return admin.database().ref('/'+fileDir+'/'+createDownloadablepath[0]+'/'+createDownloadablepath[1]+'/thumbnails/'+onlyFileName[1]).update({thumbnailURL : thumbFileUrl })
})
.then(() => {
console.log('All done successfully');
return null
})
}
else if (lastDir[1] === 'gallery' ) {
return streamAsPromise
.then(() => {
console.log('Thumbnail created successfully');
thumbFile = bucket.file(thumbFilePath);
return thumbFile.getSignedUrl(config)
})
.then((results)=>{
thumbFileUrl = results[0];
console.log('Got Signed URLs. upto 03-01-2500',thumbFileUrl);
updatedatabasepath['/'+fileDir+'/'+createDownloadablepath[0]+'/'+createDownloadablepath[1]+'/thumbnails/'+onlyFileName[1]+'/thumbnailURL'] = thumbFileUrl;
updatedatabasepath['/'+fileDir+'/'+createDownloadablepath[0]+'/thumbnailURL'] = thumbFileUrl;
return admin.database().ref().update(updatedatabasepath)
}).then(() => {
console.log('All done successfully');
return null
})
}
else {
return streamAsPromise
.then(() => {
console.log('Thumbnail created successfully');
return null
})
}
}); //exports.thumbnailGen