tanam
Version:
Pluggable CMS for Firebase
104 lines • 5.04 kB
JavaScript
;
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
const admin = require("firebase-admin");
const functions = require("firebase-functions");
const sharp = require("sharp");
const crypto_js_1 = require("crypto-js");
exports.onUserImageUpload = functions.storage.object().onFinalize((storageObject) => __awaiter(this, void 0, void 0, function* () {
const regexNameMatch = storageObject.name.match(/^\/?tanam\/(.*)\/upload\//);
if (!regexNameMatch) {
console.log(`Not a user image upload task: ${storageObject.name} (${storageObject.contentType})`);
return null;
}
if (!storageObject.contentType.startsWith('image/')) {
console.log(`File is not an image: ${storageObject.name} (${storageObject.contentType})`);
return null;
}
console.log(`Processing file: ${storageObject.name}`);
const siteId = regexNameMatch[1];
const bucket = admin.storage().bucket(storageObject.bucket);
const [originalFileBuffer] = yield bucket.file(storageObject.name).download();
const resizeAndConvertImage = (size) => sharp(originalFileBuffer)
.resize(size, size, {
withoutEnlargement: true,
fit: sharp.fit.inside,
})
.toFormat(sharp.format.webp)
.toBuffer();
const originalSuffix = storageObject.name.lastIndexOf('.') > 0
? storageObject.name.substr(storageObject.name.lastIndexOf('.'))
: '';
const firestoreRef = admin.firestore()
.collection('tanam').doc(siteId)
.collection('files').doc();
const newFileName = firestoreRef.id;
const newFilePath = `tanam/${siteId}/images/`;
const metadata = {
contentType: 'image/webp',
metadata: storageObject.metadata,
};
const tanamFile = {
id: firestoreRef.id,
title: storageObject.name.substr(storageObject.name.lastIndexOf('/') + 1),
bucket: storageObject.bucket,
filePath: [newFilePath, newFileName, originalSuffix].join(''),
updated: admin.firestore.FieldValue.serverTimestamp(),
created: admin.firestore.FieldValue.serverTimestamp(),
bytes: originalFileBuffer.byteLength,
variants: {
small: `${newFilePath}${newFileName}_small.webp`,
medium: `${newFilePath}${newFileName}_medium.webp`,
large: `${newFilePath}${newFileName}_large.webp`,
},
mimeType: storageObject.contentType,
fileType: 'image',
};
return yield Promise.all([
firestoreRef.set(tanamFile),
bucket.file(storageObject.name).delete(),
bucket.file(tanamFile.filePath).save(originalFileBuffer, storageObject.metadata),
bucket.file(tanamFile.variants.small).save(yield resizeAndConvertImage(300), metadata),
bucket.file(tanamFile.variants.medium).save(yield resizeAndConvertImage(800), metadata),
bucket.file(tanamFile.variants.large).save(yield resizeAndConvertImage(1600), metadata),
]);
}));
exports.onThemeAssetsFileUpload = functions.storage.object().onFinalize((storageObject) => __awaiter(this, void 0, void 0, function* () {
const regexNameMatch = storageObject.name.match(/^\/?tanam\/(.*)\/themes\//);
if (!regexNameMatch) {
console.log(`Not an upload asset file task: ${storageObject.name} (${storageObject.contentType})`);
return null;
}
console.log('[UploadAssetFiles]' + JSON.stringify(storageObject));
const objectNameArr = storageObject.name.split('/');
const themeId = objectNameArr[3];
const siteId = regexNameMatch[1];
const fileId = crypto_js_1.SHA1(storageObject.name).toString().toLowerCase();
const fileRef = admin.firestore()
.collection('tanam').doc(siteId)
.collection('themes').doc(themeId)
.collection('assets').doc(fileId);
const fileData = {
id: fileId,
title: storageObject.name.substr(storageObject.name.lastIndexOf('/') + 1),
bucket: storageObject.bucket,
filePath: storageObject.name,
updated: admin.firestore.FieldValue.serverTimestamp(),
bytes: Number(storageObject.size),
mimeType: storageObject.contentType,
fileType: storageObject.contentType,
};
const fileDoc = yield fileRef.get();
if (!fileDoc.exists) {
fileData.created = admin.firestore.FieldValue.serverTimestamp();
}
return fileRef.set(fileData);
}));
//# sourceMappingURL=storage.js.map