Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- "use strict";
- const moment = require('moment')
- const admin = require("firebase-admin")
- const functions = require("firebase-functions")
- admin.initializeApp(functions.config().firebase)
- // const nodemailer = require('nodemailer')
- // const gmailEmail = functions.config().gmail.email;
- // const gmailPassword = functions.config().gmail.password;
- // const mailTransport = nodemailer.createTransport({
- // service: 'gmail',
- // auth: {
- // user: gmailEmail,
- // pass: gmailPassword,
- // },
- // });
- // const APP_NAME = 'Nur Al-Zaytouna'
- // exports.sendWelcomeEmail = functions.auth.user().onCreate((event) => {
- // const user = event.data
- // const email = user.email
- // const displayName = user.displayName
- // return sendEmail(email, displayName);
- // });
- // function sendEmail(email, displayName) {
- // const mailOptions = {
- // from: `${APP_NAME} noreply`,
- // to: email,
- // };
- // mailOptions.subject = `Bienvenue à ${APP_NAME}!`;
- // mailOptions.text = `Bienvenue ${displayName || ''} à Nur Al Zaytouna! \n L'équipe Nur`
- // return mailTransport.sendMail(mailOptions).then(() => {
- // return console.log('New welcome email sent to:', email);
- // });
- // }
- // exports.postFacebookContent = functions.https.onRequest((req, res) => {
- // console.log(JSON.stringify(req.body))
- // return admin.auth().getUser("nk0LlyCqEJhhPAl7QXC9MdIhmYr1").then(user => {
- // let postData = {
- // userID: user.uid,
- // timestamp: admin.database.ServerValue.TIMESTAMP,
- // numberOfLikes: 0,
- // numberOfComments: 0,
- // numberOfShares: 0,
- // userPic: user.photoURL,
- // displayName: user.displayName,
- // postText: req.body.entry[0].changes[0].value.message || ''
- // }
- // if (req.body.entry[0].changes[0].value.item === "photo") {
- // postData.photo = req.body.entry[0].changes[0].value.link || null
- // }
- // if (req.body.entry[0].changes[0].value.item === "video") {
- // postData.video = req.body.entry[0].changes[0].value.link || null
- // }
- // const newKey = admin.database().ref('/posts').push().key
- // let updates = {}
- // updates['/posts/' + newKey] = postData
- // updates['/users/' + user.uid + '/posts/' + newKey] = postData
- // return admin.database().ref().update(updates).then(() => {
- // console.log('success')
- // return res.status(200).send()
- // })
- // })
- // // if (req.query['hub.verify_token'] === '123456789') {
- // // res.status(200).send(req.query['hub.challenge'])
- // // } else {
- // // res.status(404).send('Error Token')
- // // }
- // })
- exports.sendShareNotification = functions.database
- .ref('/shares/{ShareKey}')
- .onWrite((change, context) => {
- //const shareData = event.data.val()
- const shareData = change.after.val()
- // WhoShared: Backend.auth().currentUser.uid,
- // Owner: this.props.uid,
- // PostID: this.props.Key
- return Promise.all([
- admin.auth().getUser(shareData.WhoShared),
- admin.database().ref('/users/' + shareData.Owner + '/token').once('value'),
- admin.database().ref(`/users/${shareData.Owner}/numberOfNotifications`).once('value')
- ]).then(results => {
- const UserWhoShared = results[0]
- const PostOwnerToken = results[1].val()
- let numberOfNotifications = results[2].val() ? results[2].val() : 0
- if (PostOwnerToken === null) {
- return console.log('The user has no token')
- }
- const payload = {
- notification: {
- title: 'Nur Al-Zaytouna',
- body: `${UserWhoShared.displayName} a partagé votre post.`
- },
- data: {
- title: `Nur Al-Zaytouna`,
- body: `${UserWhoShared.displayName} a partagé votre post.`
- }
- }
- return admin.messaging().sendToDevice(PostOwnerToken, payload).then(response => {
- return admin.database().ref(`/users/${shareData.Owner}/notifications`)
- .push({
- seen: false,
- type: 'share',
- UID: shareData.PostID,
- name: UserWhoShared.displayName,
- whoImage: UserWhoShared.photoURL || '',
- timestamp: admin.database.ServerValue.TIMESTAMP
- }).then(() => {
- numberOfNotifications++;
- return admin.database().ref(`/users/${shareData.Owner}/numberOfNotifications`).set(numberOfNotifications)
- .then(() => {
- return console.log('Operation Success')
- })
- })
- })
- })
- })
- exports.sendCommentSecondNotification = functions.database
- .ref('/posts/{PostUID}/comments/{CommentUID}')
- .onWrite((change, context) => {
- const Comment = change.after.val()
- const PostUID = context.params.PostUID
- const CommentUID = context.params.CommentUID
- // send notifications to all user that commented except the post's owner (handeled by the function below) and the one who commented
- const getPostOwnerUID = admin.database().ref(`/posts/${PostUID}/userID`).once('value')
- const getAllComments = admin.database().ref(`/posts/${PostUID}/comments`).once('value')
- return Promise.all([
- getPostOwnerUID,
- getAllComments
- ]).then(results => {
- const PostOwnerUID = results[0].val()
- const CommentsSnapchot = results[1]
- const AllUsersWhoCommentedUIDS = []
- CommentsSnapchot.forEach(CommentSnapchot => {
- AllUsersWhoCommentedUIDS.push(CommentSnapchot.child('uid').val())
- })
- let tokenPromises = []
- AllUsersWhoCommentedUIDS.forEach(userWhoCommentedUID => {
- if (userWhoCommentedUID !== PostOwnerUID && userWhoCommentedUID !== Comment.uid) {
- tokenPromises.push(
- admin.database().ref(`/users/${userWhoCommentedUID}/token`).once('value')
- )
- }
- })
- return Promise.all(tokenPromises).then(results => {
- let payload = {
- notification: {
- title: 'Nur Al-Zaytouna',
- body: `${Comment.displayName} a commenté un post que vous avez commenté.`
- },
- data: {
- title: 'Nur Al-Zaytouna',
- body: `${Comment.displayName} a commenté un post que vous avez commenté.`
- }
- }
- let tokens = []
- results.forEach(tokenSnapchot => {
- tokens.push(tokenSnapchot.val())
- })
- return admin.messaging().sendToDevice(tokens, payload).then(response => {
- response.results.forEach((result, index) => {
- const error = result.error
- if (error) {
- return console.error('Failure sending notification to', tokens[index], error)
- } else {
- return admin.database().ref(`/users/${AllUsersWhoCommentedUIDS[index]}/numberOfNotifications`).once('value')
- .then(snapchot => {
- let numberOfNotifications = snapchot.val() ? snapchot.val() : 0
- numberOfNotifications++
- return admin.database().ref(`/users/${AllUsersWhoCommentedUIDS[index]}/numberOfNotifications`).set(numberOfNotifications)
- .then(() => {
- return console.log('Operation Success');
- })
- })
- }
- });
- return console.log('Done')
- })
- })
- })
- })
- exports.sendCommentNotification = functions.database
- .ref('/posts/{PostUID}/comments/{CommentUID}')
- .onWrite((change, context) => {
- const Comment = change.after.val()
- const PostUID = context.params.PostUID
- const CommentUID = context.params.CommentUID
- const getPostOwnerUID = admin.database().ref(`/posts/${PostUID}/userID`).once('value')
- return admin.database().ref(`/posts/${PostUID}/userID`).once('value').then(snapchot => {
- const ownerUID = snapchot.val()
- if (ownerUID === Comment.uid) {
- return console.log('Same user commented')
- }
- const getUserWhoCommentedPromise = admin.auth().getUser(Comment.uid)
- const getPostOwnerTokenPromise = admin.database().ref(`/users/${ownerUID}/token`).once('value')
- const getNumberOfNotificationsPromise = admin.database().ref(`/users/${ownerUID}/numberOfNotifications`).once('value')
- return Promise.all([
- getUserWhoCommentedPromise,
- getPostOwnerTokenPromise,
- getNumberOfNotificationsPromise
- ]).then(results => {
- const UserWhoCommented = results[0]
- const PostOwnerToken = results[1].val()
- let numberOfNotifications = results[2].val() ? results[2].val() : 0
- if (PostOwnerToken === null) {
- return console.log('No token found')
- }
- const payload = {
- notification: {
- title: 'Nur Al-Zaytouna',
- body: `${UserWhoCommented.displayName} a commenté votre post.`
- },
- data: {
- title: `Nur Al-Zaytouna`,
- body: `${UserWhoCommented.displayName} a commenté votre post.`
- }
- }
- return admin.messaging().sendToDevice(PostOwnerToken, payload).then(response => {
- return admin.database().ref(`/users/${ownerUID}/notifications`)
- .push({
- seen: false,
- type: 'comment',
- UID: PostUID,
- name: UserWhoCommented.displayName,
- whoImage: UserWhoCommented.photoURL || '',
- timestamp: admin.database.ServerValue.TIMESTAMP
- }).then(() => {
- numberOfNotifications++;
- return admin.database().ref(`/users/${ownerUID}/numberOfNotifications`).set(numberOfNotifications)
- .then(() => {
- return console.log('Operation Success')
- })
- })
- })
- })
- })
- })
- exports.sendLikeNotification = functions.database
- .ref('/posts/{PostUid}/likes/{UserWhoLikedThePostUid}')
- .onWrite((change, context) => {
- const PostUid = context.params.PostUid;
- const UserWhoLikedThePostUid = context.params.UserWhoLikedThePostUid;
- // If un-follow we exit the function.
- if (!event.data.val()) {
- return console.log('Dislike');
- }
- const getUserWhoLikedPromise = admin.auth().getUser(UserWhoLikedThePostUid)
- const getPostOwnerUID = admin.database().ref(`/posts/${PostUid}/userID`).once('value')
- return Promise.all([
- getUserWhoLikedPromise,
- getPostOwnerUID
- ]).then(results => {
- const UserWhoLiked = results[0]
- const PostOwnerUIDSnapchot = results[1]
- if (UserWhoLikedThePostUid === PostOwnerUIDSnapchot.val()) {
- return console.log(
- 'Same person liked his post'
- );
- }
- const getTokenPromise = admin.database().ref(`/users/${PostOwnerUIDSnapchot.val()}/token`).once('value')
- const getNumberOfNotificationsPromise = admin.database().ref(`/users/${PostOwnerUIDSnapchot.val()}/numberOfNotifications`).once('value')
- return Promise.all([
- getTokenPromise,
- getNumberOfNotificationsPromise
- ])
- .then(results => {
- const tokenSnapshot = results[0];
- let numberOfNotifications = results[1].val() ? results[1].val() : 0
- // Check if there are any device tokens.
- if (tokenSnapshot.val() === null) {
- return console.log(
- "There are no notification tokens to send to."
- );
- }
- const token = tokenSnapshot.val()
- const payload = {
- notification: {
- title: 'Nur Al-Zaytouna',
- body: `${UserWhoLiked.displayName} aime votre publication.`
- },
- data: {
- title: `Nur Al-Zaytouna`,
- body: `${UserWhoLiked.displayName} aime votre publication.`
- }
- };
- return admin.messaging().sendToDevice(token, payload).then(response => {
- return admin.database().ref(`/users/${PostOwnerUIDSnapchot.val()}/notifications`)
- .push({
- seen: false,
- type: 'like',
- UID: PostUid,
- name: UserWhoLiked.displayName,
- whoImage: UserWhoLiked.photoURL || '',
- timestamp: admin.database.ServerValue.TIMESTAMP
- }).then(() => {
- numberOfNotifications++;
- return admin.database().ref(`/users/${PostOwnerUIDSnapchot.val()}/numberOfNotifications`).set(numberOfNotifications)
- .then(() => {
- return console.log('Operation Success')
- })
- })
- })
- })
- })
- })
- exports.sendFollowerNotification = functions.database
- .ref("/followers/{followedUid}/{followerUid}")
- .onWrite((change, context) => {
- const followerUid = context.params.followerUid;
- const followedUid = context.params.followedUid;
- // If un-follow we exit the function.
- if (!change.after.val()) {
- return console.log(
- "User ",
- followerUid,
- "un-followed user",
- followedUid
- );
- }
- console.log(
- "We have a new follower UID:",
- followerUid,
- "for user:",
- followedUid
- );
- // Get the list of device notification tokens.
- const getDeviceTokenPromise = admin
- .database()
- .ref(`/users/${followedUid}/token`)
- .once("value");
- // Get the follower profile.
- const getFollowerProfilePromise = admin.auth().getUser(followerUid)
- const getNumberOfNotificationsPromise = admin.database().ref(`/users/${followedUid}/numberOfNotifications`).once('value')
- return Promise.all([
- getDeviceTokenPromise,
- getFollowerProfilePromise,
- getNumberOfNotificationsPromise
- ]).then(results => {
- const tokenSnapshot = results[0];
- const follower = results[1];
- let numberOfNotifications = results[2].val() ? results[2].val() : 0
- // Check if there are any device tokens.
- if (tokenSnapshot.val() === null || tokenSnapshot.val() === undefined) {
- return console.log(
- "There are no notification tokens to send to."
- );
- }
- // Notification details.
- const payload = {
- notification: {
- title: 'Nur Al-Zaytouna',
- body: `${follower.displayName} a commencé a vous suivre.`
- },
- data: {
- title: "Nouveau abonnée!",
- body: `${follower.displayName} a commencé a vous suivre.`
- }
- };
- // Listing all tokens.
- const token = tokenSnapshot.val()
- // Send notifications to all tokens.
- return admin
- .messaging()
- .sendToDevice(token, payload)
- .then(response => {
- return admin.database().ref(`/users/${followedUid}/notifications`)
- .push({
- seen: false,
- type: 'follow',
- UID: followerUid,
- name: follower.displayName,
- whoImage: follower.photoURL || '',
- timestamp: admin.database.ServerValue.TIMESTAMP
- }).then(() => {
- numberOfNotifications++
- return admin.database().ref(`/users/${followedUid}/numberOfNotifications`).set(numberOfNotifications)
- .then(() => {
- return console.log('Operation Success')
- })
- })
- });
- });
- });
- exports.writePostToFollowersFeed = functions.database.ref('/users/{UserUID}/posts/{PostUID}').onWrite((change, context) => {
- // get followers of UserUID
- const UserUID = context.params.UserUID
- const PostUID = context.params.PostUID
- const followers = []
- return admin.database().ref(`/users/${UserUID}/followers`).once('value')
- .then((snapshot) => {
- let promises = []
- promises.push(
- admin.database().ref(`/feed/${UserUID}/${PostUID}`).set(true)
- )
- snapshot.forEach(follower => {
- // false
- if (follower.val()) {
- promises.push(
- admin.database().ref(`/feed/${follower.key}/${PostUID}`).set(true)
- )
- }
- })
- return Promise.all(promises)
- })
- .then((results) => {
- return console.log(`Done Posting this post ${PostUID} to the followers feeds`)
- })
- .catch(error => {
- console.log(error)
- })
- })
- exports.getFeedForUserUID = functions.region('europe-west1').https.onRequest((request, response) => {
- if (request.query.uid === undefined) {
- return response.status(500).send('User UID required')
- }
- const UserUID = request.query.uid
- const lastPostUID = request.query.lastPostUID
- if (lastPostUID === 'end') {
- return response.status(200).send([])
- }
- // lastPostID
- if (lastPostUID === undefined) {
- return admin
- .database()
- .ref(`/feed/${UserUID}`)
- .orderByKey()
- .limitToLast(10)
- .once('value')
- .then((snapshot) => {
- let postUIDS = []
- snapshot.forEach(post => {
- postUIDS.push(post.key)
- })
- postUIDS.reverse()
- let dataPromises = []
- postUIDS.forEach(pUID => {
- dataPromises.push (
- admin.database().ref(`/posts/${pUID}`).once('value')
- )
- })
- return Promise.all(dataPromises)
- })
- .then((results) => {
- let feed = []
- results.forEach(postSnapshot => {
- feed.push(
- Object.assign({key: postSnapshot.key}, postSnapshot.val())
- )
- })
- return response.status(200).send(feed)
- })
- } else {
- return admin
- .database()
- .ref(`/feed/${UserUID}`)
- .orderByKey()
- .endAt(lastPostUID)
- .limitToLast(10)
- .once('value')
- .then((snapshot) => {
- let postUIDS = []
- snapshot.forEach(post => {
- postUIDS.push(post.key)
- })
- postUIDS.reverse()
- let dataPromises = []
- postUIDS.forEach(pUID => {
- dataPromises.push (
- admin.database().ref(`/posts/${pUID}`).once('value')
- )
- })
- return Promise.all(dataPromises)
- })
- .then((results) => {
- let feed = []
- results.forEach(postSnapshot => {
- feed.push(Object.assign({key: postSnapshot.key}, postSnapshot.val()))
- })
- feed.splice(0, 1)
- return response.status(200).send(feed)
- })
- }
- })
- ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
- ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
- ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
- exports.addPost = functions.region('europe-west1').https.onRequest((request, response) => {
- if (request.method !== 'POST') {
- return response.status(500).send('Only Post allowed')
- }
- let postData = request.body
- const ref = admin.database().ref('/posts').push()
- return ref.set(postData)
- .then(() => {
- return response.status(200).send()
- })
- .catch(error => {
- console.log(error)
- return response.status(500).send(error)
- })
- })
- exports.cronJob = functions.region('europe-west1').https.onRequest((request, response) => {
- // get cronned posts
- let cronPosts = []
- let postsToPublish = []
- let serverTime = null
- return admin.database().ref('/cronnedposts').once('value')
- .then((snapshot) => {
- snapshot.forEach(post => {
- cronPosts.push(post.val())
- // post.child('timestamp).val()
- })
- return admin.database().ref("/.info/serverTimeOffset").once('value')
- })
- // get current Time
- .then((offset) => {
- var offsetVal = offset.val() || 0
- serverTime = Date.now() + offsetVal
- console.log(serverTime)
- cronPosts.forEach(post => {
- if (moment(post.timestamp).isBefore(moment(serverTime).add('1', 'minutes'))) {
- postsToPublish.push(post)
- }
- })
- let promisesOfPostsToPublish = []
- postsToPublish.forEach(post => {
- promisesOfPostsToPublish.push(
- admin.database().ref('/posts').push(post)
- )
- })
- return Promise.all(promisesOfPostsToPublish)
- })
- .then((results) => {
- return response.status(200).send('DONE')
- })
- .catch(error => {
- console.log(error)
- return response.status(500).send(error)
- })
- })
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement