Firebase messaging.setBackgroundMessageHandler not receiving messages - javascript

I am trying Firebase Cloud Messaging. It's awesome and all, but I am having the hardest time getting it to work for me.
The problem I am facing is with the service worker, here is my firebase-messaging-sw.js :
console.log('Service worker is loaded!');
self.addEventListener('install', function(event) {
console.log('Service Worker is being installed.');
});
self.addEventListener('activate', function(event) {
console.log('Service Worker is being activated.');
});
importScripts('https://www.gstatic.com/firebasejs/3.6.5/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/3.6.5/firebase-messaging.js');
firebase.initializeApp({
'messagingSenderId': ' ... '
});
var messaging = firebase.messaging();
messaging.setBackgroundMessageHandler(function(payload){
console.log('Received background message: ', payload);
return self.registration.showNotification('Title', {'body': 'Body'});
});
When I send a message (I am using PHP-FCM BTW) the message gets received as expected in the browser when the page is under focus, through onMessage( ... ), but never when the page isn't under focus or the browser is closed; the service worker just doesn't receive the message!
The line "Received background message: ... " never shows; meaning that the message handler wasn't registered at all!
Here's a sample message response:
{
"from": " ... ",
"collapse_key": "do_not_collapse",
"data": {
"id": "111"
},
"priority": "high",
"notification": {
"title": "Hi there",
"body": "Message body",
"badge": "1",
"color": "#ffffff"
}
}
What could be the issue here? It's driving me crazy.

No it is registered but not invoked because of the way you choose to structure your notification. Referring to the FCM docs:
https://firebase.google.com/docs/cloud-messaging/js/receive
"Note: If you set notification fields in your HTTP or XMPP send request, those values take precedence over any values specified in the service worker."
So, you have
{
"from": " ... ",
"collapse_key": "do_not_collapse",
"data": {
"id": "111"
},
"priority": "high",
"notification": {
"title": "Hi there",
"body": "Message body",
"badge": "1",
"color": "#ffffff"
}
}
and this structure never triggers the BackgroundMessageHandler. Because sending data this way, simply overrides your variables. If you want to trigger it you need to send your notification like this:
{
"from": " ... ",
"collapse_key": "do_not_collapse",
"priority": "high",
"data": {
"id": "111",
"notification": {
"title": "Hi there",
"body": "Message body",
"badge": "1",
"color": "#ffffff"
}
},
"to": "topic",
}

I'm not sure that you can define the imports roots in the middle of your javascript, I think those calls need to be at the top.
Also the badge value and color are not supported by the FCM SDK. If you want to set the badge you can use the background message handler to show a notification use the normal APi and define the badge through that APi

Related

How to add user properties to Service Bus topic output from Javascript Azure Function

I'm working on a TypeScript Azure Function that has an Azure Service bus topic as its output. I can send messages with it without any problem, but I cannot set any metadata as custom property on the message.
I've tried using an object with the same interface as the ServiceBusMessage from the Service Bus Javascript SDK, like this:
import { AzureFunction, Context, HttpRequest } from "#azure/functions";
const httpTrigger: AzureFunction = async function (
context: Context,
req: HttpRequest
): Promise<void> {
const message = {
body: "my message content",
applicationProperties: { key: "value" },
};
context.bindings.myTopic = message;
};
export default httpTrigger;
But the message is sent as-is, and the applicationProperties is not taken into account. I cannot see them on the Azure Portal in the Service Bus Explorer. The content of the message will be the JSON version of the message object.
I've tried with the extension bundles 3 and 4, without success.
I'm using this function.json file:
{
"bindings": [
{
"authLevel": "function",
"type": "httpTrigger",
"direction": "in",
"name": "req",
"methods": ["get", "post"]
},
{
"type": "http",
"direction": "out",
"name": "res"
},
{
"name": "myTopic",
"type": "serviceBus",
"queueName": "myTopic",
"connection": "SERVICE_BUS_CONNECTION_STRING",
"direction": "out"
}
],
"scriptFile": "../dist/servicebus-writer/index.js"
}
And this host.json file:
{
"version": "2.0",
"logging": {
"applicationInsights": {
"samplingSettings": {
"isEnabled": true,
"excludedTypes": "Request"
}
}
},
"extensionBundle": {
"id": "Microsoft.Azure.Functions.ExtensionBundle",
"version": "[3.3.0, 4.0.0)"
}
}
How can I set those custom properties?
As of today, there is no way to set metadata using bindings in non-C# languages. The workaround would be to use the Service Bus SDK directly to send out messages.
There is this feature request that you could up vote to gain more traction.

Issues adding sessions and information to the Google Fit REST Api using JS

So I am reasonably new to using API's with Js but I am struggling a lot to understand how the Google Fit API works. I am attempting to add a new Workout's data to the API by adding a session and some data for the intensity (heart points) of the session. I can get the session to appear correctly but run into constant errors when I try to create a dataSource and add a point to it for the session. It would be greatly appreciated if someone could help me to fix my code to achieve this or could direct me to a more thorough example of similar code as the API docs don't seem to be too well detailed with examples etc. Thanks in advance.
Here's the 3 api calls that I have written so far, one for creating the DataSource, one for the DataPoint and one for the Session. The session works correctly and adds a session of 1 hr for the correct activity but I am unable to get any of the other API requests to work.
Data Source :
``gapi.client.fitness.users.dataSources.create({
"userId":"me",
"resource": {
"application": {
"name": "LittleWorkouts"
},
"dataType": {"field":[{
"format": "floatPoint",
"name": "com.google.heart_minutes"
}],
"name": "com.google.heart_minutes"
},
"device": {
"manufacturer": "op",
"model": "6",
"type": "phone",
"uid": "1000019",
"version": "1"
},
"type": "raw"
}
})
.then(function(response) {
// Handle the results here (response.result has the parsed body).
console.log("Response", response);
},
function(err) { console.error("Execute error 1", err); });
``
Data Point :
``
gapi.client.fitness.users.dataSources.datasets.patch({
"dataSourceId":"raw:com.google.heart_minutes:292824132082:op:6:1000019",
"userId": "me",
"datasetId": "1592087806561000000-1592287806561000000",
"resource": {
"minStartTimeNs": "1592087806561000000",
"maxEndTimeNs": "1592287806561000000",
"dataSourceId": "raw:com.google.heart_minutes:292824132082:op:6:1000019",
"point": [
{
"startTimeNanos": "1592087806561000000",
"endTimeNanos": "1592287806561000000",
"value": [
{
"fpVal": 89.1
}
],
"dataTypeName": "com.google.heart_minutes"
}
]
}
})
.then(function(response) {
// Handle the results here (response.result has the parsed body).
console.log("Response", response);
},
function(err) { console.error("Execute error 2", err); });
``
Session :
``gapi.client.fitness.users.sessions.update({
"userId":"me",
"sessionId": "someSessionId19",
"id": "someSessionId19",
"name": "Awesome Workout19",
"description": "A very intense workout",
"startTimeMillis": new Date().getTime() - 3600000,
"endTimeMillis": new Date().getTime(),
"version": 1,
"lastModifiedToken": "exampleToken",
"application": {
"detailsUrl": "http://example.com",
"name": "LittleWorkouts",
"version": "1.0"
},
"activityType": 21,
"activeTimeMillis": 3600000
}).then((res) => {console.log(res)});
console.log('res')
//request.execute((res) => {console.log(res);console.log('executrd')})
console.log(auth2.currentUser.get().getBasicProfile().getGivenName());
var request2 = gapi.client.fitness.users.sessions.list({
"userId":"me"
}).then((res) => {console.log(res)})
``
Error message
{message: "Unable to fetch DataSource for Dataset: raw:com.google.heart_minutes:292824132082:op:6:1000019", domain: "global", reason: "invalidArgument"}
It looks like it could be that you're trying to pass in the wrong fields for the data type: if you want to use a standard data type (like com.google.heart_minutes), you should either pass the exact fields of the standard data type (the field should be called "intensity"); or just pass the data type name, and the backend will fill them in for you.
So, if you change the data type to
"dataType": {"name": "com.google.heart_minutes"}
It should work.
Then, you need to use the data source ID returned from that request for the data points.
Awesome, so after some support in the comments I have some working code to add a new session with data from a previously defined data source using 3 API calls. The first call is to create a data source and only needs to be run once. The second and third then add a data point to a data set and creates a new session for the workout respectively. Here's the final working code:
Data Source:
/*
gapi.client.fitness.users.dataSources.create({
"userId":"me",
"resource": {
"application": {
"name": "LittleWorkouts"
},
"dataType": {
"name": "com.google.heart_minutes"
},
"device": {
"manufacturer": "op",
"model": "6",
"type": "phone",
"uid": "1000020",
"version": "1"
},
"type": "raw"
}
})
.then(function(response) {
// Handle the results here (response.result has the parsed body).
console.log("Response", response);
},
function(err) { console.error("Execute error 1", err); });
*/
Data and Data Set:
gapi.client.fitness.users.dataSources.datasets.patch({
"dataSourceId":"raw:com.google.heart_minutes:108881196053:op:6:1000020",
"userId": "me",
"datasetId": z,
"resource": {
"minStartTimeNs": workoutStartTime * 1000000,
"maxEndTimeNs": workoutEndTime * 1000000,
"dataSourceId": "raw:com.google.heart_minutes:108881196053:op:6:1000020",
"point": [
{
"originDataSourceId": "raw:com.google.heart_minutes:108881196053:op:6:1000020",
"value": [
{
"fpVal": 8
}
],
"dataTypeName": "com.google.heart_minutes",
"endTimeNanos": workoutEndTime * 1000000,
"startTimeNanos": workoutStartTime * 1000000,
}
]
}
})
.then(function(response) {
// Handle the results here (response.result has the parsed body).
console.log("Response", response);
},
function(err) { console.error("Execute error 2", err); });
Session:
gapi.client.fitness.users.sessions.update({
"userId":"me",
"sessionId": id,
"id": id,
"name": "Morning Workout",
"description": "A very intense workout",
"startTimeMillis": workoutStartTime,
"endTimeMillis": workoutEndTime,
"version": 1,
"lastModifiedToken": "exampleToken",
"application": {
"detailsUrl": "http://example.com",
"name": "LittleWorkouts",
"version": "1.0"
},
"activityType": 21,
"activeTimeMillis": workoutEndTime - workoutStartTime
}).then((res) => {console.log(res)});
console.log('res')

Javascript parse JSON error, but works fine in validator

When I try to parse this JSON (Discord webhook):
{
"content": "this `supports` __a__ **subset** *of* ~~markdown~~ 😃 ```js\nfunction foo(bar) {\n console.log(bar);\n}\n\nfoo(1);```",
"embed": {
"title": "title ~~(did you know you can have markdown here too?)~~",
"description": "this supports [named links](https://discordapp.com) on top of the previously shown subset of markdown. ```\nyes, even code blocks```",
"url": "https://discordapp.com",
"color": 16324973,
"timestamp": "2018-12-18T09:22:12.841Z",
"footer": {
"icon_url": "https://cdn.discordapp.com/embed/avatars/0.png",
"text": "footer text"
},
"thumbnail": {
"url": "https://cdn.discordapp.com/embed/avatars/0.png"
},
"image": {
"url": "https://cdn.discordapp.com/embed/avatars/0.png"
},
"author": {
"name": "author name",
"url": "https://discordapp.com",
"icon_url": "https://cdn.discordapp.com/embed/avatars/0.png"
},
"fields": [
{
"name": "🤔",
"value": "some of these properties have certain limits..."
},
{
"name": "😱",
"value": "try exceeding some of them!"
},
{
"name": "🙄",
"value": "an informative error should show up, and this view will remain as-is until all issues are fixed"
},
{
"name": "<:thonkang:219069250692841473>",
"value": "these last two",
"inline": true
},
{
"name": "<:thonkang:219069250692841473>",
"value": "are inline fields",
"inline": true
}
]
}
}
Using this code:
var parsed = JSON.parse(req.body)
I get this error:
SyntaxError: Unexpected token o in JSON at position 1
But if I use a website such as
https://jsonformatter.curiousconcept.com
To validate the JSON, it says the JSON is valid.
What is wrong here?
UPDATE
I'm using an express server to simulate discord server, so it sends web hooks to the express server instead, I get the JSON using req.body.
This happens because JSON is a global object (it's the same object where you read the method parse!), so when you invoke JSON.parse(JSON) javascript thinks you want to parse it.
The same thing doesn't happen when you pass the variable to the validator, because it will be assigned to a local variable:
let JSON = "{}";
validate(JSON);
function(x) {
JSON.parse(x); // here JSON is again your global object!
}
EDIT
According to your updated question, maybe it happens because you already use bodyParser.json() as middleware, and when you use it, req.body is already an object and you don't need to parse it again.
Trying to parsing an already parsed object will throw an error.
It would be something like without using JSONStream:
http.request(options, function(res) {
var buffers = []
res
.on('data', function(chunk) {
buffers.push(chunk)
})
.on('end', function() {
JSON.parse(Buffer.concat(buffers).toString())
})
})
For using it with JSONStream, it would be something like:
http.request(options, function(res) {
var stream = JSONStream.parse('*')
res.pipe(stream)
stream.on('data', console.log.bind(console, 'an item'))
})
(OR)
Here is the Some Steps for this issue..
You Can use lodash for resolving this.
import the lodash and call unescape().
const _ = require('lodash');
let htmlDecoder = function(encodedStr){
return _.unescape(encodedStr);
}
htmlDecoder(JSON);

Setting up a webhook without Google Cloud Project

Want to set up the webhook on my pc and not on google cloud project like the guide is sugesting, and I'm not quite sure how to.
This is the guide: https://dialogflow.com/docs/getting-started/basic-fulfillment-conversation
It says to create a index.js with the following code in it
/*
* HTTP Cloud Function.
*
* #param {Object} req Cloud Function request context.
* #param {Object} res Cloud Function response context.
*/
exports.helloHttp = function helloHttp (req, res) {
response = "This is a sample response from your webhook!"
//Default response from the webhook to show it's working
res.setHeader('Content-Type', 'application/json');
//Requires application/json MIME type
res.send(JSON.stringify({ "speech": response, "displayText": response
//"speech" is the spoken version of the response, "displayText" is the visual version
}));
};
Never seen exports. before. The guide wants me to do something with 'google functions' and make one called hellohttp or something. Trying to figure out how to do it without google cloud projects.
I installed Node.js and created that file. I set the webhook url to https://my_ip/index.js but doesn't work. Not really sure what to do
this is the JSON I get
{
"id": "9c244834-3ee9-4291-98fd-aab8e975fb1f",
"timestamp": "2018-02-22T23:11:34.067Z",
"lang": "en",
"result": {
"source": "agent",
"resolvedQuery": "weather TOMORROW in VIRGINIA",
"action": "",
"actionIncomplete": false,
"parameters": {
"date": "2018-02-24",
"geo-city": "Virginia"
},
"contexts": [],
"metadata": {
"intentId": "44486050-dfd5-4c35-bcbf-4e168379df28",
"webhookUsed": "true",
"webhookForSlotFillingUsed": "false",
"webhookResponseTime": 5006,
"intentName": "Weather"
},
"fulfillment": {
"speech": "I don't know about the weather for 2018-02-24 in Virginia. Sorry!",
"messages": [
{
"type": 0,
"speech": "I don't know about the weather for 2018-02-24 in Virginia. Sorry!"
}
]
},
"score": 1
},
"status": {
"code": 206,
"errorType": "partial_content",
"errorDetails": "Webhook call failed. Error: Webhook response was empty.",
"webhookTimedOut": false
},
"sessionId": "9cdbd5bc-403e-4840-8970-e420f27d23e2"
}

Push Notification to android device with custom GCM parameters

I am using JavaScript SDK - v2.1.2 :
My Query : How to send push notification with custom gcm parameters in android device using JavaScript.
I am trying to send push notification to android devices with my JavaScript code but in our app we are using third party receiver called CleverTap for notification.
Following are the mandatory parameters for CleverTap receiver:
"wzrk_pn"
"wzrk_sound"
"nt"
"nm"
"wzrk_dl" which I need to send as custom parameters.
Following is my code for Push Notification :
var pushCustomParams = {
message: 'Message received from Bob',
wzrk_pn: 1,
wzrk_sound: 1,
nt: 'Revofit',
nm: 'This msg is from application',
wzrk_dl: ''
}
var params = {
notification_type : 'push',
push_type : 'gcm', // 'gcm' is for Android, 'apns' - for iOS.
user : { ids: [14411551] }, // recipients.
environment : 'development', // environment, can be 'production' as well.
message : QB.pushnotifications.base64Encode(JSON.stringify(pushCustomParams)), // See how to form iOS or Android spesific push notifications
};
QB.pushnotifications.events.create(params, function(err, response) {
if (err) {
console.log(err);
} else {
// success
console.log(response);
}
});
Logs generated after executing the above code is as follows:
{
"notification": {
"registration_ids": ["dFCRdN7MJD0:APA91bFsaOdorqhvRyMuUGH-Ds8Z_EB6pQWHpQIYy5YVUefwYFwqK39E5BsLtJ2cHYDLv9mPXDQc4mAQRhJTdM2unUgy6-kmWSWMorp0ZSbBL1EdjFZLiorh4LQT3JR454dqEP1bL2_l"],
"delay_while_idle": false,
"data": {
"message": "{\"message\":\"Message received from Bob\",\"wzrk_pn\":1,\"wzrk_sound\":1,\"nt\":\"Revofit\",\"nm\":\"This msg is from application\"}",
"collapse_key": "event7637817"
},
"priority": "high",
"time_to_live": 86400
},
"log": [{
"device_token": null,
"created_at": "2016-06-30T14:26:46Z",
"delivered_at": "2016-06-30T14:26:47Z",
"failed_at": null,
"error_code": null,
"error_description": null
}]
}
But when I tried to send push notification from admin panel with my customized channel setting of GCM Parameters it worked fine.
Log generated for notification from admin panel :
{
"notification": {
"registration_ids": ["eShiPWpBngA:APA91bFzFeaB0LryAt9FmEJ9xl2KHWhZWlfzpYhng4KONN60yr3ySl2R58Eye-qSmhzQ56T2Fyuzr0Yg4y1VWMIm20LH74U7BWO_Az7MgogBD2IGvmWEKvJWWgVH6sD-3wP_gaIgJEAY"],
"delay_while_idle": false,
"data": {
"message": "hii",
"wzrk_pn": "1",
"nm": "New message",
"nt": "revofit",
"collapse_key": "event7632938"
},
"priority": "high",
"time_to_live": 86400
},
"log": [{
"device_token": null,
"created_at": "2016-06-30T08:17:25Z",
"delivered_at": "2016-06-30T08:17:26Z",
"failed_at": null,
"error_code": null,
"error_description": null
}]
}
I am unable to rectify my mistake
Kindly Help me out with this.
Sorry for my bad English. I tried my best.
Since we weren't able to get the solution as required we changed the GCM receiver.

Categories

Resources