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
/*
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.
*/
// See GGLInstanceID.h
#define GMP_NO_MODULES true
#import "PushPlugin.h"
#import "AppDelegate+notification.h"
@import Firebase;
@import FirebaseCore;
// @import FirebaseInstanceID;
@import FirebaseMessaging;
@implementation PushPlugin : CDVPlugin
@synthesize notificationMessage;
@synthesize isInline;
@synthesize coldstart;
@synthesize callbackId;
@synthesize notificationCallbackId;
@synthesize callback;
@synthesize clearBadge;
@synthesize handlerObj;
@synthesize usesFCM;
@synthesize fcmSandbox;
@synthesize fcmSenderId;
@synthesize fcmRegistrationOptions;
@synthesize fcmRegistrationToken;
@synthesize fcmTopics;
-(void)initRegistration;
{
[[FIRMessaging messaging] tokenWithCompletion:^(NSString *token, NSError *error) {
if (error != nil) {
NSLog(@"Error getting FCM registration token: %@", error);
} else {
NSLog(@"FCM registration token: %@", token);
[self setFcmRegistrationToken: token];
NSString* message = [NSString stringWithFormat:@"Remote InstanceID token: %@", token];
id topics = [self fcmTopics];
if (topics != nil) {
for (NSString *topic in topics) {
NSLog(@"subscribe to topic: %@", topic);
id pubSub = [FIRMessaging messaging];
[pubSub subscribeToTopic:topic];
}
}
[self registerWithToken: token];
}
}];
}
// FCM refresh token
// Unclear how this is testable under normal circumstances
- (void)onTokenRefresh {
#if !TARGET_IPHONE_SIMULATOR
// A rotation of the registration tokens is happening, so the app needs to request a new token.
NSLog(@"The FCM registration token needs to be changed.");
[self initRegistration];
#endif
}
// contains error info
- (void)didSendDataMessageWithID:messageID {
NSLog(@"didSendDataMessageWithID");
}
- (void)willSendDataMessageWithID:messageID error:error {
NSLog(@"willSendDataMessageWithID");
}
- (void)unregister:(CDVInvokedUrlCommand*)command;
{
NSArray* topics = [command argumentAtIndex:0];
if (topics != nil) {
id pubSub = [FIRMessaging messaging];
for (NSString *topic in topics) {
NSLog(@"unsubscribe from topic: %@", topic);
[pubSub unsubscribeFromTopic:topic];
}
} else {
[[UIApplication sharedApplication] unregisterForRemoteNotifications];
[self successWithMessage:command.callbackId withMsg:@"unregistered"];
}
}
- (void)subscribe:(CDVInvokedUrlCommand*)command;
{
NSString* topic = [command argumentAtIndex:0];
if (topic != nil) {
NSLog(@"subscribe from topic: %@", topic);
id pubSub = [FIRMessaging messaging];
[pubSub subscribeToTopic:topic];
NSLog(@"Successfully subscribe to topic %@", topic);
[self successWithMessage:command.callbackId withMsg:[NSString stringWithFormat:@"Successfully subscribe to topic %@", topic]];
} else {
NSLog(@"There is no topic to subscribe");
[self successWithMessage:command.callbackId withMsg:@"There is no topic to subscribe"];
}
}
- (void)unsubscribe:(CDVInvokedUrlCommand*)command;
{
NSString* topic = [command argumentAtIndex:0];
if (topic != nil) {
NSLog(@"unsubscribe from topic: %@", topic);
id pubSub = [FIRMessaging messaging];
[pubSub unsubscribeFromTopic:topic];
NSLog(@"Successfully unsubscribe from topic %@", topic);
[self successWithMessage:command.callbackId withMsg:[NSString stringWithFormat:@"Successfully unsubscribe from topic %@", topic]];
} else {
NSLog(@"There is no topic to unsubscribe");
[self successWithMessage:command.callbackId withMsg:@"There is no topic to unsubscribe"];
}
}
- (void)init:(CDVInvokedUrlCommand*)command;
{
NSMutableDictionary* options = [command.arguments objectAtIndex:0];
NSMutableDictionary* iosOptions = [options objectForKey:@"ios"];
id voipArg = [iosOptions objectForKey:@"voip"];
if (([voipArg isKindOfClass:[NSString class]] && [voipArg isEqualToString:@"true"]) || [voipArg boolValue]) {
[self.commandDelegate runInBackground:^ {
NSLog(@"Push Plugin VoIP set to true");
self.callbackId = command.callbackId;
PKPushRegistry *pushRegistry = [[PKPushRegistry alloc] initWithQueue:dispatch_get_main_queue()];
pushRegistry.delegate = self;
pushRegistry.desiredPushTypes = [NSSet setWithObject:PKPushTypeVoIP];
}];
} else {
NSLog(@"Push Plugin VoIP missing or false");
[[NSNotificationCenter defaultCenter]
addObserver:self selector:@selector(onTokenRefresh)
name:FIRMessagingRegistrationTokenRefreshedNotification object:nil];
[self.commandDelegate runInBackground:^ {
NSLog(@"Push Plugin register called");
self.callbackId = command.callbackId;
NSArray* topics = [iosOptions objectForKey:@"topics"];
[self setFcmTopics:topics];
UNAuthorizationOptions authorizationOptions = UNAuthorizationOptionNone;
id badgeArg = [iosOptions objectForKey:@"badge"];
id soundArg = [iosOptions objectForKey:@"sound"];
id alertArg = [iosOptions objectForKey:@"alert"];
id criticalArg = [iosOptions objectForKey:@"critical"];
id clearBadgeArg = [iosOptions objectForKey:@"clearBadge"];
if (([badgeArg isKindOfClass:[NSString class]] && [badgeArg isEqualToString:@"true"]) || [badgeArg boolValue])
{
authorizationOptions |= UNAuthorizationOptionBadge;
}
if (([soundArg isKindOfClass:[NSString class]] && [soundArg isEqualToString:@"true"]) || [soundArg boolValue])
{
authorizationOptions |= UNAuthorizationOptionSound;
}
if (([alertArg isKindOfClass:[NSString class]] && [alertArg isEqualToString:@"true"]) || [alertArg boolValue])
{
authorizationOptions |= UNAuthorizationOptionAlert;
}
if (@available(iOS 12.0, *))
{
if ((([criticalArg isKindOfClass:[NSString class]] && [criticalArg isEqualToString:@"true"]) || [criticalArg boolValue]))
{
authorizationOptions |= UNAuthorizationOptionCriticalAlert;
}
}
if (clearBadgeArg == nil || ([clearBadgeArg isKindOfClass:[NSString class]] && [clearBadgeArg isEqualToString:@"false"]) || ![clearBadgeArg boolValue]) {
NSLog(@"PushPlugin.register: setting badge to false");
clearBadge = NO;
} else {
NSLog(@"PushPlugin.register: setting badge to true");
clearBadge = YES;
[[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
}
NSLog(@"PushPlugin.register: clear badge is set to %d", clearBadge);
// isInline = NO;
NSLog(@"PushPlugin.register: better button setup");
// setup action buttons
NSMutableSet<UNNotificationCategory *> *categories = [[NSMutableSet alloc] init];
id categoryOptions = [iosOptions objectForKey:@"categories"];
if (categoryOptions != nil && [categoryOptions isKindOfClass:[NSDictionary class]]) {
for (id key in categoryOptions) {
NSLog(@"categories: key %@", key);
id category = [categoryOptions objectForKey:key];
id yesButton = [category objectForKey:@"yes"];
UNNotificationAction *yesAction;
if (yesButton != nil && [yesButton isKindOfClass:[NSDictionary class]]) {
yesAction = [self createAction: yesButton];
}
id noButton = [category objectForKey:@"no"];
UNNotificationAction *noAction;
if (noButton != nil && [noButton isKindOfClass:[NSDictionary class]]) {
noAction = [self createAction: noButton];
}
id maybeButton = [category objectForKey:@"maybe"];
UNNotificationAction *maybeAction;
if (maybeButton != nil && [maybeButton isKindOfClass:[NSDictionary class]]) {
maybeAction = [self createAction: maybeButton];
}
// Identifier to include in your push payload and local notification
NSString *identifier = key;
NSMutableArray<UNNotificationAction *> *actions = [[NSMutableArray alloc] init];
if (yesButton != nil) {
[actions addObject:yesAction];
}
if (noButton != nil) {
[actions addObject:noAction];
}
if (maybeButton != nil) {
[actions addObject:maybeAction];
}
UNNotificationCategory *notificationCategory = [UNNotificationCategory categoryWithIdentifier:identifier
actions:actions
intentIdentifiers:@[]
options:UNNotificationCategoryOptionNone];
NSLog(@"Adding category %@", key);
[categories addObject:notificationCategory];
}
}
UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
[center setNotificationCategories:categories];
[self handleNotificationSettingsWithAuthorizationOptions:[NSNumber numberWithInteger:authorizationOptions]];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(handleNotificationSettings:)
name:pushPluginApplicationDidBecomeActiveNotification
object:nil];
// Read GoogleService-Info.plist
NSString *path = [[NSBundle mainBundle] pathForResource:@"GoogleService-Info" ofType:@"plist"];
// Load the file content and read the data into arrays
NSDictionary *dict = [[NSDictionary alloc] initWithContentsOfFile:path];
fcmSenderId = [dict objectForKey:@"GCM_SENDER_ID"];
BOOL isGcmEnabled = [[dict valueForKey:@"IS_GCM_ENABLED"] boolValue];
NSLog(@"FCM Sender ID %@", fcmSenderId);
// GCM options
[self setFcmSenderId: fcmSenderId];
if(isGcmEnabled && [[self fcmSenderId] length] > 0) {
NSLog(@"Using FCM Notification");
[self setUsesFCM: YES];
dispatch_async(dispatch_get_main_queue(), ^{
if([FIRApp defaultApp] == nil)
[FIRApp configure];
[self initRegistration];
});
} else {
NSLog(@"Using APNS Notification");
[self setUsesFCM:NO];
}
id fcmSandboxArg = [iosOptions objectForKey:@"fcmSandbox"];
[self setFcmSandbox:@NO];
if ([self usesFCM] &&
(([fcmSandboxArg isKindOfClass:[NSString class]] && [fcmSandboxArg isEqualToString:@"true"]) ||
[fcmSandboxArg boolValue]))
{
NSLog(@"Using FCM Sandbox");
[self setFcmSandbox:@YES];
}
if (notificationMessage) { // if there is a pending startup notification
dispatch_async(dispatch_get_main_queue(), ^{
// delay to allow JS event handlers to be setup
[self performSelector:@selector(notificationReceived) withObject:nil afterDelay: 0.5];
});
}
}];
}
}
- (UNNotificationAction *)createAction:(NSDictionary *)dictionary {
NSString *identifier = [dictionary objectForKey:@"callback"];
NSString *title = [dictionary objectForKey:@"title"];
UNNotificationActionOptions options = UNNotificationActionOptionNone;
id mode = [dictionary objectForKey:@"foreground"];
if (mode != nil && (([mode isKindOfClass:[NSString class]] && [mode isEqualToString:@"true"]) || [mode boolValue])) {
options |= UNNotificationActionOptionForeground;
}
id destructive = [dictionary objectForKey:@"destructive"];
if (destructive != nil && (([destructive isKindOfClass:[NSString class]] && [destructive isEqualToString:@"true"]) || [destructive boolValue])) {
options |= UNNotificationActionOptionDestructive;
}
return [UNNotificationAction actionWithIdentifier:identifier title:title options:options];
}
- (void)didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
if (self.callbackId == nil) {
NSLog(@"Unexpected call to didRegisterForRemoteNotificationsWithDeviceToken, ignoring: %@", deviceToken);
return;
}
NSLog(@"Push Plugin register success: %@", deviceToken);
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 130000
// [deviceToken description] is like "{length = 32, bytes = 0xd3d997af 967d1f43 b405374a 13394d2f ... 28f10282 14af515f }"
NSString *token = [self hexadecimalStringFromData:deviceToken];
#else
// [deviceToken description] is like "<124686a5 556a72ca d808f572 00c323b9 3eff9285 92445590 3225757d b83967be>"
NSString *token = [[[[deviceToken description] stringByReplacingOccurrencesOfString:@"<"withString:@""]
stringByReplacingOccurrencesOfString:@">" withString:@""]
stringByReplacingOccurrencesOfString: @" " withString: @""];
#endif
#if !TARGET_IPHONE_SIMULATOR
// Get FCM Token after APNS token initialized
[self initRegistration];
// Check what Notifications the user has turned on. We registered for all three, but they may have manually disabled some or all of them.
UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
__weak PushPlugin *weakSelf = self;
[center getNotificationSettingsWithCompletionHandler:^(UNNotificationSettings * _Nonnull settings) {
if(![weakSelf usesFCM]) {
[weakSelf registerWithToken: token];
}
}];
#endif
}
- (NSString *)hexadecimalStringFromData:(NSData *)data
{
NSUInteger dataLength = data.length;
if (dataLength == 0) {
return nil;
}
const unsigned char *dataBuffer = data.bytes;
NSMutableString *hexString = [NSMutableString stringWithCapacity:(dataLength * 2)];
for (int i = 0; i < dataLength; ++i) {
[hexString appendFormat:@"%02x", dataBuffer[i]];
}
return [hexString copy];
}
- (void)didFailToRegisterForRemoteNotificationsWithError:(NSError *)error
{
if (self.callbackId == nil) {
NSLog(@"Unexpected call to didFailToRegisterForRemoteNotificationsWithError, ignoring: %@", error);
return;
}
NSLog(@"Push Plugin register failed");
[self failWithMessage:self.callbackId withMsg:@"" withError:error];
}
- (void)notificationReceived {
NSLog(@"Notification received");
if (notificationMessage && self.callbackId != nil)
{
NSMutableDictionary* message = [NSMutableDictionary dictionaryWithCapacity:4];
NSMutableDictionary* additionalData = [NSMutableDictionary dictionaryWithCapacity:4];
for (id key in notificationMessage) {
if ([key isEqualToString:@"aps"]) {
id aps = [notificationMessage objectForKey:@"aps"];
for(id key in aps) {
NSLog(@"Push Plugin key: %@", key);
id value = [aps objectForKey:key];
if ([key isEqualToString:@"alert"]) {
if ([value isKindOfClass:[NSDictionary class]]) {
for (id messageKey in value) {
id messageValue = [value objectForKey:messageKey];
if ([messageKey isEqualToString:@"body"]) {
[message setObject:messageValue forKey:@"message"];
} else if ([messageKey isEqualToString:@"title"]) {
[message setObject:messageValue forKey:@"title"];
} else {
[additionalData setObject:messageValue forKey:messageKey];
}
}
}
else {
[message setObject:value forKey:@"message"];
}
} else if ([key isEqualToString:@"title"]) {
[message setObject:value forKey:@"title"];
} else if ([key isEqualToString:@"badge"]) {
[message setObject:value forKey:@"count"];
} else if ([key isEqualToString:@"sound"]) {
[message setObject:value forKey:@"sound"];
} else if ([key isEqualToString:@"image"]) {
[message setObject:value forKey:@"image"];
} else {
[additionalData setObject:value forKey:key];
}
}
} else {
[additionalData setObject:[notificationMessage objectForKey:key] forKey:key];
}
}
if (isInline) {
[additionalData setObject:[NSNumber numberWithBool:YES] forKey:@"foreground"];
} else {
[additionalData setObject:[NSNumber numberWithBool:NO] forKey:@"foreground"];
}
if (coldstart) {
[additionalData setObject:[NSNumber numberWithBool:YES] forKey:@"coldstart"];
} else {
[additionalData setObject:[NSNumber numberWithBool:NO] forKey:@"coldstart"];
}
[message setObject:additionalData forKey:@"additionalData"];
// send notification message
CDVPluginResult* pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:message];
[pluginResult setKeepCallbackAsBool:YES];
[self.commandDelegate sendPluginResult:pluginResult callbackId:self.callbackId];
self.coldstart = NO;
self.notificationMessage = nil;
}
}
- (void)clearNotification:(CDVInvokedUrlCommand *)command
{
NSNumber *notId = [command.arguments objectAtIndex:0];
[[UNUserNotificationCenter currentNotificationCenter] getDeliveredNotificationsWithCompletionHandler:^(NSArray<UNNotification *> * _Nonnull notifications) {
/*
* If the server generates a unique "notId" for every push notification, there should only be one match in these arrays, but if not, it will delete
* all notifications with the same value for "notId"
*/
NSPredicate *matchingNotificationPredicate = [NSPredicate predicateWithFormat:@"request.content.userInfo.notId == %@", notId];
NSArray<UNNotification *> *matchingNotifications = [notifications filteredArrayUsingPredicate:matchingNotificationPredicate];
NSMutableArray<NSString *> *matchingNotificationIdentifiers = [NSMutableArray array];
for (UNNotification *notification in matchingNotifications) {
[matchingNotificationIdentifiers addObject:notification.request.identifier];
}
[[UNUserNotificationCenter currentNotificationCenter] removeDeliveredNotificationsWithIdentifiers:matchingNotificationIdentifiers];
NSString *message = [NSString stringWithFormat:@"Cleared notification with ID: %@", notId];
CDVPluginResult *commandResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:message];
[self.commandDelegate sendPluginResult:commandResult callbackId:command.callbackId];
}];
}
- (void)setApplicationIconBadgeNumber:(CDVInvokedUrlCommand *)command
{
NSMutableDictionary* options = [command.arguments objectAtIndex:0];
int badge = [[options objectForKey:@"badge"] intValue] ?: 0;
[[UIApplication sharedApplication] setApplicationIconBadgeNumber:badge];
NSString* message = [NSString stringWithFormat:@"app badge count set to %d", badge];
CDVPluginResult *commandResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:message];
[self.commandDelegate sendPluginResult:commandResult callbackId:command.callbackId];
}
- (void)getApplicationIconBadgeNumber:(CDVInvokedUrlCommand *)command
{
NSInteger badge = [UIApplication sharedApplication].applicationIconBadgeNumber;
CDVPluginResult *commandResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsInt:(int)badge];
[self.commandDelegate sendPluginResult:commandResult callbackId:command.callbackId];
}
- (void)clearAllNotifications:(CDVInvokedUrlCommand *)command
{
[[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
NSString* message = [NSString stringWithFormat:@"cleared all notifications"];
CDVPluginResult *commandResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:message];
[self.commandDelegate sendPluginResult:commandResult callbackId:command.callbackId];
}
- (void)hasPermission:(CDVInvokedUrlCommand *)command
{
id<UIApplicationDelegate> appDelegate = [UIApplication sharedApplication].delegate;
if ([appDelegate respondsToSelector:@selector(checkUserHasRemoteNotificationsEnabledWithCompletionHandler:)]) {
[appDelegate performSelector:@selector(checkUserHasRemoteNotificationsEnabledWithCompletionHandler:) withObject:^(BOOL isEnabled) {
NSMutableDictionary* message = [NSMutableDictionary dictionaryWithCapacity:1];
[message setObject:[NSNumber numberWithBool:isEnabled] forKey:@"isEnabled"];
CDVPluginResult *commandResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:message];
[self.commandDelegate sendPluginResult:commandResult callbackId:command.callbackId];
}];
}
}
-(void)successWithMessage:(NSString *)myCallbackId withMsg:(NSString *)message
{
if (myCallbackId != nil)
{
CDVPluginResult *commandResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:message];
[self.commandDelegate sendPluginResult:commandResult callbackId:myCallbackId];
}
}
-(void)registerWithToken:(NSString*)token; {
// Send result to trigger 'registration' event but keep callback
NSMutableDictionary* message = [NSMutableDictionary dictionaryWithCapacity:2];
[message setObject:token forKey:@"registrationId"];
if ([self usesFCM]) {
[message setObject:@"FCM" forKey:@"registrationType"];
} else {
[message setObject:@"APNS" forKey:@"registrationType"];
}
CDVPluginResult* pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:message];
[pluginResult setKeepCallbackAsBool:YES];
[self.commandDelegate sendPluginResult:pluginResult callbackId:self.callbackId];
}
-(void)failWithMessage:(NSString *)myCallbackId withMsg:(NSString *)message withError:(NSError *)error
{
NSString *errorMessage = (error) ? [NSString stringWithFormat:@"%@ - %@", message, [error localizedDescription]] : message;
CDVPluginResult *commandResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:errorMessage];
[self.commandDelegate sendPluginResult:commandResult callbackId:myCallbackId];
}
-(void) finish:(CDVInvokedUrlCommand*)command
{
NSLog(@"Push Plugin finish called");
[self.commandDelegate runInBackground:^ {
NSString* notId = [command.arguments objectAtIndex:0];
dispatch_async(dispatch_get_main_queue(), ^{
[NSTimer scheduledTimerWithTimeInterval:0.1
target:self
selector:@selector(stopBackgroundTask:)
userInfo:notId
repeats:NO];
});
CDVPluginResult* pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK];
[self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
}];
}
-(void)stopBackgroundTask:(NSTimer*)timer
{
UIApplication *app = [UIApplication sharedApplication];
NSLog(@"Push Plugin stopBackgroundTask called");
if (handlerObj) {
NSLog(@"Push Plugin handlerObj");
completionHandler = [handlerObj[[timer userInfo]] copy];
if (completionHandler) {
NSLog(@"Push Plugin: stopBackgroundTask (remaining t: %f)", app.backgroundTimeRemaining);
completionHandler(UIBackgroundFetchResultNewData);
completionHandler = nil;
}
}
}
- (void)pushRegistry:(PKPushRegistry *)registry didUpdatePushCredentials:(PKPushCredentials *)credentials forType:(NSString *)type
{
if([credentials.token length] == 0) {
NSLog(@"VoIPPush Plugin register error - No device token:");
return;
}
NSLog(@"VoIPPush Plugin register success");
const unsigned *tokenBytes = [credentials.token bytes];
NSString *sToken = [NSString stringWithFormat:@"%08x%08x%08x%08x%08x%08x%08x%08x",
ntohl(tokenBytes[0]), ntohl(tokenBytes[1]), ntohl(tokenBytes[2]),
ntohl(tokenBytes[3]), ntohl(tokenBytes[4]), ntohl(tokenBytes[5]),
ntohl(tokenBytes[6]), ntohl(tokenBytes[7])];
[self registerWithToken:sToken];
}
- (void)pushRegistry:(PKPushRegistry *)registry didReceiveIncomingPushWithPayload:(PKPushPayload *)payload forType:(NSString *)type
{
NSLog(@"VoIP Notification received");
self.notificationMessage = payload.dictionaryPayload;
[self notificationReceived];
}
- (void)handleNotificationSettings:(NSNotification *)notification
{
[self handleNotificationSettingsWithAuthorizationOptions:nil];
}
- (void)handleNotificationSettingsWithAuthorizationOptions:(NSNumber *)authorizationOptionsObject
{
UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
UNAuthorizationOptions authorizationOptions = [authorizationOptionsObject unsignedIntegerValue];
__weak UNUserNotificationCenter *weakCenter = center;
[center getNotificationSettingsWithCompletionHandler:^(UNNotificationSettings * _Nonnull settings) {
switch (settings.authorizationStatus) {
case UNAuthorizationStatusNotDetermined:
{
[weakCenter requestAuthorizationWithOptions:authorizationOptions completionHandler:^(BOOL granted, NSError * _Nullable error) {
if (granted) {
[self performSelectorOnMainThread:@selector(registerForRemoteNotifications)
withObject:nil
waitUntilDone:NO];
}
}];
break;
}
case UNAuthorizationStatusAuthorized:
{
[self performSelectorOnMainThread:@selector(registerForRemoteNotifications)
withObject:nil
waitUntilDone:NO];
break;
}
case UNAuthorizationStatusDenied:
default:
break;
}
}];
}
- (void)registerForRemoteNotifications
{
[[UIApplication sharedApplication] registerForRemoteNotifications];
}
@end
/*!
* 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);
// Type definitions for phonegap-plugin-push
// Project: https://github.com/havesource/cordova-plugin-push
// Definitions by: Frederico Galvão <https://github.com/fredgalvao>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
declare namespace PhonegapPluginPush {
type EventResponse = RegistrationEventResponse | NotificationEventResponse | Error
interface PushNotification {
/**
* The event registration will be triggered on each successful registration with the 3rd party push service.
* @param event
* @param callback
*/
on(event: "registration", callback: (response: RegistrationEventResponse) => any): void
/**
* The event notification will be triggered each time a push notification is received by a 3rd party push service on the device.
* @param event
* @param callback
*/
on(event: "notification", callback: (response: NotificationEventResponse) => any): void
/**
* The event error will trigger when an internal error occurs and the cache is aborted.
* @param event
* @param callback
*/
on(event: "error", callback: (response: Error) => any): void
/**
*
* @param event Name of the event to listen to. See below(above) for all the event names.
* @param callback is called when the event is triggered.
* @param event
* @param callback
*/
on(event: string, callback: (response: EventResponse) => any): void
off(event: "registration", callback: (response: RegistrationEventResponse) => any): void
off(event: "notification", callback: (response: NotificationEventResponse) => any): void
off(event: "error", callback: (response: Error) => any): void
/**
* As stated in the example, you will have to store your event handler if you are planning to remove it.
* @param event Name of the event type. The possible event names are the same as for the push.on function.
* @param callback handle to the function to get removed.
* @param event
* @param callback
*/
off(event: string, callback: (response: EventResponse) => any): void
/**
* The unregister method is used when the application no longer wants to receive push notifications.
* Beware that this cleans up all event handlers previously registered,
* so you will need to re-register them if you want them to function again without an application reload.
* @param successHandler
* @param errorHandler
* @param topics
*/
unregister(successHandler: () => any, errorHandler?: () => any, topics?: string[]): void
/**
* The subscribe method is used when the application wants to subscribe a new topic to receive push notifications.
* @param topic Topic to subscribe to.
* @param successHandler Is called when the api successfully unregisters.
* @param errorHandler Is called when the api encounters an error while unregistering.
*/
subscribe(topic: string, successHandler: () => any, errorHandler: () => any): void;
/**
* The unsubscribe method is used when the application no longer wants to receive push notifications
* from a specific topic but continue to receive other push messages.
* @param topic Topic to unsubscribe from.
* @param successHandler Is called when the api successfully unregisters.
* @param errorHandler Is called when the api encounters an error while unregistering.
*/
unsubscribe(topic: string, successHandler: () => any, errorHandler: () => any): void;
/*TODO according to js source code, "errorHandler" is optional, but is "count" also optional? I can't read objetive-C code (can anyone at all? I wonder...)*/
/**
* Set the badge count visible when the app is not running
*
* The count is an integer indicating what number should show up in the badge.
* Passing 0 will clear the badge.
* Each notification event contains a data.count value which can be used to set the badge to correct number.
* @param successHandler
* @param errorHandler
* @param count
*/
setApplicationIconBadgeNumber(successHandler: () => any, errorHandler: () => any, count: number): void
/**
* Get the current badge count visible when the app is not running
* successHandler gets called with an integer which is the current badge count
* @param successHandler
* @param errorHandler
*/
getApplicationIconBadgeNumber(successHandler: (count: number) => any, errorHandler: () => any): void
/**
* iOS only
* Tells the OS that you are done processing a background push notification.
* successHandler gets called when background push processing is successfully completed.
* @param successHandler
* @param errorHandler
* @param id
*/
finish(successHandler?: () => any, errorHandler?: () => any, id?: string): void
/**
* Tells the OS to clear all notifications from the Notification Center
* @param successHandler Is called when the api successfully clears the notifications.
* @param errorHandler Is called when the api encounters an error when attempting to clears the notifications.
*/
clearAllNotifications(successHandler: () => any, errorHandler: () => any): void
}
/**
* platform specific initialization options.
*/
interface InitOptions {
/**
* Android specific initialization options.
*/
android?: {
/**
* The name of a drawable resource to use as the small-icon. The name should not include the extension.
*/
icon?: string
/**
* Sets the background color of the small icon on Android 5.0 and greater.
* Supported Formats - http://developer.android.com/reference/android/graphics/Color.html#parseColor(java.lang.String)
*/
iconColor?: string
/**
* If true it plays the sound specified in the push data or the default system sound. Default is true.
*/
sound?: boolean
/**
* If true the device vibrates on receipt of notification. Default is true.
*/
vibrate?: boolean
/**
* If true the icon badge will be cleared on init and before push messages are processed. Default is false.
*/
clearBadge?: boolean
/**
* If true the app clears all pending notifications when it is closed. Default is true.
*/
clearNotifications?: boolean
/**
* If true will always show a notification, even when the app is on the foreground. Default is false.
*/
forceShow?: boolean
/**
* If the array contains one or more strings each string will be used to subscribe to a GcmPubSub topic.
*/
topics?: string[]
/**
* The key to search for text of notification. Default is 'message'.
*/
messageKey?: string
/**
* The key to search for title of notification. Default is 'title'.
*/
titleKey?: string
}
/**
* Browser specific initialization options.
*/
browser?: {
/**
* URL for the push server you want to use. Default is 'http://push.api.phonegap.com/v1/push'.
*/
pushServiceURL?: string
/**
* Your GCM API key if you are using VAPID keys.
*/
applicationServerKey?: string
}
/**
* iOS specific initialization options.
*/
ios?: {
/**
* If true|"true" the device will be set up to receive VoIP Push notifications and the other options will be ignored
* since VoIP notifications are silent notifications that should be handled in the "notification" event.
* Default is false|"false".
*/
voip?: boolean | string
/**
* If true|"true" the device sets the badge number on receipt of notification.
* Default is false|"false".
* Note: the value you set this option to the first time you call the init method will be how the application always acts.
* Once this is set programmatically in the init method it can only be changed manually by the user in Settings>Notifications>App Name.
* This is normal iOS behaviour.
*/
badge?: boolean | string
/**
* If true|"true" the device plays a sound on receipt of notification.
* Default is false|"false".
* Note: the value you set this option to the first time you call the init method will be how the application always acts.
* Once this is set programmatically in the init method it can only be changed manually by the user in Settings>Notifications>App Name.
* This is normal iOS behaviour.
*/
sound?: boolean | string
/**
* If true|"true" the device shows an alert on receipt of notification.
* Default is false|"false".
* Note: the value you set this option to the first time you call the init method will be how the application always acts.
* Once this is set programmatically in the init method it can only be changed manually by the user in Settings>Notifications>App Name.
* This is normal iOS behaviour.
*/
alert?: boolean | string
/**
* If true|"true" the badge will be cleared on app startup. Defaults to false|"false".
*/
clearBadge?: boolean | string
/**
* The data required in order to enable Action Buttons for iOS.
* Action Buttons on iOS - https://github.com/havesource/cordova-plugin-push/blob/master/docs/PAYLOAD.md#action-buttons-1
*/
categories?: CategoryArray
/**
* Whether to use prod or sandbox GCM setting. Defaults to false.
*/
fcmSandbox?: boolean
/**
* If the array contains one or more strings each string will be used to subscribe to a FcmPubSub topic. Defaults to [].
*/
topics?: string[]
}
/**
* Windows specific initialization options.
*/
windows?: {
}
}
interface CategoryArray {
[name: string]: CategoryAction
}
interface CategoryAction {
yes?: CategoryActionData
no?: CategoryActionData
maybe?: CategoryActionData
}
interface CategoryActionData {
callback: string
title: string
foreground: boolean
destructive: boolean
}
interface RegistrationEventResponse {
/**
* The registration ID provided by the 3rd party remote push service.
*/
registrationId: string
}
interface NotificationEventResponse {
/**
* The text of the push message sent from the 3rd party service.
*/
message: string
/**
* The optional title of the push message sent from the 3rd party service.
*/
title?: string
/**
* The number of messages to be displayed in the badge iOS or message count in the notification shade in Android.
* For windows, it represents the value in the badge notification which could be a number or a status glyph.
*/
count: string
/**
* The name of the sound file to be played upon receipt of the notification.
*/
sound: string
/**
* The path of the image file to be displayed in the notification.
*/
image: string
/**
* An optional collection of data sent by the 3rd party push service that does not fit in the above properties.
*/
additionalData: NotificationEventAdditionalData
}
/**
* TODO: document all possible properties (I only got the android ones)
*
* Loosened up with a dictionary notation, but all non-defined properties need to use (map['prop']) notation
*
* Ideally the developer would overload (merged declaration) this or create a new interface that would extend this one
* so that he could specify any custom code without having to use array notation (map['prop']) for all of them.
*/
interface NotificationEventAdditionalData {
[name: string]: any
/**
* Whether the notification was received while the app was in the foreground
*/
foreground?: boolean
/**
* Will be true if the application is started by clicking on the push notification, false if the app is already started. (Android/iOS only)
*/
coldstart?: boolean
collapse_key?: string
from?: string
notId?: string
}
interface Channel {
/**
* The id of the channel. Must be unique per package. The value may be truncated if it is too long.
*/
id: string;
/**
* The user visible name of the channel. The recommended maximum length is 40 characters; the value may be truncated if it is too long.
*/
description: string;
/**
* The importance of the channel. This controls how interruptive notifications posted to this channel are. The importance property goes from 1 = Lowest, 2 = Low, 3 = Normal, 4 = High and 5 = Highest.
*/
importance: number;
/**
* The name of the sound file to be played upon receipt of the notification in this channel. Empty string to disable sound. Cannot be changed after channel is created.
*/
sound?: string;
/**
* Boolean sets whether notification posted to this channel should vibrate. Array sets custom vibration pattern. Example - vibration: [2000, 1000, 500, 500]. Cannot be changed after channel is created.
*/
vibration?: boolean|number[];
/**
* Sets whether notifications posted to this channel appear on the lockscreen or not, and if so, whether they appear in a redacted form. 0 = Private, 1 = Public, -1 = Secret.
*/
visibility?: number;
}
interface PushNotificationStatic {
new (options: InitOptions): PushNotification
/**
* Initializes the plugin on the native side.
* @param options An object describing relevant specific options for all target platforms.
*/
init(options: InitOptions): PushNotification
/**
* Checks whether the push notification permission has been granted.
* @param successCallback Is called when the api successfully retrieves the details on the permission.
* @param errorCallback Is called when the api fails to retrieve the details on the permission.
*/
hasPermission(successCallback: (data: {isEnabled: boolean}) => void, errorCallback: () => void): void;
/**
* Android only
* Create a new notification channel for Android O and above.
* @param successCallback Is called when the api successfully creates a channel.
* @param errorCallback Is called when the api fails to create a channel.
* @param channel The options for the channel.
*/
createChannel(successCallback: () => void, errorCallback: () => void, channel: Channel): void;
/**
* Android only
* Delete a notification channel for Android O and above.
* @param successCallback Is called when the api successfully deletes a channel.
* @param errorCallback Is called when the api fails to create a channel.
* @param channelId The ID of the channel.
*/
deleteChannel(successCallback: () => void, errorCallback: () => void, channelId: string): void;
/**
* Android only
* Returns a list of currently configured channels.
* @param successCallback Is called when the api successfully retrieves the list of channels.
* @param errorCallback Is called when the api fails to retrieve the list of channels.
*/
listChannels(successCallback: (channels: Channel[]) => void, errorCallback: () => void): void;
}
}
interface Window {
PushNotification: PhonegapPluginPush.PushNotificationStatic
}
declare var PushNotification: PhonegapPluginPush.PushNotificationStatic;
/*!
* Module dependencies.
*/
cordova.require('cordova/exec');
/**
* PushNotification constructor.
*
* @param {Object} options to initiate Push Notifications.
* @return {PushNotification} instance that can be monitored and cancelled.
*/
var serviceWorker, subscription;
var PushNotification = function (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;
// subscription options
var subOptions = { userVisibleOnly: true };
if (this.options.browser && this.options.browser.applicationServerKey) {
subOptions.applicationServerKey = urlBase64ToUint8Array(this.options.browser.applicationServerKey);
}
// triggered on registration and notification
var that = this;
// Add manifest.json to main HTML file
var linkElement = document.createElement('link');
linkElement.rel = 'manifest';
linkElement.href = 'manifest.json';
document.getElementsByTagName('head')[0].appendChild(linkElement);
if ('serviceWorker' in navigator && 'MessageChannel' in window) {
var result;
var channel = new MessageChannel();
channel.port1.onmessage = function (event) {
that.emit('notification', event.data);
};
navigator.serviceWorker.register('ServiceWorker.js').then(function () {
return navigator.serviceWorker.ready;
})
.then(function (reg) {
serviceWorker = reg;
reg.pushManager.subscribe(subOptions).then(function (sub) {
subscription = sub;
result = { registrationId: sub.endpoint.substring(sub.endpoint.lastIndexOf('/') + 1) };
that.emit('registration', result);
// send encryption keys to push server
var xmlHttp = new XMLHttpRequest();
var xmlURL = (options.browser.pushServiceURL || 'http://push.api.phonegap.com/v1/push') + '/keys';
xmlHttp.open('POST', xmlURL, true);
var formData = new FormData();
formData.append('subscription', JSON.stringify(sub));
xmlHttp.send(formData);
navigator.serviceWorker.controller.postMessage(result, [channel.port2]);
}).catch(function () {
if (navigator.serviceWorker.controller === null) {
// When you first register a SW, need a page reload to handle network operations
window.location.reload();
return;
}
throw new Error('Error subscribing for Push notifications.');
});
}).catch(function (error) {
console.log(error);
throw new Error('Error registering Service Worker');
});
} else {
throw new Error('Service Workers are not supported on your browser.');
}
};
/**
* Unregister from push notifications
*/
PushNotification.prototype.unregister = function (successCallback, errorCallback, options) {
if (!errorCallback) { errorCallback = function () {}; }
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;
}
var that = this;
if (!options) {
that._handlers = {
registration: [],
notification: [],
error: []
};
}
if (serviceWorker) {
serviceWorker.unregister().then(function (isSuccess) {
if (isSuccess) {
var deviceID = subscription.endpoint.substring(subscription.endpoint.lastIndexOf('/') + 1);
var xmlHttp = new XMLHttpRequest();
var xmlURL = (that.options.browser.pushServiceURL || 'http://push.api.phonegap.com/v1/push') +
'/keys/' + deviceID;
xmlHttp.open('DELETE', xmlURL, true);
xmlHttp.send();
successCallback();
} else {
errorCallback();
}
});
}
};
/**
* subscribe to a topic
* @param {String} topic topic to subscribe
* @param {Function} successCallback success callback
* @param {Function} errorCallback error callback
* @return {void}
*/
PushNotification.prototype.subscribe = function (topic, successCallback, errorCallback) {
if (!errorCallback) { errorCallback = function () {}; }
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;
}
successCallback();
};
/**
* unsubscribe to a topic
* @param {String} topic topic to unsubscribe
* @param {Function} successCallback success callback
* @param {Function} errorCallback error callback
* @return {void}
*/
PushNotification.prototype.unsubscribe = function (topic, successCallback, errorCallback) {
if (!errorCallback) { errorCallback = function () {}; }
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;
}
successCallback();
};
/**
* Call this to set the application icon badge
*/
PushNotification.prototype.setApplicationIconBadgeNumber = function (successCallback, errorCallback, badge) {
if (!errorCallback) { errorCallback = function () {}; }
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;
}
successCallback();
};
/**
* Get the application icon badge
*/
PushNotification.prototype.getApplicationIconBadgeNumber = function (successCallback, errorCallback) {
if (!errorCallback) { errorCallback = function () {}; }
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;
}
successCallback();
};
/**
* Get the application icon badge
*/
PushNotification.prototype.clearAllNotifications = function (successCallback, errorCallback) {
if (!errorCallback) { errorCallback = function () {}; }
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;
}
successCallback();
};
/**
* 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.
*/
PushNotification.prototype.on = function (eventName, callback) {
if (Object.prototype.hasOwnProperty.call(this._handlers, eventName)) {
this._handlers[eventName].push(callback);
}
};
/**
* Remove event listener.
*
* @param {String} eventName to match subscription.
* @param {Function} handle function associated with event.
*/
PushNotification.prototype.off = function (eventName, handle) {
if (Object.prototype.hasOwnProperty.call(this._handlers, eventName)) {
var 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.
*/
PushNotification.prototype.emit = function () {
var args = Array.prototype.slice.call(arguments);
var eventName = args.shift();
if (!Object.prototype.hasOwnProperty.call(this._handlers, eventName)) {
return false;
}
for (var i = 0, length = this._handlers[eventName].length; i < length; i++) {
var callback = this._handlers[eventName][i];
if (typeof callback === 'function') {
callback.apply(undefined, args);
} else {
console.log('event handler: ' + eventName + ' must be a function');
}
}
return true;
};
PushNotification.prototype.finish = function (successCallback, errorCallback, id) {
if (!successCallback) { successCallback = function () {}; }
if (!errorCallback) { errorCallback = function () {}; }
if (!id) { 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;
}
successCallback();
};
/*!
* Push Notification Plugin.
*/
/**
* Converts the server key to an Uint8Array
*
* @param base64String
*
* @returns {Uint8Array}
*/
function urlBase64ToUint8Array (base64String) {
const padding = '='.repeat((4 - base64String.length % 4) % 4);
const base64 = (base64String + padding)
.replace(/-/g, '+')
.replace(/_/g, '/');
const rawData = window.atob(base64);
const outputArray = new Uint8Array(rawData.length);
for (var i = 0; i < rawData.length; ++i) {
outputArray[i] = rawData.charCodeAt(i);
}
return outputArray;
}
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: function (options) {
return new PushNotification(options);
},
hasPermission: function (successCallback, errorCallback) {
const granted = Notification && Notification.permission === 'granted';
successCallback({
isEnabled: granted
});
},
unregister: function (successCallback, errorCallback, options) {
PushNotification.unregister(successCallback, errorCallback, options);
},
/**
* PushNotification Object.
*
* Expose the PushNotification object for direct use
* and testing. Typically, you should use the
* .init helper method.
*/
PushNotification: PushNotification
};
/**
* This file has been generated by Babel.
*
* DO NOT EDIT IT DIRECTLY
*
* Edit the JS source file src/js/push.js
**/
"use strict";
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
/*!
* Module dependencies.
*/
var exec = cordova.require('cordova/exec');
var PushNotification = /*#__PURE__*/function () {
/**
* PushNotification constructor.
*
* @param {Object} options to initiate Push Notifications.
* @return {PushNotification} instance that can be monitored and cancelled.
*/
function PushNotification(options) {
var _this = this;
_classCallCheck(this, PushNotification);
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
var success = function 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
var fail = function fail(msg) {
var e = typeof msg === 'string' ? new Error(msg) : msg;
_this.emit('error', e);
}; // wait at least one process tick to allow event subscriptions
setTimeout(function () {
exec(success, fail, 'PushNotification', 'init', [options]);
}, 10);
}
/**
* Unregister from push notifications
*/
_createClass(PushNotification, [{
key: "unregister",
value: function unregister(successCallback) {
var _this2 = this;
var errorCallback = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : function () {};
var options = arguments.length > 2 ? arguments[2] : undefined;
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;
}
var cleanHandlersAndPassThrough = function cleanHandlersAndPassThrough() {
if (!options) {
_this2.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}
*/
}, {
key: "subscribe",
value: function subscribe(topic, successCallback) {
var errorCallback = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : function () {};
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}
*/
}, {
key: "unsubscribe",
value: function unsubscribe(topic, successCallback) {
var errorCallback = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : function () {};
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
*/
}, {
key: "setApplicationIconBadgeNumber",
value: function setApplicationIconBadgeNumber(successCallback) {
var errorCallback = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : function () {};
var badge = arguments.length > 2 ? arguments[2] : undefined;
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: badge
}]);
}
/**
* Get the application icon badge
*/
}, {
key: "getApplicationIconBadgeNumber",
value: function getApplicationIconBadgeNumber(successCallback) {
var errorCallback = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : function () {};
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
*/
}, {
key: "clearAllNotifications",
value: function clearAllNotifications() {
var successCallback = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : function () {};
var errorCallback = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : function () {};
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.
*/
}, {
key: "clearNotification",
value: function clearNotification() {
var successCallback = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : function () {};
var errorCallback = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : function () {};
var id = arguments.length > 2 ? arguments[2] : undefined;
var 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.
*/
}, {
key: "on",
value: function 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.
*/
}, {
key: "off",
value: function off(eventName, handle) {
if (Object.prototype.hasOwnProperty.call(this.handlers, eventName)) {
var 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.
*/
}, {
key: "emit",
value: function emit() {
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
var eventName = args.shift();
if (!Object.prototype.hasOwnProperty.call(this.handlers, eventName)) {
return false;
}
for (var i = 0, length = this.handlers[eventName].length; i < length; i += 1) {
var callback = this.handlers[eventName][i];
if (typeof callback === 'function') {
callback.apply(void 0, args); // eslint-disable-line node/no-callback-literal
} else {
console.log("event handler: ".concat(eventName, " must be a function"));
}
}
return true;
}
}, {
key: "finish",
value: function finish() {
var successCallback = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : function () {};
var errorCallback = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : function () {};
var id = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : '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]);
}
}]);
return PushNotification;
}();
/*!
* 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: function init(options) {
return new PushNotification(options);
},
hasPermission: function hasPermission(successCallback, errorCallback) {
exec(successCallback, errorCallback, 'PushNotification', 'hasPermission', []);
},
createChannel: function createChannel(successCallback, errorCallback, channel) {
exec(successCallback, errorCallback, 'PushNotification', 'createChannel', [channel]);
},
deleteChannel: function deleteChannel(successCallback, errorCallback, channelId) {
exec(successCallback, errorCallback, 'PushNotification', 'deleteChannel', [channelId]);
},
listChannels: function 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: PushNotification
};
\ No newline at end of file
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