Skip to content

Commit

Permalink
Merge pull request #1186 from OneSignal/api/notification-create-removal
Browse files Browse the repository at this point in the history
Api/notification create removal
  • Loading branch information
rgomezp authored Jul 26, 2024
2 parents ff52c3c + 43d0616 commit d2302b6
Show file tree
Hide file tree
Showing 10 changed files with 117 additions and 77 deletions.
6 changes: 6 additions & 0 deletions express_webpack/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -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: {
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@
"jest": "jest --coverage"
},
"config": {
"sdkVersion": "160201"
"sdkVersion": "160202"
},
"repository": {
"type": "git",
Expand Down
23 changes: 0 additions & 23 deletions src/shared/api/OneSignalApi.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<string>,
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,
Expand Down
33 changes: 0 additions & 33 deletions src/shared/api/OneSignalApiShared.ts
Original file line number Diff line number Diff line change
@@ -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<string>,
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<void> {
Log.info('Outcome payload:', data);
try {
Expand Down
11 changes: 4 additions & 7 deletions src/shared/helpers/EventHelper.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 &&
Expand All @@ -172,13 +171,11 @@ 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,
undefined,
{ __isOneSignalWelcomeNotification: true },
undefined,
);
Expand Down
89 changes: 89 additions & 0 deletions src/shared/helpers/MainHelper.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,97 @@ 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<string, any>,
buttons?: Array<any>,
): Promise<void> {
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<any>) => {
const convertedButtons = [];

for (let i = 0; i < buttons.length; i++) {
const button = buttons[i];
convertedButtons.push({
action: button.id,
title: button.text,
icon: button.icon,
url: button.url,
});
}

return convertedButtons;
};
const dataPayload = {
data,
url,
buttons: buttons
? convertButtonsToNotificationActionType(buttons)
: undefined,
};

OneSignal.context.serviceWorkerManager
.getRegistration()
.then(async (registration?: ServiceWorkerRegistration | null) => {
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',
Expand Down
2 changes: 1 addition & 1 deletion src/shared/services/Database.ts
Original file line number Diff line number Diff line change
Expand Up @@ -129,7 +129,7 @@ export default class Database {
* @param keypath
*/
async put(table: OneSignalDbTable, keypath: any): Promise<void> {
await new Promise<void>((resolve, reject) => {
await new Promise<void>((resolve) => {
this.database.put(table, keypath).then(() => resolve());
});
this.emitter.emit(Database.EVENTS.SET, keypath);
Expand Down
22 changes: 13 additions & 9 deletions src/shared/services/IndexedDb.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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');
}

Expand Down Expand Up @@ -330,16 +330,20 @@ 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);
Expand Down
2 changes: 1 addition & 1 deletion src/shared/services/OneSignalEvent.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
4 changes: 2 additions & 2 deletions src/sw/serviceWorker/ServiceWorker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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();
Expand Down

0 comments on commit d2302b6

Please sign in to comment.