Schedule Push notification on Parse - parse-platform

I was wondering if Schedule Push is available on Parse Server? (I'm using Back4App)
Here is my cloud code:
Parse.Cloud.define("pushMultiple",async (request) => {
//Getting Current Date instance
var d = new Date();
//Where I live Current Hour is 14, so setting it to 15
d.setHours(15);
//Sending push to a specific device
return Parse.Push.send({
push_time: d,
channels: [ "t1g.com"],
data: {alert: "The Giants won against the Mets 2-3."}
},{ useMasterKey: true });
});
But the code does not seem to be working. The push is sent out immediately.
And if it's not possible, please let me know how I can schedule push using a Cloud Job. A code snippet would be very helpful. Also will the Cloud Job stop running after it has completed sending the push?

According to this document setHours method doesnt add your value to your date but just replace it.
Try this:
var extraTime = 1000*60*60*15; //15 hours
var currentDate = new Date();
//since date object is just number we can add our extra time to our date.
var pushDate = currentDate + extraTime; //push date is 15 hours later than now
return Parse.Push.send({
push_time: pushDate,
channels: [ "t1g.com"],
data: {alert: "The Giants won against the Mets 2-3."}
},{ useMasterKey: true });
Edit: Parse docs says push_time is not supported yet.
https://docs.parseplatform.org/parse-server/guide/#push-notifications
Docs can be outdated or if you are using back4app, they may be implemented this feature to their servers.

Related

How to update an User with useMasterKey in Parse

Issue Description
I'm trying to update an User when another user click on my Xamarin button.
Then, I used Cloud Code to perform this but it doesnt work
My Code
Here is my complete JS code :
Parse.Cloud.beforeSave("Archive", function(request, response) {
Parse.serverURL = 'https://pg-app-0brffxkawi8lqvf2eyc2isqrs66zsu.scalabl.cloud/1/';
var status = request.object.get("status");
if (status == "validated") {
var event = request.object.get("event");
event.fetch({
success: function(myEvent) {
var coinsEvent = myEvent.get("coins");
var user = request.object.get("user");
user.fetch({
success: function(myUser, coinsEvent, user) {
var email = myUser.get("email");
var coinsUser = myUser.get("coins");
myUser.set("coins", coinsUser + coinsEvent);
return myUser.save(null, {useMasterKey:true});
}
});
}
});
}
response.success();
});
I think myUser.save(null, {useMasterKey:true}); should work
I actually have that error :
Dec 24, 2017, 12:27 GMT+1 - ERRORError generating response for [PUT] /1/classes/_User/1GPcqmn6Hd
"Cannot modify user 1GPcqmn6Hd."
{
"coins": 250
}
Environment Setup
Server
parse-server version : v2.3.3
Server: Sashido
Your success branch never calls response.success() which is a problem... though maybe not THE problem.
You are also doing 2 fetches inside a 'beforeSave' function which is not recommended. 'BeforeSave' must happen very quickly and fetches take time. I would consider thinking through other options.
If you really need to do it this way, consider doing a Parse.Query("event") with an include("user") and trigger the query with query.first({useMasterKey:true}).
Are you sure coinsEvent is what you think it is? Fetch only returns the object fetched... not sure that you can curry in other parameters. I would change your final success routine to (double checking that coinsEvent is valid):
success: function(myUser) {
var coinsUser = myUser.get("coins");
myUser.set("coins", coinsUser + coinsEvent);
return myUser.save(null, {useMasterKey:true}).then(_ => response.success());
}

Getting 500 error into frisby delete request

Hello I am facing 500 error during delete request into frisby. The code is below please correct me if I have done any wrong..!
var frisby = require('frisby');
//get the current UTC time from this URL: (https://currentmillis.com/)
var now = new Date();
var now_utc = new Date(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate(), now.getUTCHours(), now.getUTCMinutes(), now.getUTCSeconds())
var currentUTCTime = now_utc.getTime() - (now_utc.getTimezoneOffset() * 60000);
frisby.create('Authentication for Delete Request Valid User Name and Password')
.delete('http://example.com',
{
headers:
{
'Accept':'application/json',
'Auth-Username':'abcd',
'X-Application-Key':'xyzzzz',
'Content-Type':'application/json',
'x-locale':'en_US',
'x-microtime':currentUTCTime, //get the current UTC time
'auth-signature': 'example', // Added new auth-signature for new responses
}
}
)
.expectStatus(200)
.toss()
500 signifies internal server error. Which means your REST call broke something in the server. Please check server logs to see the real issue. There might be some problem server side for this.

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,
});
})

Parse Cloud Code multiple push dilemma

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.

doesNotMatch query in Parse not working

I have two objects in Parse. The first one is notification where I save every challenge my user get. The second one is UserChallenge where I store every challenge a user completes. I tried to do a combined query where I only get results of notifications for challenges the user didn't complete and I get nothing in return. I checked my data and I should get two objects back.
Does anyone can tell what I did wrong in the query?
var Completed = Parse.Object.extend("Picok_User_Challenge");
var completedQuery = new Parse.Query(Completed);
completedQuery.equalTo("picok_user_id",currentUser);
var Challenges = Parse.Object.extend("Picok_Notifications");
var challengesQuery = new Parse.Query(Challenges);
challengesQuery.include("new_challenge_id");
challengesQuery.equalTo("type", "CHALLENGE");
challengesQuery.equalTo("who_recived", currentUser);
challengesQuery.doesNotMatchKeyInQuery("new_challenge_id","picok_challenge_id",
completedQuery);
challengesQuery.find({
success: function(results) {
console.log("createNotifiction success count: " + results.length);
response.success("YAY");
},
error: function(object, error)
{
console.log(error);
alert('Failed to get challenge not completed for: ' + request.params.user);
response.error('Failed to get user challenges to complete for: ' + request.params.user);`
}
});

Resources