Firebase onWrite Trigger - Disable trigger on update - android

How do I do this? I used the code below but it is not working. I still receive notification when I update my Database
exports.sendNewPostNotif = functions.database.ref('/News/{ID}').onWrite(event => {
const announce_data = event.data.val();
const announce_data_type = announce_data.categ_post;
const announce_data_title = announce_data.title_post;
const announce_data_uid = announce_data.uid; id
const announce_post_key = announce_data.postkey;
if(!event.data.val()) {
return console.log('No data');
}
if(event.data.previous.exist()) {
return;
}
Whenever I send a new content, it'll go through the onWrite event then send the notification. Mmy current issue is whenever I edit the post, it'll send a notification which I do not require. I tried the above and it works as I receive no notification when I update the news content BUT I don't receive a notification when I create a new content.

If you only want your function to run when the node is created, and not when it is updated or deleted, you can use the onCreate trigger:
exports.sendNewPostNotif = functions.database.ref('/News/{ID}').onCreate(event => {
See the Firebase documentation on database trigger types and the blog post where these are introduced.

Related

how to send touch event from one app to another app

I have developed screen casting app. I am making connection using twilio but I want to share touch events from receiver(participant) to sender(host) as a live data. Is there any possible solution to simplify this?
If you are using Twilio Video for this connection then you can use the DataTrack API to send arbitrary data over your connection.
You can create a LocalDataTrack object:
const { LocalDataTrack } = require(`twilio-video`);
const dataTrack = new LocalDataTrack();
Connect it to a room, either by sending it as part of the tracks option when connecting, or by publishing it to the room after a connection has been made.
const { connect } = require('twilio-video');
const room = await connect('$TOKEN', {
name: 'my-chat-room',
tracks: [dataTrack]
});
You can send a message down the data track once it is published:
dataTrack.send(message)
And you can receive data track messages by subscribing to the track and listening for the message event:
participant.on('trackSubscribed', track => {
console.log(`Participant "${participant.identity}" added ${track.kind} Track ${track.sid}`);
if (track.kind === 'data') {
track.on('message', data => {
console.log(data);
});
}
});
See the documentation for more detail.

How to make the React Native Gifted Chat icon change if the chat isn't sent to server?

I use react native gifted chat, and I want that when a user fails to send a chat to the server then the icon in the bubble changes?
Maybe if a user fails to send a message, an icon like this will appear:
Thank you, please help
I know it was a long time ago, but maybe it can help someone. If you are using Hooks and your messages array is defined like this const [messages, setMessages] = useState();
So, when tap on Send, you can add a new message to your state. Important to add pending and sent properties like
yourMessage.pending = true;
yourMessage.sent = false;
So, when you have the backend response, you can update
yourMessage.pending = false;
yourMessage.sent = true;
Finally, update the message state
setMessages(previousMessages => {
const index = previousMessages.findIndex(aMessage => aMessage._id == yourMessage._id);
const newArr = [...previousMessages];
newArr[foundIndex] = yourMessage;
return newArr;
});

React Native: Handle silent push notification

Im using react-native-firebase for handling push notification for our React Native app (for android and iOS).
I noticed that there is only have 1 callback for a push notification that is received when the app is running (foreground or background) and not when its closed or killed.
firebase
.notifications()
.onNotification(notification => {
console.log('Notification received');
);
But if the app is closed or killed, it will just put the notification in the tray and will not execute the console.log above.
Then enter silent push notification. So when I just send data part in the payload of the notification and even if app is in foreground, the callback above wont be triggered.
I don't see other callbacks that would help on receiving silent push notifications.
So how do we handle push notification in the javascript part?
You don't need additional packages like suggested in other answers.
Use RNFirebase.io, you can handle this easily.
If you receive Notification if App is in Background, you have to handle it by your own to display this Notification. As an example see my init-Method for Push-Notifications.
import firebase from 'react-native-firebase';
const notifications = firebase.notifications();
....
notifications.onNotification((notif) => {
notif.android.setChannelId('app-infos');
notifications.displayNotification(notif);
});
You do it with displayNotification. But make sure, that you set the Notification-Channel before calling it, because else it wouldn't work on >= Android 8.0
BTW: Make sure, that you fully setup Firebase and grant all needed Permissions to be able to listen for Notifications if App is closed or in Background. (https://rnfirebase.io/docs/v5.x.x/notifications/android)
Appendix
I add this as example to show how I implemented the firebase-notification-stuff as a tiny library (remove the redux-stuff if you don't need it):
import firebase from 'react-native-firebase';
import { saveNotificationToken } from 'app/actions/firebase';
import reduxStore from './reduxStore';
import NavigationService from './NavigationService';
const messaging = firebase.messaging();
const notifications = firebase.notifications();
const crashlytics = firebase.crashlytics();
function registerNotifChannels() {
try {
// Notification-Channels is a must-have for Android >= 8
const channel = new firebase.notifications.Android.Channel(
'app-infos',
'App Infos',
firebase.notifications.Android.Importance.Max,
).setDescription('General Information');
notifications.android.createChannel(channel);
} catch (error) {
crashlytics.log(`Error while creating notification-channel \n ${error}`);
}
}
// This is the Promise object that we use to initialise the push
// notifications. It will resolve when the token was successfully retrieved. The
// token is returned as the value of the Promise.
const initPushNotifs = new Promise(async (resolve, reject) => {
try {
const isPermitted = await messaging.hasPermission();
if (isPermitted) {
registerNotifChannels();
try {
const token = await messaging.getToken();
if (token) {
resolve(token);
}
} catch (error) {
crashlytics.log(`Error: failed to get notification-token \n ${error}`);
}
}
} catch (error) {
crashlytics.log(`Error while checking notification-permission\n ${error}`);
}
// If we get this far then there was no token available (or something went
// wrong trying to get it)
reject();
});
function init() {
// Initialise the push notifications, then save the token when/if it's available
initPushNotifs.then(token => reduxStore.dispatch(saveNotificationToken(token)));
// Save the (new) token whenever it changes
messaging.onTokenRefresh(token => reduxStore.dispatch(saveNotificationToken(token)));
notifications.onNotification((notif) => {
notif.android.setChannelId('app-infos');
notifications.displayNotification(notif);
});
notifications.onNotificationOpened((notif) => {
const { notification: { _data: { chatroom: chatRoomId } } = {} } = notif;
if (chatRoomId) {
NavigationService.navigate('ChatRoom', { chatRoomId });
}
});
}
export default {
init,
};
With this, only go to your index.js file (or your root-file for your app, how ever it will be named) and call the init-Metod:
...
import LPFirebase from 'lib/LPFirebase';
LPFirebase.init();

How to set a FCM based alarm using firebase cloud functions?

I am working on Firebase FireStore and Firebase real time database apps,
how can I set an alarm (based on a value set by the user) on android using firebase cloud functions?
There is currently no one-time scheduling functionality in Cloud Functions. You will have to provide your own scheduling mechanism, and that could trigger an HTTP function that deals with Firestore or Realtime Database.
You can use Javacript native function in Firebasefunctions -
setTimeOut()
setInterval()
for triggering some events .
Working for me.My use case is to trigger some API after each 5mins.
Sample Code -
exports.process_sms = functions.https.onRequest((req, res) => {
admin.database().ref(FIREBASE_DB + '/sms_new').once('value').then(function(users) {
let sms_array = [];
users.forEach(function(user) {
user.forEach(function(sms) {
if (sms.val().status == 0) {
sms_array.push(sms);
}
});
});
let i = 0;
let interval = setInterval(function() {
// do your work ... and it gets repeated after 2 sec
}, 2000);
res.status(200).send("Sms processing Done");
});
});

A phone call notification simulation using ionic framework

I want to send a push notification from server to an ionic client and show this notification in client like a phone call (mobile device should play a sound and show 'Accept' or 'Reject' buttons with caller information). It should work if mobile app is not running or in background, that's why I decided to use FCM messages.
this.storage.get('firebase_token').then((token) => {
console.log('Orders get firebase token and call register. Token: ' + token);
this.agentService.registerPushNotifications(token, () => {
this.firebase.onNotificationOpen().subscribe((notification) => {
// How to open the app and show the page with a ringtone ??
});
});
});
How can I open the app and show the call page with a ringtone in incoming push notification? Or maybe there is a better way for this kind of feature.
What you are asking for (the same format like a phone call) isn't possible with Ionic. You can however redirect the user to a view inside the application where you ask him to take action.
Take the following example for push notification. In app.components.ts I initialize this function when the platform is ready
initializePushNotifications() {
let pushObject = this.push.init({
android: {
senderID: 'Your ID Here',
icon: 'logo'
},
ios: {
alert: true,
badge: false,
sound: true
},
windows: {}
});
if (!pushObject['error']) {
pushObject.on('registration').subscribe((data: RegistrationEventResponse) => {
// Whatever you want to do
}, err => {
console.log('Couldnt register:', err);
})
pushObject.on('notification').subscribe((data: any) => {
let self = this;
// When the user click the push notification
if (!data.additionalData.foreground) {
switch (data.additionalData.entity_type) {
case 'takeAction':
this.openView(data.additionalData.user_name, data.additionalData.id);
break;
......
}
}
});
pushObject.on('error').subscribe((e: any) => {
console.log(e.message);
});
} else {
console.error(pushObject);
}
}
See, in the pushed message we add an object under the key additionalData where you can pass whatever you want. You can pass something like entity_type with the value takeAction. When the user click it, you can open a new view and pass additional parameters like the name of the user and the id of the entity or whatever.
On this screen you can open an alert asking the user to click yes or no and based on his input you fire the correct request.
Note
I know this is different from what you were asking for but your request cannot be fulfilled using Ionic.

Categories

Resources