@nativescript/firebase-messaging-core
Version:
NativeScript Push Messaging Core
338 lines • 13.1 kB
JavaScript
import { Application, ApplicationSettings, Device } from '@nativescript/core';
import { AuthorizationStatus } from './common';
let _registerDeviceForRemoteMessages = {
resolve: null,
reject: null,
};
const REMOTE_NOTIFICATIONS_REGISTRATION_STATUS = 'org.nativescript.firebase.notifications.status';
let defaultInstance;
const onMessageCallbacks = new Set();
const onTokenCallbacks = new Set();
const onNotificationTapCallbacks = new Set();
function deserialize(data) {
if (data instanceof NSNull) {
return null;
}
if (data instanceof NSArray) {
let array = [];
for (let i = 0, n = data.count; i < n; i++) {
array[i] = deserialize(data.objectAtIndex(i));
}
return array;
}
if (data instanceof NSDictionary) {
let dict = {};
for (let i = 0, n = data.allKeys.count; i < n; i++) {
let key = data.allKeys.objectAtIndex(i);
dict[key] = deserialize(data.objectForKey(key));
}
return dict;
}
return data;
}
export class MessagingCore {
_onMessage(message, remoteMessage, completionHandler) {
if (onMessageCallbacks.size > 0) {
const msg = deserialize(message);
Promise.all(Array.from(onMessageCallbacks).map((cb) => cb(msg))).finally(() => completionHandler());
}
else {
MessagingCore._messageQueues._onMessage.push(message);
completionHandler();
}
}
_onToken(token) {
this._APNSToken = token;
if (this._getTokenQeueue.length > 0) {
this._getTokenQeueue.forEach((item) => {
item.resolve(token);
});
this._getTokenQeueue.splice(0);
}
if (onTokenCallbacks.size > 0) {
onTokenCallbacks.forEach((cb) => {
cb(token);
});
}
else {
MessagingCore._messageQueues._onToken.push(token);
}
}
_onNotificationTap(message, remoteMessage, completionHandler) {
if (onNotificationTapCallbacks.size > 0) {
const msg = deserialize(message);
Promise.all(Array.from(onNotificationTapCallbacks).map((cb) => cb(msg, remoteMessage))).finally(() => completionHandler());
}
else {
MessagingCore._messageQueues._onNotificationTap.push(message);
MessagingCore._messageQueues._onNativeNotificationTap.push(remoteMessage);
completionHandler();
}
}
static addToResumeQueue(callback) {
if (typeof callback !== 'function') {
return;
}
MessagingCore._onResumeQueue.push(callback);
}
static get inForeground() {
return MessagingCore._inForeground;
}
static get appDidLaunch() {
return MessagingCore._appDidLaunch;
}
constructor() {
this._getTokenQeueue = [];
if (defaultInstance) {
return defaultInstance;
}
defaultInstance = this;
Application.on('launch', (args) => {
MessagingCore._onResumeQueue.forEach((callback) => {
callback();
});
MessagingCore._onResumeQueue.splice(0);
});
Application.on('resume', (args) => {
MessagingCore._inForeground = true;
MessagingCore._appDidLaunch = true;
});
Application.on('suspend', (args) => {
MessagingCore._inForeground = false;
});
NSCFirebaseMessagingCore.onMessageCallback = this._onMessage.bind(this);
NSCFirebaseMessagingCore.onTokenCallback = this._onToken.bind(this);
NSCFirebaseMessagingCore.onNotificationTapCallback = this._onNotificationTap.bind(this);
}
static getInstance() {
if (defaultInstance) {
return defaultInstance;
}
return new MessagingCore();
}
get showNotificationsWhenInForeground() {
return NSCFirebaseMessagingCore.showNotificationsWhenInForeground;
}
set showNotificationsWhenInForeground(value) {
NSCFirebaseMessagingCore.showNotificationsWhenInForeground = value;
}
getCurrentToken() {
return new Promise(async (resolve, reject) => {
if (!TNSFirebaseCore.isSimulator() && !UIApplication.sharedApplication.registeredForRemoteNotifications) {
reject(new Error('You must be registered for remote messages before calling getToken, see MessagingCore.getInstance().registerDeviceForRemoteMessages()'));
return;
}
if (!this._APNSToken) {
if ((await this.hasPermission()) === AuthorizationStatus.DENIED) {
reject(new Error('Device is unauthorized to receive an APNSToken token.'));
return;
}
this._getTokenQeueue.push({ resolve, reject });
return;
}
resolve(this.getAPNSToken());
});
}
getAPNSToken() {
return this._APNSToken;
}
_hasPermission(resolve, reject) {
if (parseInt(Device.osVersion) >= 10) {
UNUserNotificationCenter.currentNotificationCenter().getNotificationSettingsWithCompletionHandler((settings) => {
let status = AuthorizationStatus.NOT_DETERMINED;
switch (settings.authorizationStatus) {
case 2 /* UNAuthorizationStatus.Authorized */:
status = AuthorizationStatus.AUTHORIZED;
break;
case 1 /* UNAuthorizationStatus.Denied */:
status = AuthorizationStatus.DENIED;
break;
case 4 /* UNAuthorizationStatus.Ephemeral */:
status = AuthorizationStatus.EPHEMERAL;
break;
case 3 /* UNAuthorizationStatus.Provisional */:
status = AuthorizationStatus.PROVISIONAL;
break;
case 0 /* UNAuthorizationStatus.NotDetermined */:
status = AuthorizationStatus.NOT_DETERMINED;
break;
}
resolve(status);
});
}
else {
resolve(AuthorizationStatus.AUTHORIZED);
}
}
hasPermission() {
return new Promise((resolve, reject) => {
this._hasPermission(resolve, reject);
});
}
addOnMessage(listener) {
if (typeof listener === 'function') {
onMessageCallbacks.add(listener);
this._triggerPendingCallbacks('_onMessage');
}
}
removeOnMessage(listener) {
if (typeof listener === 'function') {
return onMessageCallbacks.delete(listener);
}
return false;
}
addOnToken(listener) {
if (typeof listener === 'function') {
onTokenCallbacks.add(listener);
this._triggerPendingCallbacks('_onToken');
}
}
removeOnToken(listener) {
if (typeof listener === 'function') {
return onTokenCallbacks.delete(listener);
}
return false;
}
addOnNotificationTap(listener) {
if (typeof listener === 'function') {
onNotificationTapCallbacks.add(listener);
this._triggerPendingCallbacks('_onNotificationTap');
}
}
removeOnNotificationTap(listener) {
if (typeof listener === 'function') {
return onNotificationTapCallbacks.delete(listener);
}
return false;
}
registerDeviceForRemoteMessages() {
return new Promise((resolve, reject) => {
if (TNSFirebaseCore.isSimulator()) {
ApplicationSettings.setBoolean(REMOTE_NOTIFICATIONS_REGISTRATION_STATUS, true);
resolve();
}
NSCFirebaseMessagingCore.registerDeviceForRemoteMessagesCallback = (result, error) => {
if (error) {
const err = new Error(error?.localizedDescription);
err.native = error;
if (this._getTokenQeueue.length > 0) {
this._getTokenQeueue.forEach((item) => {
item.reject(err);
});
this._getTokenQeueue.splice(0);
}
reject(err);
}
else {
resolve();
}
};
if (UIApplication?.sharedApplication) {
UIApplication?.sharedApplication?.registerForRemoteNotifications?.();
}
else {
const cb = (args) => {
UIApplication?.sharedApplication?.registerForRemoteNotifications?.();
Application.off('launch', cb);
};
Application.on('launch', cb);
}
});
}
requestPermission(permissions) {
return new Promise((resolve, reject) => {
const version = parseInt(Device.osVersion);
if (version >= 10) {
let options = UNAuthorizationOptionNone;
if (permissions?.ios?.alert ?? true) {
options = options | 4 /* UNAuthorizationOptions.Alert */;
}
if (permissions?.ios?.badge ?? true) {
options = options | 1 /* UNAuthorizationOptions.Badge */;
}
if (permissions?.ios?.sound ?? true) {
options = options | 2 /* UNAuthorizationOptions.Sound */;
}
if (permissions?.ios?.carPlay ?? true) {
options = options | 8 /* UNAuthorizationOptions.CarPlay */;
}
if (version >= 12) {
if (permissions?.ios?.criticalAlert) {
options = options | 16 /* UNAuthorizationOptions.CriticalAlert */;
}
if (permissions?.ios?.provisional) {
options = options | 64 /* UNAuthorizationOptions.Provisional */;
}
}
if (version >= 13 && version <= 15) {
options = options | 128 /* UNAuthorizationOptions.Announcement */;
}
UNUserNotificationCenter.currentNotificationCenter().requestAuthorizationWithOptionsCompletionHandler(options, (result, error) => {
if (error) {
const err = new Error(error?.localizedDescription);
err.native = error;
reject(err);
reject(err);
}
else {
this._hasPermission(resolve, reject);
}
});
}
else {
const notificationTypes = 2 /* UIUserNotificationType.Sound */ | 4 /* UIUserNotificationType.Alert */ | 1 /* UIUserNotificationType.Badge */;
const settings = UIUserNotificationSettings.settingsForTypesCategories(notificationTypes, null);
UIApplication.sharedApplication.registerUserNotificationSettings(settings);
this._hasPermission(resolve, reject);
}
});
}
unregisterDeviceForRemoteMessages() {
return new Promise((resolve, reject) => {
try {
UIApplication.sharedApplication.unregisterForRemoteNotifications();
ApplicationSettings.setBoolean(REMOTE_NOTIFICATIONS_REGISTRATION_STATUS, false);
resolve();
}
catch (e) {
reject(e);
}
});
}
get isDeviceRegisteredForRemoteMessages() {
return UIApplication.sharedApplication.registeredForRemoteNotifications;
}
_triggerPendingCallbacks(type) {
const queue = MessagingCore._messageQueues[type];
let remoteQueue;
const isNotificationTap = type === '_onNotificationTap';
if (isNotificationTap) {
remoteQueue = MessagingCore._messageQueues._onNativeNotificationTap;
}
if (queue.length > 0) {
MessagingCore._messageQueues[type] = [];
if (isNotificationTap) {
MessagingCore._messageQueues._onNativeNotificationTap = [];
}
queue.forEach((message, index) => {
if (isNotificationTap) {
this[type](message, remoteQueue[index], () => { });
}
else {
this[type](message, () => { });
}
});
}
}
}
MessagingCore._onResumeQueue = [];
MessagingCore._messageQueues = {
_onMessage: [],
_onNotificationTap: [],
_onNativeNotificationTap: [],
_onToken: [],
};
MessagingCore._inForeground = false;
MessagingCore._appDidLaunch = false;
export { AuthorizationStatus } from './common';
//# sourceMappingURL=index.ios.js.map