push.js 9.65 KB
Newer Older
Chok's avatar
Chok committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
/*!
 * Module dependencies.
 */

const exec = cordova.require('cordova/exec');

class PushNotification {
  /**
   * PushNotification constructor.
   *
   * @param {Object} options to initiate Push Notifications.
   * @return {PushNotification} instance that can be monitored and cancelled.
   */
  constructor (options) {
    this.handlers = {
      registration: [],
      notification: [],
      error: []
    };

    // require options parameter
    if (typeof options === 'undefined') {
      throw new Error('The options argument is required.');
    }

    // store the options to this object instance
    this.options = options;

    // triggered on registration and notification
    const success = (result) => {
      if (result && typeof result.registrationId !== 'undefined') {
        this.emit('registration', result);
      } else if (
        result &&
        result.additionalData &&
        typeof result.additionalData.actionCallback !== 'undefined'
      ) {
        _this.emit('notification', result);
      } else if (result) {
        this.emit('notification', result);
      }
    };

    // triggered on error
    const fail = (msg) => {
      const e = typeof msg === 'string' ? new Error(msg) : msg;
      this.emit('error', e);
    };

    // wait at least one process tick to allow event subscriptions
    setTimeout(() => {
      exec(success, fail, 'PushNotification', 'init', [options]);
    }, 10);
  }

  /**
   * Unregister from push notifications
   */
  unregister (successCallback, errorCallback = () => {}, options) {
    if (typeof errorCallback !== 'function') {
      console.log('PushNotification.unregister failure: failure parameter not a function');
      return;
    }

    if (typeof successCallback !== 'function') {
      console.log(
        'PushNotification.unregister failure: success callback parameter must be a function'
      );
      return;
    }

    const cleanHandlersAndPassThrough = () => {
      if (!options) {
        this.handlers = {
          registration: [],
          notification: [],
          error: []
        };
      }
      successCallback();
    };

    exec(cleanHandlersAndPassThrough, errorCallback, 'PushNotification', 'unregister', [options]);
  }

  /**
   * subscribe to a topic
   * @param   {String}      topic               topic to subscribe
   * @param   {Function}    successCallback     success callback
   * @param   {Function}    errorCallback       error callback
   * @return  {void}
   */
  subscribe (topic, successCallback, errorCallback = () => {}) {
    if (typeof errorCallback !== 'function') {
      console.log('PushNotification.subscribe failure: failure parameter not a function');
      return;
    }

    if (typeof successCallback !== 'function') {
      console.log(
        'PushNotification.subscribe failure: success callback parameter must be a function'
      );
      return;
    }

    exec(successCallback, errorCallback, 'PushNotification', 'subscribe', [topic]);
  }

  /**
   * unsubscribe to a topic
   * @param   {String}      topic               topic to unsubscribe
   * @param   {Function}    successCallback     success callback
   * @param   {Function}    errorCallback       error callback
   * @return  {void}
   */
  unsubscribe (topic, successCallback, errorCallback = () => {}) {
    if (typeof errorCallback !== 'function') {
      console.log('PushNotification.unsubscribe failure: failure parameter not a function');
      return;
    }

    if (typeof successCallback !== 'function') {
      console.log(
        'PushNotification.unsubscribe failure: success callback parameter must be a function'
      );
      return;
    }

    exec(successCallback, errorCallback, 'PushNotification', 'unsubscribe', [topic]);
  }

  /**
   * Call this to set the application icon badge
   */
  setApplicationIconBadgeNumber (successCallback, errorCallback = () => {}, badge) {
    if (typeof errorCallback !== 'function') {
      console.log(
        'PushNotification.setApplicationIconBadgeNumber failure: failure ' +
          'parameter not a function'
      );
      return;
    }

    if (typeof successCallback !== 'function') {
      console.log(
        'PushNotification.setApplicationIconBadgeNumber failure: success ' +
          'callback parameter must be a function'
      );
      return;
    }

    exec(successCallback, errorCallback, 'PushNotification', 'setApplicationIconBadgeNumber', [
      { badge }
    ]);
  }

  /**
   * Get the application icon badge
   */

  getApplicationIconBadgeNumber (successCallback, errorCallback = () => {}) {
    if (typeof errorCallback !== 'function') {
      console.log(
        'PushNotification.getApplicationIconBadgeNumber failure: failure ' +
          'parameter not a function'
      );
      return;
    }

    if (typeof successCallback !== 'function') {
      console.log(
        'PushNotification.getApplicationIconBadgeNumber failure: success ' +
          'callback parameter must be a function'
      );
      return;
    }

    exec(successCallback, errorCallback, 'PushNotification', 'getApplicationIconBadgeNumber', []);
  }

  /**
   * Clear all notifications
   */

  clearAllNotifications (successCallback = () => {}, errorCallback = () => {}) {
    if (typeof errorCallback !== 'function') {
      console.log(
        'PushNotification.clearAllNotifications failure: failure parameter not a function'
      );
      return;
    }

    if (typeof successCallback !== 'function') {
      console.log(
        'PushNotification.clearAllNotifications failure: success callback ' +
          'parameter must be a function'
      );
      return;
    }

    exec(successCallback, errorCallback, 'PushNotification', 'clearAllNotifications', []);
  }

  /**
   * Clears notifications that have the ID specified.
   * @param  {Function} [successCallback] Callback function to be called on success.
   * @param  {Function} [errorCallback] Callback function to be called when an error is encountered.
   * @param  {Number} id    ID of the notification to be removed.
   */
  clearNotification (successCallback = () => {}, errorCallback = () => {}, id) {
    const idNumber = parseInt(id, 10);
    if (Number.isNaN(idNumber) || idNumber > Number.MAX_SAFE_INTEGER || idNumber < 0) {
      console.log(
        'PushNotification.clearNotification failure: id parameter must' +
          'be a valid integer.'
      );
      return;
    }

    exec(successCallback, errorCallback, 'PushNotification', 'clearNotification',
      [idNumber]);
  }

  /**
   * Listen for an event.
   *
   * The following events are supported:
   *
   *   - registration
   *   - notification
   *   - error
   *
   * @param {String} eventName to subscribe to.
   * @param {Function} callback triggered on the event.
   */

  on (eventName, callback) {
    if (!Object.prototype.hasOwnProperty.call(this.handlers, eventName)) {
      this.handlers[eventName] = [];
    }
    this.handlers[eventName].push(callback);
  }

  /**
   * Remove event listener.
   *
   * @param {String} eventName to match subscription.
   * @param {Function} handle function associated with event.
   */

  off (eventName, handle) {
    if (Object.prototype.hasOwnProperty.call(this.handlers, eventName)) {
      const handleIndex = this.handlers[eventName].indexOf(handle);
      if (handleIndex >= 0) {
        this.handlers[eventName].splice(handleIndex, 1);
      }
    }
  }

  /**
   * Emit an event.
   *
   * This is intended for internal use only.
   *
   * @param {String} eventName is the event to trigger.
   * @param {*} all arguments are passed to the event listeners.
   *
   * @return {Boolean} is true when the event is triggered otherwise false.
   */

  emit (...args) {
    const eventName = args.shift();

    if (!Object.prototype.hasOwnProperty.call(this.handlers, eventName)) {
      return false;
    }

    for (let i = 0, { length } = this.handlers[eventName]; i < length; i += 1) {
      const callback = this.handlers[eventName][i];
      if (typeof callback === 'function') {
        callback(...args); // eslint-disable-line node/no-callback-literal
      } else {
        console.log(`event handler: ${eventName} must be a function`);
      }
    }

    return true;
  }

  finish (successCallback = () => {}, errorCallback = () => {}, id = 'handler') {
    if (typeof successCallback !== 'function') {
      console.log('finish failure: success callback parameter must be a function');
      return;
    }

    if (typeof errorCallback !== 'function') {
      console.log('finish failure: failure parameter not a function');
      return;
    }

    exec(successCallback, errorCallback, 'PushNotification', 'finish', [id]);
  }
}

/*!
 * Push Notification Plugin.
 */

module.exports = {
  /**
   * Register for Push Notifications.
   *
   * This method will instantiate a new copy of the PushNotification object
   * and start the registration process.
   *
   * @param {Object} options
   * @return {PushNotification} instance
   */

  init: (options) => new PushNotification(options),

  hasPermission: (successCallback, errorCallback) => {
    exec(successCallback, errorCallback, 'PushNotification', 'hasPermission', []);
  },

  createChannel: (successCallback, errorCallback, channel) => {
    exec(successCallback, errorCallback, 'PushNotification', 'createChannel', [channel]);
  },

  deleteChannel: (successCallback, errorCallback, channelId) => {
    exec(successCallback, errorCallback, 'PushNotification', 'deleteChannel', [channelId]);
  },

  listChannels: (successCallback, errorCallback) => {
    exec(successCallback, errorCallback, 'PushNotification', 'listChannels', []);
  },

  /**
   * PushNotification Object.
   *
   * Expose the PushNotification object for direct use
   * and testing. Typically, you should use the
   * .init helper method.
   */
  PushNotification
};