Skip to content

Instantly share code, notes, and snippets.

@mfurlend
Created February 6, 2018 02:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mfurlend/86b130c1fba42afeed7dbf0e32076704 to your computer and use it in GitHub Desktop.
Save mfurlend/86b130c1fba42afeed7dbf0e32076704 to your computer and use it in GitHub Desktop.
#google #cloud functions #cloud storage #gcs #firebase
'use strict';
const admin = require('firebase-admin');
const functions = require('firebase-functions');
const gcs = require('@google-cloud/storage')({keyFilename:
'adotapet-476b5-firebase-adminsdk-p67hf-60281ac514.json'});
const spawn = require('child-process-promise').spawn;
admin.initializeApp(functions.config().firebase);
exports.generateThumbnail = functions.storage.object()
.onChange(event => {
const object = event.data
const filePath = object.name
const fileName = filePath.split('/').pop()
const fileBucket = object.bucket
const bucket = gcs.bucket(fileBucket)
const tempFilePath = `/tmp/${fileName}`
const ref = admin.database().ref()
const file = bucket.file(filePath)
const thumbFilePath = filePath.replace(/(\/)?([^\/]*)$/,'$1thumb_$2')
if (fileName.startsWith('thumb_')) {
console.log('Já é uma thumbnail')
return
}
if (!object.contentType.startsWith('image/')) {
console.log('Isto não é uma imagem')
return
}
if (object.resourceState === 'not_exists') {
console.log('Este é um evento de deletar')
return
}
return bucket.file(filePath).download({
destination: tempFilePath
}).then(() => {
return spawn('convert', [tempFilePath, '-thumbnail', '200X200>', tempFilePath])
})
.then(() => {
console.log('Thumbnail criada.')
return bucket.upload(tempFilePath, {
destination: thumbFilePath
})
}).then(() => {
const thumbFile = bucket.file(thumbFilePath)
const config = {
action: 'read',
expires: '03-09-2025'
}
return Promise.all([
thumbFile.getSignedUrl(config),
file.getSignedUrl(config)
])
}).then(results => {
const thumbResult = results[0]
const originalResult = results[1]
const thumbFileUrl = thumbResult[0]
const fileUrl = originalResult[0]
var key = filePath.substr(14,20)
console.log(key)
return ref.child('adocao/pets/' + key).update({thumbnail: thumbFileUrl})
})
})
// TODO: Make sure you configure the 'dev_motivator.device_token' Google Cloud environment variables.
const deviceToken = functions.config().dev_motivator.device_token;
// Deletes the user data in the Realtime Datastore when the accounts are deleted.
exports.cleanupUserData = functions.auth.user().onDelete(event => {
const uid = event.data.uid
return admin.database().ref(`/usuarios/${uid}`).remove()
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment