GithubHelp home page GithubHelp logo

sns-mobile's Introduction

Maintainer(s)

I no longer use this and haven't got the capacity to maintain it. If you'd like to be a maintainer of this library please get in touch.

A current active fork is available at https://github.com/kalisio/sns-mobile (have a look to #34 for some details).

SNS Mobile Push

Module to make interacting with mobile push notifications for iOS and Android easier. Wraps the Amazon aws-sdk node module. The idea is that you can create an object to represent each Platform Application you plan to use and remove the excess features that aren't needed for Android and iOS applications.

Installation

npm install sns-mobile

Setting Up a User for SNS

To use Amazon SNS you need a Secret Access Key and an Access Key Id. Getting these will require you to create a user under the IAM section of AWS and attach a User Policy with the following Policy Document:

Disclaimer: I'm not an AWS ninja, this configuration may be too liberal but it works!

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "AccessToSNS",
      "Effect": "Allow",
      "Action": [
        "sns:*"
      ],
      "Resource": [
        "*"
      ]
    }
  ]
}

Simple Code Example for Android

The below example creates an SNS instance for an Android application identified by a PlatformApplicationArn.

var SNS = require('sns-mobile'),
    EVENTS = SNS.EVENTS;

var SNS_KEY_ID = process.env['SNS_KEY_ID'],
  SNS_ACCESS_KEY = process.env['SNS_ACCESS_KEY'],
  ANDROID_ARN = process.env['SNS_ANDROID_ARN'];

var androidApp = new SNS({
  platform: SNS.SUPPORTED_PLATFORMS.ANDROID,
  region: 'eu-west-1',
  apiVersion: '2010-03-31',
  accessKeyId: SNS_KEY_ID,
  secretAccessKey: SNS_ACCESS_KEY,
  platformApplicationArn: ANDROID_ARN,
  //sandbox: true (This is required for targetting (iOS) APNS_SANDBOX only)
});

// Add a user, the endpointArn is their unique id
// endpointArn is required to send messages to the device
androidApp.addUser('some_fake_deviceid_that_i_made_up', JSON.stringify({
  some: 'extra data'
}), function(err, endpointArn) {
  if(err) {
    throw err;
  }

  // Send a simple String or data to the client
  androidApp.sendMessage(endpointArn, 'Hi There!', function(err, messageId) {
    if(err) {
      throw err;
    }

    console.log('Message sent, ID was: ' + messageId);
  });
});

Running Tests

SNS_KEY_ID="<your_sns_key_id>" SNS_ACCESS_KEY="<your_sns_access_key>" SNS_ANDROID_ARN="arn:aws:sns:..." npm test

Events Emitted

Instances created will emit events as listed below and callbacks should have the shown format. Event strings can be accessed as shown below.

var SNS = require('sns-mobile'),
    EVENTS = SNS.EVENTS;

// EVENTS.SENT_MESSAGE
// EVENTS.BROADCAST_END
// EVENTS.BROADCAST_START
// EVENTS.FAILED_SEND
// EVENTS.DELETED_USER
// EVENTS.ADD_USER_FAILED
// EVENTS.ADDED_USER
// EVENTS.ATTRIBUTES_UPDATE_FAILED
// EVENTS.ATTRIBUTES_UPDATED
// EVENTS.TOPIC_CREATED
// EVENTS.CREATE_TOPIC_FAILED
// EVENTS.TOPIC_DELETED
// EVENTS.DELETE_TOPIC_FAILED
// EVENTS.SUBSCRIBED
// EVENTS.SUBSCRIBE_FAILED
// EVENTS.UNSUBSCRIBED
// EVENTS.UNSUBSCRIBE_FAILED
// EVENTS.PUBLISH_FAILED
// EVENTS.PUBLISHED_MESSAGE

var myApp = new SNS({
  platform: SNS.SUPPORTED_PLATFORMS.ANDROID,
  region: 'eu-west-1',
  apiVersion: '2010-03-31',
  accessKeyId: SNS_ACCESS_KEY,
  secretAccessKey: SNS_KEY_ID,
  platformApplicationArn: ANDROID_ARN
  // sandbox: true/false (If we're targetting Apple dev/live APNS)
});

myApp.on(EVENTS.ADDED_USER, function(endpointArn, deviceId){
    // Save user details to a db
});

broadcastStart

function () {}

Emitted prior to broadcasting the first message.

broadcastEnd

function () {}

Emitted once all messages are broadcast.

messageSent

function (endpointArn, res.MessageId) {}

Emitted when a message sends successfully.

userDeleted

function (endpointArn) {}

When a user is deleted this is emitted.

sendFailed

function (endpointArn, err) {}

If a message fails to send this is emitted.

addUserFailed

function(deviceToken, err)

Fired when adding a user fails.

userAdded

function (endpointArn, deviceId) {}

When a user is added this is emitted.

attributesUpdateFailed

function (endpointArn, err) {}

If updating the attributes for an endpoint fails this is emitted.

attributesUpdated

function (endpointArn, attributes) {}

When an endpoint's attributes are updated this is emitted.

topicCreated

function (topicArn, topicName) {}

Emitted when a topic has been created successfully.

createTopicFailed

function (topicName) {}

Emitted when an attempt to create a topic has failed.

topicDeleted

function (topicArn) {}

Emitted when a topic has been deleted successfully.

deleteTopicFailed

function (topicArn) {}

Emitted when an attempt to delete a topic has failed.

subscribed

function (subscriptionArn, endpointArn, topicArn) {}

Emitted when an endpoint has been subscribed to a topic successfully.

subscribeFailed

function (endpointArn, topicArn, err) {}

Emitted when an attempt to subscribe an endpoint to a topic has failed.

unsubscribed

function (subscriptionArn) {}

Emitted when an endpoint has been unsubscribed from a topic successfully.

unsubscribeFailed

function (subscriptionArn, err) {}

Emitted when an attempt to unsubscribe an endpoint from a topic has failed.

publishedMessage

function (topicArn, messageId) {}

Emitted when a message has been published to a topic successfully.

publishFailed

function (topicArn, err) {}

Emitted when an attempt to publish a message to a topic has failed.

API

SNS(opts)

Expects an object with the following params:

  • platform: Supply any of the platforms in SNS.SUPPORTED_PLATFORMS
  • region: The Amazon region e.g 'eu-west-1'
  • apiVersion: Amazon API version, I have only used '2010-03-31'
  • accessKeyId: Amazon user Access Key.
  • secretAccessKey: Amazon user Secret Access Key.
  • platformApplicationArn: The PlatformApplicationArn for the Platform Application the interface operates on.
  • sandbox: Set this to true to target the Apple APNS_SANDBOX environment with messages.

SUPPORTED_PLATFORMS

An object containing supported platforms. Available options are:

  • SUPPORTED_PLATFORMS.ANDROID
  • SUPPORTED_PLATFORMS.IOS
  • SUPPORTED_PLATFORMS.KINDLE_FIRE

getPlatformApplicationArn()

Returns the platformApplicationArn provided to the constructor.

getRegion()

Returns the region being used.

getApiVersion()

Returns apiVersion being used.

getApplications(callback)

Get all Platform Applications. This will not allow you to interface with other PlatformApplications but may be useful to just get a list of you applications. Callback format callback(err, users)

getUser(endpointArn, callback)

Get a user via endpointArn. The callback(err, user) receives an Object containg Attributes for the user and the EndpointArn.

getUsers(callback)

Get all users, this could take a while due to a potentially high number of requests required to get each page of users. The callback(err, users) receives an Array containing users.

getTopics(callback)

Get all topics by paging through them. The callback(err, topics) receives an Array containing topic objects.

getSubscriptions(topicArn, callback)

Get all subscriptions for the topic with the given topicArn by paging through them. The callback(err, subscriptions) receives an Array containing subscription objects.

addUser(deviceToken, [data], callback)

Add a device/user to SNS with optional extra data. Callback has format fn(err, endpointArn).

createTopic(name, callback)

Create a new topic with the given name. The callback has the format fn(err, topicArn).

setAttributes(endpointArn, attributes, callback)

Update an existing endpoint's attributes. Attributes is an object with the following optional properties:

  • CustomUserData: <object|string>
  • Enabled:
  • Token:

Callback has format fn(err, attributes).

deleteUser(endpointArn, callback)

Delete a user from SNS. Callback has format callback(err)

deleteTopic(topicArn, callback)

Delete the topic with the given topicArn. The callback has the format fn(err).

sendMessage(endpointArn, message, callback)

Send a message to a user. The message parameter can be a String, or an Object with the formats below. The callback format is callback(err, messageId).

subscribe(endpointArn, topicArn, callback)

Subscribe an endpoint to a topic. The callback has the format fn(err, subscriptionArn).

unsubscribe(subscriptionArn, callback)

Unsubscribe an endpoint from a topic via the given subscriptionArn. The callback has the format fn(err).

publishToTopic(topicArn, message, callback)

Publish a message a topic. The callback has the format fn(err, messageId). Please note that the message must be in the final Amazon SNS format as specified here, i.e. it must contain a key called default and platform-specific messages must already be JSON-stringified. Example:

{
  "default": "Default message which must be present when publishing a message to a topic. Will only be used if a message is not present for one of the notification platforms.",
  "APNS": "{\"aps\":{\"alert\": \"Check out these awesome deals!\",\"url\":\"www.amazon.com\"} }",
  "GCM":"{\"data\":{\"message\":\"Check out these awesome deals!\",\"url\":\"www.amazon.com\"}}"
}

You can read about Amazon SNS message formats here.

iOS:

{
  aps: {
    alert: message
  }
}

Read more about APNS payload here.

Android & Kindle Fire:

{
  data: {
    message: message
  }
}

Read more about GCM here and ADM here.

broadcastMessage(message, callback)

Send message to all users. May take some time with large sets of users as it has to page through users. Callback format is callback(err). If a single/mulitple messages fail to send the error will not be propogated/returned to the callback. To catch these errors use the sendFailed event.

Contributors

Contrinbutions are very much welcome, just submit a PR with updated tests where applicable. Current tests run against the actual SNS service, which may not be ideal so feel free to mock that out if you like too ;)

Thanks to these awesome folks for contributions:

sns-mobile's People

Contributors

bryant1410 avatar claustres avatar evanshortiss avatar iclems avatar jokecamp avatar mugli avatar rodrigoespinosa avatar santimacia avatar sundeepk avatar thepletch avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

sns-mobile's Issues

example for kindle fire?

Hi sorry for the rude and n00b question, but i got:
Error: Unsupported platform option, "kindle_fire". Please provide a platform from SNS.SUPPORTED_PLATFORMS

can not send message as a object

I am using sendMessage to send notification, but it is working with strings only, when i try to send object it does not work.

// working code
app.sendMessage(arn, 'string message', function (err, messageId) {
console.log(messageId);
});

// not working
app.sendMessage(arn, {message : 'object message'}, function (err, messageId) {
console.log(messageId);
});

Support for topics?

Curious if you plan on adding support for subscribing and unsubscribing to topics?

Push sending has random error

'Invalid parameter: Token Reason: Endpoint arn:aws:sns:*******************:endpoint/APNS_SANDBOX/**************/480e971c-******-bc02-****** already exists with the same Token, but different attributes.',
It give above error ..
Randomly it not goes addUser function also and not give any error too..
plz tell me what i did wrong.
It runs some and some time not
I declare iosApp object as well..

iosApp.addUser(deviecToken, JSON.stringify({
   									some: 'extra data'
   								}), function (err, endpointArn) {
   									if (err) {
   										console.log(err);
   										//resolve(1);
   									} else {
   										
   										console.log("addUser : " + messageId)
   										let endpp = endpointArn;
   										// Send a simple String or data to the client
   										iosApp.sendMessage(endpp, msg, function (err, messageId) {
   											console.log("Push send to : " + messageId)
   											//resolve(1);
   										});
   									}
   								});

I cant reveal whole code..but almost..
@evanshortiss

Windows Phone support?

Hi!

First of all I would like to thank you for this awesome library. I have a question. Are you planning to add windows phone to supported platforms ?

Thank You, Have a nice day.

how to send image with message

i am send messages to all devices for which the users registered. How can i send message along with image. i am using this method to send message to all devices.
sendMessage(endpointArn, message, callback);
//here this method allow two params endpointArn and message.
is there any scope to send image along with that message

license

I don't see a license defined anywhere in the repo. Would you mink determining and adding a license?. Otherwise I cannot use it for a current project. Thank you

Send VOIP Push to IOS

Hi, I am trying to send AWS push to IOS but getting error. Does this library supports sending voip push via Amazon SNS?

Invalid parameter: JSON must contain an entry for 'default' or 'APNS_SANDBOX'.

Any idea why I might be getting this? (more info below)

2015-03-19 20:40:02 - error: ! Error: Invalid parameter: JSON must contain an entry for 'default' or 'APNS_SANDBOX'.
2015-03-19 20:40:02 - error: !     at Request.extractError (/src/node_modules/sns-mobile/node_modules/aws-sdk/lib/service_interface/query.js:61:35)
2015-03-19 20:40:02 - error: !     at Request.callListeners (/src/node_modules/sns-mobile/node_modules/aws-sdk/lib/sequential_executor.js:132:20)
2015-03-19 20:40:02 - error: !     at Request.callListeners (/src/node_modules/sns-mobile/node_modules/aws-sdk/lib/sequential_executor.js:133:16)
2015-03-19 20:40:02 - error: !     at Request.emit (/src/node_modules/sns-mobile/node_modules/aws-sdk/lib/sequential_executor.js:100:10)
2015-03-19 20:40:02 - error: !     at Request.emitEvent (/src/node_modules/sns-mobile/node_modules/aws-sdk/lib/request.js:536:10)
2015-03-19 20:40:02 - error: !     at Request.emitEvents (/src/node_modules/sns-mobile/node_modules/aws-sdk/lib/request.js:510:12)
2015-03-19 20:40:02 - error: !     at Request.completeRequest (/src/node_modules/sns-mobile/node_modules/aws-sdk/lib/request.js:480:10)
2015-03-19 20:40:02 - error: !     at Request.HTTP_DONE (/src/node_modules/sns-mobile/node_modules/aws-sdk/lib/event_listeners.js:230:12)
2015-03-19 20:40:02 - error: !     at Request.callListeners (/src/node_modules/sns-mobile/node_modules/aws-sdk/lib/sequential_executor.js:132:20)
2015-03-19 20:40:02 - error: !     at Request.emit (/src/node_modules/sns-mobile/node_modules/aws-sdk/lib/sequential_executor.js:100:10)
2015-03-19 20:40:02 - error: !     at Request.emitEvent (/src/node_modules/sns-mobile/node_modules/aws-sdk/lib/request.js:536:10)
2015-03-19 20:40:02 - error: !     at IncomingMessage.onEnd (/src/node_modules/sns-mobile/node_modules/aws-sdk/lib/event_listeners.js:190:26)
2015-03-19 20:40:02 - error: !     at IncomingMessage.emit (events.js:117:20)
2015-03-19 20:40:02 - error: !     at _stream_readable.js:944:16
2015-03-19 20:40:02 - error: !     at process._tickDomainCallback (node.js:492:13)
2015-03-19 20:40:02 - error: *

This is my sns object when logged

{ platformApplicationArn: 'my_sandbox_arn',
  platform: 'IOS',
  sandbox: true,
  sns:
   { config:
      { credentials: [Object],
        credentialProvider: [Object],
        region: 'us-east-1',
        logger: null,
        apiVersions: {},
        apiVersion: '2010-03-31',
        endpoint: undefined,
        httpOptions: {},
        maxRetries: undefined,
        maxRedirects: 10,
        paramValidation: true,
        sslEnabled: true,
        s3ForcePathStyle: false,
        computeChecksums: true,
        dynamoDbCrc32: true,
        accessKeyId: 'my_key_id',
        secretAccessKey: 'my_secret_key' },
     endpoint:
      { protocol: 'https:',
        host: 'sns.us-east-1.amazonaws.com',
        port: 443,
        hostname: 'sns.us-east-1.amazonaws.com',
        pathname: '/',
        path: '/',
        href: 'https://sns.us-east-1.amazonaws.com/' } },

Message sent:

{ APNS:
   { aps: { alert: 'Some message to send' },
     otherAppData: 'my data string yay' } }

Allow sns-mobile to take in a reference to an AWS SNS object

Currently sns-mobile always constructs an AWS SNS object for internal use and abstracts this away from the client. However, there are many options that the SNS object can take AWS js Doc.

Allowing clients to pass in their own SNS object allows them to fully configure however they want to, and allow sns-mobile to abstract away the appropriate code to do mobile push. Also, this way we don't need to always supply AWS key and secret. This would be a problem for servers which work on IAM roles.

I can have a crack at fixing this when I get time since it is something that I need and send a pull request.

Unable to resolve module

Hi ,
I am stuck with this error : UnableToResolve. Can you help me ? :)
I tried to

  1. Clear watchman watches: watchman watch-del-all.\n 2. Delete the node_modules folder: rm -rf node_modules && npm install.\n 3. Reset packager cache: rm -fr $TMPDIR/react-* or npm start -- --reset-cache.
    it is not solve my problem :/

error: bundling failed: "Unable to resolve module util from /home/dby/react-native/sns/node_modules/sns-mobile/lib/interface.js: Module does not exist in the module map\n\nThis might be related to https://github.com/facebook/react-native/issues/4968\nTo resolve try the following:\n 1. Clear watchman watches: watchman watch-del-all.\n 2. Delete the node_modules folder: rm -rf node_modules && npm install.\n 3. Reset packager cache: rm -fr $TMPDIR/react-* or npm start -- --reset-cache.

Can't send quotation characters in message

Try to send something like (notice the quotation marks in "these awesome"):

{
  "GCM":"{\"data\":{\"message\":\"Check out "these awesome" deals!\",\"url\":\"www.amazon.com\"}}"
}

And you will get the following error:
'Invalid parameter: Message Reason: Invalid notification for protocol GCM: Notification payload is malformed',

InvalidClientTokenId

I'm getting this error:

[InvalidClientTokenId: The security token included in the request is invalid.]
message: 'The security token included in the request is invalid.',
code: 'InvalidClientTokenId',

I checked the the policy and key details for the user and they are all fine. Not sure why it's giving me this.

Any ideas?

Batch sending

How can I send a 1000 push different notification to a different users at the same time efficiently? For the same message I guess I can use the publish topic but if are different?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.