How to integrate React native navigation with AWS Amplify push notifications in android? - react-native-navigation

I am trying to get FCM push notifications working in my react native project for android with react-native-notification library and aws-amplify. I have an issue with PushNotification.onRegister method is not called in android to get device token to send remote notifications.How can I make these two library working together in my react native project?
I followed aws-amplify documentation https://aws-amplify.github.io/docs/js/start?ref=amplify-rn-btn&platform=react-native
to include amplify library in react native project.
I then added push notifications set up as per https://aws-amplify.github.io/docs/js/push-notifications
I have included react-native-navigation library to support navigation in my react-native app as per
https://wix.github.io/react-native-navigation/#/docs/Installing
After the installation react-native navigation library pushNotification.onRegister method is not getting called to receive device token without which I am unable to send push notifications in android.
I have push notifications configured in App.js as per below
import PushNotification from '#aws-amplify/pushnotification';
import Analytics from '#aws-amplify/analytics';
import Auth from '#aws-amplify/auth';
// retrieve temporary AWS credentials and sign requests
Auth.configure(awsconfig);
// send analytics events to Amazon Pinpoint
Analytics.configure(awsconfig);
console.log(PushNotification);
PushNotification.configure(awsconfig);
Then in the constructor of App.js I am registering for PushNotification events.
Navigation.events().registerAppLaunchedListener(() => {
PushNotification.onNotification((notification) => {
// Note that the notification object structure is different from Android and IOS
console.log('in app notification', notification);
// required on iOS only (see fetchCompletionHandler docs: https://facebook.github.io/react-native/docs/pushnotificationios.html)
notification.finish(PushNotificationIOS.FetchResult.NoData);
});
// get the registration token
PushNotification.onRegister((token) => {
Alert.alert(token);
this.setState({token:token});
console.log('in app registration', token);
});
// get the notification data when notification is opened
PushNotification.onNotificationOpened((notification) => {
console.log('the notification is opened', notification);
});
});
This set up works fine and PushNotification.onRegister event is called and device token is getting printed if I don't include react-native-navigation library.
In iOS I am able to get device token with react-native-navigation library but in android it is not working. Any pointers on this issue would be greatly appreciated!

See here: https://github.com/aws-amplify/amplify-js/issues/2541#issuecomment-455245033
the Android app calls .onRegister() once only, when the app/device is completely new. The calls afterwards seems to load from cache.

Related

React native and IBM Watson

I have been using expo to build a react native app and would like to integrate an IBM Watson chatbot onto my platform. When I import the module however I receive a lot of error messages as core node modules such as os and fs seem to be missing, but aren't downloaded with node.js for some reason. When I try and add these manually, the HTTPS module is missing the index.js file. Is there any way for me to find this file or resolve this problem another way?
It's not completely clear from your question but I shall assume that you are using the Node SDK for Watson Assistant. This is designed to be run in a Node.js environment which a react native JavaScript bundle is not (with or without expo). That's why you are missing key libraries like os and fs which the Node SDK expects. Installing fs won't resolve your problem because it also expects a Node.js environment to work, hence why there are react native specific fs libraries that are able to use ios and android code to interact with the file system of the phone.
What you should be attempting is running the Node SDK on an independent server and running simple api requests using libraries like axios or for more robust production systems graphql so that your architecture will approximate this high level design.
a high level architecture diagram which shows a phone connected by an arrow reading axios api request to another box labelled cloud hosted server. From this box another arrow labelled Node SDK is pointing to another box labelled Watson Assistant
Web applications are similarly limited. The code run on the user's browsers can't directly use the Watson Assistant SDK, these requests to Watson Assistant need to be run by a server. There is an example starter Watson Assistant web application that does this. If you run or host this application you can use the same server for your requests (although bear in mind this simple app and shared traffic probably isn't scalable for anything but a proof of concept).
So rather than running the api requests to Watson Assistant directly you run them to this domain of the server and then the necessary endpoint. The server in the example app is set up to accept requests to start the session at <your domain>/api/session and to send messages at <your domain>/api/message
You optionally can run direct api calls to Watson Assistant from a react native app without the SDK. It's not advisable because you would need to store your private keys on the device where they could be viewed by anyone.
Here is a functional component that is able to complete api calls direct to Watson Assistant using the v1 of the message tool without the SDK. BUT IT IS NOT ADVISED BECAUSE I MUST STORE MY KEYS INSECURELY.
import React, { useState } from 'react';
import { View, Text, TouchableOpacity } from 'react-native';
import axios from 'axios';
import base64 from 'react-native-base64';
const workspace = ''; //replace with your own workspace id
const key = ''; //replace with your own key
const encodedKey = base64.encode(`apikey:${key}`);
// the following url will be different depending on where you host your Watson Assistant
// this is for Frankfurt as an example hence eu-de in the domain name
const assistantInstance =
'https://api.eu-de.assistant.watson.cloud.ibm.com/instances/<This is your own>/v1'; //replace with your own
const ExampleComponent = () => {
const [response, setResponse] = useState('');
const sendMessage = () => {
axios
.post(
`${assistantInstance}/workspaces/${workspace}/message?version=2018-09-20`,
{
input: { text: 'This is the message' },
},
{
headers: {
Authorization: `Basic ${encodedKey}`,
'Content-Type': 'application/json',
},
},
)
.then((data: any) => {
console.log(data);
setResponse('Got response');
})
.catch((err: any) => {
console.log(err);
setResponse('Got an error');
});
};
return (
<View>
<Text>{response}</Text>
<TouchableOpacity
onPress={() => {
sendMessage();
}}
>
Send message
</TouchableOpacity>
</View>
);
};
export default ExampleComponent;
The next complication you will find is that you will need to add code to store the context returned in the response otherwise your state is lost. Your body would end up looking something like
{
input: { text: 'This is the message' },
context: savedContextObject
},
The newer version of the API has a stateful version which you may want to use instead. You can use this axios as a pattern for constructing whatever requests your prefer.
For the third and final time PLEASE DO NOT SAVE TO THE JS FILE YOUR API KEY as I do here. This is just as an example and for proof of concepts. Anyone who downloads your app will be able to unzip your apk and read these strings in your generated JS bundle unencrypted!

BuildFire: Push Notification Testing

I'm have a plugin that I'd like to send push notifications with. Referencing the BuildFire SDK Wiki, I've followed the documentation, but never received any notifications. As a trouble shooting step I've created a bare bones plugin that does nothing else aside from scheduling a push notification.
Here's the code that I'm using:
let now = new Date();
const fiveMinutes = (1000 * 60 * 5);
const sendAt = new Date(now.getTime() + fiveMinutes);
buildfire.notifications.pushNotification.schedule({
title:"Notification title"
,text:"Notification text"
,at: sendAt
},function(e){
if(e) console.error(e);
});
I'm testing this using a simple test app, from within the BuildFire Previewer app. As this is not a real app, it doesn't have any certificates for Push Notification. Can I receive the pushNotification SDK calls from within a test app via the Previewer that doesn't have any certificates?
Additionally, I don't receive any errors when testing via the SDK or the control panel. I do get the the callback function as expected, and no exception data in returned.
You are correct. The Previewer app will not allow you to send push notifications properly and here is why...
The previewer app is set up with a certificate. However, When your hot loaded app sends a push notification to queue up in the server. It will not find a certificate matching your hot loaded app id. And thus fail on the server.

How to catch Facebook messaging_optins with Azure Bot Channels Registration + Botbuilder SDK?

I've got a chatbot up and running, built using Node.JS Microsoft Bot Framework, and deployed to an Azure server as a Web App, with a Bot Channels Registration resource as the frontend endpoint.
This Bot Channels Registration is connected to Facebook Messenger (via a FB App) - meaning, the webhook for the Facebook App points to https://facebook.botframework.com/api/v1/bots/<BOT_CHANNELS_REGISTRATION_RESOURCE_NAME>.
This all works well for normal chat functionality.
However, I'd now like to add an opt-in checkbox to a separate web page I have. This checkbox works by pinging FB, which then sends a very specific payload to the already configured bot webhook.
{
"recipient":{
"id":"<PAGE_ID>"
},
"timestamp":<UNIX_TIMESTAMP>,
"optin":{
"ref":"<PASS_THROUGH_PARAM>",
"user_ref":"<UNIQUE_REF_PARAM>"
}
}
My question is this:
How does the Bot Channels Registration receive and handle the above payload? Will it just automatically forward it to the Messaging Endpoint I have configured in the Bot Channels Registration settings? Or will it get stuck, and never reach my actual bot Web App?
Finally, if it does reach my normal messages endpoint, how can I handle the specific payload with my botbuilder.ChatConnector() listener? Given that my web app code looks like (in essence)
var restify = require('restify');
var builder = require('botbuilder');
var dialogues = require('./dialogues');
var chatbot = function (config) {
var bot = {};
chatbot.listen = function () {
var stateStorage = new builder.MemoryBotStorage();
var connector = new builder.ChatConnector({
appId: process.env.APP_ID,
appPassword: process.env.APP_PASSWORD
});
bot = new builder.UniversalBot(connector, function (session) {
session.beginDialog(dialogues.base(bot).name);
}).set('storage', stateStorage);
return connector.listen();
};
return chatbot;
}
var server = restify.createServer();
// Listen for messages from users
server.post('/api/messages', chatbot.listen());
server.listen(process.env.port, function () {
console.log('%s listening to %s', server.name, server.url);
});
Thanks!
EDIT: I've figured out how to handle the above payload within my messaging endpoint - by adding a server.pre() handler to my server, e.g.
server.pre(function (req, res, next) {
if (req.body && req.body.optin_payload_specific_field){
// handle opt-in payload
} else {
return next();
}
});
However, via extra logging lines, it seems the opt-in payload isn't even making it to this endpoint. It seems to be stopped within the Bot Channels Registration. Currently looking for a way to resolve that major roadblock.
So, per #JJ_Wailes investigation, it seems like this is not a supported feature (in fact, it's a current feature request). See his comments on the original post for more details.
However, I did find a half-workaround to capture the user_ref identifier generated by the checkbox_plugin, for those interested:
1) From your external site, follow the steps from the documentation here for sending the initial user_ref to FB. FB will then make a callout to your bot, but per the above, that gets blocked by the Bot Channels Registration piece, so it's ignored.
2) From that same external site, use the user_ref to send a message to the user (just using the normal requests library). A successful send means that the user_ref was properly registered in FB by that step #1 call - a failure means you'll need to repeat step #1 (or use some other error handling flow).
3) After that, the next time the user responds to your bot in FB (as long as you don't send any other messages to them), the message your bot will receive will contain this as part of the payload:
{ ...
channelData:
{ ...
prior_message:
{ source: 'checkbox_plugin',
identifier: <user_ref> }
}
}
So I've currently added a check within my bot.use(), where if that section is present in the incoming message payload (session.message.sourceEvent.prior_message) and the source is "checkbox_plugin", I store the corresponding user_ref in the session.userData, and can work from there.
I would love to see this feature added into the supported Azure bot stack, but in the meantime hopefully this helps anyone else encountering this (admittedly niche) hurdle.

how to setup twilio sms api in ionic angular?

#types/twilio
ran the following code and
installed twilio npm package
npm install twilio
In my provider i have imported by specifying
import * as twilio from 'twilio'
when i run by ionic serve --verbose
my console show an error that it cannot find module '../../package.json'
eventhough the library file has one, I will attach an image for reference
Twilio developer evangelist here.
The main Twilio Node.js module is not intended for use in a front end application so is unlikely to work well for you there. You are most likely getting that error as the Twilio module relies on some core Node modules that are unavailable in a browser environment.
It is not a good idea to try to use Twilio APIs from the client side as you expose your account credentials which would allow a malicious attacker to use your account for their own purposes.
Instead, we recommend you build a server that interacts with the Twilio API and that you make calls to from your own front end. If you are trying to use any of the Twilio client side SDKs, like Twilio Video, Twilio Chat or Twilio Sync, then you should install their respective modules twilio-video, twilio-chat and twilio-sync. You will still need a server side component that can generate access tokens for those services though.
Edit
In Node.js I just did a quick test for importing the Twilio module using TypeScript 2.6.2. This worked for me:
import { Twilio } from 'twilio';
const client = new Twilio("MY_ACCOUNT_SID", "MY_AUTH_TOKEN");
client.messages.each({ limit: 10 }, function(message) {
console.log(message.body);
});
Could you try this format for importing?
import { * as twilio } from 'twilio'
As philnash said, Twilio is not designed to run clientside. I tried to do the same thing you were doing. And you just have to have your Twilio run on a server and have your angular connect to that server to run it. Easiest way. Send a POST to your server via ajax and then have it run what you need.

Receive GCM push notification in node.js app

I'm building a command-line application in node.js and would like to receive GCM push notifications (the command-line app will be interacting with the same set of services that iOS/Android apps use, hence wanted to use the same notification service).
Given that GCM can be used on iOS (and thus is not Android-specific) I am hoping it can be used from node.js as well.
I've seen many articles about sending push notifications from node.js, but haven't been able to find anything about using node.js on the receiving end.
i think if you have to send push notification ,to ios and andriod then fcm is better then gcm use this
router.post('/pushmessage', function (req, res) {
var serverKey = '';//put server key here
var fcm = new FCM(serverKey);
var token = "";// put token here which user you have to send push notification
var message = {
to: token,
collapse_key: 'your_collapse_key',
notification: {title: 'hello', body: 'test'},
data: {my_key: 'my value', contents: "abcv/"}
};
fcm.send(message, function (err, response) {
if (err) {
res.json({status: 0, message: err});
} else {
res.json({status: 1, message: response});
}
});
});
I believe you can using service workers.
Push is based on service workers because service workers operate in the background. This means the only time code is run for a push notification (in other words, the only time the battery is used) is when the user interacts with a notification by clicking it or closing it. If you're not familiar with them, check out the service worker introduction. We will use service worker code in later sections when we show you how to implement pushes and notifications.
So basically there is a background service that waits for push and thats what you are going to build.
Two technologies
Push and notification use different, but complementary, APIs: push is invoked when a server supplies information to a service worker; a notification is the action of a service worker or web page script showing information to a user.
self.addEventListener('push', function(event) {
const promiseChain = getData(event.data)
.then(data => {
return self.registration.getNotifications({tag: data.tag});
})
.then(notifications => {
//Do something with the notifications.
});
event.waitUntil(promiseChain);
});
https://developers.google.com/web/fundamentals/engage-and-retain/push-notifications/handling-messages
I don't think it possible (in a simple way)...
Android/iOS has an OS behind with a service that communicates with GCM...
If you are trying to run a CLI tool, you'll need to implement a service on top of the OS (Linux, Windows Mac) so it can receive notifications.
GCM sends the notifications against the device tokens which are generated from iOS/Android devices when they are registered with push notification servers. If you are thinking of receiving the notifications without devices tokens it is fundamentally incorrect.
It's not mandatory to depend only on GCM, today there are many packages are available for sending pushNotification.
Two node packages are listed below.
fcm-call - you can find documentation from https://www.npmjs.com/package/fcm-call
fcm-node
fcm-call is used - you can find documentation from https://www.npmjs.com/package/fcm-node/
let FCM = require('fcm-call');
const serverKey = '<Your Server Key>';
const referenceKey = '<Your reference key>'; //Device Key
let title = '<Your notification title here.>';
let message = '<Your message here>';
FCM.FCM(serverKey, referenceKey, title, message);
And Your notification will be sent within 2-3 seconds.
Happy Notification.

Resources