Commit 3e2631f3 authored by Chok's avatar Chok
Browse files

chok: init commit

parent 511add9c
Pipeline #20 failed with stages
in 0 seconds
/*
Copyright 2009-2011 Urban Airship Inc. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binaryform must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided withthe distribution.
THIS SOFTWARE IS PROVIDED BY THE URBAN AIRSHIP INC``AS IS'' AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
EVENT SHALL URBAN AIRSHIP INC OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
@import Foundation;
@import UserNotifications;
#import <Cordova/CDV.h>
#import <Cordova/CDVPlugin.h>
#import <PushKit/PushKit.h>
@protocol GGLInstanceIDDelegate;
@protocol GCMReceiverDelegate;
@interface PushPlugin : CDVPlugin
{
NSDictionary *notificationMessage;
BOOL isInline;
NSString *notificationCallbackId;
NSString *callback;
BOOL clearBadge;
NSMutableDictionary *handlerObj;
void (^completionHandler)(UIBackgroundFetchResult);
BOOL ready;
}
@property (nonatomic, copy) NSString *callbackId;
@property (nonatomic, copy) NSString *notificationCallbackId;
@property (nonatomic, copy) NSString *callback;
@property (nonatomic, strong) NSDictionary *notificationMessage;
@property BOOL isInline;
@property BOOL coldstart;
@property BOOL clearBadge;
@property (nonatomic, strong) NSMutableDictionary *handlerObj;
- (void)init:(CDVInvokedUrlCommand*)command;
- (void)unregister:(CDVInvokedUrlCommand*)command;
- (void)subscribe:(CDVInvokedUrlCommand*)command;
- (void)unsubscribe:(CDVInvokedUrlCommand*)command;
- (void)clearNotification:(CDVInvokedUrlCommand*)command;
- (void)didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken;
- (void)didFailToRegisterForRemoteNotificationsWithError:(NSError *)error;
- (void)setNotificationMessage:(NSDictionary *)notification;
- (void)notificationReceived;
- (void)willSendDataMessageWithID:(NSString *)messageID error:(NSError *)error;
- (void)didSendDataMessageWithID:(NSString *)messageID;
// VoIP Features
- (void)pushRegistry:(PKPushRegistry *)registry didUpdatePushCredentials:(PKPushCredentials *)credentials forType:(NSString *)type;
- (void)pushRegistry:(PKPushRegistry *)registry didReceiveIncomingPushWithPayload:(PKPushPayload *)payload forType:(NSString *)type;
// FCM Features
@property(nonatomic, assign) BOOL usesFCM;
@property(nonatomic, strong) NSNumber *fcmSandbox;
@property(nonatomic, strong) NSString *fcmSenderId;
@property(nonatomic, strong) NSDictionary *fcmRegistrationOptions;
@property(nonatomic, strong) NSString *fcmRegistrationToken;
@property(nonatomic, strong) NSArray *fcmTopics;
@end
This diff is collapsed.
/*!
* 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
};
var myApp = {};
var pushNotifications = Windows.Networking.PushNotifications;
var createNotificationJSON = function (e) {
var result = { message: '' }; // Added to identify callback as notification type in the API in case where notification has no message
var notificationPayload;
switch (e.notificationType) {
case pushNotifications.PushNotificationType.toast:
case pushNotifications.PushNotificationType.tile:
if (e.notificationType === pushNotifications.PushNotificationType.toast) {
notificationPayload = e.toastNotification.content;
} else {
notificationPayload = e.tileNotification.content;
}
var texts = notificationPayload.getElementsByTagName('text');
if (texts.length > 1) {
result.title = texts[0].innerText;
result.message = texts[1].innerText;
} else if (texts.length === 1) {
result.message = texts[0].innerText;
}
var images = notificationPayload.getElementsByTagName('image');
if (images.length > 0) {
result.image = images[0].getAttribute('src');
}
var soundFile = notificationPayload.getElementsByTagName('audio');
if (soundFile.length > 0) {
result.sound = soundFile[0].getAttribute('src');
}
break;
case pushNotifications.PushNotificationType.badge:
notificationPayload = e.badgeNotification.content;
result.count = notificationPayload.getElementsByTagName('badge')[0].getAttribute('value');
break;
case pushNotifications.PushNotificationType.raw:
result.message = e.rawNotification.content;
break;
}
result.additionalData = { coldstart: false }; // this gets called only when the app is running
result.additionalData.pushNotificationReceivedEventArgs = e;
return result;
};
module.exports = {
init: function (onSuccess, onFail, args) {
var onNotificationReceived = function (e) {
var result = createNotificationJSON(e);
onSuccess(result, { keepCallback: true });
};
try {
pushNotifications.PushNotificationChannelManager.createPushNotificationChannelForApplicationAsync().done(
function (channel) {
var result = {};
result.registrationId = channel.uri;
myApp.channel = channel;
channel.addEventListener('pushnotificationreceived', onNotificationReceived);
myApp.notificationEvent = onNotificationReceived;
onSuccess(result, { keepCallback: true });
var context = cordova.require('cordova/platform').activationContext;
var launchArgs = context ? (context.argument || context.args) : null;
if (launchArgs) { // If present, app launched through push notification
result = { message: '' }; // Added to identify callback as notification type in the API
result.launchArgs = launchArgs;
result.additionalData = { coldstart: true };
onSuccess(result, { keepCallback: true });
}
}, function (error) {
onFail(error);
});
} catch (ex) {
onFail(ex);
}
},
unregister: function (onSuccess, onFail, args) {
try {
myApp.channel.removeEventListener('pushnotificationreceived', myApp.notificationEvent);
myApp.channel.close();
onSuccess();
} catch (ex) {
onFail(ex);
}
},
hasPermission: function (onSuccess) {
var notifier = Windows.UI.Notifications.ToastNotificationManager.createToastNotifier();
onSuccess({ isEnabled: !notifier.setting });
},
subscribe: function () {
console.log('Subscribe is unsupported');
},
unsubscribe: function () {
console.log('Subscribe is unsupported');
}
};
require('cordova/exec/proxy').add('PushNotification', module.exports);
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment