Parse Cloud: Send a notifications to a specific user - javascript

I'm currently implementing push notifications to follow user. Apparently, I managed to get push notifications done and responsive well.Hence, The notifications were sent to everyone.I would like to create push notifications and received the notification only by one respective user each time when other users have followed their user account.
I haven't create a pointer that should associate with User. Even If I create, is there any amendments that I should amends on my Cloudcode?
I would like to send push notifications to a specific user whenever other user has followed that user.
eg: Test 1 followed you.
Parse.Cloud.define("FollowersAndFollowing", function(request,result){
var query = new Parse.Query(Parse.User);
var message = request.params.message;
var pushQuery = new Parse.Query(Parse.Installation);
query.equalTo('userLink',request.params.User);
Parse.Push.send({
where: pushQuery,
data : {
alert: message,
badge: "Increment",
sound: "",
}
}, {
success: function(result) {
console.log(JSON.stringify(result));
response.success(result);
},
error: function(error) {
console.error(JSON.stringify(error));
response.error(error)
}
});
});
Above this ^ is my cloud code in .JS
if (status == false) {
// Create the push notification message.s
let pushMessage = "\(PFUser.currentUser()!.username!) has followed you."
// Submit the push notification.
PFCloud.callFunctionInBackground("FollowersAndFollowing", withParameters: ["message" : pushMessage, "User" : "\(userData.username!)"])
}
and above this is in swift code for frontend.
enter image description here
and the second the url is my class and subclasses of how I setting up
enter image description here

Use a cloud code beforeSave trigger on the Installation class to keep User pointers up to date.
// Make sure all installations point to the current user
Parse.Cloud.beforeSave(Parse.Installation, function(request, response) {
Parse.Cloud.useMasterKey();
if (request.user) {
request.object.set("user", request.user);
} else {
request.object.unset("user");
}
response.success();
});
You may also want to use an afterSave trigger on your Follow class to send out the push notification instead of calling a cloud function. Without knowing the structure of that class or how you have implemented a follower/following scheme it's hard to give any further information.

Related

Send notification using Cloud Functions for Firebase to specific user

I'm using Cloud Functions for Firebase to send notifications to the user. I'm able to get the notification but the problem is that everyone is getting the notification, I'm trying to send the notification to a particular user. I'm saving user's device id in Firebase's database and then send that particular person the notification. Here is my code:
To save user's data, which is actually working fine:
DatabaseReference root = FirebaseDatabase.getInstance().getReference();
DatabaseReference groupsRef = root.child("users").child(Settings.Secure
.getString(ctx.getContentResolver(), Settings.Secure.ANDROID_ID));
groupsRef.child("isLogin").setValue(2);
In first activity subscribing to the topic:
FirebaseMessaging.getInstance().subscribeToTopic("android");
And finally javascript code(something I know very little about):
var functions = require('firebase-functions');
var admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
exports.sendNotification = functions.database.ref('/users')
.onWrite(event => {
var eventSnapshot = event.data;
var str = "This is notification"
console.log(str);
var topic = "android";
var payload = {
data: {
isLogin: eventSnapshot.child("975af90b767584c5").child("isLogin").val()
}
};
return admin.messaging().sendToTopic(topic, payload)
.then(function (response) {
// See the MessagingTopicResponse reference documentation for the
// contents of response.
console.log("Successfully sent message:", response);
})
.catch(function (error) {
console.log("Error sending message:", error);
});
});
Here instead of "975af90b767584c5" which is hardcoded right now, I want to send device id, which I don't know how to do in javascript. Or if there is any other way.
Any help is appreciated, thanks.
First in app, get User FCM token by
String Token = FirebaseInstanceId.getInstance().getToken();
Now, send this token to your server and save it with other user details in Database.
Then when you want to send Notification to specific use, fetch that user's FCM token from Database via user id or something else.If you want to send notification to multiple user then fetch multiple user FCM token from database and put it in arrayList.
Now for main part, call fcm endpoint with your KEY, notification content
and most important: token or token array.
In your case, do not use sendToTopic, use send to: Token/Array
You can google for java script syntax, but this is main logic.For more info:
https://firebase.google.com/docs/cloud-messaging/admin/send-messages

Parse Login in node.js - Login successful but 'There is no current user'

I'm having trouble interacting with my Parse data in node.js. I'm able to login successfully, but Parse.User.current() returns null. After running the below code, I'd like to query data that has ACL read/write only for that user. Currently, that query returns empty, but if I change that data to public read/write, I can see the results of the query output in the terminal.
Here is my node.js code:
Prompt.get([{
name: 'username',
required: true}, {
name: 'password',
hidden: true}], function (err, result) {
if (err) {
console.log('Error: ' + err);
} else {
Parse.User.logIn(result.username, result.password, {
success: function(user) {
console.log('LOGGED IN');
console.log(user);
console.log(Parse.Session.current());
console.log(Parse.User.current());
... (query happens below this)
And my console output:
prompt: username: pablo
prompt: password:
LOGGED IN
ParseUser { _objCount: 0, className: '_User', id: 'EXyg99egkv' }
ParsePromise {
_resolved: false,
_rejected: true,
_resolvedCallbacks: [],
_rejectedCallbacks: [],
_error: 'There is no current user.' }
null
Thanks in advance.
Is this not a usecase for Parse.User.become()? From the parse docs:
If you’ve created your own authentication routines, or otherwise
logged in a user on the server side, you can now pass the session
token to the client and use the become method. This method will ensure
the session token is valid before setting the current user.
Parse.User.become("session-token-here").then(function (user) {
// The current user is now set to user.
}, function (error) {
// The token could not be validated.
});
I had similar problems and found this Parse blog that explains the issue:
Also in Cloud Code, the concept of a method that returns the current user makes sense, as it does in JavaScript on a web page, because there’s only one active request and only one user. However in a context like node.js, there can’t be a global current user, which requires explicit passing of the session token. Version 1.6 and higher of the Parse JavaScript SDK already requires this, so if you’re at that version, you’re safe in your library usage.
You can execute queries with user credentials in a node.js environment like this:
query.find({ sessionToken: request.user.getSessionToken() }).then(function(data) {
// do stuff with data
}, function(error) {
// do stuff with error
});
If you wish to validate that token before using it, here's an explanation of how you could go about doing that:
one way would be to query for an object known to be only readable by the user. You could have a class that stores such objects, and have each one of them use an ACL that restricts read permissions to the user itself. If running a find query over this class returns 0 objects with a given sessionToken, you know it's not valid. You can take it a step further and also compare the user object id to make sure it belongs to the right user.
Session tokens cannot be queried even with the master key.

Sending a welcome email parse cloudcode with mailgun

I have a working mailgun server in my parse cloudcode for an iOS app. I have set up a series of emails to be triggered by status changes in the database. I have now set up a welcome email that was formerly hard coded into the app. I have it set up as an afterSave however during the app the user is saved more than once, causing the welcome to be triggered. Is there a way I can only send this out once, or do I have to make it specific to a new user registering in the function if that is possible. Thanks.
Parse.Cloud.afterSave(Parse.User, function(request) {
console.log("aftersave fired");
if(!request.user.existed()){
var email = "Hello and welcome";
var subject = "Welcome to W!";
var recipient = request.user.get("email");
console.log(recipient);
Mailgun.sendEmail({
to: "#gmail.com",
from: "#gmail.com",
subject: subject,
text: email
}, {
success: function(httpResponse) {
response.success();
},
error: function(httpResponse) {
response.success();
}
});
}
});
You can do something as simple as set a flag in a new column on the User class which indicates that they have been welcomed. When the user is saved, check that flag and decide wether to send or not (and update the flag).

Sending Push Notification using javaScript in Parse

Actually we are done with sending push notification from mobile to mobile & parse to mobile using parse quires. Now we are trying to send push notification from web application to mobile device using Javascript.
function authentication() {
Parse.$ = jQuery;
// Initialize Parse with your Parse application javascript keys
Parse.initialize("app key",
"javascript key");
Parse.Push.send({
//where: pushQuery,
channels: [ "Demo","Done" ],
data: {
alert : "Hello word"
}}, { success: function() {
// Push was successful
alert : "Push was successful"
// debugger;
},
error: function(error) {
}}).then (function(error) {
//Marks this promise as fulfilled,
//firing any callbacks waiting on it.
});
}
Plz Guide us,we are new to javascript.
we getting error like this
POST https://api.parse.com/1/push 400 (Bad Request)
Did you activate Client Push Enabled in the Push Notifications settings of your Parse app ?
However, if you decide to send notifications from the JavaScript SDK outside of Cloud Code or any of the other client SDKs, you will need to set Client Push Enabled in the Push Notifications settings of your Parse app.
From: https://parse.com/docs/js/guide#push-notifications-sending-pushes
Note that you shouldn't send notification from any clients, instead trigger the notifications from cloud code
However, be sure you understand that enabling Client Push can lead to a security vulnerability in your app, as outlined on our blog. We recommend that you enable Client Push for testing purposes only, and move your push notification logic into Cloud Code when your app is ready to go into production.
I am also sending the notification from javascript to Mobile using parse.
My code is almost similar to you except one thing,
Instead of this
Parse.initialize("app key",
"javascript key");
I am using
Parse.initialize("APP_ID", "API_KEY", "JAVASCRIPT KEY");
My complete code is.. though I am using node.js you can relate to corresponding code.
var query = new Parse.Query(Parse.Installation);
query.equalTo('installationId', parseInstallationId);
Parse.Push.send({
where: query, // Set our Installation query
data: {
alert: "Willie Hayes injured by own pop fly."
}
}, {
success: function() {
// Push was successful
console.log('successful');
},
error: function(error) {
// Handle error
console.log('error');
}
});

How can I include data specific to a user in Parse push notifications?

This is how I'm using Parse JS Cloud Code to send push notifications to the "highPush" subset of users:
Parse.Cloud.job("sendHighPush", function(request, status) {
Parse.Cloud.useMasterKey();
Parse.Push.send({
channels: ["highPush"],
data: {
alert: "New match found!",
badge: "Increment"
}
},
{
success: function() {
// Push was successful
console.log('Push Notifications completed successfully.');
},
error: function(error) {
throw "Got an error " + error.code + " : " + error.message;
}
}).then(function() {
// Set the job's success status
status.success("Push Notifications completed successfully.");
}, function(error) {
// Set the job's error status
status.error("Uh oh, ain't no pushing going on here.");
});
});
What I want to do is not only send this push notification to all "highPush" users, but for the push notification string to include info specific to each user respectively. So rather than the alert saying "New match found!", I want it to say "New match found for iPhone 5S 16gb!", where "iPhone 5S 16gb" is a string property of an object associated with that specific user.
From what I can see in the Parse documentation, I can only find ways to send a standard push notification to a subset of users, but no way to customize the push notification content to each user individually. Is there any way to do this?
Unfortunately no.. The push data / alert is not customizable for each target in the push query.
At this time you would need to send individual push notifications to those users and include the specific information.

Categories

Resources