summaryrefslogtreecommitdiff
path: root/plugins/de.appplant.cordova.plugin.local-notification/src/windows/LocalNotificationUtil.js
blob: 4081a0b8471c6cdf17f918b5b962cee53621cda3 (plain)
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
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
/*
    Copyright 2013-2015 appPlant UG

    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.
*/


exports = require('de.appplant.cordova.plugin.local-notification.LocalNotification.Proxy').core;

var channel = require('cordova/channel');


/***********
 * MEMBERS *
 ***********/

// True if App is running, false if suspended
exports.isInBackground = true;

// Indicates if the device is ready (to receive events)
exports.isReady = false;

// Queues all events before deviceready
exports.eventQueue = [];

/********
 * UTIL *
 ********/

/**
 * The repeating interval in milliseconds.
 *
 * @param {String} interval
 *      A number or a placeholder like `minute`.
 *
 * @return {Number}
 *      Interval in milliseconds
 */
exports.getRepeatInterval = function (every) {

    if (!every)
        return 0;

    if (every == 'minute')
        return 60000;

    if (every == 'hour')
        return 360000;

    if (!NaN(every))
        return parseInt(every) * 60000;

    return 0;
};

/**
 * If the notification is repeating.
 *
 * @param {Object} notification
 *      Local notification object
 *
 * @return Boolean
 */
exports.isRepeating = function (notification) {
    return this.getRepeatInterval(notification.every) !== 0;
};

/**
 * Parses sound file path.
 *
 * @param {String} path
 *      Relative path to sound resource
 *
 * @return {String} XML Tag for Sound-File
 */
exports.parseSound = function (path) {
	if (!path.match(/^file/))
		return '';

	var uri = this.parseUri(path),
		audio = "<audio src=" + uri + " loop='false'/>";

	return audio;
};

/**
 * Parses image file path.
 *
 * @param {String} path
 *      Relative path to image resource
 *
 * @return {String} XML-Tag for Image-File
 */
exports.parseImage = function (path) {
    if (!path.match(/^file/))
        return '';

    var uri = this.parseUri(path),
        image = "<image id='1' src=" + uri + " />";

    return image;
};

/**
 * Parses file path to URI.
 *
 * @param {String} path
 *      Relative path to a resource
 *
 * @return {String} URI to File
 */
exports.parseUri = function (path) {
    var pkg = Windows.ApplicationModel.Package.current,
        pkgId = pkg.id,
        pkgName = pkgId.name;

	var uri = "'ms-appx://" + pkgName + "/www" + path.slice(6, path.length) + "'";

	return uri;
};

/**
 * Builds the xml payload for a local notification based on its options.
 *
 * @param {Object} options
 *      Local notification properties
 *
 * @return Windows.Data.Xml.Dom.XmlDocument
 */
exports.build = function (options) {
    var template = this.buildToastTemplate(options),
        notification = new Windows.Data.Xml.Dom.XmlDocument();

    try {
        notification.loadXml(template);
    } catch (e) {
        console.error(
            'LocalNotification#schedule',
            'Error loading the xml, check for invalid characters.');
    }

    // Launch Attribute to enable onClick event
    var launchAttr = notification.createAttribute('launch'),
        toastNode = notification.selectSingleNode('/toast');

    launchAttr.value = options.id.toString();
    toastNode.attributes.setNamedItem(launchAttr);

    return notification;
};

/**
 * Builds the toast template with the right style depend on the options.
 *
 * @param {Object} options
 *      Local notification properties
 *
 * @return String
 */
exports.buildToastTemplate = function (options) {
	var title = options.title,
		message = options.text || '',
		json = JSON.stringify(options),
		sound = '';

	if (options.sound && options.sound !== '') {
		sound = this.parseSound(options.sound);
	}

	var templateName = "ToastText",
		imageNode;
	if (options.icon && options.icon !== '') {
		imageNode = this.parseImage(options.icon);
		// template with Image
		if (imageNode !== '') {
			templateName = "ToastImageAndText";
		}
	} else {
		imageNode = "";
	}

	var bindingNode;
	if (title && title !== '') {
		bindingNode = "<binding template='" + templateName + "02'>" +
							imageNode +
							"<text id='1'>" + title + "</text>" +
							"<text id='2'>" + message + "</text>" +
						"</binding>";
	} else {
		bindingNode = "<binding template='" + templateName + "01'>" +
							imageNode +
							"<text id='1'>" + message + "</text>" +
						"</binding>";
	}
	return "<toast>" +
				"<visual>" +
						bindingNode +
				"</visual>" +
				sound +
				"<json>" + json + "</json>" +
			"</toast>";
};

/**
 * Short-hand method for the toast notification history.
 */
exports.getToastHistory = function () {
    return Windows.UI.Notifications.ToastNotificationManager.history;
};

/**
 * Gets a toast notifier instance.
 *
 * @return Object
 */
exports.getToastNotifier = function () {
    return Windows.UI.Notifications.ToastNotificationManager
            .createToastNotifier();
};

/**
 * List of all scheduled toast notifiers.
 *
 * @return Array
 */
exports.getScheduledToasts = function () {
    return this.getToastNotifier().getScheduledToastNotifications();
};

/**
 * Gets the Id from the toast notifier.
 *
 * @param {Object} toast
 *      A toast notifier object
 *
 * @return String
 */
exports.getToastId = function (toast) {
    var id = toast.id;

    if (id.match(/-2$/))
        return id.match(/^[^-]+/)[0];

    return id;
};

/**
 * Gets the notification life cycle type
 * (scheduled or triggered)
 *
 * @param {Object} toast
 *      A toast notifier object
 *
 * @return String
 */
exports.getToastType = function (toast) {
    return this.isToastTriggered(toast) ? 'triggered' : 'scheduled';
};

/**
 * If the toast is already scheduled.
 *
 * @param {Object} toast
 *      A toast notifier object
 *
 * @return Boolean
 */
exports.isToastScheduled = function (toast) {
    return !this.isToastTriggered(toast);
};

/**
 * If the toast is already triggered.
 *
 * @param {Object} toast
 *      A toast notifier object
 *
 * @return Boolean
 */
exports.isToastTriggered = function (toast) {
    var id = this.getToastId(toast),
        notification = this.getAll([id])[0],
        fireDate = new Date((notification.at) * 1000);

    if (this.isRepeating(notification))
        return false;

    return fireDate <= new Date();
};

/**
 * Finds the toast by it's ID.
 *
 * @param {String} id
 *      Local notification ID
 *
 * @param Object
 */
exports.findToastById = function (id) {
    var toasts = this.getScheduledToasts();

    for (var i = 0; i < toasts.length; i++) {
        var toast = toasts[i];

        if (this.getToastId(toast) == id)
            return toast;
    }

    return null;
};

/**
 * Sets trigger event for local notification.
 *
 * @param {Object} notification
 *      Local notification object
 * @param {Function} callback
 *      Callback function
 */
exports.callOnTrigger = function (notification, callback) {
    var triggerTime = new Date((notification.at * 1000)),
        interval = triggerTime - new Date();

    if (interval <= 0) {
        callback.call(this, notification);
        return;
    }

    WinJS.Promise.timeout(interval).then(function () {
        if (exports.isPresent(notification.id)) {
            callback.call(exports, notification);
        }
    });
};

/**
 * Sets trigger event for all scheduled local notification.
 *
 * @param {Function} callback
 *      Callback function
 */
exports.callOnTriggerForScheduled = function (callback) {
    var notifications = this.getScheduled();

    for (var i = 0; i < notifications.length; i++) {
        this.callOnTrigger(notifications[i], callback);
    }
};

/**
 * The application state - background or foreground.
 *
 * @return String
 */
exports.getApplicationState = function () {
    return this.isInBackground ? 'background' : 'foreground';
};

/**
 * Fires the event about a local notification.
 *
 * @param {String} event
 *      The event
 * @param {Object} notification
 *      The notification
 */
exports.fireEvent = function (event, notification) {
    var plugin = cordova.plugins.notification.local.core,
        state = this.getApplicationState(),
        args;

    if (notification) {
        args = [event, notification, state];
    } else {
        args = [event, state];
    }

    if (this.isReady && plugin) {
        plugin.fireEvent.apply(plugin, args);
    } else {
        this.eventQueue.push(args);
    }
};


/**************
 * LIFE CYCLE *
 **************/

// Called before 'deviceready' event
channel.onCordovaReady.subscribe(function () {
    // Register trigger handler for each scheduled notification
    exports.callOnTriggerForScheduled(function (notification) {
        this.updateBadge(notification.badge);
        this.fireEvent('trigger', notification);
    });
});

// Handle onclick event
WinJS.Application.addEventListener('activated', function (args) {
    var id = args.detail.arguments,
        notification = exports.getAll([id])[0];

    if (!notification)
        return;

    exports.clearLocalNotification(id);

    var repeating = exports.isRepeating(notification);

    exports.fireEvent('click', notification);
    exports.fireEvent(repeating ? 'clear' : 'cancel', notification);
}, false);

// App is running in background
document.addEventListener('pause', function () {
    exports.isInBackground = true;
}, false);

// App is running in foreground
document.addEventListener('resume', function () {
    exports.isInBackground = false;
}, false);

// App is running in foreground
document.addEventListener('deviceready', function () {
    exports.isInBackground = false;
}, false);