#ParseServer #OneSignal #ScheduledPush #ParseServerOneSignalPushAdapter - push-notification

Issue Description
We are using OneSignal as 3rd party push service and configured it using parse-server-onesignal-push-adapter as we are sending pushes from cloud code. Normal pushes are working but scheduled pushes are not. No matter what we set to "push_time" parameter on Push.send(), pushes are sent immediately.
Expected Results
Working scheduled pushes
Actual Outcome
Pushes are sent immediately even if there is push_time parameter set on Parse.Push.send().
How we send pushes
Parse.Push.send({
where: query,
data: {
"alert": "Voting complete. Click here to see the results.",
"sound": "cheering.caf",
//"badge": "Increment",
"content-available": 1,
"category": "VOTING_COMPLETE",
"qc": request.object.id
},
push_time: pushTime
}, {
success: function() {
console.log('##### PUSH OK');
},
error: function(error) {
console.log('##### PUSH ERROR');
},
useMasterKey: true
});
Environment Setup
var express = require('express');
var ParseServer = require('parse-server').ParseServer;
var path = require('path');
var databaseUri = process.env.DATABASE_URI || process.env.MONGODB_URI;
if (!databaseUri) {
console.log('DATABASE_URI not specified, falling back to localhost.');
}
var OneSignalPushAdapter = require('parse-server-onesignal-push-adapter');
var oneSignalPushAdapter = new OneSignalPushAdapter({
oneSignalAppId:"***************************",
oneSignalApiKey:"***************************"
});
var api = new ParseServer({
databaseURI: databaseUri || 'mongodb://localhost:27017/dev',
cloud: process.env.CLOUD_CODE_MAIN || __dirname + '/cloud/main.js',
appId: process.env.APP_ID || 'myAppId',
masterKey: process.env.MASTER_KEY || '',
fileKey: process.env.FILE_KEY || '******************************',
serverURL: process.env.SERVER_URL || 'http://localhost:1337/parse',
verifyUserEmails: true,
emailVerifyTokenValidityDuration: 2 * 60 * 60,
preventLoginWithUnverifiedEmail: true,
publicServerURL: 'http://***************************/parse',
enableAnonymousUsers: false,
revokeSessionOnPasswordReset: true,
appName: '************************',
emailAdapter: {
module: 'parse-server-simple-mailgun-adapter',
options: {
fromAddress: 'no-reply#***************************.com',
domain: 'mg.******************************.com',
apiKey: 'key-******************************',
}
},
oauth: {
twitter: {
consumer_key: "***************************",
consumer_secret: "***************************"
}
},
push: {
adapter: oneSignalPushAdapter
}
});
var app = express();
app.use('/public', express.static(path.join(__dirname, '/public')));
var mountPath = process.env.PARSE_MOUNT || '/parse';
app.use(mountPath, api);
app.get('/', function(req, res) {
res.status(200).send('Make sure to star the parse-server repo on GitHub!');
});
app.get('/test', function(req, res) {
res.sendFile(path.join(__dirname, '/public/test.html'));
});
var port = process.env.PORT || 1337;
var httpServer = require('http').createServer(app);
httpServer.listen(port, function() {
console.log('parse-server-example running on port ' + port + '.');
});
ParseServer.createLiveQueryServer(httpServer);

the reason is because scheduling of push messages is not supported (yet) by parse server. Only parse.com currently supports it.
You can read about it in here
If you really need this feature i suggest you to try to schedule a job in cloud code that will do it for you. Since scheduling jobs is also not supported out of the box you can find temporary solution in here

Related

hapi server : when i request with POST method, hapi server responding with null, but working fine in localhost

using hapi server -v = 16.7
joi -v = 10.6
deployed in aws ec2, nginx reverse proxy
Server Code in server.js:
'use strict';
//let newrelic = require('newrelic');
let Hapi = require('hapi');
let Routes = require('./Routes');
let Plugins = require('./Plugins');
let Bootstrap = require('./Utils/BootStrap');
process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0";
const Inert = require('inert');
const Vision = require('vision');
const HapiSwagger = require('hapi-swagger');
const Pack = require('./package');
const Config = require('./Config');
const mongoose = require('mongoose');
mongoose.Promise = global.Promise;
const server = new Hapi.Server();
server.connection({
port: Config.dbConfig.config.PORT,
routes: {cors: true}
});
let mongoOpts = {
reconnectTries: 60,
reconnectInterval: 2000,
useMongoClient:true
};
mongoose.connect(Config.dbConfig.config.dbURI,mongoOpts, (err, res) => {
if (err) {
console.log("DB Error: ", err);
process.exit(1);
} else {
console.log('MongoDB Connected');
}
});
server.register([
Inert,
Vision,
{
'register': HapiSwagger,
'options': {
info: {
'title': Config.dbConfig.config.SWAGGERNAME,
'version': Pack.version,
description: '',
},
//documentationPath: '/',
tags:[
{
name: 'v2.1.0',
description: 'API'
}
],
grouping: 'tags',
},
}], (err) => {
server.start((err) => {
if (err) {
console.log("Server err----------->", err);
} else {
console.log('Server running at:', server.info.uri);
}
});
});
server.on('response', (request) => {console.log('response===>>>:');
if(request.url.path.startsWith('/panel')){
}
else {//console.log('HEADERS===========>:',request.headers);
/* console for checking the params in the request*/
console.log(request.info.remoteAddress + ': ' + request.method.toUpperCase() +
' ' + request.url.path + ' --> ' + request.response.statusCode);
console.log('Request payload:', request.payload);
}
});
process.on('uncaughtException', function (err) {
console.log(err);
});
server.register(Plugins, function (err) {
if (err) {
server.error('Error while loading plugins : ' + err)
} else {
server.log('info', 'Plugins Loaded')
}
});
server.register(Inert, function (err) {
if (err) {
throw err;
}
server.route(Routes);
});
server.route([
{
method: 'GET',
path: '/{param*}', /* show error page */
handler: function (req, res) {
res.file('./error.html')
}
},
{
path: "/panel/{path*}",
method: "GET",
handler: { /* open admin panel index from panel path*/
directory: {
path: ['./_admin'],
listing: false,
index: ['index.html']
}
}
}
]);
This is deployed in AWS-EC2, with Nginx reverse proxy.When we hit POST request with payload, working fine in localhost and saves data to MongoDB. But when we hit same POST method from another domain against ec2 deployed server, the below error is showing in pm2 logs. It seems its responding with null before running the controller.
Error in pm2 logs, when we hit POST method:
TypeError: Cannot read property 'statusCode' of null
at /var/www/html/vhosts/custom_BE_ecommerce/api/server.js:123:65
at Object.internals.handler (/var/www/html/vhosts/custom_BE_ecommerce/api/node_modules/podium/lib/index.js:283:33)
at invoke (/var/www/html/vhosts/custom_BE_ecommerce/api/node_modules/podium/lib/index.js:255:23)
at each (/var/www/html/vhosts/custom_BE_ecommerce/api/node_modules/podium/lib/index.js:259:13)
at Object.exports.parallel (/var/www/html/vhosts/custom_BE_ecommerce/api/node_modules/items/lib/index.js:70:13)
at Object.internals.emit (/var/www/html/vhosts/custom_BE_ecommerce/api/node_modules/podium/lib/index.js:276:18)
at module.exports.internals.Server.internals.Podium._emit (/var/www/html/vhosts/custom_BE_ecommerce/api/node_modules/podium/lib/index.js:156:15)
at each (/var/www/html/vhosts/custom_BE_ecommerce/api/node_modules/podium/lib/index.js:197:47)
at Object.exports.parallel (/var/www/html/vhosts/custom_BE_ecommerce/api/node_modules/items/lib/index.js:70:13)
at relay (/var/www/html/vhosts/custom_BE_ecommerce/api/node_modules/podium/lib/index.js:198:15)
at Object.internals.emit (/var/www/html/vhosts/custom_BE_ecommerce/api/node_modules/podium/lib/index.js:202:16)
at internals.emitEmitter (/var/www/html/vhosts/custom_BE_ecommerce/api/node_modules/podium/lib/index.js:303:15)
at processTicksAndRejections (node:internal/process/task_queues:79:21)
Need help on this issue.

Can't able to fetch the user location in meteor

I developed a meteor app in which while registering I am fetching the user location at the client side, to do so I have added the packages listed below:
meteor add mdg:geolocation
meteor add jeremy:geocomplete
meteor aldeed:geocoder
meteor add jaymc:google-reverse-geocode
The code written at client side is as follows:
if (Meteor.isClient) {
Meteor.startup(() => {
GoogleMaps.load({
v: '3.26',
key: '',
libraries: 'geometry,places'
});
console.log("is GoogleMaps.loaded",GooglMaps.loaded());
});
Template.Registration.onRendered(function () {
Tracker.autorun(() => {
if (GoogleMaps.loaded()) {
$('#txt_address').geocomplete({country: "AU", type:
['()']});
}
});
var date = new Date();
$('#div_dob').datetimepicker({
format: 'DD/MM/YYYY',
maxDate : date,
ignoreReadonly: true
});
date=null;
});
Template.Registration.helpers({
location:function(){
$('input[name="txt_address"]').val(Session.get('location'));
}
});
Template.Registration.events({
'click #btn_findlocation':function(event){
alert('Find Location')
event.preventDefault();
function success(position) {
var crd = position.coords;
console.log(`Latitude0 : ${crd.latitude}`);
console.log(`Longitude0: ${crd.longitude}`);
var lat = crd.latitude;
var long = crd.longitude;
reverseGeocode.getLocation(lat, long, function(location)
{
console.log("Address",JSON.stringify(reverseGeocode.getAddrStr()));
Session.set('location', reverseGeocode.getAddrStr());
});
};// end of function success(position)
function error(err) {
console.warn('ERROR(' + err.code + '): ' + err.message);
};//end of function error(err)
// geolocation options
var options = {
enableHighAccuracy: true,
maximumAge: 0
};// end of var options
navigator.geolocation.getCurrentPosition(success, error,
options);
},
})
}
But I am getting false value for GoogleMaps.loaded() function and the following below error when I click a button to fetch the location.
Can't able to read formatted address of undefined.
Results are inconsistent as sometimes I was able to fetch the location other times not.
Please give any suggestions...

Alexa skill forgets session between intents

I'm not sure if it's because I'm testing in the alexa developer console but it appears the session is restarted after every intent.
In the below code, if I invoke SetMyVarA it will write out the correct value to cloudwatch (or the terminal when using serverless), but if I then invoke SetMyVarB immediately after then I'll get "Hmm, I don't know that one" (running locally will just give me undefined for the value).
I've also tried following the advice in this question but it didn't seem to have an effect: adding alexa skill session attributes from nodejs
/*jslint es6 */
"use strict";
const Alexa = require(`alexa-sdk`);
module.exports.handler = (event, context, callback) => {
console.log(`handler: ${JSON.stringify(event.request)}`);
const alexa = Alexa.handler(event, context, callback);
alexa.appId = process.env.APP_ID;
alexa.registerHandlers(handlers);
alexa.execute();
};
const handlers = {
"LaunchRequest": function() {
console.log(`LaunchRequest`);
this.emit(`AMAZON.HelpIntent`);
},
"SetMyVarA": function() {
console.log(`Set MyVarA`);
var myVarA = this.event.session.attributes.myVarA = this.event.request.intent.slots.myVarA.value;
console.log(`MyVarA is ${myVarA}.`);
var speechOutput = `MyVarA has been set to ` + myVarA + `.`;
this.response.speak(speechOutput);
this.emit(`:responseReady`);
},
"SetMyVarB": function() {
console.log(`Set MyVarB`);
var myVarB = this.event.session.attributes.myVarB = this.event.request.intent.slots.myVarB.value;
console.log(`MyVarB is ${myVarB}.`);
var myVarA = this.event.session.attributes.myVarA
console.log(`MyVarA is ${myVarA}.`);
var speechOutput = {
"type": `SSML`,
"ssml": `<speak>MyVarB is ` + myVarB + `.</speak>`,
};
this.response.speak(speechOutput);
this.emit(`:responseReady`);
},
"AMAZON.HelpIntent": function() {
var speechOutput = `This is a skill.`;
var reprompt = `Help here.`;
speechOutput = speechOutput + reprompt;
this.response.speak(speechOutput)
.listen(reprompt);
this.emit(`:responseReady`);
},
"AMAZON.CancelIntent": function() {
},
"AMAZON.StopIntent": function() {
},
"AMAZON.RepeatIntent": function() {
console.log(`RepeatIntent`);
this.emit(`LaunchRequest`);
},
"Unhandled": function() {
// handle any intent in interaction model with no handler code
console.log(`Unhandled`);
this.emit(`LaunchRequest`);
},
"SessionEndedRequest": function() {
// "exit", timeout or error. Cannot send back a response
console.log(`Session ended: ${this.event.request.reason}`);
},
};
In SetMyVar if you use speak() and then emit a responseReady the session gets closed by default, so you're already out of it when you try to call your 2nd intent.
If you want to do exactly the same thing you're doing in SetMyVarA but not close the session immediately you need to set this.response.shouldEndSession to false. The Alexa Dev Console can handle skill sessions with no problems, so don't worry about that.
By the way, you're using ASK v1 which is outdated. Please switch to v2 code like this:
https://developer.amazon.com/blogs/alexa/post/decb3931-2c81-497d-85e4-8fbb5ffb1114/now-available-version-2-of-the-ask-software-development-kit-for-node-js
https://ask-sdk-for-nodejs.readthedocs.io/en/latest/ASK-SDK-Migration-Guide.html

Grunt jshint reporter to send out emails

I have added grunt jshint task to my grunt. I created custom reporter to send out jsHint output as email. My custom reporter function is invoked. But no emails are coming through. There are no errors in the code.
Grunt version: "grunt": "^0.4.5",
"nodemailer": "^1.11.0",
"nodemailer-sendmail-transport": "^1.0.0"
Here is the sample code:
var nodemailer = require('nodemailer');
var smtpTransport = require('nodemailer-smtp-transport');
var async = require('async');
module.exports = {
reporter: function (errors) {
var len = errors.length,
str = '';
var items = [1];
errors.forEach(function (r) {
var file = r.file,
err = r.error;
str += file + ": line " + err.line + ", col " +
err.character + ", " + err.reason + "\n";
});
if (str) {
str += "\n" + len + " error" + ((len === 1) ? "" : "s") + "\n";
}
var transporter = nodemailer.createTransport( smtpTransport( {
service: "gmail",
secureConnection: false, // use SSL
port: 587, // port for secure SMTP
auth: {
user: "<my gmail username>",
pass: "<gmail account password>"
},
tls:{
ciphers:'SSLv3'
},
logger: true, // log to console
debug: true // include SMTP traffic in the logs
}));
// setup e-mail data with unicode symbols
var mailOptions = {
from: '<sender address>',
to: '<recipient address>',
subject: 'Hello', // Subject line
text: "why are you not working"
/* text: str */// plaintext body
/*html: '<b>Hello world</b>' // html body*/
};
async.eachSeries(items, function (item, next) {
transporter.sendMail(mailOptions, function(error, response){
// THIS CALLBACK IS NOT CALLED AT ALL
if(error){
console.log(error);
}else{
console.log("Message sent");
}
next(null);
});
}, function(err){
// All tasks are done now
console.log('All tasks are done now');
});
}
};
with async or without async doesn't matter. No emails are coming. I tried bye turning on the "Receive emails from unsecured apps" by following another stackoverflow post. That also did not help.
I would like to know is this correct approach or not? Any help/input is appreicated.

Internal Server Error trying to update server database in Meteor.js

I've been modifying the example meteor app at http://meteor.com/examples/leaderboard. As you can see in the code bellow, I'm trying to update the score of players upon someone hitting the reset button. This updated fine on the client side but in my console I noticed the error "update failed: 500 -- Internal server error". Upon further inspection I saw that indeed, the server side database was not being updated. Any thoughts? (relevant code is in the reset function but I've posted the rest here just in case)
// Set up a collection to contain player information. On the server,
// it is backed by a MongoDB collection named "players."
Players = new Meteor.Collection("players");
var SORT_OPTIONS = {
name: {name: 1, score: -1},
score: {score: -1, name: 1}
}
var NAMES = [ "Ada Lovelace",
"Grace Hopper",
"Marie Curie",
"Carl Friedrich Gauss",
"Nikola Tesla",
"Claude Shannon" ];
function reset(options) {
if (options && options['seed'] === true) {
for (var i = 0; i < NAMES.length; i++) {
Players.insert({ name: NAMES[i], score: Math.floor(Math.random()*10)*5 });
}
}
if (options && options['restart'] === true) {
Players.update( {},
{ $set: { score: Math.floor(Math.random()*10)*5 } },
{multi: true});
}
}
if (Meteor.is_client) {
Template.leaderboard.players = function () {
var sort_by = SORT_OPTIONS[Session.get("sort_by")]
return Players.find({}, {sort: sort_by});
};
Template.leaderboard.selected_name = function () {
var player = Players.findOne(Session.get("selected_player"));
return player && player.name;
};
Template.player.selected = function () {
return Session.equals("selected_player", this._id) ? "selected" : '';
};
Template.leaderboard.events = {
'click input.inc': function () {
Players.update(Session.get("selected_player"), {$inc: {score: 5}});
},
'click input.sort': function () {
Session.get("sort_by") == "score" ? Session.set("sort_by", "name") : Session.set("sort_by", "score");
},
'click input.reset': function () {
reset({'restart': true});
}
};
Template.player.events = {
'click': function () {
Session.set("selected_player", this._id);
}
};
}
// On server startup, create some players if the database is empty.
if (Meteor.is_server) {
Meteor.startup(function () {
if (Players.find().count() === 0) {
reset({'seed': true});
}
});
}
This also happened to me, but checking the server log, the problem I had was that the $inc modifier requires a number for the argument for the update method, so I made sure it got it with
Number()
Time went by and it now works :) I guess it was some server issue on their demo deploy site.

Resources