Skip to content

Instantly share code, notes, and snippets.

@Auwalms
Created April 1, 2017 09:42
Show Gist options
  • Save Auwalms/ee7237ce70e01dc67ee470d263dfa22e to your computer and use it in GitHub Desktop.
Save Auwalms/ee7237ce70e01dc67ee470d263dfa22e to your computer and use it in GitHub Desktop.
Cloud Function Talks snippets
// Adds a message that welcomes new users into the chat.
exports.addWelcomeMessages = functions.auth.user().onCreate(event => {
const user = event.data;
console.log('A new user signed in for the first time.');
const fullName = user.displayName || 'Anonymous';
// Saves the new welcome message into the database
// which then displays it in the FriendlyChat clients.
return admin.database().ref('messages').push({
name: 'Firebase Bot',
photoUrl: '/images/firebase-logo.png', // Firebase logo
text: `${fullName} signed in for the first time! Welcome!`
});
});
const functions = require('firebase-functions'),
admin = require('firebase-admin');
exports.moderator = functions.database.ref('/messages/{messageId}')
.onWrite(event => {
const message = event.data.val();
if (message && !message.sanitized) {
const moderatedMessage = moderateMessage(message.text);
return event.data.adminRef.update({
text: moderatedMessage,
sanitized: true,
moderated: message.text !== moderatedMessage
});
}
// Moderates the given message if appropriate.
function moderateMessage(message) {
/**
*moderation logic comes in here, after sanitation is completed,
* a sanitized text is expected to be returned.
*/
}
exports.helloHttp = functions helloHttp (req, res){
res.send (`Hello ${req.body.name || ‘Covenant University’} `);
};
exports.sendFollowerNotification = functions.database.ref('/followers/{followedUid}/{followerUid}').onWrite(event => {
const followerUid = event.params.followerUid;
const followedUid = event.params.followedUid;
// Get the list of device notification tokens.
const getDeviceTokensPromise = admin.database().ref(`/users/${followedUid}/notificationTokens`).once('value');
//fetch followers information
const getFollowerProfilePromise = admin.auth().getUser(followerUid);
return Promise.all([getDeviceTokensPromise, getFollowerProfilePromise]).then(results => {
// Notification details.
const payload = {
notification: {
title: 'You have a new follower!',
body: `${follower.displayName} is now following you.`,
icon: follower.photoURL
}
};
// Send notifications to all tokens.
return admin.messaging().sendToDevice(tokens, payload).then(response => {
//logic comes here and then return promise
});
});
});
// Blurs uploaded images that are flagged as Adult or Violence.
exports.blurOffensiveImages = functions.storage.object().onChange(event => {
const object = event.data;
// Exit if this is a deletion or a deploy event.
if (object.resourceState === 'not_exists') {
return console.log('This is a deletion event.');
} else if (!object.name) {
return console.log('This is a deploy event.');
}
const bucket = gcs.bucket(object.bucket);
const file = bucket.file(object.name);
// Check the image content using the Cloud Vision API.
return vision.detectSafeSearch(file).then(safeSearchResult => {
if (safeSearchResult[0].adult || safeSearchResult[0].violence) {
console.log('The image', object.name, 'has been detected as inappropriate.');
return blurImage(object.name, bucket);
} else {
console.log('The image', object.name,'has been detected as OK.');
}
});
});
// Blurs the given image located in the given bucket using ImageMagick.
function blurImage(filePath, bucket, metadata) {
const fileName = filePath.split('/').pop();
const tempLocalFile = `/tmp/${fileName}`;
const messageId = filePath.split('/')[1];
// Download file from bucket.
return bucket.file(filePath).download({destination: tempLocalFile})
.then(() => {
console.log('Image has been downloaded to', tempLocalFile);
// Blur the image using ImageMagick.
return exec(`convert ${tempLocalFile} -channel RGBA -blur 0x24 ${tempLocalFile}`);
}).then(() => {
console.log('Image has been blurred');
// Uploading the Blurred image back into the bucket.
return bucket.upload(tempLocalFile, {destination: filePath});
}).then(() => {
console.log('Blurred image has been uploaded to', filePath);
// Indicate that the message has been moderated.
return admin.database().ref(`/messages/${messageId}`).update({moderated: true});
}).then(() => {
console.log('Marked the image as moderated in the database.');
});
}
/**
* Webhook that will be called each time there is a new GitHub commit and will post a message to
* Slack.
*/
exports.githubWebhook = functions.https.onRequest((req, res) => {
const cipher = 'sha1';
const signature = req.headers['x-hub-signature'];
// TODO: Configure the `github.secret` Google Cloud environment variables.
const hmac = crypto.createHmac(cipher, functions.config().github.secret)
// The JSON body is automatically parsed by Cloud Functions so we re-stringify it.
.update(JSON.stringify(req.body, null, 0))
.digest('hex');
const expectedSignature = `${cipher}=${hmac}`;
// Check that the body of the request has been signed with the GitHub Secret.
if (signature === expectedSignature) {
postToSlack(req.body.compare, req.body.commits.length, req.body.repository).then(() => {
res.end();
}).catch(error => {
console.error(error);
res.status(500).send('Something went wrong while posting the message to Slack.');
});
} else {
console.error('x-hub-signature', signature, 'did not match', expectedSignature);
res.status(403).send('Your x-hub-signature\'s bad and you should feel bad!');
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment