From d0d464154dc80614ee771ef703f9399ac78f903b Mon Sep 17 00:00:00 2001 From: Rodrigo Gomez Palacio Date: Tue, 23 Jul 2024 14:28:50 -0500 Subject: [PATCH 1/7] Remove `sendNotification` API calls Motivation: cleaning up dead code. Shifting to use of local notifications --- src/shared/api/OneSignalApi.ts | 23 ------------------- src/shared/api/OneSignalApiShared.ts | 33 ---------------------------- 2 files changed, 56 deletions(-) diff --git a/src/shared/api/OneSignalApi.ts b/src/shared/api/OneSignalApi.ts index 656ed357c..d0b15418b 100755 --- a/src/shared/api/OneSignalApi.ts +++ b/src/shared/api/OneSignalApi.ts @@ -2,32 +2,9 @@ import JSONP from 'jsonp'; import SdkEnvironment from '../managers/SdkEnvironment'; import { WindowEnvironmentKind } from '../models/WindowEnvironmentKind'; import OneSignalApiSW from './OneSignalApiSW'; -import OneSignalApiShared from './OneSignalApiShared'; import { ServerAppConfig } from '../models/AppConfig'; export default class OneSignalApi { - static sendNotification( - appId: string, - playerIds: Array, - titles, - contents, - url, - icon, - data, - buttons, - ) { - return OneSignalApiShared.sendNotification( - appId, - playerIds, - titles, - contents, - url, - icon, - data, - buttons, - ); - } - static jsonpLib( url: string, fn: (err: Error, data: ServerAppConfig) => void, diff --git a/src/shared/api/OneSignalApiShared.ts b/src/shared/api/OneSignalApiShared.ts index 1ba6f6263..9531397f9 100644 --- a/src/shared/api/OneSignalApiShared.ts +++ b/src/shared/api/OneSignalApiShared.ts @@ -1,41 +1,8 @@ import { OutcomeRequestData } from '../../page/models/OutcomeRequestData'; -import Utils from '../context/Utils'; import Log from '../libraries/Log'; import OneSignalApiBase from './OneSignalApiBase'; export default class OneSignalApiShared { - static sendNotification( - appId: string, - playerIds: Array, - titles, - contents, - url, - icon, - data, - buttons, - ) { - const params = { - app_id: appId, - contents: contents, - include_player_ids: playerIds, - isAnyWeb: true, - data: data, - web_buttons: buttons, - }; - if (titles) { - (params as any).headings = titles; - } - if (url) { - (params as any).url = url; - } - if (icon) { - (params as any).chrome_web_icon = icon; - (params as any).firefox_icon = icon; - } - Utils.trimUndefined(params); - return OneSignalApiBase.post('notifications', params); - } - static async sendOutcome(data: OutcomeRequestData): Promise { Log.info('Outcome payload:', data); try { From 17bc986270ea165c5111ddae48f082b438158863 Mon Sep 17 00:00:00 2001 From: Rodrigo Gomez Palacio Date: Tue, 23 Jul 2024 14:44:02 -0500 Subject: [PATCH 2/7] Add `showLocalNotification` to MainHelper Motivation: no longer on the public namespaces, we will put `showLocalNotification` here for use by the welcome notification mechanism --- src/shared/helpers/MainHelper.ts | 69 ++++++++++++++++++++++++++++++++ 1 file changed, 69 insertions(+) diff --git a/src/shared/helpers/MainHelper.ts b/src/shared/helpers/MainHelper.ts index d8d538d5b..456707754 100755 --- a/src/shared/helpers/MainHelper.ts +++ b/src/shared/helpers/MainHelper.ts @@ -12,8 +12,77 @@ import Utils from '../context/Utils'; import Database from '../services/Database'; import { PermissionUtils } from '../utils/PermissionUtils'; import Environment from './Environment'; +import { getPlatformNotificationIcon, logMethodCall } from '../utils/utils'; +import { NotSubscribedError, NotSubscribedReason } from '../errors/NotSubscribedError'; +import { InvalidArgumentError, InvalidArgumentReason } from '../errors/InvalidArgumentError'; +import { ValidatorUtils } from '../../page/utils/ValidatorUtils'; export default class MainHelper { + static async showLocalNotification( + title: string, + message: string, + url: string, + icon?: string, + data?: Record, + buttons?: Array + ): Promise { + logMethodCall('MainHelper:showLocalNotification: ', title, message, url, icon, data, buttons); + + const appConfig = await Database.getAppConfig(); + + if (!appConfig.appId) + throw new InvalidStateError(InvalidStateReason.MissingAppId); + if (!(OneSignal.Notifications.permission)) + throw new NotSubscribedError(NotSubscribedReason.NoDeviceId); + if (!ValidatorUtils.isValidUrl(url)) + throw new InvalidArgumentError('url', InvalidArgumentReason.Malformed); + if (!ValidatorUtils.isValidUrl(icon, { allowEmpty: true, requireHttps: true })) + throw new InvalidArgumentError('icon', InvalidArgumentReason.Malformed); + if (!icon) { + // get default icon + const icons = await MainHelper.getNotificationIcons(); + icon = getPlatformNotificationIcon(icons); + } + + const convertButtonsToNotificationActionType = (buttons: Array) => { + const convertedButtons = []; + + for (let i=0; i { + if (!registration) { + Log.error('Service worker registration not available.'); + return; + } + + const options = { + body: message, + data: dataPayload, + icon: icon, + actions: buttons ? convertButtonsToNotificationActionType(buttons) : [], + }; + registration.showNotification(title, options); + } + ); + } + static async checkAndTriggerNotificationPermissionChanged() { const previousPermission = await Database.get( 'Options', From 1d1b92c680cdae6ef5ab89916145fe855705cc3b Mon Sep 17 00:00:00 2001 From: Rodrigo Gomez Palacio Date: Tue, 23 Jul 2024 14:48:53 -0500 Subject: [PATCH 3/7] Update `EventHelper` to use `MainHelper` local notification --- src/shared/helpers/EventHelper.ts | 13 +++++-------- 1 file changed, 5 insertions(+), 8 deletions(-) diff --git a/src/shared/helpers/EventHelper.ts b/src/shared/helpers/EventHelper.ts index 1d6c8e39c..b266b20ef 100755 --- a/src/shared/helpers/EventHelper.ts +++ b/src/shared/helpers/EventHelper.ts @@ -146,7 +146,6 @@ export default class EventHelper { return; } - const { appId } = await Database.getAppConfig(); let title = welcome_notification_opts !== undefined && welcome_notification_opts['title'] !== undefined && @@ -172,15 +171,13 @@ export default class EventHelper { message = BrowserUtils.decodeHtmlEntities(message); Log.debug('Sending welcome notification.'); - OneSignalApiShared.sendNotification( - appId, - [pushSubscriptionId], - { en: title }, - { en: message }, + MainHelper.showLocalNotification( + title, + message, url, - null, - { __isOneSignalWelcomeNotification: true }, undefined, + { __isOneSignalWelcomeNotification: true }, + undefined ); OneSignalEvent.trigger(OneSignal.EVENTS.WELCOME_NOTIFICATION_SENT, { title: title, From 5743957bae56340c78564850490ac70e3def673b Mon Sep 17 00:00:00 2001 From: Rodrigo Gomez Palacio Date: Tue, 23 Jul 2024 14:56:45 -0500 Subject: [PATCH 4/7] Add welcome notification config to index.html --- express_webpack/index.html | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/express_webpack/index.html b/express_webpack/index.html index 25f077142..8bd717122 100644 --- a/express_webpack/index.html +++ b/express_webpack/index.html @@ -33,6 +33,12 @@ OneSignalDeferred.push(async function(onesignal) { await onesignal.init({ appId, + welcomeNotification: { + disable: false, + title: "Custom Welcome Notification Title", + message: "Custom Welcome Notification Message", + url: "https://example.com", + }, serviceWorkerParam: { scope: '/' + SERVICE_WORKER_PATH }, serviceWorkerPath: SERVICE_WORKER_PATH + 'OneSignalSDKWorker.js', notifyButton: { From 2f52a2d44fd22346385b24af85601b6747d3450e Mon Sep 17 00:00:00 2001 From: Rodrigo Gomez Palacio Date: Wed, 24 Jul 2024 18:02:56 -0500 Subject: [PATCH 5/7] Lint fixes --- src/shared/helpers/EventHelper.ts | 2 +- src/shared/helpers/MainHelper.ts | 47 ++++++++++++++++++--------- src/shared/services/Database.ts | 2 +- src/shared/services/IndexedDb.ts | 21 +++++++----- src/shared/services/OneSignalEvent.ts | 2 +- src/sw/serviceWorker/ServiceWorker.ts | 4 +-- 6 files changed, 49 insertions(+), 29 deletions(-) diff --git a/src/shared/helpers/EventHelper.ts b/src/shared/helpers/EventHelper.ts index b266b20ef..f5dded02a 100755 --- a/src/shared/helpers/EventHelper.ts +++ b/src/shared/helpers/EventHelper.ts @@ -177,7 +177,7 @@ export default class EventHelper { url, undefined, { __isOneSignalWelcomeNotification: true }, - undefined + undefined, ); OneSignalEvent.trigger(OneSignal.EVENTS.WELCOME_NOTIFICATION_SENT, { title: title, diff --git a/src/shared/helpers/MainHelper.ts b/src/shared/helpers/MainHelper.ts index 456707754..46b028590 100755 --- a/src/shared/helpers/MainHelper.ts +++ b/src/shared/helpers/MainHelper.ts @@ -13,7 +13,10 @@ import Database from '../services/Database'; import { PermissionUtils } from '../utils/PermissionUtils'; import Environment from './Environment'; import { getPlatformNotificationIcon, logMethodCall } from '../utils/utils'; -import { NotSubscribedError, NotSubscribedReason } from '../errors/NotSubscribedError'; +import { + NotSubscribedError, + NotSubscribedReason, +} from '../errors/NotSubscribedError'; import { InvalidArgumentError, InvalidArgumentReason } from '../errors/InvalidArgumentError'; import { ValidatorUtils } from '../../page/utils/ValidatorUtils'; @@ -24,19 +27,29 @@ export default class MainHelper { url: string, icon?: string, data?: Record, - buttons?: Array + buttons?: Array, ): Promise { - logMethodCall('MainHelper:showLocalNotification: ', title, message, url, icon, data, buttons); + logMethodCall( + 'MainHelper:showLocalNotification: ', + title, + message, + url, + icon, + data, + buttons, + ); const appConfig = await Database.getAppConfig(); if (!appConfig.appId) throw new InvalidStateError(InvalidStateReason.MissingAppId); - if (!(OneSignal.Notifications.permission)) + if (!OneSignal.Notifications.permission) throw new NotSubscribedError(NotSubscribedReason.NoDeviceId); if (!ValidatorUtils.isValidUrl(url)) throw new InvalidArgumentError('url', InvalidArgumentReason.Malformed); - if (!ValidatorUtils.isValidUrl(icon, { allowEmpty: true, requireHttps: true })) + if ( + !ValidatorUtils.isValidUrl(icon, { allowEmpty: true, requireHttps: true }) + ) throw new InvalidArgumentError('icon', InvalidArgumentReason.Malformed); if (!icon) { // get default icon @@ -47,26 +60,29 @@ export default class MainHelper { const convertButtonsToNotificationActionType = (buttons: Array) => { const convertedButtons = []; - for (let i=0; i { + OneSignal.context.serviceWorkerManager + .getRegistration() + .then(async (registration?: ServiceWorkerRegistration | null) => { if (!registration) { Log.error('Service worker registration not available.'); return; @@ -76,11 +92,12 @@ export default class MainHelper { body: message, data: dataPayload, icon: icon, - actions: buttons ? convertButtonsToNotificationActionType(buttons) : [], + actions: buttons + ? convertButtonsToNotificationActionType(buttons) + : [], }; registration.showNotification(title, options); - } - ); + }); } static async checkAndTriggerNotificationPermissionChanged() { diff --git a/src/shared/services/Database.ts b/src/shared/services/Database.ts index 3338a7567..6b77cd10b 100644 --- a/src/shared/services/Database.ts +++ b/src/shared/services/Database.ts @@ -129,7 +129,7 @@ export default class Database { * @param keypath */ async put(table: OneSignalDbTable, keypath: any): Promise { - await new Promise((resolve, reject) => { + await new Promise((resolve) => { this.database.put(table, keypath).then(() => resolve()); }); this.emitter.emit(Database.EVENTS.SET, keypath); diff --git a/src/shared/services/IndexedDb.ts b/src/shared/services/IndexedDb.ts index ecfff0df8..8f2ed925f 100644 --- a/src/shared/services/IndexedDb.ts +++ b/src/shared/services/IndexedDb.ts @@ -109,7 +109,7 @@ export default class IndexedDb { * * Ref: https://developer.mozilla.org/en-US/docs/Web/API/IDBDatabase/onversionchange */ - private onDatabaseVersionChange(_: IDBVersionChangeEvent): void { + private onDatabaseVersionChange(): void { Log.debug('IndexedDb: versionchange event'); } @@ -330,16 +330,19 @@ export default class IndexedDb { await this.ensureDatabaseOpen(); return await new Promise((resolve, reject) => { try { - const request = this.database!.transaction([table], 'readwrite') + const request = this.database?.transaction([table], 'readwrite') .objectStore(table) .put(key); - request.onsuccess = () => { - resolve(key); - }; - request.onerror = (e) => { - Log.error('Database PUT Transaction Error:', e); - reject(e); - }; + + if (request) { + request.onsuccess = () => { + resolve(key); + }; + request.onerror = (e) => { + Log.error('Database PUT Transaction Error:', e); + reject(e); + }; + } } catch (e) { Log.error('Database PUT Error:', e); reject(e); diff --git a/src/shared/services/OneSignalEvent.ts b/src/shared/services/OneSignalEvent.ts index ae2a82215..ccb51ab51 100755 --- a/src/shared/services/OneSignalEvent.ts +++ b/src/shared/services/OneSignalEvent.ts @@ -29,7 +29,7 @@ export default class OneSignalEvent { static async trigger(eventName: string, data?: any, emitter?: Emitter) { if (!Utils.contains(SILENT_EVENTS, eventName)) { const displayData = data; - let env = Utils.capitalize(SdkEnvironment.getWindowEnv().toString()); + const env = Utils.capitalize(SdkEnvironment.getWindowEnv().toString()); if (displayData || displayData === false) { Log.debug(`(${env}) ยป ${eventName}:`, displayData); diff --git a/src/sw/serviceWorker/ServiceWorker.ts b/src/sw/serviceWorker/ServiceWorker.ts index 3d0990f26..622994a7c 100755 --- a/src/sw/serviceWorker/ServiceWorker.ts +++ b/src/sw/serviceWorker/ServiceWorker.ts @@ -193,7 +193,7 @@ export class ServiceWorker { static setupMessageListeners() { ServiceWorker.workerMessenger.on( WorkerMessengerCommand.WorkerVersion, - (_) => { + () => { Log.debug('[Service Worker] Received worker version message.'); ServiceWorker.workerMessenger.broadcast( WorkerMessengerCommand.WorkerVersion, @@ -241,7 +241,7 @@ export class ServiceWorker { ); ServiceWorker.workerMessenger.on( WorkerMessengerCommand.AmpSubscriptionState, - async (_appConfigBundle: any) => { + async () => { Log.debug('[Service Worker] Received AMP subscription state message.'); const pushSubscription = await self.registration.pushManager.getSubscription(); From 10ab2d80c5ffbaaf35595f2b63de1b2df59d2828 Mon Sep 17 00:00:00 2001 From: Rodrigo Gomez Palacio Date: Fri, 26 Jul 2024 13:07:03 -0500 Subject: [PATCH 6/7] Fix lint warnings --- src/shared/helpers/MainHelper.ts | 5 ++++- src/shared/services/IndexedDb.ts | 3 ++- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/src/shared/helpers/MainHelper.ts b/src/shared/helpers/MainHelper.ts index 46b028590..44ed23523 100755 --- a/src/shared/helpers/MainHelper.ts +++ b/src/shared/helpers/MainHelper.ts @@ -17,7 +17,10 @@ import { NotSubscribedError, NotSubscribedReason, } from '../errors/NotSubscribedError'; -import { InvalidArgumentError, InvalidArgumentReason } from '../errors/InvalidArgumentError'; +import { + InvalidArgumentError, + InvalidArgumentReason, +} from '../errors/InvalidArgumentError'; import { ValidatorUtils } from '../../page/utils/ValidatorUtils'; export default class MainHelper { diff --git a/src/shared/services/IndexedDb.ts b/src/shared/services/IndexedDb.ts index 8f2ed925f..1c5398e79 100644 --- a/src/shared/services/IndexedDb.ts +++ b/src/shared/services/IndexedDb.ts @@ -330,7 +330,8 @@ export default class IndexedDb { await this.ensureDatabaseOpen(); return await new Promise((resolve, reject) => { try { - const request = this.database?.transaction([table], 'readwrite') + const request = this.database + ?.transaction([table], 'readwrite') .objectStore(table) .put(key); From 43d06169596ee267fdc1c6e5b763495ad14a88ef Mon Sep 17 00:00:00 2001 From: Rodrigo Gomez Palacio Date: Tue, 23 Jul 2024 14:58:03 -0500 Subject: [PATCH 7/7] 160202 Release Commit Update SDK version --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index 11bfc688b..471774c42 100644 --- a/package.json +++ b/package.json @@ -42,7 +42,7 @@ "jest": "jest --coverage" }, "config": { - "sdkVersion": "160201" + "sdkVersion": "160202" }, "repository": { "type": "git",