module.exports.handler = (event, context) => {
  const body = qs.parse(event['body-json']);
  const text = [
    body.theme + ' theme deployed',
    'by ' + body.deployer,
    'from r' + body.previous_revision,
    'to r' + body.deployed_revision
  ].join(' ');

  let sns = new AWS.SNS();
  let p1 = sns.publish({
    Message: text, 
    Subject: "Deploy Notification",
    TopicArn: process.env.SNS_TOPIC_ARN
  }).promise();

  let p2 = slack.notify({
    'url': process.env.SLACK_URL,
    'text': text
  });

  Promise.all([p1, p2]).then((values) => {
    context.done(null, {
      success: true
    });
  });
};
Esempio n. 2
0
exports.handler = (event, context, callback) => {
  // signature validation
  const bodyString = JSON.stringify(event.body);
  const hmac = crypto.createHmac('sha256', CHANNEL_SECRET);
  const bodyBuffer = new Buffer(bodyString, 'utf8');
  hmac.update(bodyBuffer);
  const signature = hmac.digest('base64');
  const validation = signature === event.headers[SIGNATURE_HEADER];

  if (!validation) {
    callback(new Error('Invalid signature.'));
  }

  // publish
  if (validation) {
    let params = {};
    params.Message = bodyString;
    params.Subject = CONFIG.messageSubject || 'Receiving messages from LINE BOT API';
    params.TopicArn = CONFIG.topicArn;


    let sns = new AWS.SNS({'apiVersion': '2010-03-31'});
    sns.publish(params, (err, data) => {
      if (err) {
        callback(err);
      } else {
        console.info('Published to an AWS SNS topic.');
        console.info('MessageId: ', data.MessageId);
      }
    });
  }
};
Esempio n. 3
0
var fireEvent = function(params, messageId, result) {
  var deferred = Q.defer();
  var sns = new AWS.SNS();
  var message = {
    header: {
      id: messageId,
      type: _.capitalize(params.type),
      action: params.action,
      rpc : params.rpc || false,
      created_by: 'AwsRecAPI v1',
      created_at: new Date().toISOString()
    },
    body: params.handler_result_func ? params.handler_result_func(result) : params.handler_args
  };
  var snsMsg = {
    Subject: '[BORG-EVENT] ' + params.type,
    Message: JSON.stringify(message),
    TopicArn: topicBase + ':' + params.type + '-event'
  };
  sns.publish(snsMsg, function(err, data) {
    if (err) return deferred.reject(err);
    deferred.resolve(data);
  });
  return deferred.promise;
}
Esempio n. 4
0
exports.sns = function(req, res){
  var client = new AWS.SNS();
  client.listTopics({}, function(err, data) {
      res.write(JSON.stringify(data.Topics));
  });
  res.end();
};
function sendSNS(data, callback) {
  if (process.env.NODE_ENV !== 'production') {
    console.log('Skipping SNS as not in production.');
    return callback(null, data);
  }

  const sns = new AWS.SNS();
  sns.publish({
    TargetArn: PUBLISH_ARN,
    Message: JSON.stringify(data),
    Subject: 'Sermon uploaded',
  }, (error, response) => {
    if (error) {
      console.log('SNS message failed to send');
      console.error(error);
      return callback(error);
    }

    console.log(`SNS message sent to ${PUBLISH_ARN}`);
    data.sns_response = response;

    return callback(null, data);
  });

  return null;
}
Esempio n. 6
0
    }).then(function(result){
      console.log("RESULT",result)
      var response = {
          statusCode: 200,
          body: JSON.stringify(result)
      };

      var message = {
        token: result["access_token"],
        app_id: app_id,
        ttl: result["expires_in"]
      }
      console.log("message",message)
      var sns = new AWS.SNS();
      sns.publish({
          Message: JSON.stringify(message),
          TopicArn: process.env.SNS_OAUTH_SYNC_ARN
      }, function(err, data) {
        console.log(err,data)
          if (err) {
              console.log("SNS error",err.stack);
              return;
          }
          console.log('push sent',data);
          context.succeed(response)
      });
    }) //end then
Esempio n. 7
0
        sendNotification: function (params, callback) // sendEmail(message_params, callback)
            {
                aws.config.update({region: "us-west-2"});
                var sns = new aws.SNS();

                params.TopicArn = CONFIG.snsEmails;

                sns.publish(params, callback);
            },
Esempio n. 8
0
 t.test('mock function replaces method with a function that returns replace string', function(st){
   awsMock.mock('SNS', 'publish', 'message');
   var sns = new AWS.SNS();
   sns.publish({}, function(err, data){
     st.equals(data, 'message');
     awsMock.restore('SNS');
     st.end();
   })
 });
Esempio n. 9
0
 t.test('Specific Modules can be set for mocking', function(st) {
   awsMock.setSDK('aws-sdk');
   awsMock.mock('SNS', 'publish', 'message');
   var sns = new AWS.SNS();
   sns.publish({}, function(err, data){
     st.equals(data, 'message');
     awsMock.restore('SNS');
     st.end();
   })
 });
Esempio n. 10
0
 t.test('mock function replaces method with replace function', function(st){
   awsMock.mock('SNS', 'publish', function(params, callback){
     callback(null, "message");
   });
   var sns = new AWS.SNS();
   sns.publish({}, function(err, data){
     st.equals(data, 'message');
     awsMock.restore('SNS');
     st.end();
   })
 })
Esempio n. 11
0
// Sends an SMS message using SNS
// kindOfDay: response from Holly on the kind of day she had
// completedCallback(status) : Callback with status message when the function completes.
function TextMom(kindOfDay, callback) {
    var day = kindOfDay.value;
    console.log("Day value is " + day);
    
    if (day)
    {
        var sns = new AWS.SNS();
        var params = {
            Message: 'Holly is home and she had a ' + day + " day.", 
            TopicArn: 'arn:aws:sns:us-east-1:664961887072:MomImHome'
        };
    
        sns.publish(params, function (err, data) {
            if (err) console.log(err, err.stack); // an error occurred
            else
            {   
                console.log("Success"); 
                
                 if ("good" === day)
                    {
                        speechOutput = "I'm glad to know you had a good day! " +
                        "I will inform your mom so she can raise the roof with her hands like your dad does. ";
                    } 
                    else if ("bad" === day)
                    { 
                        speechOutput = "I'm sorry you had a bad day. " +
                        "I will inform your mom but she will want to know why when she gets home. ";
                    }
                    
                    var sessionAttributes = {};
                    var speechOutput = speechOutput + "Ok, the message was sent.";
                            
                    var repromptText = "";
                    var shouldEndSession = true;
                    
                    callback(sessionAttributes,
                        buildSpeechletResponse(speechOutput, repromptText, shouldEndSession));
                    
            }
        });
    }
    else
        {
            var sessionAttributes = {};
            var shouldEndSession = false;
            speechOutput = "I'm not sure what kind of day you had. Please try again";
            repromptText = "I'm not sure what kind of day you had. You can tell me if " +
            "you had a good or bad day.";
            
            callback(sessionAttributes,
                        buildSpeechletResponse(speechOutput, repromptText, shouldEndSession));
        }
    }
Esempio n. 12
0
 t.test('service is not re-mocked if a mock already exists', function(st){
   awsMock.mock('SNS', 'publish', function(params, callback){
     callback(null, "message");
   });
   var sns = new AWS.SNS();
   awsMock.mock('SNS', 'subscribe', function(params, callback){
     callback(null, "test");
   });
   sns.subscribe({}, function(err, data){
     st.equals(data, 'test');
     awsMock.restore('SNS');
     st.end();
   })
 })
  const create = (name, callback) => {
    // If this queue already exists, it just returns the ARN
    const sns = new AWS.SNS();
    console.log(`Creating SNS topic: ${name}`);

    sns.createTopic({
      Name: name
    }, (err, result) => {
      if (err) {
        callback(err);
      } else {
        callback(null, result.TopicArn);
      }
    });
  };
Esempio n. 14
0
        rtm.on(RTM_EVENTS.MESSAGE, function handleRtmMessage(message) {
            // TODO: THIS HAS TO BE REMOVED BEFORE GOING LIVE
            // Log the message recieved.
            console.log('Message:', message);

            // Construct the client.
            snsClient = new AWS.SNS({credentials:AWS.credentials});

            // Get the list of topics
            snsClient.listTopics(null, function (err,data) {
                if(err) console.log(err, err.stack);
                else   publishMsgToTopic(message.text.toString('utf-8'), // Ensure that its in UTF.
                                         data.Topics[0].TopicArn);
            });
        });
Esempio n. 15
0
	this.sendSMS = function(msg) {
		var deferred = Q.defer();
		var sns = new AWS.SNS();
		var params = {
			Message: msg, /* required */
			TopicArn: this.topicArn
		};
		var request = sns.publish(params, function(err, data) {
			if (err) 
				deferred.reject(new Error(err));
			else 
				deferred.resolve(data);
		});
		return deferred.promise;
	};
Esempio n. 16
0
 findExistingSubscription(topicArn, null, (err, res) => {
     if (err) {
         console.log('Error finding existing subscription.', err);
         cb(err);
         return;
     }
     if (!res) {
         // no subscription, create one
         const params = {
             Protocol: 'email',
             TopicArn: topicArn,
             Endpoint: EMAIL,
         };
         SNS.subscribe(params, (err, data) => {
             if (err) {
                 console.log('Error setting up email subscription.', err);
                 cb(err);
                 return;
             }
             // subscription complete
             console.log(`Subscribed ${EMAIL} to ${topicArn}.`);
             cb(null, topicArn);
         });
     } else {
         // subscription already exists, continue
         cb(null, topicArn);
     }
 });
Esempio n. 17
0
 return callbackPromise((cb) => {
     sns.subscribe({
         TopicArn: topicArn,
         Protocol: 'lambda',
         Endpoint: functionArn
     }, cb);
 })
Esempio n. 18
0
 return __awaiter(this, void 0, void 0, function* () {
     var snsClient = new AWS.SNS();
     var topicArn = "arn:aws:sns:eu-west-1:170643467817:MessageBus_" + this.messageType;
     console.log("Topic Arn: " + topicArn);
     var publishResponse = yield this.executeAwsRequestAsync((callback) => snsClient.publish({ TopicArn: topicArn, Message: this.message }, callback));
     console.log("Published: " + publishResponse.MessageId);
 });
Esempio n. 19
0
function sentMessageToOne() {
    console.log("in send");
    console.log(endPoint);
    var params = {
        Message: 'test from node',//  required
        MessageAttributes:{
            coldstart: {
                DataType: 'String',
                StringValue: 'true'
            },
            msgcnt:{
                DataType: 'String',
                StringValue: '3'
            }
        },
        MessageStructure: 'String',
        Subject: 'AWS and node',
        TargetArn: 'arn:aws:sns:us-west-2:483527748797:endpoint/GCM/NoSolo/72e39431-528f-39d5-9135-9c09291e0191'//endPoint.EndpointArn
    };
    sns.publish(params, function (err, data) {
        if (err) {
            console.log('in sent err');
            console.log(err, err.stack);

        } // an error occurred
        else {
            console.log(data);
        }
        // successful response
    });
};
Esempio n. 20
0
  build.statusEmitter.on('finish', (err, buildInfo) => {
    var subject = `LambCI Build #${buildInfo.buildNum} successful!`
    var message = `LambCI Build #${buildInfo.buildNum}
Repo: ${this.repo}
${this.prNum ? `Pull Request: ${this.prNum}` : `Branch: ${this.branch}`}
Commit: ${this.commit}
Log: ${this.logUrl}
`
    if (err) {
      message += `Error: ${err.message}`
      if (err.logTail) {
        message += `\n${err.logTail}`
      }
      subject = `LambCI Build #${buildInfo.buildNum} failed`
    }
    sns.publish({
      TopicArn: this.topicArn,
      Subject: subject,
      Message: message,
      MessageAttributes: {
        status: {
          DataType: 'String',
          StringValue: err ? 'failure' : 'success',
        },
      },
    }, log.logIfErr)
  })
Esempio n. 21
0
function sendSilentNotification (endpoint) {
  var payload = {
    APNS_SANDBOX: {
      aps: {}
    }
  };
  var aps = {}

  aps['content-available'] = 1;
  aps['endpoint'] = endpoint;

  payload.APNS_SANDBOX.aps = aps;
  payload.APNS_SANDBOX = JSON.stringify(payload.APNS_SANDBOX);
  payload = JSON.stringify(payload);

  // Determine what ARN or other targeting you want to use for the destination of the notification
  var targetARN = "";

  var snsInfo = {
    Message: payload,
    MessageStructure: 'json',
    TargetArn: targetARN
  };
  sns.publishAsync(snsInfo)
    .then(function (data) {
    })
    .catch(function (error) {
    });

  return true;
}
Esempio n. 22
0
            }, function(err, data) {
            
                if (err) {
                    console.log(err.stack);
                    return;
                }
                
                var endpointArn = data.EndpointArn;

                payload.GCM = JSON.stringify(payload.GCM);
                payload = JSON.stringify(payload);
                                
                sns.publish({
                
                    Message: payload,
                    MessageStructure: 'json',
                    TargetArn: endpointArn
                    
                }, function(err, data) {
                
                    if (err) {
                        console.log(err.stack);
                        return;
                    }
                    
                
                });
                
        });
Esempio n. 23
0
module.exports.addNote = (event, context, callback) => {
  const data = JSON.parse(event.body);
  if (typeof data.note !== 'string') {
    console.error('Validation Failed');
    callback(new Error('Couldn\'t add the note.'));
    return;
  }

  const params = {
    Message: data.note,
    TopicArn: `arn:aws:sns:us-east-1:${config.awsAccountId}:analyzeNote`,
  };

  sns.publish(params, (error) => {
    if (error) {
      console.error(error);
      callback(new Error('Couldn\'t add the note due an internal error. Please try again later.'));
    }
    // create a resonse
    const response = {
      statusCode: 200,
      body: JSON.stringify({ message: 'Successfully added the note.' }),
    };
    callback(null, response);
  });
};
Esempio n. 24
0
			db.collection('tweets').update(item, update, false, function(err, result) {
				if(err) {
					console.log('Updating doc failed');
				}
				else{// Updated 
					// delete message from queue
					var paramsD = {
						QueueUrl: 'https://sqs.us-west-2.amazonaws.com/582714090425/tweets',
						ReceiptHandle: data.Messages[0].ReceiptHandle
					};

					sqs.deleteMessage(paramsD, function (err, data){
						if (err) console.log(err, err.stack);
						//else	console.log(data);
					});
					// send to SNS
					var paramsSNS = {
						Message: JSON.stringify({_id: data.Messages[0].MessageAttributes.tweetID.StringValue}),
						Subject: 'sentiment',
						TopicArn: 'arn:aws:sns:us-west-2:582714090425:TweetSentiment'
					};
					sns.publish(paramsSNS, function(err, data) {
						if(err) {
							console.log(err);
						}
						//else console.log(data);
					});
				}
			});
Esempio n. 25
0
File: sns.js Progetto: lambci/lambci
  build.statusEmitter.finishTasks.push((build, cb) => {
    var subject = `LambCI Build #${build.buildNum} successful!`
    var message = `LambCI Build #${build.buildNum}
Repo: ${this.repo}
${this.prNum ? `Pull Request: ${this.prNum}` : `Branch: ${this.branch}`}
Commit: ${this.commit}
Log: ${this.logUrl}
`
    if (build.error) {
      message += `Error: ${build.error.message}`
      if (build.error.logTail) {
        message += `\n${build.error.logTail}`
      }
      subject = `LambCI Build #${build.buildNum} failed`
    }
    sns.publish({
      TopicArn: this.topicArn,
      Subject: subject,
      Message: message,
      MessageAttributes: {
        status: {
          DataType: 'String',
          StringValue: build.error ? 'failure' : 'success',
        },
      },
    }, function(err) {
      log.logIfErr(err)
      cb()
    })
  })
Esempio n. 26
0
  t.test('all the services are restored when no arguments given to awsMock.restore', function(st){
    awsMock.mock('SNS', 'publish', function(params, callback){
      callback(null, "message");
    });
    awsMock.mock('DynamoDB', 'putItem', function(params, callback){
      callback(null, "test");
    });
    awsMock.mock('DynamoDB.DocumentClient', 'put', function(params, callback){
      callback(null, "test");
    });
    var sns      = new AWS.SNS();
    var docClient = new AWS.DynamoDB.DocumentClient();
    var dynamoDb = new AWS.DynamoDB();

    st.equals(AWS.SNS.isSinonProxy, true);
    st.equals(AWS.DynamoDB.DocumentClient.isSinonProxy, true);
    st.equals(AWS.DynamoDB.isSinonProxy, true);
    st.equals(sns.publish.isSinonProxy, true);
    st.equals(docClient.put.isSinonProxy, true);
    st.equals(dynamoDb.putItem.isSinonProxy, true);

    awsMock.restore();

    st.equals(AWS.SNS.hasOwnProperty('isSinonProxy'), false);
    st.equals(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false);
    st.equals(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false);
    st.equals(sns.publish.hasOwnProperty('isSinonProxy'), false);
    st.equals(docClient.put.hasOwnProperty('isSinonProxy'), false);
    st.equals(dynamoDb.putItem.hasOwnProperty('isSinonProxy'), false);
    st.end();
  })
Esempio n. 27
0
	.then(() => {
		if (newObjects.snsTopic) {
			return sns.deleteTopic({
				TopicArn: newObjects.snsTopic
			}).promise();
		}
	})
Esempio n. 28
0
 validator.validate(JSON.parse(this.request.body), (err, message) => {
   if (err) {
     console.log(err.message);
     res.statusCode = 403;
     res.end('Invalid message\n');
   } else if (message['Type'] === 'SubscriptionConfirmation') {
     sns.confirmSubscription({
       Token: message['Token'],
       TopicArn: message['TopicArn']
     }, (err, data) => {
       if (err) {
         console.log(err.message);
       }
       else {
         console.log(data);
       }
     });
   } else if (message['Type'] === 'Notification') {
     let tweet = JSON.parse(message['Message']);
     Meteor.call('indexTweet', tweet, (err) => {
       if (err) {
         console.log(err.message);
       }
     });
   }
 });
Esempio n. 29
0
    Recipient.update(omitEmpty(recipient), event.listId, event.recipientId).then((newRecipient) => {
      debug('= unsubscribeRecipient.action', 'Success');
      const recipientParams = {
        campaignId: event.campaignId,
        userId: newRecipient.userId,
        listId: event.listId
      };
      const params = {
        Message: JSON.stringify(recipientParams),
        TopicArn: process.env.UNSUBSCRIBED_RECIPIENT_TOPIC_ARN
      };
      sns.publish(params, (err, data) => {
        if (err) {
          debug('= unsubscribeRecipient.action', 'Error publishing to SNS', JSON.stringify(err));
          return cb(ApiErrors.response(err));
        } else {
          debug('= unsubscribeRecipient.action', 'Successfully published to SNS');
          List.get(newRecipient.userId, event.listId).then((list) => {
            const callbackUrl = buildRedirectCallback(process.env.UNSUBSCRIBED_CALLBACK_URL, list, event.recipientId, event.campaignId);
            return cb(null, { url: callbackUrl });
          }).catch((e) => {
            const callbackUrl = process.env.UNSUBSCRIBED_CALLBACK_URL;
            return cb(null, { url: callbackUrl });
          });

        }
      });
    })
Esempio n. 30
0
  function sendSMS(message) {
    var params = {
      Message: message,
      TopicArn: config.aws.topicArn 
    };

    sns.publish(params, function(error, data) {});
  }