Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
fileType: 'image',
};
return await Promise.all([
firestoreRef.set(tanamFile),
bucket.file(storageObject.name).delete(),
bucket.file(tanamFile.filePath).save(originalFileBuffer, storageObject.metadata),
bucket.file(tanamFile.variants.small).save(await resizeAndConvertImage(300), metadata),
bucket.file(tanamFile.variants.medium).save(await resizeAndConvertImage(800), metadata),
bucket.file(tanamFile.variants.large).save(await resizeAndConvertImage(1600), metadata),
]);
});
// noinspection JSUnusedGlobalSymbols
export const onThemeAssetsFileUpload = functions.storage.object().onFinalize(async (storageObject) => {
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 = SHA1(storageObject.name).toString().toLowerCase();
const fileRef = admin.firestore()
.collection('tanam').doc(siteId)
.collection('themes').doc(themeId)
const mkdirp = require('mkdirp-promise');
const spawn = require('child-process-promise').spawn;
const path = require('path');
const os = require('os');
const fs = require('fs');
admin.initializeApp();
// File extension for the created JPEG files.
const JPEG_EXTENSION = '.jpg';
/**
* When an image is uploaded in the Storage bucket it is converted to JPEG automatically using
* ImageMagick.
*/
exports.imageToJPG = functions.storage.object().onFinalize(async (object) => {
const filePath = object.name;
const baseFileName = path.basename(filePath, path.extname(filePath));
const fileDir = path.dirname(filePath);
const JPEGFilePath = path.normalize(path.format({dir: fileDir, name: baseFileName, ext: JPEG_EXTENSION}));
const tempLocalFile = path.join(os.tmpdir(), filePath);
const tempLocalDir = path.dirname(tempLocalFile);
const tempLocalJPEGFile = path.join(os.tmpdir(), JPEGFilePath);
// Exit if this is triggered on a file that is not an image.
if (!object.contentType.startsWith('image/')) {
console.log('This is not an image.');
return null;
}
// Exit if the image is already a JPEG.
if (object.contentType.startsWith('image/jpeg')) {
*/
'use strict';
const functions = require('firebase-functions');
const gcs = require('@google-cloud/storage')();
const path = require('path');
const sharp = require('sharp');
const THUMB_MAX_WIDTH = 200;
const THUMB_MAX_HEIGHT = 200;
/**
* When an image is uploaded in the Storage bucket We generate a thumbnail automatically using
* Sharp.
*/
exports.generateThumbnail = functions.storage.object().onFinalize((object) => {
const fileBucket = object.bucket; // The Storage bucket that contains the file.
const filePath = object.name; // File path in the bucket.
const contentType = object.contentType; // File content type.
// 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.
if (fileName.startsWith('thumb_')) {
console.log('Already a Thumbnail.');
return null;
const path = require("path");
const spawn = require("child-process-promise").spawn;
const cors = require("cors")({ origin: true });
const Busboy = require("busboy");
const fs = require("fs");
const gcconfig = {
projectId: "fb-cloud-functions-demo",
keyFilename: "fb-cloud-functions-demo-firebase-adminsdk-km39q-405896eddb.json"
};
const gcs = require("@google-cloud/storage")(gcconfig);
// // Create and Deploy Your First Cloud Functions
// // https://firebase.google.com/docs/functions/write-firebase-functions
//
exports.onFileChange = functions.storage.object().onChange(event => {
const object = event.data;
const bucket = object.bucket;
const contentType = object.contentType;
const filePath = object.name;
console.log("File change detected, function execution started");
if (object.resourceState === "not_exists") {
console.log("We deleted a file, exit...");
return;
}
if (path.basename(filePath).startsWith("resized-")) {
console.log("We already renamed that file!");
return;
}
*/
'use strict';
const functions = require('firebase-functions');
const gcs = require('@google-cloud/storage')();
const path = require('path');
const os = require('os');
const fs = require('fs');
const ffmpeg = require('fluent-ffmpeg');
const ffmpeg_static = require('ffmpeg-static');
/**
* When an audio is uploaded in the Storage bucket We generate a mono channel audio automatically using
* node-fluent-ffmpeg.
*/
exports.generateMonoAudio = functions.storage.object().onChange(event => {
const object = event.data; // The Storage object.
const fileBucket = object.bucket; // The Storage bucket that contains the file.
const filePath = object.name; // File path in the bucket.
const contentType = object.contentType; // File content type.
const resourceState = object.resourceState; // The resourceState is 'exists' or 'not_exists' (for file/folder deletions).
const metageneration = object.metageneration; // Number of times metadata has been generated. New objects have a value of 1.
// Exit if this is triggered on a file that is not an audio.
if (!contentType.startsWith('audio/')) {
console.log('This is not an audio.');
return;
}
// Get the file name.
const fileName = path.basename(filePath);
// [START import]
const functions = require('firebase-functions');
const gcs = require('@google-cloud/storage')();
const spawn = require('child-process-promise').spawn;
const path = require('path');
const os = require('os');
const fs = require('fs');
// [END import]
// [START generateThumbnail]
/**
* When an image is uploaded in the Storage bucket We generate a thumbnail automatically using
* ImageMagick.
*/
// [START generateThumbnailTrigger]
exports.generateThumbnail = functions.storage.object().onChange(event => {
// [END generateThumbnailTrigger]
// [START eventAttributes]
const object = event.data; // The Storage object.
const fileBucket = object.bucket; // The Storage bucket that contains the file.
const filePath = object.name; // File path in the bucket.
const contentType = object.contentType; // File content type.
const resourceState = object.resourceState; // The resourceState is 'exists' or 'not_exists' (for file/folder deletions).
const metageneration = object.metageneration; // Number of times metadata has been generated. New objects have a value of 1.
// [END eventAttributes]
// [START stopConditions]
// 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;
const functions = require('firebase-functions');
const admin = require('firebase-admin');
try {admin.initializeApp(functions.config().firebase);} catch(e) {}
const mkdirp = require('mkdirp-promise');
const gcs = require('@google-cloud/storage')();
const vision = require('@google-cloud/vision')();
const spawn = require('child-process-promise').spawn;
const path = require('path');
const os = require('os');
const fs = require('fs');
/**
* When an image is uploaded we check if it is flagged as Adult or Violence by the Cloud Vision
* API and if it is we blur it using ImageMagick.
*/
exports = module.exports = functions.storage.object().onChange(event => {
const object = event.data;
// Exit if this is a move or deletion event.
if (object.resourceState === 'not_exists') {
console.log('This is a deletion event.');
return;
}
const image = {
source: {imageUri: `gs://${object.bucket}/${object.name}`}
};
// Check the image content using the Cloud Vision API.
return vision.safeSearchDetection(image).then(batchAnnotateImagesResponse => {
console.log('SafeSearch results on image', batchAnnotateImagesResponse);
const safeSearchResult = batchAnnotateImagesResponse[0].safeSearchAnnotation;
bucket: object.bucket,
name: object.name,
md5: object.md5Hash,
updateTime: admin.database.ServerValue.TIMESTAMP,
contentType: object.contentType,
fileType: object.contentType.split('/')[0]
};
return admin.database().ref(ContentFirebasePath.fileMetaData).child(id).set(data);
});
/**
* Cloud function that triggers on each user content file upload.
* For each user content file that is deleted, remove its entry in metadata registry.
*/
export const tanam_onFileDeleteUpdateRegistry = functions.storage.object().onDelete(async (object) => {
if (!object.name.startsWith('content/')) {
console.log(`File is not a user content file. Ignoring it.`);
return null;
}
console.log(`File deleted: gs://${object.bucket}/${object.name} (${object.md5Hash})`);
const id = SHA256(object.bucket + object.name + object.timeCreated).toString().toLowerCase();
return admin.database().ref(ContentFirebasePath.fileMetaData).child(id).remove();
});
payload: payload
}
predictionClient.predict(reqBody)
.then(responses => {
console.log('Got a prediction from AutoML API!', JSON.stringify(responses));
resolve(responses);
})
.catch(err => {
console.log('AutoML API Error: ',err);
reject(err);
});
});
}
exports.callCustomModel = functions.storage.object().onFinalize(event => {
const file = gcsClient.bucket(event.bucket).file(event.name);
let destination = '/tmp/' + event.name.replace(/\s/g, '');
return file.download({destination: destination})
.then(() => {
if(sizeOf(destination).width > 600) {
console.log('scaling image down...');
return resizeImg(destination);
} else {
return destination;
}
})
.then(() => {
let bitmap = fs.readFileSync(destination);
let data = new Buffer(bitmap).toString('base64');
return callAutoMLAPI(data);
})
from: `${globalConfig.sender_name} <${globalConfig.sender_email}>`,
to: data.user.email,
subject: 'You order: ' + orderId,
text: emailTemplates.customer(data, globalConfig)
});
const sendToAdmin = sendEmail({
from: `${globalConfig.sender_name} <${globalConfig.sender_email}>`,
to: globalConfig.admin_email,
subject: 'You have new order ' + orderId,
text: emailTemplates.admin(data, globalConfig)
});
return Promise.all([sendToAdmin, sendToCustomer]);
});
exports.generateThumbnail = functions.storage
.object('uploads/{imageId}')
.onChange(images.resizeImage);
const sendEmail = ({ from, to, subject, text }) => {
const emailData = {
from,
to,
subject,
//text
html: text
};
return new Promise((resolve, reject) => {
const { mailgun } = require('./inits');
mailgun.messages().send(emailData, (error, body) => {
if (error) {