Show TOC

push.jsLocate this document in the navigation structure

1       // ${project.version}
2       var exec = require("cordova/exec");
3       
4       /**
5        * The push plugin provides an abstraction layer over the
6        * <a href="http://developer.android.com/google/gcm/index.html">Google Cloud Messaging for Android (GCM)</a>
7        * and
8        * <a href="http://developer.apple.com/library/mac/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/Chapters/ApplePushService.html#//apple_ref/doc/uid/TP40008194-CH100-SW9">Apple Push Notification Service (APNS)</a>.
9        * <br/><br/>
10       * A notification can be sent to a device registered with an application through a
11       * rest call at <pre>http://SMP_3.0_SERVER:8080/Notifications/application_registration_id</pre>
12       * <br/><br/>
13       * <b>Adding and Removing the Push Plugin</b><br/>
14       * The Push plugin is added and removed using the
15       * <a href="http://cordova.apache.org/docs/en/edge/guide_cli_index.md.html#The%20Command-line%20Interface">Cordova CLI</a>.<br/>
16       * <br/>
17       * To add the Push plugin to your project, use the following command:<br/>
18       * cordova plugin add <path to directory containing Kapsel plugins>\push<br/>
19       * <br/>
20       * To remove the Push plugin from your project, use the following command:<br/>
21       * cordova plugin rm com.sap.mp.cordova.plugins.push
22       * <br/>
23       *
24       * @namespace
25       * @alias Push
26       * @memberof sap
27       */
28      
29      module.exports = {
30          
31          
32          
33          /**
34           * Helper method for handling failure callbacks. It is configured as a failure callback in <code> call_native() </code>
35           *
36           *
37           * @param {msg} Error message with the cause of failure
38           *
39           * @private
40           * @name failure
41           * @function
42           */
43          
44      failure: function (msg) {
45          sap.Logger.debug("Javascript Callback Error: " + msg,"PUSHJS",function(m){},function(m){});
46          
47      },
48          /**
49           * Helper method for handling push registration success callbacks. It is configured as a failure callback in <code> call_native() </code>
50           *
51           *
52           * @param {msg} Error message with the cause of failure
53           *
54           * @private
55           * @name pushregsuccsss
56           * @function
57           */
58          
59      pushregsuccsss: function(msg) {
60          sap.Logger.debug("Javascript Callback Success ","PUSHJS",function(m){},function(m){});
61      },
62          
63          /**
64           * Helper method for calling native methods
65           *
66           * @param {function} callback
67           * @param {string} Name of the action to invoke on the plugin
68           * @param {array} List of arguments
69           * @private
70           * @name call_native
71           * @function
72           */
73      call_native: function (callback, name, args) {
74          
75          if(arguments.length == 2) {
76              args = [];
77          }
78          ret = exec(
79                     callback,                /**  Called when signature capture is successful */
80                     sap.Push.failure,            /** Called when signature capture encounters an error */
81                     'SMPPushPlugin',         /**  Tell Cordova that we want to run "PushNotificationPlugin" */
82                     name,                    /**  Tell the plugin the action we want to perform */
83                     args);                   /**  List of arguments to the plugin */
84          return ret;
85      },
86          
87          /**
88           * Helper method to check if platform is iOS.
89           *
90           * @return {bool} Whether the current platform is iOS or not.
91           * @private
92           * @name isPlatformIOS
93           * @function
94           */
95      isPlatformIOS: function () {
96          return device.platform == "iPhone" || device.platform == "iPad" || device.platform == "iPod touch" || device.platform == "iOS";
97      },
98          /**
99           * Function called by the application to get connection information.
100          *
101          * @param {string} [types] Types of notifications the application wants to receive. The different types of notifications are expressed in <code>notificationType</code>
102          * @param {string} [successCB] Success callback to call when registration is successful.
103          * @param {string} [errorCB] Error callback to call when registration attempt fails.
104          * @private
105          * @memberof sap.Push
106          * @function getConnectionSettings
107          * @example
108          * sap.Push.getConnectionSettings(function(){
109          * sap.Logger.debug("getting Connection Settings","PUSHJS",function(m){},function(m){});
110          *  console.log("getting Connection Settings");
111          *  sap.Push.registerForNotification(types,  successCallback, errorCallback, notificationListenerFunc, senderId );
112          **/
113         getConnectionSettings : function (successCB, errorCB) {
114             
115             
116            
117                 var pd ="";
118                 sap.Logon.unlock(function (connectionInfo) {
119                                  var userName = connectionInfo["registrationContext"]["user"];
120                                  var password  = connectionInfo["registrationContext"]["password"];
121                                  var applicationConnectionId = connectionInfo["applicationConnectionId"];
122                                  var securityConfig = connectionInfo["registrationContext"]["securityConfig"];
123                                  var endpoint = connectionInfo["applicationEndpointURL"];
124                                  var keySSLEnabled = "false";
125                                  var splitendpoint = endpoint.split("/");
126                                  if (splitendpoint[0] == "https:")
127                                  {
128                                      keySSLEnabled="true";
129                                  }
130                                  if (securityConfig == null) {
131                                      securityConfig = "";
132                                  }
133                                 var burl = ""; 
134                          		for (var i=2; i<splitendpoint.length-2; i++){
135                              		burl += splitendpoint[i] +"/";
136                          		}
137                          		burl += splitendpoint[splitendpoint.length-2];
138                          		var appId = splitendpoint[splitendpoint.length-1];
139     
140                                  pd = appId+userName+password;
141                                  //sap.Settings.store = new sap.EncryptedStorage("SettingsStore");
142                                  connectionData = {
143                                      "keyMAFLogonOperationContextConnectionData": {
144                                          "keyMAFLogonConnectionDataApplicationSettings":
145                                          {
146                                          "DeviceType":device.platform,
147                                          "DeviceModel":device.model,
148                                          "ApplicationConnectionId":applicationConnectionId
149                                          },
150                                          "keyMAFLogonConnectionDataBaseURL":burl
151                                      },
152                                      "keyMAFLogonOperationContextApplicationId":appId,
153                                      "keyMAFLogonOperationContextBackendUserName":userName,
154                                      "keyMAFLogonOperationContextBackendPassword":password,
155                                      "keyMAFLogonOperationContextSecurityConfig":securityConfig,
156                                      "keySSLEnabled":keySSLEnabled
157                                  };
158                                  sap.Settings.start(connectionData,
159                                                     function(mesg) {
160                                                         sap.Settings.isInitialized = true;
161                                                         sap.Logger.debug("Setting Exchange is succesful ","SETTINGSJS",function(m){},function(m){});
162                                                         successCB();
163                                                     },
164                                                     function(mesg){
165                                                         sap.Logger.debug("Setting Exchange failed" + mesg,"SETTINGSJS",function(m){},function(m){});
166                                                         sap.Settings.isInitialized = false;
167                                                         errorCB();
168                                                     });
169                                  }
170                                  , function () {
171                                      console.log("unlock failed");
172                                      sap.Logger.debug("unlock failed ","SETTINGSJS",function(m){},function(m){});
173                                  }
174                             );
175                 
176            
177             
178             
179     },
180         
181         /**
182          * Function called by the application to register notification types to receive.
183          *
184          * @param {string} [types] Types of notifications the application wants to receive. The different types of notifications are expressed in <code>notificationType</code>
185          * @param {string} [successCallback] Success callback to call when registration is successful.
186          * @param {string} [errorCallback] Error callback to call when registration attempt fails.
187          * @param {string} [notificationlistenerfunc] The function that receives the notification for processing by the application.
188          * @param {string} [senderId] The sender ID that is used for GCM registration. For other platforms it is null.
189          * @private
190          * @memberof sap.Push
191          * @function registerForNotificationTypes
192          * @example
193          * regid = "211112269206";
194              * function registerSuccess(mesg){}
195              * function registerFailure(mesg) {}
196              * function ProcessNotification(mesg){}
197              * sap.Push.registerForNotificationTypes(sap.Push.notificationType.badge | sap.Push.notificationType.sound | sap.Push.notificationType.alert, registerSuccess, registerFailure, ProcessNotification, regid);
198          */
199         
200             registerForNotification: function (types, successCallback, errorCallback, notificationListenerFunc, senderId) {
201             	sap.Push.RegisterSuccess = successCallback;
202             	sap.Push.RegisterFailed = errorCallback;
203             	sap.Push.ProcessNotificationForUser = notificationListenerFunc;
204             	sap.Push.call_native(sap.Push.pushregsuccsss, "registerForNotificationTypes", [types, senderId]);
205             
206        
207         
208     },
209         
210         /* Core APIS */
211         
212         /**
213          * Function called by the application to register notification types to receive.
214          *
215          * @param {string} types Types of notifications the application wants to receive. The different types of notifications are expressed in <code>notificationType</code>
216              *                  Notificaion types allowed are Disable all notifications (NONE: 0), Set badge count on app icon (BADGE: 1), Play sounds on receiving notification (SOUNDS: 2) and Show alert on receiving notification (ALERT: 4).
217          * @param {string} successCallback Success callback to call when registration is successful.
218          * @param {string} errorCallback Error callback to call when registration attempt fails.
219          * @param {string} notificationlistenerfunc The function that receives the notification for processing by the application.
220          * @param {string} [senderId] The sender ID that is used for GCM registration. For other platforms it is null.
221          * @public
222          * @memberof sap.Push
223          * @function registerForNotificationTypes
224          * @example
225          * regid = "211112269206";
226          * function registerSuccess(mesg){}
227          * function registerFailure(mesg) {}
228          * function ProcessNotification(mesg){}
229          * sap.Push.registerForNotificationTypes(sap.Push.notificationType.badge | sap.Push.notificationType.sound | sap.Push.notificationType.alert, registerSuccess, registerFailure, ProcessNotification, regid);
230          */
231     registerForNotificationTypes: function (types, registerSuccess, registerFailure, notificationListenerFunc, senderId ) {
232         
233         sap.Push.getConnectionSettings(function(){
234                                        sap.Logger.debug("getting Connection Settings","PUSHJS",function(m){},function(m){});
235                                        console.log("getting Connection Settings");
236                                        sap.Push.registerForNotification(types, registerSuccess, registerFailure, notificationListenerFunc, senderId);
237                                        },
238                                        function(){ registerFailure("Could not exchange Server settings");});
239     },
240         
241         
242         /**
243          * Function called by the application to unregister from future notifications.
244          *
245          * @param {function} callback Success callback to call when deregistration is successful. This callback function will contain a string with a message. This message is just for informative purpose. 
246          * @public
247          * @memberof sap.Push
248          * @function unregisterForNotificationTypes
249          * @example
250          * function unregCallback(mesg){}
251          * sap.Push.unregisterForNotificationTypes(unregCallback);
252          */
253         
254     unregisterForNotificationTypes: function (callbak) {
255             sap.Push.call_native(callbak,"unregisterForNotification");
256     },
257         
258         /**
259          * Used to fetch the badge count for the application. This function is used only by iOS. Other platforms do not have the badge count concept.
260          *
261          * @param {function} callback Success callback to call when to send the badge count. The callback function will contain an argument in json format with the current badge count. Look into the example for the deail on how to use them.
262          * @public
263          * @memberof sap.Push
264          * @function getBadgeNumber
265          * @example
266          * function getBadgeNumCallback(data) { badgecount = data;}
267          * sap.Push.getBadgeNumber(getBadgeNumCallback);
268          */
269     getBadgeNumber: function(callback)
270         {
271             if (sap.Push.isPlatformIOS()) {
272                 sap.Push.call_native(callback, "getBadgeNumber");
273             }
274         },
275         
276         /**
277          * Used to set the badge count for the application. This function is used only by iOS. Other platforms do not have the badge count concept.
278          *
279          * @param {number} number The badge count to set for the application.
280          * @param {function} callback Success callback to call when to send the badge count. The callback function will contain an argument in string format. This argument can be used for informative purpose.
281          * @public
282          * @memberof sap.Push
283          * @function setBadgeNumber
284          * @example
285          * function badgeCallback(mesg){}
286          * badgenum = 10;
287          * sap.Push.setBadgeNumber(badgenum, badgeCallback);
288          */
289     setBadgeNumber: function (number, callback) {
290         if (sap.Push.isPlatformIOS()) {
291             sap.Push.call_native(callback, "setBadgeNumber", [number]);
292         }
293     },
294         
295         /**
296          * Used to reset the badge count for the application.  This function is used only by iOS. Other platforms do not have the badge count concept.
297          *
298          * @param {function} callback Success callback to call when the badge count is reset. The callback function will contain an argument in string format. This argument can be used for informative purpose.
299          * @public
300          * @memberof sap.Push
301          * @function resetBadge
302          * @example
303          * function badgeCallback(mesg){}
304          * sap.Push.resetBadge(badgeCallback);
305          */
306     resetBadge: function (callback) {
307                 if (sap.Push.isPlatformIOS() || (device.platform == "windows8")) {
308             sap.Push.call_native(callback, "resetBadge");
309         }
310     },
311         
312         
313         
314         
315         
316         /**
317          * This method updates the application with the new device token in the SAP Mobile Platform server.
318          *
319          * @param {string} [devtok] The device token received from the APNS/GCM device registration.
320          * @public
321          * @callback {function} [callback] The callback function that is called with the registration result.
322          * @memberof sap.Push
323          * @example
324          * function callback(mesg) {}
325          * devToken ="123123213213";//sample device token
326          * sap.Push.updateWithDeviceToken(devToken, callback);
327          */
328         
329     updateWithDeviceToken:  function (devtok, callback) {
330         if (sap.Push.isPlatformIOS() || device.platform == "Android" ) {
331             sap.Push.call_native(callback, "updateWithDeviceToken", [devtok]);
332         }
333     },
334         
335         /**
336          * This method checks for any notifications received while the application was not running in the foreground. Application developer can call this
337          * function directly or register with an event handler to be called automatically. It is ok to call this function evenif the device is not yet registered for push notification.
338          * @param {function} callback The callback function that receives the notification. The callback function will receive a string as it's argument. This string will contain the notification message send from the server intact.
339          * @memberof sap.Push
340          * @example
341          * function processBackgroudMessage(mesg){
342          *  
343          * }
344          * function checkBackgroundNotification() {
345          *     sap.Push.checkForNotification(processBackgroudMessage);
346          * }
347          * document.addEventListener("onSapLogonSuccess", checkBackgroundNotification, false);
348          * document.addEventListener("onSapResumeSuccess", checkBackgroundNotification, false);
349          **/
350         
351     checkForNotification: function(callback) {
352                 if (sap.Push.isPlatformIOS() || device.platform == "Android" || device.platform == "windows8") {
353             sap.Push.call_native(callback, "checkForNotification");
354         }
355     },
356         
357         /**
358          * This is an internal function, which is called when there is a push notification.
359          * @private
360          **/
361     ProcessNotification: function(message) {
362         if (sap.Push.ProcessNotificationForUser == null )
363         {
364             console.log("No Processing function provided");
365             sap.Logger.debug("Notification listener function is not registered. Register it by calling registerForNotificationTypes","PUSHJS",function(m){},function(m){});
366         } else {
367             sap.Push.ProcessNotificationForUser(message);
368         }
369     },
370         /**
371          * This is an internal function, which is automatically called when the plugin is initialized. Used only for android.
372          * @private
373          **/
374     initPlugin: function(callback) {
375         if ( device.platform == "Android")
376         {
377             args = [];
378             exec(
379                  callback,
380                  function(){ sap.Logger.debug("Plugin Initialization","PUSHJS",function(m){},function(m){}); } ,
381                  'SMPPushPlugin',
382                  "initPlugin",
383                  args);
384         }
385     }
386         
387     };
388     
389     
390     /**
391      * Local private variables
392      */
393     module.exports.RegisterSuccess = null;
394     module.exports.RegisterFailed = null;
395     module.exports.ProcessNotificationForUser = null;
396     /**
397      * Enum for types of push notification.
398      * @enum {number}
399      * @private
400      */
401     module.exports.notificationType = {
402         /** Disable all notifications */
403     NONE: 0,
404         /** Set badge count on app icon */
405     BADGE: 1,
406         /** Play sound on receiving notification */
407     SOUND: 2,
408     SOUNDS: 2,
409         /** Show alert on receiving notification */
410     ALERT: 4
411     };
412     
413     
414     
415     
416     document.addEventListener('deviceready', module.exports.initPlugin, false);
417