UNPKG

@nativescript/firebase-messaging-core

Version:
372 lines (371 loc) 14.1 kB
import { Application, Device, Utils } from '@nativescript/core'; let defaultInstance; let Callback; function ensureCallback() { var CallbackImpl = /** @class */ (function (_super) { __extends(CallbackImpl, _super); function CallbackImpl() { var _this = _super.call(this) || this; return global.__native(_this); } CallbackImpl.prototype.onError = function (error) { }; CallbackImpl.prototype.onSuccess = function (message) { var _a, _b, _c; var callback = (_c = (_b = (_a = this._owner) === null || _a === void 0 ? void 0 : _a.get) === null || _b === void 0 ? void 0 : _b.call(_a)) === null || _c === void 0 ? void 0 : _c[this._propName]; if (typeof callback === 'function') { if (this._propName === '_onToken') { callback(message); } else if (this._propName === '_onNotificationTap' || this._propName === '_onMessage') { try { setTimeout(function () { callback(JSON.parse(message)); }); } catch (e) { // ignore } } else { try { callback(JSON.parse(message)); } catch (e) { // ignore } } } }; CallbackImpl = __decorate([ Interfaces([org.nativescript.firebase.messaging.FirebaseMessaging.Callback]), __metadata("design:paramtypes", []) ], CallbackImpl); return CallbackImpl; }(java.lang.Object)); Callback = CallbackImpl; } let Callback2; function ensureCallback2() { var Callback2Impl = /** @class */ (function (_super) { __extends(Callback2Impl, _super); function Callback2Impl() { var _this = _super.call(this) || this; return global.__native(_this); } Callback2Impl.prototype.onError = function (error) { }; Callback2Impl.prototype.onSuccess = function (message, remoteMessage) { var _a, _b, _c; var callback = (_c = (_b = (_a = this._owner) === null || _a === void 0 ? void 0 : _a.get) === null || _b === void 0 ? void 0 : _b.call(_a)) === null || _c === void 0 ? void 0 : _c[this._propName]; if (typeof callback === 'function') { if (this._propName === '_onToken') { callback(message); } else if (this._propName === '_onNotificationTap' || this._propName === '_onMessage') { try { setTimeout(function () { callback(JSON.parse(message), remoteMessage); }); } catch (e) { // ignore } } else { try { callback(JSON.parse(message), remoteMessage); } catch (e) { // ignore } } } }; Callback2Impl = __decorate([ Interfaces([org.nativescript.firebase.messaging.FirebaseMessaging.Callback2]), __metadata("design:paramtypes", []) ], Callback2Impl); return Callback2Impl; }(java.lang.Object)); Callback2 = Callback2Impl; } const onMessageCallbacks = new Set(); const onTokenCallbacks = new Set(); const onNotificationTapCallbacks = new Set(); let lastActivity; let requestPermissionLauncher; const _permissionQueue = []; function register(args) { if (!lastActivity) { // Some activities do not implement activity result API if (args.activity.registerForActivityResult) { lastActivity = new WeakRef(args.activity); requestPermissionLauncher = args.activity.registerForActivityResult(new androidx.activity.result.contract.ActivityResultContracts.RequestPermission(), new androidx.activity.result.ActivityResultCallback({ onActivityResult(isGranted) { _permissionQueue.forEach((callback) => { callback.resolve(isGranted ? 0 : 1); }); _permissionQueue.splice(0); }, })); } else { Application.android.once('activityCreated', register); } } } Application.android.on('activityResumed', (args) => { MessagingCore._inForeground = true; MessagingCore.appDidLaunch = true; MessagingCore._onResumeQueue.forEach((callback) => { callback(); }); MessagingCore._onResumeQueue.splice(0); }); Application.android.on('activityPaused', (args) => { MessagingCore._inForeground = false; }); Application.android.once('activityCreated', register); Application.android.on('activityDestroyed', (args) => { const activity = lastActivity?.get?.(); if (activity && args.activity === activity) { requestPermissionLauncher?.unregister?.(); lastActivity = undefined; Application.android.once('activityCreated', register); } }); export class MessagingCore { _onMessage(message, nativeMessage) { if (onMessageCallbacks.size > 0) { onMessageCallbacks.forEach((cb) => { cb(message, nativeMessage); }); } else { MessagingCore._messageQueues._onMessage.push(message); MessagingCore._messageQueues._onNativeMessage.push(nativeMessage); } } _onNotificationTap(message) { if (onNotificationTapCallbacks.size > 0) { onNotificationTapCallbacks.forEach((cb) => { cb(message); }); } else { MessagingCore._messageQueues._onNotificationTap.push(message); } } _onToken(token) { if (onTokenCallbacks.size > 0) { onTokenCallbacks.forEach((cb) => { cb(token); }); } else { MessagingCore._messageQueues._onToken.push(token); } } static addToResumeQueue(callback) { if (typeof callback !== 'function') { return; } MessagingCore._onResumeQueue.push(callback); } static get inForeground() { return MessagingCore._inForeground; } static get appDidLaunch() { return MessagingCore._appDidLaunch; } static set appDidLaunch(value) { MessagingCore._appDidLaunch = value; } constructor() { if (defaultInstance) { return defaultInstance; } defaultInstance = this; org.nativescript.firebase.messaging.FirebaseMessaging.init(Utils.android.getApplicationContext()); ensureCallback(); ensureCallback2(); // Setup onmessage handling this._onMessageCallback = new Callback2(); this._onMessageCallback._propName = '_onMessage'; this._onMessageCallback._owner = new WeakRef(this); org.nativescript.firebase.messaging.FirebaseMessaging.setOnMessageListener(this._onMessageCallback); // Setup tap notification handling this._onNotificationTapCallback = new Callback(); this._onNotificationTapCallback._propName = '_onNotificationTap'; this._onNotificationTapCallback._owner = new WeakRef(this); org.nativescript.firebase.messaging.FirebaseMessaging.setOnMessageTapListener(this._onNotificationTapCallback); this._onTokenCallback = new Callback(); this._onTokenCallback._propName = '_onToken'; this._onTokenCallback._owner = new WeakRef(this); org.nativescript.firebase.messaging.FirebaseMessaging.setOnTokenListener(this._onTokenCallback); Application.android.on(Application.AndroidApplication.activityNewIntentEvent, this._newIntentCallback.bind(this)); } static getInstance() { if (defaultInstance) { return defaultInstance; } return new MessagingCore(); } get native() { if (!this._native) { this._native = com.google.firebase.messaging.FirebaseMessaging.getInstance(); } return this._native; } _newIntentCallback(args) { org.nativescript.firebase.messaging.FirebaseMessaging.handleActivityIntent(args.intent); } getCurrentToken() { return new Promise((resolve, reject) => { org.nativescript.firebase.messaging.FirebaseMessaging.getToken(this.native, new org.nativescript.firebase.messaging.FirebaseMessaging.Callback({ onSuccess(result) { resolve(result); }, onError(error) { const err = new Error(error?.getMessage?.() || 'Failed to getToken'); err.native = error; reject(err); }, })); }); } hasPermission() { const context = Utils.android.getApplicationContext(); if (parseInt(Device.sdkVersion) >= 33) { if (androidx.core.content.ContextCompat.checkSelfPermission(context, android.Manifest.permission.POST_NOTIFICATIONS) === android.content.pm.PackageManager.PERMISSION_GRANTED) { return Promise.resolve(0); } else { return Promise.resolve(1); } } return Promise.resolve(org.nativescript.firebase.messaging.FirebaseMessaging.hasPermission(context) ? 0 : 1); } 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 Promise.resolve(); } requestPermission(permissions) { if (parseInt(Device.sdkVersion) >= 33) { const activity = Application.android.foregroundActivity || Application.android.startActivity; return new Promise((resolve, reject) => { // TODO /*const launch = (activity) => { _permissionQueue.push({ resolve, reject, }); requestPermissionLauncher.launch((android as any).Manifest.permission.POST_NOTIFICATIONS); }; if (!activity) { Application.android.once('activityCreated', (args: any) => { register(args); launch(args.activity); }); } else { launch(activity); } */ const requestPermission = (activity) => { Application.android.on('activityRequestPermissions', (event) => { if (event.requestCode === 1001) { if (event.grantResults && event.grantResults.length > 0 && event.grantResults[0] === android.content.pm.PackageManager.PERMISSION_GRANTED) { resolve(0); } else { reject(1); } } }); const perms = Array.create('java.lang.String', 1); perms[0] = android.Manifest.permission.POST_NOTIFICATIONS; activity.requestPermissions(perms, 1001); }; if (!activity) { Application.android.once('activityCreated', (args) => { requestPermission(args.activity); }); } else { requestPermission(activity); } }); } return this.hasPermission(); } unregisterDeviceForRemoteMessages() { return Promise.resolve(); } get isDeviceRegisteredForRemoteMessages() { return org.nativescript.firebase.messaging.FirebaseMessaging.hasPermission(Utils.android.getApplicationContext()); } _triggerPendingCallbacks(type) { const queue = MessagingCore._messageQueues[type]; const isOnMessage = type === '_onMessage'; const messageQueue = isOnMessage ? MessagingCore._messageQueues._onNativeMessage : undefined; if (queue.length > 0) { MessagingCore._messageQueues[type] = []; if (isOnMessage) { MessagingCore._messageQueues._onNativeMessage = []; } queue.forEach((message, index) => { if (isOnMessage) { this[type](message, messageQueue[index]); } else { this[type](message); } }); } } } MessagingCore._onResumeQueue = []; MessagingCore._messageQueues = { _onMessage: [], _onNativeMessage: [], _onNotificationTap: [], _onToken: [], }; MessagingCore._inForeground = false; MessagingCore._appDidLaunch = false; export { AuthorizationStatus } from './common'; //# sourceMappingURL=index.android.js.map