Parse Cloud Code multiple push dilemma - parse-platform

My app has notifications based on zip code and channels.
When a user changes zip code the app updates the Installation with the new zip.
In my beforeSave on Installation I grab the new zip and subscribed channels and search for relevant notifications.
Then I need to send the notifications as pushes back to that installation.
Two questions:
Can I just push to the Installation object that came into the beforeSave as such:
return Parse.Push.send({
where: request.object
data: data
})
or do I have to do an Installation query for that objectId?
I can't just push the notification object. I need to configure the data. If there are multiple notifications (not likely but possible) what's the best way to send multiple pushes back to that installation (assuming I don't want to put them all in one push)?
I can't send the pushes from a for loop. Can I do something like this:
return notificationQuery.each().then( function(notification) {
//configure push from that notification
return Parse.Push.send ... etc
})
Thanks!

You can send Push notifications in parse based on channels or where(query) but not both.
So you can do a query on Installation class with channel and zipcode:
var query = new Parse.Query(Parse.Installation);
query.equalTo('channels', 'Indians');
query.equalTo('zipcode', "345678");
Parse.Push.send({
where: query,
data: {
action: "com.example.UPDATE_STATUS"
alert: "Ricky Vaughn was injured in last night's game!",
name: "Vaughn",
newsItem: "Man bites dog"
}
}, {
success: function() {
// Push was successful
},
error: function(error) {
// Handle error
}
});
Hope this helps.

Related

How to send push notification from azure to windows mobile cordova app

Hi i am using azure process to send the push notification to windows 10
above version hybrid app and i use the below code to send the notification
https://learn.microsoft.com/en-us/azure/app-service-mobile/app-service-
mobile-cordova-get-started-push
i got this document there
pushRegistration.on('registration', function (data) {
this method is not firing is there any process to register before to send
notification
You have to implement a registerForPushNotifications method an call it every time user opens the App:
var pushRegistration = null;
function registerForPushNotifications() {
pushRegistration = PushNotification.init({
android: { senderID: 'Your_Project_ID' },
ios: { alert: 'true', badge: 'true', sound: 'true' },
wns: {}
});
If pushRegistration.on is not called, maybe registration is not complete or there is some error.
Create a breakpoint or print some message in:
pushRegistration.on('error', handleError);
And take a look if it's something wrong.
Also, you can check if there is some missing configuration following the Notification Hubs Diagnosis guidelines: https://learn.microsoft.com/en-us/azure/notification-hubs/notification-hubs-push-notification-fixer

Possible Parse bug in matchesKeyInQuery

If a post in my Parse database is liked, I want to send a push to the author via cloud code.
To be able to send pushes to specific users, all installations store the objectId of the current user. To find the author of the liked post, I use the query
var userWhosePostWasLikedQuery = new Parse.Query(Parse.Installation);
userWhosePostWasLikedQuery.equalTo(kClassInstallationKeyCurrentUserId, userWhosePostWasLiked.id);
This works fine: A single push is sent to the author.
Now I want to send this push only if the author has such pushes enabled. Thus each user stores a push settings array with enable flags for different pushes.
I use now another query for all users who have such pushes enabled:
const User = Parse.Object.extend(kClassUser);
var pushEnabledUserQuery = new Parse.Query(User);
pushEnabledUserQuery.equalTo(kClassUserKeyPushSettings, kPushNotificationTypePostLiked);
This query correctly returns all users who have such pushes enabled.
Eventually, I want to constrain the query for installations with the author as current user, by this query for users who have pushes enabled. This is done in the following way:
var userWhosePostWasLikedQuery = new Parse.Query(Parse.Installation);
userWhosePostWasLikedQuery.equalTo(kClassInstallationKeyCurrentUserId, userWhosePostWasLiked.id);
userWhosePostWasLikedQuery.matchesKeyInQuery(kClassInstallationKeyCurrentUserId, kPFObjectId, pushEnabledUserQuery);
Since the old query without the 3rd line returns 1 user, the new query with the additional constraint (matchesKeyInQuery) should return the same user, since the author has pushes enabled.
But it returns 2 users, the author and another user who liked the post.
To my understanding, this looks like a Parse bug, since all constraints to a query are ANDed.
Any ideas, maybe for a workaround?
your var "kPFObjectId" should be change to "user".
the default parse Installation come with the pointer named "user" and not "kPFObjectId".
I can tell you that Im using the same method ("matchesKeyInQuery") and it is working well:
Parse.Cloud.define("sendPushForChat", function(request, response) {
var userId = request.params.userId;
var groupId = request.params.groupId;
var query = new Parse.Query('RecentActivity');
query.equalTo('groupId',groupId);
query.include('user');
query.notEqualTo('user', {__type: "Pointer", className: "_User", objectId: userId});
var queryInstallation = new Parse.Query(Parse.Installation);
queryInstallation.matchesKeyInQuery('user', 'user', query);
var message = request.params.messageContent;
Parse.Push.send({
where: queryInstallation,
data: {
alert: message,
badge: "Increment",
title: "מה נשמע?"
}
}, {
success: function() {
console.log("Push for chat was successful");
response.success('Push for chat was successful');
},
error: function(error) {
console.error(error);
response.error('error');
},
useMasterKey:true,
});
})

Single Cross Domain AJAX Request needed

Trying to implement sending sms features in my ecommerce store.
I use service called esteria.lv and they provided me with API link that looks like this: http://api1.esteria.lv/send?api-key=api_key&sender=example.com&number=11223344&text=message
If the message is sent then it outputs message ID, now it outputs error number 3(unable to authenticate).
To get it working with my ecommerce store, I found this resource: http://www.ajax-cross-origin.com/examples/cross-origin.htm, and made this code:
$(function() {
$( '#btn' ).click(function(){
$.ajax({
crossOrigin: true,
url: 'http://api1.esteria.lv/send?api-key=api_key&sender=example.com&number=11223344&text=message',
success: function(data) {
$( '#test' ).html(data);
}
});
});
});
It works, but the problem is, it sends 6 messages (requests) instead of just one. I need just 1 request and one sent sms. Anyone have any suggestions?
To answer your comment, this is what you should do.
In your javascript you should have an ajax call to your server
// collect sms data
$.ajax({
url: 'yourserver/handlesms',
method: 'post',
data: {
sender: 'email#mail.com',
number: '1234567',
message: 'Test message'
}
}).then(function (data) {
alert("Message sent!");
});
In your server you should have an handler for sending the sms, something like (I don't know what's your platform, I'll just write a really simple php example)
$data = $_POST;
$apiKey = '12345643223213ds';
$endpoint = 'http://api1.esteria.lv/send';
// Create new curl request
$ch = curl_init($endpoint);
// curl settings, add your data, api key etc...
$result = curl_exec($ch);
// Result will contain the response from your api call
// Then you can send a result back to your client (js)
echo json_encode(['status' => 'Message sent!']);
This is just an example, the server code depends on your platform.
In this case you don't have any cross origin request (all the js request will be sent to your server, that then is in charge of contacting your sms provider and send the messages.
The problem that's executed 6 times I think depends on something else but it's hard to say without looking at the rest of the code (you can try debugging the click event on #btn and see how many times is executed every time you click on the button.

slack api rtm direct message

I'm using a node package: slack-client to interact with the api at slack. Now with or without using slack-client how do I send a direct message from my bot to a user I want to specify? Here's what have so far with a plain socket connection:
var WebSocket = require('ws')
,ws2 = new WebSocket(myURL); //from rtm start
ws2.on('open', function() {
ws2.send({
"id": 333,
"type": "message",
"channel": "#user1", //User I want to send to
"text": "HEY!!!!"
});
});
ws2.on('message', function(message) {
console.log('received: %s', message);
});
I was hoping that message would go directly to me from the bot but nothing. I get a reply of type hello though? The send details above I got on another post about this but it doesn't work for me. The message Id was one I created.
Ok so when calling the rtm.start via the web api, you would get a list of DM's that would be open for various users otherwise you can easily just open an im with im.open. I'm using the node package slack-client as mentioned in my question so you can do this:
//name of user your bot wants to send a msg to.
var userTest = slack.getUserByName('user1');
slack.openDM(userTest.id, function(res)
{
TestMsg(res.channel.id, 'some other msg');//test function I'm using
});
Next is the TestMsg function:
function TestMsg(userChannelId, msg)
{
request.post({url: 'https://slack.com/api/chat.postMessage',
form: { token: "xxxx-yourbot-token",channel: userChannelId,text: msg ,username: "yourBotNamehere", as_user: false}
}, function(error, response, body){
console.log(response.body);
});
}
I couldn't get it to work yet using the websockets send method but I suppose the api of postMessage will do for now as you can post richly formatted messages with postMessage. Hope this helps someone

Parse background notifications

I am trying to use Parse Cloud Jobs to trigger a download in my app. The documents suggest that I should use content-available to send this background push that would not be visible to the user, but to the app.
I tried implementing it as follows:
Parse.Cloud.job("sendAlert", function(sendAlert) {
// Set up to modify user data
Parse.Push.send({
data: {
content-available: 1,
}
}, {
success: function() {
// Push was successful
},
error: function(error) {
// Handle error
}
});
});
I also want to schedule it to run every 15 min.
With the expected behavior that it runs every 15 minuites, and sends a background push notification to the app.
However, when I try to deploy it, I get
Update failed with Could not load triggers. The error was Uncaught SyntaxError: Unexpected token - in main.js:5
and when I try to schedule it, it doesn't show up, most likely due to the error.
Change to:
data: {
"content-available": 1,
}
It was trying to do some subtraction without the quotes.

Resources