I've been trying to get push notifications to work with my Parse application. I tried to do so my adding the below code into my Parse server.js file but my server does not start up again when this code is contained inside of the file. I have my p12 file available and linked in the code below (on my actual sever) as well so Im not sure what the issue is.
push: {
android: {
senderId: '...',
apiKey: '...'
},
ios: {
pfx: '/file/path/to/XXX.p12',
passphrase: '', // optional password to your p12/PFX
bundleId: '',
production: false
}
}
My server is running on an Amazon EC2 instance as well.
Are you using AWS SNS to use push notification? If so, you can try setting this in your server code:
function sendPhoneNotification() {
AWS = require('aws-sdk');
AWS.config.update({
accessKeyId: '***',
secretAccessKey: '***',
region: 'ap-southeast-1'
});
var sns = new AWS.SNS();
var promise = new Parse.Promise();
sns.createPlatformEndpoint({
PlatformApplicationArn: '***',
Token: "***"
}, function (err, data) {
if (err) {
console.log("Error in endpoint" + err.stack);
//res.error("error stack 1: " + err.stack);
promise.reject(err.stack);
return promise;
}
var endpointArn = data.EndpointArn;
var payload = {
GCM: {
data: {
title: "YOUR TITLE",
message: "HELLO PUSH NOTIFICATION"
}
}
/* APNS: {
aps: {
alert: 'Hello World',
sound: 'default',
badge: 1
}
}*/
};
// payload.APNS = JSON.stringify(payload.APNS);
payload.GCM = JSON.stringify(payload.GCM);
payload = JSON.stringify(payload);
var result = sns.publish({
Message: payload,
MessageStructure: 'json',
TargetArn: endpointArn
}, function (err, data) {
if (err) {
promise.reject(err.stack);
return promise;
}
res.success("push sent " + JSON.stringify(data));
});
});
return promise;
}
Related
Getting duplicate push notifications while sending one push notification through AWS Pinpoint Service using FCM channel pinpoint.sendMessage method.
pushing notification on an FCM token but getting two different request IDs.
Push Notification callback Reponse
Why does this happen?
How can stop to send duplicate notification from node server?. and I am using "aws-sdk": "^2.1266.0". Any help would be appreciated.
code sample to send push notification :
export const sendPushNotification = async (userId: number, payload: RealTimeNotificationPayload) => {
const deviceTokens = await getAllDeviceTokensForUser(userId);
logInfo('deviceTokens==', deviceTokens)
const tokensTobeRemoved = [];
const pushNotificationPromises = deviceTokens.map(async (deviceToken) => {
const pinpoint = new AWS.Pinpoint();
const params = {
ApplicationId: commonConfig.aws.pinPointApplicationId,
MessageRequest: {
Addresses: {
[deviceToken]: {
ChannelType: PushNotifications.ChannelType.GCM
}
},
MessageConfiguration: {
GCMMessage: {
RawContent: JSON.stringify({
notification: {
title: "Title",
body: "Test body"
}
}),
Priority: 'medium',
SilentPush: false,
TimeToLive: 30,
} as AWS.Pinpoint.GCMMessage
}
}
} as AWS.Pinpoint.Types.SendMessagesRequest;
logInfo('params.MessageRequest==', params.MessageRequest.MessageConfiguration)
await pinpoint.sendMessages(params, async function (err, data) {
if (err) {
logError(err, `Error while sending push notification device token ${deviceToken}`);
}
else {
if (checkIfTokenInvalid(deviceToken, data)) {
tokensTobeRemoved.push(deviceToken);
}
console.log("Response data==> ", JSON.stringify(data, null, 4));
logInfo('data==', deviceToken, data.MessageResponse.Result[deviceToken].DeliveryStatus)
}
}).promise();
})
await Promise.all(pushNotificationPromises);
logInfo('tokensTobeRemoved==', tokensTobeRemoved)
if (tokensTobeRemoved.length) {
await deleteInvalidDeviceTokens(tokensTobeRemoved);
}
}
I am trying to have lambda trigger a codebuild function when it hits the point within the lambda function, here is the current code im using for lamda:
console.log('Loading function');
const aws = require('aws-sdk');
const s3 = new aws.S3();
exports.handler = async (event, context) => {
const codebuild = new aws.CodeBuild();
let body = JSON.parse(event.body);
let key = body.model;
var getParams = {
Bucket: 'bucketname', // your bucket name,
Key: key + '/config/training_parameters.json' // path to the object you're looking for
}
if (key) {
const objects = await s3.listObjects({
Bucket: 'bucketname',
Prefix: key + "/data"
}).promise();
console.log(objects)
if (objects.Contents.length == 3) {
console.log("Pushing")
await s3.getObject(getParams, function(err, data) {
if (err)
console.log(err);
if (data) {
let objectData = JSON.parse(data.Body.toString('utf-8'));
const build = {
projectName: "projname",
environmentVariablesOverride: [
{
name: 'MODEL_NAME',
value: objectData.title,
type: 'PLAINTEXT',
},
]
};
console.log(objectData.title)
codebuild.startBuild(build,function(err, data){
if (err) {
console.log(err, err.stack);
}
else {
console.log(data);
}
});
console.log("Done with codebuild")
}
}).promise();
const message = {
'message': 'Execution started successfully!',
}
return {
'statusCode': 200,
'headers': {'Content-Type': 'application/json'},
'body': JSON.stringify(message)
};
}
}
};
Specifically this part should trigger it:
codebuild.startBuild(build,function(err, data){
if (err) {
console.log(err, err.stack);
}
else {
console.log(data);
}
});
But its not, it even outputs after the function? Im thinking its something to do with promises/await/async but cant find the right solution? Any help would be appreciated.
As you pointed out the problem is related to promises. Change your code like this:
const result = await codebuild.startBuild(build).promise();
And if you configured your lambda permissions for CodeBuild it should work.
You can change your s3.getObject the same way without the callback function:
const file = await s3.getObject(getParams).promise();
console.log(file.Body);
I want to send emails using the ses from aws from lambda. The problem is that the email is only sent some times using the same code. We don't get errors.
Here's the code:
const AWS = require('aws-sdk');
var ses = new AWS.SES();
exports.handler = async (event, context, callback) => {
context.callbackWaitsForEmptyEventLoop = false;
await new Promise((resolve, reject) => {
var params = {
Destination: {
ToAddresses: [myEmail]
},
Message: {
Body: {
Text: { Data: "Test"
}
},
Subject: { Data: "Test Email"
}
},
Source: "sourceMail"
};
ses.sendEmail(params, function (err, data) {
if (err) {
console.log(err);
context.fail(err);
} else {
console.log(data);
context.succeed(event);
}
callback(null, {err: err, data: data});
});
});
}
I would be careful with using callbackWaitsForEmptyEventLoop as it can lead to unexpected results (If this is false, any outstanding events continue to run during the next invocation.).
Can you try using this simplified version:
const AWS = require('aws-sdk');
var ses = new AWS.SES();
exports.handler = async (event, context, callback) => {
const params = {
Destination: {
ToAddresses: [myEmail],
},
Message: {
Body: {
Text: { Data: 'Test' },
},
Subject: { Data: 'Test Email' },
},
Source: 'sourceMail',
};
await ses.sendEmail(params).promise();
return event;
};
I'm trying to invoke a code in AWS Lambda. This Lambda code has been configured with my IOT button. On running this code, I don't see any errors. Also,I don't really see the required push notification on my mobile device.
I can see this message in my console : MissingRequiredParameter: Missing required key 'Message' in params
This is my code:
'use strict';
console.log('Loading function');
var AWS = require('aws-sdk');
var sns = new AWS.SNS();
AWS.config.region = 'xxxxx';
const TopicArn = 'xxxxxxxxxxxxxxxxxxxxxxxxxx'
exports.handler = function(event, context) {
console.log("\n\nLoading handler\n\n");
console.log('Received event:', event);
const sin =
{
"default": "Start",
"APNS_SANDBOX":"{\"aps\":{\"alert\":\"Start\"}}",
"GCM": "{ \"notification\": { \"text\": \"Start\" } }"
} // for single click
const doub = {
"default": "Stop",
"APNS_SANDBOX":"{\"aps\":{\"alert\":\"Stop\"}}",
"GCM": "{ \"notification\": { \"text\": \"Stop\" } }"
} // for double click
const lon = {
"default": "SOS",
"APNS_SANDBOX":"{\"aps\":{\"alert\":\"SOS\"}}",
"GCM": "{ \"notification\": { \"text\": \"SOS\" } }"
} // for long click
var singleClick = sin[Math.floor(Math.random()*sin.length)];
var doubleClick = doub[Math.floor(Math.random()*doub.length)];
var longClick = lon[Math.floor(Math.random()*lon.length)];
var randomMessage = singleClick;
if(event.clickType == "DOUBLE")
{
randomMessage = doubleClick;
}
if(event.clickType == "LONG")
{
randomMessage = longClick;
}
sns.publish ({
Message: randomMessage,
TopicArn: TopicArn
},
function(err, data) {
if (err) {
console.log(err.stack);
return;
}
console.log('push sent');
console.log(data);
context.done(null, 'Function Finished!');
});
}
Can someone help me debug this error?
I found the answer. I had to define my variable too as a string using stringify() command or else JSON formatted message cannot be sent.
I'm using Amazon Simple DB (http://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/SimpleDB.html)
and I'm trying to use putAttributes by writing the following node.js code:
AWS.config = new AWS.Config({accessKeyId: '***', secretAccessKey: '***', region: '***'});
var simpledb = new AWS.SimpleDB();
var params = {
Attributes: [
{
Name: 'firstname',
Value: 'David'
},
],
DomainName: '***', /* required */
ItemName: 'per2', /* required */
};
simpledb.putAttributes(params, function(err, data) {
if (err) console.log(err, err.stack); // an error occurred
else console.log(data); // successful response
});
Unfortunately, I get the following error in console after reading the line:
var simpledb = new AWS.SimpleDB();
try.html?_ijt=no554cohakgtacn421reh33mpr:22 Uncaught TypeError:
AWS.SimpleDB is not a constructor
Do you have any idea what is the problem?