- const functions = require('firebase-functions');
- const admin = require('firebase-admin');
- const express = require('express');
- const cors = require('cors');
- const app = express();
- const _ = require('lodash');
- app.use(cors({ origin: true }));
- app.get('/hello-world', (req, res) => {
- return res.status(200).send('Hello World!');
- });
- app.post('/api/sendSensorData', (req, res) => {
- (async () => {
- try {
- const sensorBody = {
- deviceID: req.body.deviceID,
- dateCreated: new Date(),
- batteryState: req.body.batteryState,
- temp: req.body.temp,
- moisture: req.body.moisture,
- humidity: req.body.humidity,
- light: req.body.light
- }
- await db.collection('SensorData').add(sensorBody);
- return res.status(200).send(`Sent sensor data from ${req.body.deviceID}`);
- } catch (error) {
- console.log(error);
- return res.status(500).send(error);
- }
- })();
- });
- exports.app = functions.https.onRequest(app);
- var serviceAccount = require("./permissions.json");
- admin.initializeApp({
- credential: admin.credential.cert(serviceAccount),
- storageBucket: 'gs://flora-85fce.appspot.com',
- });
- // MARK: Test Production
- // admin.initializeApp({
- // credential: admin.credential.cert(serviceAccount)
- //storageBucket: 'gs://flora-test-63309.appspot.com',
- // });
- const db = admin.firestore();
- exports.sendDailyReminder = functions.firestore
- .document('/UserReminders/{documentId}')
- .onCreate((snap, context) => {
- const reminderId = context.params.documentId;
- const data = snap.data();
- // access a particular field as you would any JS property
- const plantName = data.plantName;
- console.log('We have a new Reminder:', reminderId);
- console.log('Checking value of plantName:', plantName);
- // Notification details.
- const payload = {
- notification: {
- title: 'You have a plant to save!',
- body: `Your ${plantName} needs some water - make sure to take care of it!`,
- badge: '1'
- }
- };
- console.log(payload)
- admin.messaging().sendToDevice(registrationTokens, payload)
- .then(function(response) {
- // See the MessagingDevicesResponse reference documentation for
- // the contents of response.
- console.log('Successfully sent message:', response);
- })
- .catch(function(error) {
- console.log('Error sending message:', error);
- });
- });
- exports.sendFollowerNotification = functions.firestore.document('/Users/{followedUid}/followers/{followerUid}')
- .onCreate((snap, context) => {
- const data = snap.data();
- const token = data.userFCMToken
- const followerUsername = data.username;
- const userPicture = data.userPic;
- const payload = {
- notification: {
- title: 'You have a new plant buddy!',
- body: `${followerUsername} is now following you. ☺️🌱`,
- icon: userPicture,
- badge: '1'
- }
- };
- admin.messaging().sendToDevice(token, payload)
- .then(function(response) {
- console.log('Sending following payload:', payload);
- })
- .catch(function(error) {
- console.log('Error sending message:', error);
- });
- });
- exports.sendLikesNotification = functions.firestore.document('/UserActivity/{userPostId}/likes/{likerUid}')
- .onCreate((snap, context) => {
- const data = snap.data();
- const token = data.userFCMToken
- const followerUsername = data.username;
- const userPicture = data.userPic;
- const plantCommonName = data.plantName;
- const plantCommonNickname = data.plantNickname;
- const activity = data.activityType;
- var payloadBody = ""
- if (activity == "watering") {
- var payloadBody = `${followerUsername} liked that you watered ${plantCommonNickname}! ❤️`
- } else {
- var payloadBody = `${followerUsername} liked that you added ${plantCommonNickname}! ❤️`
- }
- const payload = {
- notification: {
- title: `Your ${plantCommonName} is popular!`,
- body: payloadBody,
- icon: userPicture,
- badge: '1'
- }
- };
- admin.messaging().sendToDevice(token, payload)
- .then(function(response) {
- console.log('Sending following payload:', payload);
- })
- .catch(function(error) {
- console.log('Error sending message:', error);
- });
- });
- exports.sendCommentsNotification = functions.firestore.document('/Comments/{commentId}')
- .onCreate((snap, context) => {
- const data = snap.data();
- var token = ""
- var replyTitle = ""
- var payloadBody = ""
- const commentUsername = data.username;
- const plantCommonName = data.plantName;
- if (!!data.parentCommentUserFCMToken) {
- token = data.parentCommentUserFCMToken
- replyTitle = `You have a new reply! 🙂`
- payloadBody = `${commentUsername} commented on your reply!`
- } else {
- token = data.postUserFCMToken
- replyTitle = `You have a new comment on your post! 🙂`
- if (!!plantCommonName) {
- payloadBody = `${commentUsername} commented on your ${plantCommonName}!`
- } else {
- payloadBody = `${commentUsername} commented on your post!`
- }
- }
- const payload = {
- notification: {
- title: replyTitle,
- body: payloadBody,
- badge: '1'
- }
- };
- admin.messaging().sendToDevice(token, payload)
- .then(function(response) {
- console.log('Sending following payload:', payload);
- })
- .catch(function(error) {
- console.log('Error sending message:', error);
- });
- });
- //MARK - Old schedule async
- // exports.scheduleAsyncMorningNotif = functions.pubsub.schedule('10 08 * * *')
- // .timeZone('America/Chicago')
- // .onRun((context) => {
- // const tsToMillis = admin.firestore.Timestamp.now().toMillis();
- // const today = new Date(tsToMillis + (15 * 60 * 60 * 1000));
- // const userPlants = db.collection('UserPlants');
- // let lastVisible = null;
- // let totalSuccessCount = 0;
- // function handleUserPlantsFCM() {
- // const snapshot = !!lastVisible ? userPlants.where('nextWatering', '<=', today).where('notificationsEnabled', '==', true).orderBy("nextWatering").startAfter(lastVisible).limit(500).get()
- // : userPlants.where('nextWatering', '<=', today).where('notificationsEnabled', '==', true).orderBy("nextWatering").limit(500).get();
- // if (snapshot.empty) {
- // console.log('No matching documents.');
- // return;
- // }
- // snapshot.then(async function(querySnapshot) {
- // console.log('Query Snapshot of UserPlants showing as:', querySnapshot.size);
- // lastVisible = querySnapshot.docs[querySnapshot.docs.length - 1];
- // var messages = [];
- // querySnapshot.forEach((doc) => {
- // const data = doc.data();
- // const { plantName, userFCMToken } = data;
- // if (plantName && userFCMToken) {
- // const message = {
- // notification: {
- // title: 'You have a plant to save! 🌱',
- // body: `Your ${plantName} needs some water - make sure to take care of it! ☔️`,
- // },
- // token: userFCMToken
- // };
- // messages.push(message);
- // } else {
- // console.log('Nil/false on user token, skipping for now');
- // }
- // });
- // if (!!messages.length) {
- // try {
- // const response = await admin.messaging().sendAll(messages);
- // totalSuccessCount += response.successCount;
- // } catch(err) {
- // console.log(err);
- // }
- // messages = [];
- // }
- // handleUserPlantsFCM();
- // });
- // }
- // handleUserPlantsFCM();
- // console.log(totalSuccessCount + ' messages were sent successfully');
- // return null;
- // });
- // exports.scheduleAsyncMorningNotif = functions.pubsub.schedule('10 08 * * *')
- exports.scheduleAsyncMorningNotif = functions.pubsub.schedule('10 08 * * *')
- .timeZone("America/Chicago")
- .onRun((context) => {
- const tsToMillis = admin.firestore.Timestamp.now().toMillis();
- const today = new Date(tsToMillis + 15 * 60 * 60 * 1000);
- const userPlants = db.collection("TestUserPlants");
- var lastVisible = null;
- // let totalSuccessCount = 0;
- var multipleUsers = [];
- function handleUserPlantsFCM() {
- const snapshot = !!lastVisible
- ? userPlants
- .where("nextWatering", "<=", today)
- .where("notificationsEnabled", "==", true)
- .orderBy("nextWatering")
- .startAfter(lastVisible)
- .limit(500)
- .get()
- : userPlants
- .where("nextWatering", "<=", today)
- .where("notificationsEnabled", "==", true)
- .orderBy("nextWatering")
- .limit(500)
- .get();
- if (snapshot.size === 0) {
- console.log("No matching documents.");
- return;
- }
- snapshot.then(querySnapshot => {
- console.log(
- "Query Snapshot of UserPlants showing as:",
- querySnapshot.size
- );
- if (querySnapshot.size === 0) {
- console.log("No matching documents.");
- console.log(
- "*****************************************Sending Messages*************************************************"
- );
- if (!!multipleUsers.length) {
- const matchedMultipleUsers = multipleUsers.filter(
- (plant) => plant.count > 2
- );
- if (!!matchedMultipleUsers.length) {
- const matchedNotifications = matchedMultipleUsers.map(
- (plant) => ({
- notification: {
- title: `You have ${plant.count} plants to water! 🌱 `,
- body: `Your plants need some water - make sure to take care of them! ☔️`,
- },
- token: plant.userFCMToken,
- data: {
- body: `Your plants need some water - make sure to take care of them! ☔️`,
- },
- })
- );
- if (!!matchedNotifications && matchedNotifications.length) {
- try {
- admin
- .messaging()
- .sendAll(matchedNotifications)
- .then((response) => {
- const multipleSuccessCount = response.successCount;
- console.log(
- `${multipleSuccessCount} grouping messages are sent successfully.`
- );
- console.log(matchedMultipleUsers.length, matchedNotifications.length);
- });
- } catch (err) {
- console.log(err);
- }
- } else {
- console.log("There is no grouping messages to be sent!");
- }
- } else {
- console.log("There are no users who have multiple plants.");
- }
- const matchedOneOrTwoUsers = multipleUsers.filter(
- (plant) => plant.count < 3
- );
- if (!!matchedOneOrTwoUsers.length) {
- const matchedNotifications = matchedOneOrTwoUsers.map(
- (plant) => ({
- notification: {
- title: `You have a plant to save! 🌱 `,
- body: `Your ${plant.plantName.toString()} plant needs some water - make sure to take care of it! ☔️`,
- },
- token: plant.userFCMToken,
- data: {
- body: `Your ${plant.plantName.toString()} needs some water - make sure to take care of it! ☔️`,
- },
- })
- );
- if (!!matchedNotifications && matchedNotifications.length) {
- try {
- admin
- .messaging()
- .sendAll(matchedNotifications)
- .then((response) => {
- const multipleSuccessCount = response.successCount;
- console.log(
- `${multipleSuccessCount} messages are sent successfully.`
- );
- console.log(matchedOneOrTwoUsers.length, matchedNotifications.length);
- });
- } catch (err) {
- console.log(err);
- }
- } else {
- console.log("There is no any messages to be sent!");
- }
- } else {
- console.log("There is no any user who has a plant.");
- }
- }
- return;
- }
- lastVisible = querySnapshot.docs[querySnapshot.docs.length - 1];
- // var messages = [];
- querySnapshot.forEach((doc) => {
- const data = doc.data();
- const { plantName, userFCMToken, userRef } = data;
- if (plantName && userFCMToken) {
- // check if user does not exist in multiple users
- if (!multipleUsers.some((plant) => plant.userRef === userRef)) {
- let arr = [];
- const userObj = {
- userRef: userRef,
- userFCMToken: userFCMToken,
- plantName: [plantName],
- count: 1,
- };
- console.log("==============NewUserPlant", plantName);
- multipleUsers.push(userObj);
- } else {
- const existingUserPlant = multipleUsers.find(
- (plant) => plant.userRef === userRef
- );
- console.log(
- "++++++++++++++existingUserPlant:",
- existingUserPlant.plantName[0]
- );
- let arr = [];
- const updatedUserPlant = {
- ...existingUserPlant,
- count: parseInt(existingUserPlant.count) + 1,
- plantName: Array.isArray(existingUserPlant.plantName)
- ? existingUserPlant.plantName.push(plantName)
- : [plantName],
- };
- const updatedMultipleUsers = multipleUsers.map((plant) => {
- if (plant.userRef === userRef) return updatedUserPlant;
- else return plant;
- });
- multipleUsers = updatedMultipleUsers;
- }
- } else {
- console.log("Nil/false on user token, skipping for now");
- }
- });
- handleUserPlantsFCM();
- });
- }
- return handleUserPlantsFCM();
- });
- // exports.scheduleAsyncMorningNotif = functions.pubsub.schedule('10 08 * * *')
- // .timeZone('America/Chicago')
- // .onRun((context) => {
- // const tsToMillis = admin.firestore.Timestamp.now().toMillis();
- // const today = new Date(tsToMillis + (15 * 60 * 60 * 1000));
- //
- // const userPlants = db.collection('UserPlants');
- //
- // let lastVisible = null;
- // let totalSuccessCount = 0;
- // let multipleUsers = [];
- //
- // function handleUserPlantsFCM() {
- // const snapshot = !!lastVisible ? userPlants.where('nextWatering', '<=', today).where('notificationsEnabled', '==', true)
- // .orderBy("nextWatering").startAfter(lastVisible).limit(500).get()
- // : userPlants.where('nextWatering', '<=', today).where('notificationsEnabled', '==', true).orderBy("nextWatering").limit(500).get();
- //
- // if (snapshot.empty) {
- // console.log('No matching documents.');
- // return;
- // }
- //
- // snapshot.then(async function (querySnapshot) {
- // console.log('Query Snapshot of UserPlants showing as:', querySnapshot.size);
- // lastVisible = querySnapshot.docs[querySnapshot.docs.length - 1];
- // querySnapshot.forEach((doc) => {
- // const data = doc.data();
- // const { plantName, userFCMToken, userRef } = data;
- //
- // if (plantName && userFCMToken) {
- //
- // // check if user does not exist in multiple users
- // if (!multipleUsers.some((plant) => plant.userRef === userRef)) {
- // const userObj = {
- // userRef: userRef,
- // userFCMToken: userFCMToken,
- // plantName: [plantName],
- // count: 1
- // };
- // multipleUsers.push(userObj);
- // } else {
- // const existingUserPlant = multipleUsers.find((plant) => plant.userRef === userRef)
- // const updatedUserPlant = { ...existingUserPlant, count: parseInt(existingUserPlant.count) + 1, plantName: existingUserPlant.plantName.push(plantName) }
- // const updatedMultipleUsers = multipleUsers.map(plant => {
- // if (plant.userRef === userRef) return updatedUserPlant
- // else return plant
- // })
- // multipleUsers = updatedMultipleUsers;
- // }
- // } else {
- // console.log('Nil/false on user token, skipping for now');
- // }
- // });
- //
- // handleUserPlantsFCM();
- // });
- // }
- //
- // handleUserPlantsFCM();
- // // console.log(totalSuccessCount + ' messages were sent successfully');
- //
- // if (!!multipleUsers.length) {
- // const matchedMultipleUsers = multipleUsers.filter((plant) => plant.count > 1);
- // if (!!matchedMultipleUsers.length) {
- // const matchedNotifications = matchedMultipleUsers.map((plant) => ({
- // notification: {
- // title: `You have ${plant.count} plants to water! 🌱 `,
- // body: `Your ${plant.plantName.toString()} needs some water - make sure to take care of it! ☔️`,
- // },
- // token: plant.userFCMToken
- // }));
- // if (!!matchedNotifications && matchedNotifications.length) {
- // try {
- // admin.messaging().sendAll(matchedNotifications).then(response => {
- // const multipleSuccessCount = response.successCount;
- // console.log(`${multipleSuccessCount} grouping messages are sent successfully.`)
- // });
- // } catch (err) {
- // console.log(err);
- // }
- // } else {
- // console.log('There is no any grouping messages to be sent!')
- // }
- // } else {
- // console.log('There is no any user who has multiple plants.');
- // }
- // }
- //
- // return null;
- // });
- exports.scheduleEveningNotif = functions.pubsub.schedule('05 18 * * *')
- .timeZone('America/Chicago')
- .onRun(async (context) => {
- const tsToMillis = admin.firestore.Timestamp.now().toMillis();
- const today = new Date(tsToMillis + (8 * 55 * 60 * 1000));
- const userPlants = db.collection('UserPlants');
- let lastVisible = null;
- let totalSuccessCount = 0;
- async function handleFCMToken() {
- const snapshot = !!lastVisible ? userPlants.where('nextWatering', '<=', today).where('notificationsEnabled', '==', true).orderBy("nextWatering").startAfter(lastVisible).limit(500)
- : userPlants.where('nextWatering', '<=', today).where('notificationsEnabled', '==', true).orderBy("nextWatering").limit(500);
- const querySnapshot = await snapshot.get();
- if (querySnapshot.size === 0) {
- console.log('No matching documents.');
- return;
- }
- console.log('Query Snapshot of UserPlants showing as:', querySnapshot.size);
- lastVisible = querySnapshot.docs[querySnapshot.docs.length - 1];
- var messages = [];
- querySnapshot.forEach((doc) => {
- const data = doc.data();
- const { plantName, userFCMToken } = data;
- if (!!plantName && !!userFCMToken) {
- const message = {
- notification: {
- title: 'You have a plant to save! 🌱',
- body: `Your ${plantName} needs some water - make sure to take care of it! ☔️`,
- },
- token: userFCMToken
- };
- messages.push(message);
- } else {
- console.log('Nil/false on user token, skipping for now');
- }
- });
- if (!!messages.length) {
- try {
- const response = await admin.messaging().sendAll(messages);
- totalSuccessCount += response.successCount;
- } catch(err) {
- console.log(err);
- return;
- }
- }
- await handleFCMToken();
- }
- await handleFCMToken();
- console.log(totalSuccessCount + ' messages were sent successfully');
- return;
- });
- exports.sendFeedbackNotification = functions.firestore.document('/UserFeedback/{feedbackId}')
- .onCreate((snap, context) => {
- const data = snap.data();
- const token = data.userFCMToken
- const followerUsername = data.username;
- const userPicture = data.userPic;
- const plantCommonName = data.plantName;
- const plantCommonNickname = data.plantNickname;
- const activity = data.activityType;
- var payloadBody = ""
- if (activity == "watering") {
- var payloadBody = `${followerUsername} liked that you watered ${plantCommonNickname}! ❤️`
- } else {
- var payloadBody = `${followerUsername} liked that you added ${plantCommonNickname}! ❤️`
- }
- const payload = {
- notification: {
- title: `Your ${plantCommonName} is popular!`,
- body: payloadBody,
- icon: userPicture,
- badge: '1'
- }
- };
- admin.messaging().sendToDevice(token, payload)
- .then(function(response) {
- console.log('Sending following payload:', payload);
- })
- .catch(function(error) {
- console.log('Error sending message:', error);
- });
- });
- // exports.runStats = functions.pubsub.schedule('02 08 * * *')
- // .timeZone('America/Chicago')
- // .onRun((context) => {
- // const userPlants = db.collection('UserPlants')
- // const users = db.collection('Users')
- // const plantsSnapshot = userPlants.get();
- // const usersSnapshot = users.get();
- // if (plantsSnapshot.empty) {
- // console.log('No matching documents.');
- // return;
- // }
- // plantsSnapshot.then(async function(querySnapshot) {
- // console.log('Query Snapshot of UserPlants showing as:', querySnapshot.size);
- // });
- // if (usersSnapshot.empty) {
- // console.log('No matching documents.');
- // return;
- // }
- // usersSnapshot.then(async function(querySnapshot) {
- // console.log('Query Snapshot of Users showing as:', querySnapshot.size);
- // });
- // return null;
- // });
[text] backup
Viewer
*** This page was generated with the meta tag "noindex, nofollow". This happened because you selected this option before saving or the system detected it as spam. This means that this page will never get into the search engines and the search bot will not crawl it. There is nothing to worry about, you can still share it with anyone.
Editor
You can edit this paste and save as new: