Sending voip push notification from one signal triggered firebase cloud functions - swift

I`m trying to send Voip push notification from one signal triggered by firebase cloud functions. So far it being able to send normal message push notifications from one signal to IOS devices using firebase cloud functions with below code.
var sendNotification = function(data) {
var headers = {
"Content-Type": "application/json; charset=utf-8"
};
var options = {
host: "onesignal.com",
port: 443,
path: "/api/v1/notifications",
method: "POST",
headers: headers
};
var https = require('https');
var req = https.request(options, function(res) {
res.on('data', function(data) {
console.log("Response:");
console.log(JSON.parse(data));
});
});
req.on('error', function(e) {
console.log("ERROR:");
console.log(e);
});
req.write(JSON.stringify(data));
req.end();
};
var message = {
app_id: "*********************",
contents: {"en": "English Message"},
include_player_ids: ["******************7b0bdc38"]
};
sendNotification(message);
Does anyone know how to send Voip push notifications from one signal using firebase cloud functions??
(If the above code is required to change some part of it, it would be very thankful telling me where it is.)

As per one signal documentation (https://documentation.onesignal.com/docs/voip-notifications) you are missing the DEVICE_VOIP_TOKEN that you should have received from the iOS application.
Please try adding that and let me know, think of adding the exact error message if any.

Related

Flutter web index.html not same as examples for fcm what to do now

I am building a flutter web app. Using flutter 3.0.7. I need to send push notifications and it looks like the only real way is with fcm. So I created a project and with the cli I created a firebase_options.dart file. Then I created a firebase-messaging-sw.js file.
If I send a message from the console I recieve the message but as soon as I try to send the message from y app to a topic or registration key I get no message.
I red in the examples the few out there to change my index.html file.
To theThis code is not in my index.html, dont know if it is because I am working with flutter 3.0.7
<script>
if ("serviceWorker" in navigator) {
window.addEventListener("load", function () {
mine looks like this
<script>
// The value below is injected by flutter build, do not touch.
var serviceWorkerVersion = null;
So could that be the problem that I can not send with legacy fcm api to my app users?
The send method I use is as follows
sendPushMessageToWeb(String? fcm_token) async {
if (fcm_token == null) {
print('Unable to send FCM message, no token exists.');
return;
}
try {
await http
.post(
Uri.parse('https://fcm.googleapis.com/fcm/send'),
headers: <String, String>{
'Content-Type': 'application/json',
'Authorization':
'key=my server key'
},
body: json.encode({
'to': "${fcm_token}",
'message': {
'token': "${fcm_token}",
},
"notification": {
"title": "Push Notification",
"body": "Firebase push notification"
}
}),
)
.then((value) => print(value.body));
print('FCM request for web sent!');
} catch (e) {
print(e);
}
}
When I send the message the method it tells me the message was send but no message is recieved. But when using console with the registration key it sends the message. Could it be because I did not change my index.html?
Thank you

Keep track of installed pwa instances

We want to keep track of each pwa installation for a user. So we could track notifications, like did every instance of the app user installed (pc or phone, or ff, or chrome) have received the update. Can we know the pwa instance was uninstalled? Can we know web push was delivered to every instance?
In your service worker, fire a http post to your server in the "install" event. You'll need to get your userID from indexdb or similar. Use "fetch" not xmlhttp the service worker.
self.addEventListener('install', function(e) {
console.log('[ServiceWorker] Install');
e.waitUntil(
caches.open(cacheName).then(function(cache) {
console.log('[ServiceWorker] Caching app shell');
var rc = cache.addAll(filesToCache);
postServerStatus( "installcomplete" );
return rc;
})
);
});
function postServerStatus( strStatus ) {
var strUserID = "getfromindexdb";
fetch('./datasvc.aspx', {
method: 'post',
headers: {
'Content-type': 'application/json'
},
body: JSON.stringify({
service: strStatus,
userid: strUserID
}),
});
}

cordova background geolocation plugin on reboot

I am building an ionic app with background geolocation plugin https://github.com/mauron85/cordova-plugin-background-geolocation.
I want to make an app to send its location after reboot. The plugin I am using seems to have the option, but it is not working properly. An app only sends its location to the server only after execute an app at least once after every boot.
Any help or suggestion would be appreciated. Thank you in advance!
My code is below
Configuration
backgroundGeolocation.configure(callbackFn, failureFn, {
locationProvider: backgroundGeolocation.provider.ANDROID_ACTIVITY_PROVIDER,
desiredAccuracy: 10,
stationaryRadius: 10,
distanceFilter: 10,
interval: 60000,
maxLocations: 50,
startOnBoot: true, // from my understanding, this should make an app track its location even after reboot
stopOnTerminate: false
});
Callback Function
var callbackFn = function(location) {
console.log('[js] BackgroundGeolocation callback: ' + location.latitude + ',' + location.longitude);
// Do your HTTP request here to POST location to your server.
var link = API_URL;
$http.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded";
$http({
method: 'POST',
url: link,
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
transformRequest: function(obj) {
var str = [];
for(var p in obj)
str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
return str.join("&");
},
params: {
'device': 'android',
},
data: {
lat:location.latitude,
lng:location.longitude,
}
}).success(function(data){
console.log(data);
}).error(function(data){
console.log(data);
});
backgroundGeolocation.finish();
};
i hope you would have found your answer by now, posting this might help others too.
don't expect your callback to be executed after the reboot, as the activity might be killed, instead use url option of the plugin to continue sending your location updates to the server.

Getting and "Error, wrong validation token" when trying to create a Facebook Chatbot

I'm trying to create a Facebook chatbot with NodeJS, Express, and a Heroku server.
I created my webhook on heroku and had it verified and saved by facebook. I then started adding code that would reply to the incoming messages and I can't seem to get it connected. It keeps saying "Error, wrong validation token" when I try to load my webhook in my browser. And when I try to send my bot a message I get no response. Even though I already had it verified and didn't change the code.
Here is my code:
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
var port = process.env.PORT || 3000;
// body parser middleware
app.use(bodyParser.urlencoded({ extended: true }));
// test route
//app.get('/', function (req, res) { res.status(200).send('Hello world!') });
app.get('/', function (req, res) {
if (req.query['hub.verify_token'] === '8FKU9XWeSjnZN4ae') {
res.send(req.query['hub.challenge']);
}
res.send('Error, wrong validation token');
})
app.post('/', function (req, res) {
messaging_events = req.body.entry[0].messaging;
for (i = 0; i < messaging_events.length; i++) {
event = req.body.entry[0].messaging[i];
sender = event.sender.id;
if (event.message && event.message.text) {
text = event.message.text;
sendTextMessage(sender, "Text received, echo: "+ text.substring(0, 200));
}
}
res.sendStatus(200);
});
// error handler
app.use(function (err, req, res, next) {
console.error(err.stack);
res.status(400).send(err.message);
});
app.listen(port, function () {
console.log('Listening on port ' + port);
});
var token = <myToken>;
function sendTextMessage(sender, text) {
messageData = {
text:text
}
request({
url: 'https://graph.facebook.com/v2.6/me/messages',
qs: {access_token:token},
method: 'POST',
json: {
recipient: {id:sender},
message: messageData,
}
}, function(error, response, body) {
if (error) {
console.log('Error sending message: ', error);
} else if (response.body.error) {
console.log('Error: ', response.body.error);
}
});
}
So I'm confused as to why nothing is happening and why I'm getting that error. I feel like I'm missing a whole step. I am following this tutorial by the way: https://developers.facebook.com/docs/messenger-platform/quickstart
Any help is appreciated. Thanks!
Edit: Here are my heroku logs
Do not post your full access tokens here!
Have you tested the output of the challenge? Since it's just a GET and you know all values you can try it yourself: your-app-domain.com/your-callback-url?hub_mode=subscribe&hub_verify_token=the_token_you_set_in_your_app_config&hub_challenge=ping which sould print 'ping' if everything work fine.
Make sure you add sendStatus(200) to the hub challenge response, too.
You need to subscribe your page to the app first. To do so make a POST request to /your-page-id/subscribed_apps which should return "success". You can make a GET request to the same endpoint afterwards to double check your app is subscribed to your page
You did not mention which events you subscribed to (needs to be message_deliveries, messages, messaging_optins, messaging_postbacks)
Make sure the webhooks tab in your app dashboard now says "complete"
Test again
You are actually using "request" but you are never importing it anywhere. Here's how to fix it:
var request = require("request")
Once you have added that to your index.js or app.js file (basically whatever this file is), make sure you do:
npm install request --save
This should fix it. Unfortunately, Heroku doesn't error out and say that it does not know what "request" is and that's why it was so hard to figure this out in the first place!

Video steaming recived but not playing in WebRTC

I am trying to create a audio broadcasting app using WebRTC. To make it compatible with IE I am using Teamsys plugin from Attlasian.
In most of the demos available on internet I have seen two audio/video controls on a single page. But I am trying it with two page application. one for sender and another for reciever.
I am sending my stream description using XHR to a database where it is received by the another user and used as local description for the peer connection on receiver end.
Here is the code :
Sender
function gotStream(stream) {
console.log('Received local stream');
// Call the polyfill wrapper to attach the media stream to this element.
localstream = stream;
audio1 = attachMediaStream(audio1, stream);
pc1.addStream(localstream);
console.log('Adding Local Stream to peer connection');
pc1.createOffer(gotDescription1, onCreateSessionDescriptionError);
}
function gotDescription1(desc) {
pc1.setLocalDescription(desc);
console.log('Offer from pc1 \n' + desc);
console.log('Offer from pc1 \n' + desc.sdp);
$.ajax({
type: "POST",
url: '../../home/saveaddress',
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ SDP: desc }),
dataType: "json",
success: function (result) {
if (result) {
console.log('SDP Saved');
}
});
}
function iceCallback2(event) {
if (event.candidate) {
pc1.addIceCandidate(event.candidate,
onAddIceCandidateSuccess, onAddIceCandidateError);
console.log('Remote ICE candidate: \n ' + event.candidate.candidate);
}
}
At Receiver End
var pcConstraints = {
'optional': []
};
pc2 = new RTCPeerConnection(servers, pcConstraints);
console.log('Created remote peer connection object pc2');
pc2.onicecandidate = iceCallback1;
pc2.onaddstream = gotRemoteStream;
$.ajax({
type: "GET",
url: '../../home/getsavedaddress',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
if (result) {
gotDescription1(result);
}
},
error: function () {
}
});
function gotDescription1(desc) {
console.log('Offer from pc1 \n' + desc.sdp);
console.log('Offer from pc1 \n' + pc2);
pc2.setRemoteDescription(new RTCSessionDescription(desc));
pc2.createAnswer(gotDescription2, onCreateSessionDescriptionError,
sdpConstraints);
}
Using this I get the SDP from server , vedio tag has a source now. but video is not playing not showing anything.a an y clues..
also I am using asp.net for site , do I need to use node js in this project.
Thanks
Your question is lacking information, but I will give my opinion on it.
Are you supporting Trickle ICE? It seems you may be sending the SDP too fast!
When you do a
pc1.setLocalDescription(desc);
The ICE Candidates start being gathered based on the TURN and STUN server configured in your code here (servers parameter):
pc2 = new RTCPeerConnection(servers, pcConstraints);
That said, they are not yet included in your SDP. It can take a few milliseconds before the media ports are set in the localDescription Object. Your first error is that you are sending the "desc" Object from gotDescription1 instead of the post setLocalDescription SDP. That SDP doesn't have the proper media ports yet.
In your code, you are sending the SDP right away without waiting. My guess is that the SDP is not yet completed and you are not supporting Trickle. Because of that, even if signalling might look good, you will not see any media flowing.