<repo_name>helio-frota/unifiedpush-registration-client<file_sep>/lib/unifiedpush-registration-client.js
'use strict';

/**
* @module unified-push-registration-client
*/

const registry = require('./registry');

/**
  Creates a new UnifiedPush Registration Client
  @param {string} baseUrl - The baseurl for the AeroGear UnifiedPush server - ex: http://localhost:8080/ag-push,
  @returns {Promise} A promise that will resolve with the client object.
  @instance
  @example

  const registrationClient = require('unifiedpush-registration-client')
  const baseUrl: 'http://127.0.0.1:8080/ag-push',

  registrationClient(baseUrl)
    .then((client) => {
      client....
      ...
      ...
    })
 */
function unifiedPushRegistrationClient (baseUrl) {
  const client = {
    registry: {}
  };

  client.baseUrl = baseUrl;

  for (let func in registry) {
    client.registry[func] = registry[func](client);
  }

  return Promise.resolve(client);
}

module.exports = unifiedPushRegistrationClient;
<file_sep>/scripts/start-server.sh
#!/bin/bash

. scripts/version.sh

function waitForServer {
  # Give the server some time to start up. Look for a well-known
  # bit of text in the log file. Try at most 50 times before giving up.
  C=50
  while [ $C -gt 0 ]
  do
    grep "WildFly Full ${WILDFLYVERSION} (WildFly Core 2.0.10.Final) started" wildfly.log
    if [ $? -eq 0 ]; then
      echo "Server started."
      C=0
    else
      echo -n "."
      C=$(( $C - 1 ))
    fi
    sleep 1
  done
}

function waitForUPS {
  # Give the server some time to start up. Look for a well-known
  # bit of text in the log file. Try at most 50 times before giving up.
  C=50
  while [ $C -gt 0 ]
  do
    grep "Deployed \"ag-push.war\" (runtime-name : \"ag-push.war\")" wildfly.log
    if [ $? -eq 0 ]; then
      echo "Server started."
      C=0
    else
      echo -n "."
      C=$(( $C - 1 ))
    fi
    sleep 1
  done
}

WF="${WILDFLY}.tar.gz"
WILDFLY_URL="http://downloads.jboss.org/wildfly/${WILDFLYVERSION}/${WF}"

# Download wildfly server if we don't already have it
if [ ! -e $WILDFLY ]
then
  wget $WILDFLY_URL
  tar xzf $WF
  rm -f $WF
fi
# Download the keycloak wildfly adapter

WF_KC_ADAPTER="${KCWILDFLYADPATER}.tar.gz"
WF_KC_ADAPTER_URL="http://downloads.jboss.org/keycloak/${KCVERSION}/adapters/keycloak-oidc/${WF_KC_ADAPTER}"

wget $WF_KC_ADAPTER_URL
tar xzf $WF_KC_ADAPTER -C ./$WILDFLY
rm -f $WF_KC_ADAPTER


#Download the ups-db file
UPS_DB_FILE="unifiedpush-h2-ds.xml"
UPS_DB_FILE_URL="https://github.com/lholmquist/aerogear-unified-push-server/releases/download/0.0.1/${UPS_DB_FILE}"
wget $UPS_DB_FILE_URL
mv $UPS_DB_FILE ./$WILDFLY/standalone/deployments

#Download the ups-jms-setup
UPS_JMS_CLI="jms-setup-wildfly.cli"
UPS_JMS_CLI_URL="https://github.com/lholmquist/aerogear-unified-push-server/releases/download/0.0.1/${UPS_JMS_CLI}"
wget $UPS_JMS_CLI_URL
mv $UPS_JMS_CLI ./$WILDFLY/bin


#Download the ag-push.war
UPS_WAR="ag-push.war"
UPS_WAR_URL="https://github.com/lholmquist/aerogear-unified-push-server/releases/download/0.0.1/${UPS_WAR}"
wget $UPS_WAR_URL


## Start the wildfly server on port 8082
$WILDFLY/bin/standalone.sh -c standalone-full.xml -b 0.0.0.0 -Djboss.socket.binding.port-offset=2 > wildfly.log 2>&1 &
waitForServer

## Once started run the jms cli script
$WILDFLY/bin/jboss-cli.sh --controller=localhost:9992 --file=$WILDFLY/bin/$UPS_JMS_CLI

## then run the KC related cli commands
$WILDFLY/bin/jboss-cli.sh -c --controller=localhost:9992 --command="/system-property=ups.auth.server.url:add(value=http://localhost:8080/auth)"
$WILDFLY/bin/jboss-cli.sh -c --controller=localhost:9992 --command="/system-property=ups.realm.name:add(value=master)"

## Then add the UPS war
mv $UPS_WAR $WILDFLY/standalone/deployments
waitForUPS
<file_sep>/lib/registry.js
'use strict';

const request = require('request');
const fs = require('fs');

/**
* @module registry
*/

module.exports = {
  registerDevice: registerDevice,
  unregisterDevice: unregisterDevice,
  importer: importer
};

/**
  A function to register a device to the UnifiedPush Server
  @param {object} settings - An settings object
  @param {string} settings.variantId - The id of the variant - used for authentication and variant lookup
  @param {string} settings.secret - The variant secret - used for authentication
  **Device Options**
  These are metadata for each Device.  The Device Token is the only required thing
  @param {object} deviceOptions - a deviceOptions object
  @param {string} deviceOptions.deviceToken - unique string to identify an Installation with its PushNetwork
  @param {string} [deviceOptions.alias] - string to map the Installation to an actual user.
  @param {boolean} [deviceOptions.enabled] - Flag if the actual client installation is enabled (default) or not.
  @param {string} [deviceOptions.platform] - the name of the platform. FOR ADMIN UI ONLY - Helps with setting up Routes
  @param {string} [deviceOptions.deviceType] - the type of the registered device
  @param {string} [deviceOptions.operatingSystem] - the name of the Operating System.
  @param {string} [deviceOptions.osVersion] - the version string of the mobile OS.
  @params {Array} [deviceOptions.categories] - set of all categories the client is in
  @returns {Promise} A promise that will resolve with the device options registered
  @example
  registrationClient(baseUrl)
    .then((client) => {
      client.registry.registerDevice(settings, deviceOptions)
        .then((device) => {
        console.log(device) // {...}
      })
    })
 */
function registerDevice (client) {
  return function registerDevice (settings, deviceOptions) {
    return new Promise((resolve, reject) => {
      settings = settings || {};
      const req = {
        url: `${client.baseUrl}/rest/registry/device/`,
        method: 'POST',
        body: deviceOptions,
        json: true,
        auth: {
          user: settings.variantId,
          pass: settings.secret
        }
      };

      request(req, (err, response, body) => {
        if (err) {
          return reject(err);
        }

        if (response.statusCode !== 200) {
          return reject(response.statusMessage);
        }

        return resolve(body);
      });
    });
  };
}

/**
  A function to unregister a device to the UnifiedPush Server
  @param {object} settings - An settings object
  @param {string} settings.variantId - The id of the variant - used for authentication and variant lookup
  @param {string} settings.secret - The variant secret - used for authentication
  @param {string} settings.deviceToken - unique string to identify an Installation with its PushNetwork
  @returns {Promise} A promise that will resolve
  @example
  registrationClient(baseUrl)
    .then((client) => {
      client.registry.unregisterDevice(settings)
        .then(() => {
        console.log('success')
      })
    })
 */
function unregisterDevice (client) {
  return function unregisterDevice (settings) {
    return new Promise((resolve, reject) => {
      settings = settings || {};
      const req = {
        url: `${client.baseUrl}/rest/registry/device/${settings.deviceToken}`,
        method: 'DELETE',
        json: true,
        auth: {
          user: settings.variantId,
          pass: <PASSWORD>
        }
      };

      request(req, (err, response, body) => {
        if (err) {
          return reject(err);
        }

        if (response.statusCode !== 204) {
          return reject(body);
        }

        return resolve(body);
      });
    });
  };
}

/**
  A function for uploading a JSON file to allow massive device registration (aka import)
  @param {object} settings - An settings object
  @param {string} settings.variantId - The id of the variant - used for authentication and variant lookup
  @param {string} settings.secret - The variant secret - used for authentication
  @param {Array|Stream|String} devices - This is the list of Devices to upload.
  @returns {Promise} A promise that will resolve
  @example
  registrationClient(baseUrl)
    .then((client) => {
      client.registry.importer(settings, devices)
        .then(() => {
        console.log('success')
      })
    })
 */
function importer (client) {
  return function importer (settings, devices) {
    return new Promise((resolve, reject) => {
      settings = settings || {};
      const req = {
        url: `${client.baseUrl}/rest/registry/device/importer`,
        method: 'POST',
        json: true,
        auth: {
          user: settings.variantId,
          pass: <PASSWORD>
        }
      };

      const formData = {};
      if (typeof devices === 'string') {
        formData.file = fs.createReadStream('./scripts/importer-test.json');
      } else if (devices instanceof require('stream').Readable) {
        formData.file = devices;
      } else {
        formData.file = JSON.stringify(devices);
      }

      req.formData = formData;

      request(req, (err, response, body) => {
        if (err) {
          return reject(err);
        }

        if (response.statusCode !== 200) {
          return reject(body);
        }

        return resolve(body);
      });
    });
  };
}
<file_sep>/scripts/version.sh
#!/bin/bash

export VERSION="0.1.0"

export WILDFLYVERSION="10.0.0.Final"
export WILDFLY="wildfly-${WILDFLYVERSION}"

export KCVERSION="1.9.4.Final"
export KEYCLOAK="keycloak-${KCVERSION}"

export KCWILDFLYADPATER="keycloak-wildfly-adapter-dist-${KCVERSION}"
<file_sep>/scripts/stop-server.sh
#!/bin/bash

. scripts/version.sh

${WILDFLY}/bin/jboss-cli.sh --connect --controller=localhost:9992 command=:shutdown
<file_sep>/index.js
module.exports = require('./lib/unifiedpush-registration-client');
<file_sep>/example.js
'use strict';

const registrationClient = require('./');

const baseUrl = 'http://localhost:8082/ag-push';

registrationClient(baseUrl).then((client) => {
  const settings = {
    variantId: 'c82e79c0-1c26-45dc-b482-8f75ce35510d',
    secret: '9a2906ee-95da-45d6-8fdb-643b2d0f9a43'
  };

  const deviceOptions = {
    deviceToken: '<KEY>:<KEY>',
    alias: 'android node'
  };

  return client.registry.registerDevice(settings, deviceOptions).then((deviceRegistration) => {
    console.log(deviceRegistration);
  });
}).catch((err) => {
  console.log('error', err);
});
<file_sep>/test/unit/ups-registration-client-test.js
'use strict';

const test = require('tape');
const adminClient = require('../../');

test('test client should return a promise with the client object', (t) => {
  let baseUrl = 'http://127.0.0.1:8080/ag-push';

  const upsClient = adminClient(baseUrl);
  t.equal(upsClient instanceof Promise, true, 'should return a Promise');

  upsClient.then((client) => {
    t.equal(typeof client.baseUrl, 'string', 'client should contain a baseUrl String');
    t.equal(client.baseUrl, 'http://127.0.0.1:8080/ag-push', 'client should have a base url property');
    t.end();
  });
});
<file_sep>/README.md
# Unified Push Registration Client

[![Coverage Status](https://coveralls.io/repos/github/bucharest-gold/unifiedpush-registration-client/badge.svg?branch=master)](https://coveralls.io/github/bucharest-gold/unifiedpush-registration-client?branch=master)
[![Build Status](https://travis-ci.org/bucharest-gold/unifiedpush-registration-client.svg?branch=master)](https://travis-ci.org/bucharest-gold/unifiedpush-registration-client) 
[![Known Vulnerabilities](https://snyk.io/test/npm/unifiedpush-registration-client/badge.svg)](https://snyk.io/test/npm/unifiedpush-registration-client) 
[![dependencies Status](https://david-dm.org/bucharest-gold/unifiedpush-registration-client/status.svg)](https://david-dm.org/bucharest-gold/unifiedpush-registration-client)

[![NPM](https://nodei.co/npm/unifiedpush-registration-client.png)](https://npmjs.org/package/unifiedpush-registration-client)

A client for registering Devices to the AeroGear UnifiedPush - https://aerogear.org/docs/specs/aerogear-unifiedpush-rest/#home

|                 | Project Info  |
| --------------- | ------------- |
| License:        | Apache-2.0  |
| Build:          | make  |
| Documentation:  | http://bucharest-gold.github.io/unifiedpush-registration-client/  |
| Issue tracker:  | https://github.com/bucharest-gold/unifiedpush-registration-client/issues  |
| Engines:        | Node.js 4.x, 5.x, 6.x

## Installation

`npm install unifiedpush-registration-client -S`

## Usage

    'use strict';

    const registrationClient = require('unifiedpush-registration-client');

    const baseUrl = 'http://127.0.0.1:8080/ag-push';

    const settings = {
        variantId: 'SOME_VARIANT_ID',
        secret: 'VARIANT_SECRET'
    };

    const deviceOptions = {
        deviceToken: '<PASSWORD>',
        alias: 'thing'
    }

    registrationClient(baseUrl)
      .then((client) => {
        return client.registry.registerDevice(deviceOptions)
          .then((deviceRegistration) => {
            console.log('deviceRegistration', deviceRegistration);
          });
      })
      .catch((err) => {
        console.log('Error', err);
      });


### Importer

There is also a `importer` function that allows mass device registration.

Along with the settings object, you also need to pass it a list of devices.

This list of devices must be an array and can be passed in as a .json file or a JSON object

## Contributing

Please read the [contributing guide](./CONTRIBUTING.md)
