Skip to content

Instantly share code, notes, and snippets.

@hano
Last active August 29, 2015 14:03
Show Gist options
  • Save hano/f0c42cafde72ff7c48ee to your computer and use it in GitHub Desktop.
Save hano/f0c42cafde72ff7c48ee to your computer and use it in GitHub Desktop.
(function (scope) {
scope.mCAP = scope.mCAP || {};
var pushNotification = null;
var options = null;
var onDeviceReady = function (opt) {
options = opt;
var pushNotification = scope.plugins.pushNotification;
if (!pushNotification) {
console.error('please add the push plugin: cordova plugin add https://github.com/phonegap-build/PushPlugin.git');
return;
}
if (!device) {
console.error('the device plugin is not loaded. Install it via cordova plugin add org.apache.cordova.device');
return;
}
if (device.platform == 'android' || device.platform == 'Android' || device.platform == "amazon-fireos") {
if (!options || !options.senderId) {
console.error('No sender id given. It is mandatory for android devices');
return;
}
pushNotification.register(
successHandler,
errorHandler,
{
"senderID": options.senderId,
"ecb": "mCAP.cordovaPushPlugin.onNotification"
});
}
else {
pushNotification.register(
tokenHandler,
errorHandler,
{
"badge": "true",
"sound": "true",
"alert": "true",
"ecb": "mCAP.cordovaPushPlugin.onNotificationAPN"
});
}
// result contains any message sent from the plugin call
function successHandler(result) {
if (options && options.register && typeof options.register === 'function') {
options.register(result);
}
}
// result contains any error description text returned from the plugin call
function errorHandler(error) {
if (options && options.error && typeof options.error === 'function') {
options.error(error);
}
}
function tokenHandler(result) {
// Your iOS push server needs to know the token before it can push to this device
// here is where you might want to send it the token for later use.
if (options && options.token && typeof options.token === 'function') {
options.token(result);
}
registerDevice(result);
}
};
function onNotificationAPN(event) {
if (options && options.message && typeof options.message === 'function') {
options.message(arguments);
}
if (event && event.alert) {
navigator.notification.alert(event.alert);
}
if (event.sound && typeof Media !== 'undefined') {
var snd = new Media(event.sound);
snd.play();
}
if (event && event.badge) {
pushNotification.setApplicationIconBadgeNumber(function(){
// success
}, function(){
// error
}, event.badge);
}
}
function registerDevice(token) {
var language = window.navigator.userLanguage || window.navigator.language;
var providerType = '';
if (device.platform == 'android' || device.platform == 'Android' || device.platform == "amazon-fireos") {
providerType = 'GCM';
}
else {
providerType = 'APNS';
}
var deviceModel = mCAP.push.devices.add({
"providerType": providerType,
"user": mCAP.authentication.get('userName'),
"name": device.model,
"osVersion": device.version,
"language": language.substr(0, 2),
"country": language.substr(4, 5) || '',
"token": token
});
deviceModel.save().then(function (data) {
if (options && options.registerdevice && typeof options.registerdevice === 'function') {
options.registerdevice(data);
}
}).fail(function () {
if (options && options.registerdeviceerror && typeof options.registerdeviceerror === 'function') {
options.registerdeviceerror(data);
}
});
}
// Android and Amazon Fire OS
function onNotification(e) {
console.log(e);
switch (e.event) {
case 'registered':
if (e.regid.length > 0) {
registerDevice(e.regid);
}
break;
case 'message':
console.log(options.message);
// if this flag is set, this notification happened while we were in the foreground.
// you might want to play a sound to get the user's attention, throw up a dialog, etc.
var type = 'SOUND';
if (e.foreground && typeof Media !== 'undefined') {
// on Android soundname is outside the payload.
// On Amazon FireOS all custom attributes are contained within payload
var soundfile = e.soundname || e.payload.sound;
// if the notification contains a soundname, play it.
var my_media = new Media("/android_asset/www/" + soundfile);
my_media.play();
}
else { // otherwise we were launched because the user touched a notification in the notification tray.
if (e.coldstart) {
type = 'COLDSTART'
}
else {
type = 'BACKGROUND'
}
}
if (options && options.message && typeof options.message === 'function') {
options.message(type, e);
}
break;
case 'error':
if (options && options.error && typeof options.error === 'function') {
console.log('2');
options.error(e);
}
break;
default:
if (options && options.unknown && typeof options.unknown === 'function') {
options.unknown(e);
}
break;
}
}
scope.mCAP.cordovaPushPlugin = {
onDeviceReady: onDeviceReady,
onNotificationAPN: onNotificationAPN,
onNotification: onNotification
}
})(this);

How to use the mCAP Push service with Apache Cordova (Android and iOS)

setup the cordova project

// create the application
cordova create PushExample
// go into the application directory
cd PushExample/
// add android
cordova platform add android
// add ios
cordova platform add ios

install plugins

The push plugin

For details have a look at https://github.com/phonegap-build/PushPlugin

cordova plugin add https://github.com/phonegap-build/PushPlugin.git

The device plugin

For details have a look at https://github.com/apache/cordova-plugin-device/blob/master/doc/index.md

cordova plugin add org.apache.cordova.device

check plugin installations

cordova plugin

should display something similar to this:

com.phonegap.plugins.PushPlugin 2.2.1 "PushPlugin"
org.apache.cordova.device 0.2.10 "Device"

code the application

See the example here.

install the dependencies

cd www/
bower install mcapjs-client

get the mCAP driver for com.phonegap.plugins.PushPlugin

Download: driver.com.phonegap.plugins.PushPlugin.js to www/js/driver.com.phonegap.plugins.PushPlugin.js

update the index.html

Example: driver.com.phonegap.plugins.PushPlugin.js to www/js/driver.com.phonegap.plugins.PushPlugin.js.

Add the UI for logging:

<div id="home">
        <div id="app-status-div">
            <ul id="app-status-ul">
                <li>Cordova PushNotification Plugin Demo with mCAP support</li>
            </ul>
        </div>
    </div>

First add the mcapjs-client dependencies:


<script type="text/javascript" src="cordova.js"></script>
<script src="bower_components/jquery/dist/jquery.js"></script>
<script src="bower_components/underscore/underscore.js"></script>
<script src="bower_components/backbone/backbone.js"></script>
<script src="bower_components/uri.js/src/URI.js"></script>
<script src="bower_components/mcapjs-client/dist/mcap.js"></script>

Then the driver:

<script src="js/driver.com.phonegap.plugins.PushPlugin.js"></script>

add your business logic

 <script type="text/javascript">
 function deviceReady(){
 // set the url to the mcap server
  mCAP.application.set('baseUrl', 'http://mcap.server.io:8443');
// configure the push object with the uuid of the push you want to use
  mCAP.push.set('uuid', '5854AE59-8642-4B05-BC71-72B76B4E81E8');
  
// setup the options
var options = {
	// the sender id given from google
      senderId: "841515181518",
      // register callback
      register: function () {
          log('register', arguments);
      },
      // error callback
      error: function () {
          log('error', arguments);
      },
      // token received callback
      token: function () {
          log('token', arguments);
      },
      // callback when the device was successful registered against the mcap
      registerdevice: function () {
          log('registerdevice', arguments);
      },
      // callback when the device registration was unsuccessful
      registerdeviceerror: function () {
          log('registerdeviceerror', arguments);
      },
      // callback when a push comes in
      message: function () {
          log('message', arguments);
      },
      // if a push was received but that was not a message
      unknown: function () {
          log('unknown', arguments);
      }
  };
  // register you logic
  mCAP.cordovaPushPlugin.onDeviceReady(options);
 }
 </script>

After that register your businesslogic to the deviceready event:

 <script type="text/javascript">
 
 // just a wrapper
            function log(){
                console.log.apply(console, arguments);
                $('#app-status-ul').append('<li>' + JSON.stringify(arguments) + '</li>')
            }
            document.addEventListener('deviceready', deviceReady, false);
        </script>

test the app

  1. Enabling On-device Developer Options
  2. Connect an android device via USB
  3. cordova run android or cordova run ios
  4. Send a push

cURL

curl 'http://mcap.server.io:8443/push/api/v1/apps/5854AE59-8642-4B05-BC71-72B76B4E81E8/jobs' -H 'Pragma: no-cache' -H 'Origin: chrome-extension://fdmmgilgnpjigdojojpjoooidkmcomcm' -H 'Accept-Encoding: gzip,deflate,sdch' -H 'Accept-Language: en-US,en;q=0.8,de;q=0.6' -H 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.153 Safari/537.36' -H 'Content-Type: application/json' -H 'Accept: application/json' -H 'Cache-Control: no-cache' -H 'Authorization: Basic bWhhbm86c3lzdGVtOm1oYW5v' -H 'Cookie: JSESSIONID=1hv12083zf19e1cktvaaisn0wj' -H 'Connection: keep-alive' --data-binary $'{\n  "message" : "Hallo Android and iOS",\n  "sound" : "nameOfSound.wav",\n  "badge" : "2",\n  "extras" : {\n    "myHidden" : "Attribute"\n  }\n}' --compressed

JavaScript

// Sends a push message to all registered devices
var job = mCAP.push.jobs.add({
  "message": "Hello Android and iOS",
  "sound": "nameOfSound.wav",
  "badge": "2",
  "extras": {
    "myHidden": "Attribute"
  }
});

// login
mCAP.authentication.login().then(function () {
  return job.sendPush().then(function () {
    log('Send a push message to all registered devices');
  });
});

The log on your device should now display the push message

<!DOCTYPE html>
<!--
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
-->
<html>
<head>
<meta charset="utf-8" />
<meta name="format-detection" content="telephone=no" />
<!-- WARNING: for iOS 7, remove the width=device-width and height=device-height attributes. See https://issues.apache.org/jira/browse/CB-4323 -->
<meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width, height=device-height, target-densitydpi=device-dpi" />
<link rel="stylesheet" type="text/css" href="css/index.css" />
<meta name="msapplication-tap-highlight" content="no" />
<title>Cordova PushNotification Plugin Demo with mCAP support</title>
</head>
<body>
<div id="home">
<div id="app-status-div">
<ul id="app-status-ul">
<li>Cordova PushNotification Plugin Demo with mCAP support</li>
</ul>
</div>
</div>
<script type="text/javascript" src="cordova.js"></script>
<script src="bower_components/jquery/dist/jquery.js"></script>
<script src="bower_components/underscore/underscore.js"></script>
<script src="bower_components/backbone/backbone.js"></script>
<script src="bower_components/uri.js/src/URI.js"></script>
<script type="text/javascript" src="bower_components/mcapjs-client/dist/mcap.js"></script>
<script type="text/javascript" src="js/driver.com.phonegap.plugins.PushPlugin.js"></script>
<script type="text/javascript">
function log(){
console.log.apply(console, arguments);
$('#app-status-ul').append('<li>' + JSON.stringify(arguments) + '</li>')
}
document.addEventListener('deviceready', function(){
mCAP.application.set('baseUrl', 'http://10.21.4.97:8079');
mCAP.push.set('uuid', '5854AE59-8642-4B05-BC71-72B76B4E81E8');
mCAP.cordovaPushPlugin.onDeviceReady({
senderId: "762282634093",
register: function () {
log('register', arguments);
},
error: function () {
log('error', arguments);
},
token: function () {
log('token', arguments);
},
registerdevice: function () {
log('registerdevice', arguments);
},
registerdeviceerror: function () {
log('registerdeviceerror', arguments);
},
message: function () {
log('message', arguments);
},
unknown: function () {
log('unknown', arguments);
}
});
}, false);
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment