firebase deploy error in firebase cloud messaging - firebase

I integrate the chat application. when I log in I add fcm token in the firebase database and when sender and receiver chat I got chat notification on both sides.so I did below step
install node.js
I use node version (v13.11.0) and npm version (6.13.7)
then I use npm install -g firebase-tools (firebase-tools#7.16.1 updated 1 package in 18.481s)
firebase login (Already logged in as)
create a folder and add path then execute firebase init cmd after select function then add my project, select language, install npm ( Firebase initialization complete!)
I add below code in index.js
'use strict'
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
exports.sendNotification = functions.database.ref('/Notifications/{receiver_id}/{notification_id}')
.onWrite((data, context) =>
{
const receiver_user_id = context.params.receiver_user_id;
const notification_id = context.params.notification_id;
console.log('We have a notification to send to :' , receiver_user_id);
if (!data.after.val())
{
console.log('A notification has been deleted :' , notification_id);
return null;
}
const DeviceToken = admin.database().ref(`/Users/${receiver_user_id}/device_token`).once('value');
return DeviceToken.then(result =>
{
const token_id = result.val();
const payload =
{
notification:
{
title: "New Chat Request",
body: `you have a new Chat Request, Please Check.`,
icon: "default"
}
};
return admin.messaging().sendToDevice(token_id, payload)
.then(response =>
{
console.log('This was a notification feature.');
});
});
});
execute Firebase deploy command I got below error
=== Deploying to 'notification-ad12a8'...
i deploying functions
i functions: ensuring necessary APIs are enabled...
+ functions: all necessary APIs are enabled
i functions: preparing functions directory for uploading...
**Error: An unexpected error has occurred.**
I tried 3 -4 times but not got any solution.please check code please help me..thank you

Related

How to solve problem Firebase Cloud Messaging error in Firebase Cloud function?

I have some problem about using Firebase Cloud Messaging from Firebase Cloud Functions.
The error message is below. It is from my Firebase Cloud Functions Log console.
Error: An error occurred when trying to authenticate to the FCM servers. Make sure the credential used to authenticate this SDK has the proper permissions.
At first, I follow Firebase Cloud Functions CodeLabs.
https://firebase.google.com/codelabs/firebase-cloud-functions
And at last lab "New Message Notifications", when I insert new message at Web "FriendlyChat" app, there is not display notification message. Then I checked log in Firebase Cloud Functions Log console, there was an error message which I had told.
How to solve problem Firebase Cloud Messaging error in Firebase Cloud function?
Or ... How can I check about cloud functions credential before call FCM?
const functions = require("firebase-functions");
const admin = require("firebase-admin");
admin.initializeApp();
// Sends a notifications to all users when a new message is posted.
exports.sendNotifications = functions.firestore.document('messages/{messageId}').onCreate(
async (snapshot) => {
// Notification details.
const text = snapshot.data().text;
const payload = {
notification: {
title: `${snapshot.data().name} posted ${text ? 'a message' : 'an image'}`,
body: text ? (text.length <= 100 ? text : text.substring(0, 97) + '...') : '',
icon: snapshot.data().profilePicUrl || '/images/profile_placeholder.png',
click_action: `https://${process.env.GCLOUD_PROJECT}.firebaseapp.com`,
}
};
// Get the list of device tokens.
const allTokens = await admin.firestore().collection('fcmTokens').get();
const tokens = [];
allTokens.forEach((tokenDoc) => {
tokens.push(tokenDoc.id);
});
if (tokens.length > 0) {
// Send notifications to all tokens.
const response = await admin.messaging().sendToDevice(tokens, payload);
await cleanupTokens(response, tokens);
functions.logger.log('Notifications have been sent and tokens cleaned up.');
}
});
Thank you in advance.
I solve this problem by set "Enabled" at "Cloud Messaging API (Legacy)" at Project Settings.

How to use algolia with firstore flutter?

I am trying to deploy some cloud functions using algolia search but it gives me some errors.
When deleting this line:
const algoliasearch = require('algoliasearch') and functions that related to algolia, it deploys successfully.
The error is:
=== Deploying to 'ecommerce-8e525'...
i deploying functions
+ functions: Finished running predeploy script.
i functions: ensuring required API cloudfunctions.googleapis.com is enabled...
i functions: ensuring required API cloudbuild.googleapis.com is enabled...
+ functions: required API cloudbuild.googleapis.com is enabled
+ functions: required API cloudfunctions.googleapis.com is enabled
i functions: preparing functions directory for uploading...
i functions: packaged functions (2.92 KB) for uploading
+ functions: functions folder uploaded successfully
The following functions are found in your project but do not exist in your local source code:
onCreateSection(us-central1)
onDeleteCategory(us-central1)
onDeleteSection(us-central1)
onUpdateCategory(us-central1)
onUpdateSection(us-central1)
If you are renaming a function or changing its region, it is recommended that you create the new function first before deleting the old one to prevent event loss.
For more info, visit https://firebase.google.com/docs/functions/manage-functions#modify
? Would you like to proceed with deletion? Selecting no will continue the rest of the deployments. No
i functions: creating Node.js 14 function onCreateSubCategory(us-central1)...
i functions: creating Node.js 14 function onUpdateSubCategory(us-central1)...
i functions: creating Node.js 14 function onDeleteSubCategory(us-central1)...
i functions: creating Node.js 14 function onUpdateMainCategory(us-central1)...
i functions: creating Node.js 14 function onDeleteMainCategory(us-central1)...
i functions: updating Node.js 14 function onDeleteProduct(us-central1)...
i functions: updating Node.js 14 function onCreateCustomer(us-central1)...
i functions: updating Node.js 14 function onUpdateCustomer(us-central1)...
i functions: updating Node.js 14 function onDeleteCustomer(us-central1)...
i functions: cleaning up build files...
Functions deploy had errors with the following functions:
onCreateSubCategory(us-central1)
onDeleteCustomer(us-central1)
onCreateCustomer(us-central1)
onUpdateSubCategory(us-central1)
onUpdateCustomer(us-central1)
onUpdateMainCategory(us-central1)
onDeleteProduct(us-central1)
onDeleteSubCategory(us-central1)
onDeleteMainCategory(us-central1)
To try redeploying those functions, run:
firebase deploy --only "functions:onCreateSubCategory,functions:onDeleteCustomer,functions:onCreateCustomer,functions:onUpdateSubCategory,functions:onUpdateCustomer,functions:onUpd
ateMainCategory,functions:onDeleteProduct,functions:onDeleteSubCategory,functions:onDeleteMainCategory"
To continue deploying other features (such as database), run:
firebase deploy --except functions
Error: Functions did not deploy properly.
This is my code:
const functions = require("firebase-functions");
const admin = require('firebase-admin');
const algoliasearch = require('algoliasearch');
const ALGOLIA_APP_ID = "APP_ID";
const ALGOLIA_ADMIN_KEY = "ADMIN_KEY";
const ALGOLIA_INDEX_NAME = "users";
admin.initializeApp();
const storage = admin.storage();
// When admin create sub category:
exports.onCreateSubCategory = functions.firestore
.document("/subCategories/{subCategoryId}")
.onCreate(async (snapshot, context) => {
const createdSubCategory = snapshot.data();
const subCategoryId = context.params.subCategoryId;
const mainCategoryId = createdSubCategory['main_category_id'];
// add it to main category
admin
.firestore()
.collection("mainCategories")
.doc(mainCategoryId).update({
'sub_categories_ids': admin.firestore.FieldValue.arrayUnion(subCategoryId)
});
});
// When admin update sub category:
exports.onUpdateSubCategory = functions.firestore.document("/subCategories/{subCategoryId}").onUpdate(async (change, context) => {
const updatedSubCategoryData = change.after.data();
const oldSubCategoryData = change.before.data();
const productsRef = admin.firestore().collection('products');
// case of updating image
// delete old image from storage
var oldImage = oldSubCategoryData['image_id'];
const bucket = storage.bucket();
const path = "subCategories/" + oldImage;
await bucket.file(path).delete();
// case of updating name
// update sub category name for related products
const productsQuerySnapshot = await productsRef.where('sub_category', '==', oldSubCategoryData['name']).get();
productsQuerySnapshot.forEach(doc => {
productsRef.doc(doc.id).update({
"sub_category": updatedSubCategoryData['name'],
"categories": admin.firestore.FieldValue.arrayRemove(oldSubCategoryData['name']),
"categories": admin.firestore.FieldValue.arrayUnion(updatedSubCategoryData['name']),
})
})
})
// When admin delete sub category:
exports.onDeleteSubCategory = functions.firestore.document("/subCategories/{subCategoryId}").onDelete(async (snapshot, context) => {
const subCategoryData = snapshot.data();
const imageId = subCategoryData['image_id'];
console.log('image_id is ',imageId);
// 1- delete sub category image from storage
const bucket = storage.bucket();
const path = "subCategories/" + imageId;
await bucket.file(path).delete();
// 2- delete sub category from products
const productsRef = admin.firestore().collection('products');
const productsQuerySnapshot = await productsRef.where('sub_category', '==', subCategoryData['name']).get();
productsQuerySnapshot.forEach( async doc => {
await productsRef.doc(doc.id).update({
'sub_category': {},
'categories': admin.firestore.FieldValue.arrayRemove(subCategoryData['name'])
})
})
})
//4) when admin update main category
exports.onUpdateMainCategory = functions.firestore.document("/mainCategories/{mainCategoryId}").onUpdate(async (change, context) => {
const updatedMainCategoryData = change.after.data();
const oldMainCategoryData = change.before.data();
const mainCategoryId = context.params.mainCategoryId;
//1- when admin change main category name
/// change main category name for related products
const productsRef = admin.firestore().collection('products');
const productsQuerySnapshot = await productsRef.where('categories', 'array-contains', oldMainCategoryData['name']).get();
productsQuerySnapshot.forEach( async doc =>{
await productsRef.doc(doc.id).update({
'categories': FieldValue.arrayRemove(oldMainCategoryData['name']),
'categories': admin.firestore.FieldValue.arrayUnion(updatedMainCategoryData['name'])
})
})
//2- when admin remove subCategory
/// delete them from subCategories collection
const oldSubCategoriesIds = oldMainCategoryData['sub_categories_ids'];
const updatedSubCategories = updatedMainCategoryData['sub_categories_ids'];
let difference = oldSubCategoriesIds.filter(x => !updatedSubCategories.includes(x));
difference.forEach(async id =>{
await admin.firestore().collection('subCategories').doc(id).delete();
})
})
// 5) when admin delete main category
exports.onDeleteMainCategory = functions.firestore.document("/mainCategories/{mainCategoryId}").onDelete(async (snapshot, context) => {
const mainCategoryData = snapshot.data();
const subCategoriesIds = mainCategoryData['sub_categories_ids'];
// delete category from products
const productsRef = admin.firestore().collection('products');
const productsQuerySnapshot = await productsRef.where('categories', 'array-contains', mainCategoryData['name']).get();
productsQuerySnapshot.forEach(async doc =>{
await productsRef.doc(doc.id).update({
'categories': admin.firestore.FieldValue.arrayRemove(mainCategoryData['name'])
})
})
// delete sub categories
subCategoriesIds.forEach(async id =>{
await admin.firestore().collection('subCategories').doc(id).delete();
})
})
// 6) when admin delete product
exports.onDeleteProduct = functions.firestore.document("/products/{productId}").onDelete(async (snapshot, context) => {
const categoryData = snapshot.data();
const imageId = categoryData['image_id'];
// delete it's image from storage
const bucket = storage.bucket();
const path = "products/" + imageId;
return bucket.file(path).delete();
})
// 7) onCreate Customer
exports.onCreateCustomer = functions.firestore
.document('users/{userId}')
.onCreate( async (snap, context) => {
const newValue = snap.data();
newValue.objectID = snap.id;
var client = algoliasearch(ALGOLIA_APP_ID, ALGOLIA_ADMIN_KEY);
var index = client.initIndex(ALGOLIA_INDEX_NAME);
index.saveObject(newValue);
console.log("Finished");
});
// 8) onUpdate Customer
exports.onUpdateCustomer = functions.firestore
.document('users/{userId}')
.onUpdate( async (snap, context) => {
const afterUpdate = snap.after.data();
afterUpdate.objectID = snap.after.id;
var client = algoliasearch(ALGOLIA_APP_ID, ALGOLIA_ADMIN_KEY);
var index = client.initIndex(ALGOLIA_INDEX_NAME);
index.saveObject(afterUpdate);
});
// 9) onDelete Customer
exports.onDeleteCustomer = functions.firestore
.document('users/{userId}')
.onDelete( async (snap, context) => {
const oldID = snap.id;
var client = algoliasearch(ALGOLIA_APP_ID, ALGOLIA_ADMIN_KEY);
var index = client.initIndex(ALGOLIA_INDEX_NAME);
index.deleteObject(oldID);
});
Edit I tried to run with "firebase deploy --only function --debug and this is the result "
Functions deploy had errors with the following functions: onCreateSubCategory(us-central1) onDeleteCustomer(us-central1) onDeleteProduct(us-central1) onCreateCustomer(us-central1) onDeleteMainCategory(us-central1) onUpdateMainCategory(us-central1) onUpdateCustomer(us-central1) onDeleteSubCategory(us-central1) onUpdateSubCategory(us-central1) To try redeploying those functions, run: firebase deploy --only "functions:onCreateSubCategory,functions:onDeleteCustomer,functions:onDeleteProduct,functions:onCreateCustomer,functions:onDeleteMainCategory,functions:onUpd ateMainCategory,functions:onUpdateCustomer,functions:onDeleteSubCategory,functions:onUpdateSubCategory" To try redeploying those functions, run: firebase deploy --only "functions:onCreateSubCategory,functions:onDeleteCustomer,functions:onDeleteProduct,functions:onCreateCustomer,functions:onDeleteMainCategory,functions:onUpdateMainCategory,functions: onUpdateCustomer,functions:onDeleteSubCategory,functions:onUpdateSubCategory"
To continue deploying other features (such as database), run: firebase deploy --except functions [2021-07-31T19:29:21.057Z] Error during update for projects/ecommerce-8e525/locations/us-central1/functions/onCreateSubCategory: firebase deploy --only "functions:onCreateSubCategory,functions:onDeleteCustomer,functions:onDeleteProduct,functions:onCreateCustomer,functions:onDeleteMainCategory,functions:onUpdateMainCategory,functions: onUpdateCustomer,functions:onDeleteSubCategory,functions:onUpdateSubCategory" To continue deploying other features (such as database), run: firebase deploy --except functions [2021-07-31T19:29:21.057Z] Error during update for projects/ecommerce-8e525/locations/us-central1/functions/onCreateSubCategory: [2021-07-31T19:29:21.058Z] Error during update for projects/ecommerce-8e525/locations/us-central1/functions/onDeleteCustomer: [2021-07-31T19:29:21.058Z] Error during update for projects/ecommerce-8e525/locations/us-central1/functions/onDeleteProduct: [2021-07-31T19:29:21.058Z] Error during update for projects/ecommerce-8e525/locations/us-central1/functions/onCreateCustomer: [2021-07-31T19:29:21.058Z] Error during update for projects/ecommerce-8e525/locations/us-central1/functions/onDeleteMainCategory: [2021-07-31T19:29:21.058Z] Error during update for projects/ecommerce-8e525/locations/us-central1/functions/onUpdateMainCategory: [2021-07-31T19:29:21.058Z] Error during update for projects/ecommerce-8e525/locations/us-central1/functions/onUpdateCustomer: firebase deploy --only "functions:onCreateSubCategory,functions:onDeleteCustomer,functions:onDeleteProduct,functions:onCreateCustomer,functions:onDeleteMainCategory,functions:onUpd ateMainCategory,functions:onUpdateCustomer,functions:onDeleteSubCategory,functions:onUpdateSubCategory"
To continue deploying other features (such as database), run: firebase deploy --except functions [2021-07-31T19:29:21.057Z] Error during update for projects/ecommerce-8e525/locations/us-central1/functions/onCreateSubCategory: [2021-07-31T19:29:21.058Z] Error during update for projects/ecommerce-8e525/locations/us-central1/functions/onDeleteCustomer: [2021-07-31T19:29:21.058Z] Error during update for projects/ecommerce-8e525/locations/us-central1/functions/onDeleteProduct: [2021-07-31T19:29:21.058Z] Error during update for projects/ecommerce-8e525/locations/us-central1/functions/onCreateCustomer: [2021-07-31T19:29:21.058Z] Error during update for projects/ecommerce-8e525/locations/us-central1/functions/onDeleteMainCategory: [2021-07-31T19:29:21.058Z] Error during update for projects/ecommerce-8e525/locations/us-central1/functions/onUpdateMainCategory: [2021-07-31T19:29:21.058Z] Error during update for projects/ecommerce-8e525/locations/us-central1/functions/onUpdateCustomer: [2021-07-31T19:29:21.059Z] Error during update for projects/ecommerce-8e525/locations/us-central1/functions/onDeleteSubCategory: [2021-07-31T19:29:21.059Z] Error during update for projects/ecommerce-8e525/locations/us-central1/functions/onUpdateSubCategory:
Error: Functions did not deploy properly.
Remove these installations and reinstall again solves the problem .
npm install -g firebase-tools
firebase login
firebase init
cd functions
npm install algoliasearch --save
firebase functions:config:set algolia.appid="YOUR_APP_ID" algolia.apikey="YOUR_API_KEY"

Error: Functions did not deploy properly (delete callable function)

I am trying to deploy a delete function into the firebase cloud functions but then I get this error Error: Functions did not deploy properly. I have installed all the dependences e.g firebase-tools. Some of the steps I went through setting up the project are in these:
This is the code I am trying to deploy:
const admin = require('firebase-admin');
const firebase_tools = require('firebase-tools');
const functions = require('firebase-functions');
admin.initializeApp();
exports.mintAdminToken = functions.https.onCall(async (data, context) => {
const uid = data.uid;
const token = await admin
.auth()
.createCustomToken(uid, { admin: true });
return { token };
});
exports.recursiveDelete = functions
.runWith({
timeoutSeconds: 540,
memory: '2GB'
})
.https.onCall(async (data, context) => {
// Only allow admin users to execute this function.
if (!(context.auth && context.auth.token && context.auth.token.admin)) {
throw new functions.https.HttpsError(
'permission-denied',
'Must be an administrative user to initiate delete.'
);
}
const path = data.path;
console.log(
`User ${context.auth.uid} has requested to delete path ${path}`
);
// Run a recursive delete on the given document or collection path.
// The 'token' must be set in the functions config, and can be generated
// at the command line by running 'firebase login:ci'.
await firebase_tools.firestore
.delete(path, {
project: process.env.GCLOUD_PROJECT,
recursive: true,
yes: true,
token: functions.config().fb.token
});
return {
path: path
};
});
As from the comments, running the following solved the problem
npm install firebase-functions#latest firebase-admin#latest --save
npm install -g firebase-tools

Dialogflow - Fulfillment Inline Editor(Firebase) is timeout

I am testing with Dialogflow using Firebase project.
The Firebase Project is already used as an android backend. (Firestore)
Now, I am trying to attach chatbot.
This github code is what I want.
I create a new Dialogflow Agent, it refers to the Firebase project.
Enable Fullfillment Inline Editor, and I copy&paste a code from upper github code.
'use strict';
const functions = require('firebase-functions');
const admin = require('firebase-admin');
const {WebhookClient} = require('dialogflow-fulfillment');
process.env.DEBUG = 'dialogflow:*'; // enables lib debugging statements
admin.initializeApp(functions.config().firebase);
const db = admin.firestore();
exports.dialogflowFirebaseFulfillment = functions.https.onRequest((request, response) => {
const agent = new WebhookClient({ request, response });
function writeToDb (agent) {
const databaseEntry = agent.parameters.databaseEntry;
const dialogflowAgentRef = db.collection('dialogflow').doc('agent');
return db.runTransaction(t => {
t.set(dialogflowAgentRef, {entry: databaseEntry});
return Promise.resolve('Write complete');
}).then(doc => {
agent.add(`Wrote "${databaseEntry}" to the Firestore database.`);
}).catch(err => {
console.log(`Error writing to Firestore: ${err}`);
agent.add(`Failed to write "${databaseEntry}" to the Firestore database.`);
});
}
let intentMap = new Map();
intentMap.set('WriteToFirestore', writeToDb);
agent.handleRequest(intentMap); // Here is index.js:51
});
This is very simple.
It just writes a text into the Firestore.
That's all.
I deployed this fulfillment and linked to an Intent.
In case of first conversation after deploy, I can find below log in Firebase Cloud Functions.
Error: No handler for requested intent
at WebhookClient.handleRequest (/user_code/node_modules/dialogflow-fulfillment/src/dialogflow-fulfillment.js:317:29)
at exports.dialogflowFirebaseFulfillment.functions.https.onRequest (/user_code/index.js:51:9)
at cloudFunction (/user_code/node_modules/firebase-functions/lib/providers/https.js:57:9)
And after some times, when I retry again, I can find below logs in the Firebase Cloud Functions.
dialogflowFirebaseFulfillment - Function execution took 60002 ms, finished with status: 'timeout'
I don't know what I am missing...
It was my fault.
The key of intentMap should be same with Intent name.
After I fix it, it works fine.

Flutter: Firebase Pushnotification On Data Change

After getting the comment, i have deployed this folowing code to my firebase project and it was successfully deploed!.But there is no notifications been send to me.
Please check my Firebase Realtime database Screenshot here for better understanding.
[ITS SOLVED NOW:IT WILL SEND NOTIFICATIONS TO ONLY ONE ID ie My Admin Device]
WORKING CODE:
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firbase);
exports.codeformypeople = functions.database.ref('items/{id}').onWrite(evt => {
const payload = {
notification: { title: 'New Customer Requested', body: 'Touch to Open The App', badge: '1', sound: 'default', }
};
const token ="Lsn-bHfBWC6igTfWQ1-h7GoFMxaDWayKIpWCrzC";//replace with ur token
if (token) {
console.log('Toke is availabel .');
return admin.messaging().sendToDevice(token, payload);
} else {
console.log('token error');
}
});
[
SEE THIS VIDEO LINK FOR MORE DETAILS
note:If your app is opened and minmized then it will show notification,but if the app is opened and you are using,or if the app is terminated force close then it will not work!!
You can use firebase cloud function to trigger notification. Here is snippet of cloud functions which i am using to trigger notification:
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
exports.pushNotification = functions.database.ref('/Notifications/{pushId}')
.onWrite(( change,context) => {
console.log("Push Notification event triggered");
var request = change.after.val();
var payload = {
data:{
username: request.userName,
}
};
admin.messaging().sendToDevice(request.userTokenId, payload)
.then(function(response){
console.log("Successfully sent message: ",response);
console.log(response.results[0].error);
})
.catch(function(error){
console.log("Error sending message: ", error)
})
})
Below i have provided my notification structure, you can see below.This function will trigger if any new data is being pushed in database notification node. To see what is output/error you are getting when this function is trigger go to firebase admin panel > Functions > Logs.
You have deployed function code perfectly, but you forgot to add refresh tokenId in your database as you can see in above picture i am saving userTokenId in my database and in function admin.messaging().sendToDevice(request.userTokenId, payload) i am using that tokenId, this tokenId is used to send notification to particular device, you can get this tokenId using FirebaseInstanceId.getInstance().getToken() and save this in your fbproject1 > items database sturcture. please refer this & this

Resources