Skip to content

Commit d2302b6

Browse files
author
Rodrigo Gomez Palacio
authored
Merge pull request #1186 from OneSignal/api/notification-create-removal
Api/notification create removal
2 parents ff52c3c + 43d0616 commit d2302b6

File tree

10 files changed

+117
-77
lines changed

10 files changed

+117
-77
lines changed

express_webpack/index.html

+6
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,12 @@
3333
OneSignalDeferred.push(async function(onesignal) {
3434
await onesignal.init({
3535
appId,
36+
welcomeNotification: {
37+
disable: false,
38+
title: "Custom Welcome Notification Title",
39+
message: "Custom Welcome Notification Message",
40+
url: "https://example.com",
41+
},
3642
serviceWorkerParam: { scope: '/' + SERVICE_WORKER_PATH },
3743
serviceWorkerPath: SERVICE_WORKER_PATH + 'OneSignalSDKWorker.js',
3844
notifyButton: {

package.json

+1-1
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,7 @@
4242
"jest": "jest --coverage"
4343
},
4444
"config": {
45-
"sdkVersion": "160201"
45+
"sdkVersion": "160202"
4646
},
4747
"repository": {
4848
"type": "git",

src/shared/api/OneSignalApi.ts

-23
Original file line numberDiff line numberDiff line change
@@ -2,32 +2,9 @@ import JSONP from 'jsonp';
22
import SdkEnvironment from '../managers/SdkEnvironment';
33
import { WindowEnvironmentKind } from '../models/WindowEnvironmentKind';
44
import OneSignalApiSW from './OneSignalApiSW';
5-
import OneSignalApiShared from './OneSignalApiShared';
65
import { ServerAppConfig } from '../models/AppConfig';
76

87
export default class OneSignalApi {
9-
static sendNotification(
10-
appId: string,
11-
playerIds: Array<string>,
12-
titles,
13-
contents,
14-
url,
15-
icon,
16-
data,
17-
buttons,
18-
) {
19-
return OneSignalApiShared.sendNotification(
20-
appId,
21-
playerIds,
22-
titles,
23-
contents,
24-
url,
25-
icon,
26-
data,
27-
buttons,
28-
);
29-
}
30-
318
static jsonpLib(
329
url: string,
3310
fn: (err: Error, data: ServerAppConfig) => void,

src/shared/api/OneSignalApiShared.ts

-33
Original file line numberDiff line numberDiff line change
@@ -1,41 +1,8 @@
11
import { OutcomeRequestData } from '../../page/models/OutcomeRequestData';
2-
import Utils from '../context/Utils';
32
import Log from '../libraries/Log';
43
import OneSignalApiBase from './OneSignalApiBase';
54

65
export default class OneSignalApiShared {
7-
static sendNotification(
8-
appId: string,
9-
playerIds: Array<string>,
10-
titles,
11-
contents,
12-
url,
13-
icon,
14-
data,
15-
buttons,
16-
) {
17-
const params = {
18-
app_id: appId,
19-
contents: contents,
20-
include_player_ids: playerIds,
21-
isAnyWeb: true,
22-
data: data,
23-
web_buttons: buttons,
24-
};
25-
if (titles) {
26-
(params as any).headings = titles;
27-
}
28-
if (url) {
29-
(params as any).url = url;
30-
}
31-
if (icon) {
32-
(params as any).chrome_web_icon = icon;
33-
(params as any).firefox_icon = icon;
34-
}
35-
Utils.trimUndefined(params);
36-
return OneSignalApiBase.post('notifications', params);
37-
}
38-
396
static async sendOutcome(data: OutcomeRequestData): Promise<void> {
407
Log.info('Outcome payload:', data);
418
try {

src/shared/helpers/EventHelper.ts

+4-7
Original file line numberDiff line numberDiff line change
@@ -146,7 +146,6 @@ export default class EventHelper {
146146
return;
147147
}
148148

149-
const { appId } = await Database.getAppConfig();
150149
let title =
151150
welcome_notification_opts !== undefined &&
152151
welcome_notification_opts['title'] !== undefined &&
@@ -172,13 +171,11 @@ export default class EventHelper {
172171
message = BrowserUtils.decodeHtmlEntities(message);
173172

174173
Log.debug('Sending welcome notification.');
175-
OneSignalApiShared.sendNotification(
176-
appId,
177-
[pushSubscriptionId],
178-
{ en: title },
179-
{ en: message },
174+
MainHelper.showLocalNotification(
175+
title,
176+
message,
180177
url,
181-
null,
178+
undefined,
182179
{ __isOneSignalWelcomeNotification: true },
183180
undefined,
184181
);

src/shared/helpers/MainHelper.ts

+89
Original file line numberDiff line numberDiff line change
@@ -12,8 +12,97 @@ import Utils from '../context/Utils';
1212
import Database from '../services/Database';
1313
import { PermissionUtils } from '../utils/PermissionUtils';
1414
import Environment from './Environment';
15+
import { getPlatformNotificationIcon, logMethodCall } from '../utils/utils';
16+
import {
17+
NotSubscribedError,
18+
NotSubscribedReason,
19+
} from '../errors/NotSubscribedError';
20+
import {
21+
InvalidArgumentError,
22+
InvalidArgumentReason,
23+
} from '../errors/InvalidArgumentError';
24+
import { ValidatorUtils } from '../../page/utils/ValidatorUtils';
1525

1626
export default class MainHelper {
27+
static async showLocalNotification(
28+
title: string,
29+
message: string,
30+
url: string,
31+
icon?: string,
32+
data?: Record<string, any>,
33+
buttons?: Array<any>,
34+
): Promise<void> {
35+
logMethodCall(
36+
'MainHelper:showLocalNotification: ',
37+
title,
38+
message,
39+
url,
40+
icon,
41+
data,
42+
buttons,
43+
);
44+
45+
const appConfig = await Database.getAppConfig();
46+
47+
if (!appConfig.appId)
48+
throw new InvalidStateError(InvalidStateReason.MissingAppId);
49+
if (!OneSignal.Notifications.permission)
50+
throw new NotSubscribedError(NotSubscribedReason.NoDeviceId);
51+
if (!ValidatorUtils.isValidUrl(url))
52+
throw new InvalidArgumentError('url', InvalidArgumentReason.Malformed);
53+
if (
54+
!ValidatorUtils.isValidUrl(icon, { allowEmpty: true, requireHttps: true })
55+
)
56+
throw new InvalidArgumentError('icon', InvalidArgumentReason.Malformed);
57+
if (!icon) {
58+
// get default icon
59+
const icons = await MainHelper.getNotificationIcons();
60+
icon = getPlatformNotificationIcon(icons);
61+
}
62+
63+
const convertButtonsToNotificationActionType = (buttons: Array<any>) => {
64+
const convertedButtons = [];
65+
66+
for (let i = 0; i < buttons.length; i++) {
67+
const button = buttons[i];
68+
convertedButtons.push({
69+
action: button.id,
70+
title: button.text,
71+
icon: button.icon,
72+
url: button.url,
73+
});
74+
}
75+
76+
return convertedButtons;
77+
};
78+
const dataPayload = {
79+
data,
80+
url,
81+
buttons: buttons
82+
? convertButtonsToNotificationActionType(buttons)
83+
: undefined,
84+
};
85+
86+
OneSignal.context.serviceWorkerManager
87+
.getRegistration()
88+
.then(async (registration?: ServiceWorkerRegistration | null) => {
89+
if (!registration) {
90+
Log.error('Service worker registration not available.');
91+
return;
92+
}
93+
94+
const options = {
95+
body: message,
96+
data: dataPayload,
97+
icon: icon,
98+
actions: buttons
99+
? convertButtonsToNotificationActionType(buttons)
100+
: [],
101+
};
102+
registration.showNotification(title, options);
103+
});
104+
}
105+
17106
static async checkAndTriggerNotificationPermissionChanged() {
18107
const previousPermission = await Database.get(
19108
'Options',

src/shared/services/Database.ts

+1-1
Original file line numberDiff line numberDiff line change
@@ -129,7 +129,7 @@ export default class Database {
129129
* @param keypath
130130
*/
131131
async put(table: OneSignalDbTable, keypath: any): Promise<void> {
132-
await new Promise<void>((resolve, reject) => {
132+
await new Promise<void>((resolve) => {
133133
this.database.put(table, keypath).then(() => resolve());
134134
});
135135
this.emitter.emit(Database.EVENTS.SET, keypath);

src/shared/services/IndexedDb.ts

+13-9
Original file line numberDiff line numberDiff line change
@@ -109,7 +109,7 @@ export default class IndexedDb {
109109
*
110110
* Ref: https://developer.mozilla.org/en-US/docs/Web/API/IDBDatabase/onversionchange
111111
*/
112-
private onDatabaseVersionChange(_: IDBVersionChangeEvent): void {
112+
private onDatabaseVersionChange(): void {
113113
Log.debug('IndexedDb: versionchange event');
114114
}
115115

@@ -330,16 +330,20 @@ export default class IndexedDb {
330330
await this.ensureDatabaseOpen();
331331
return await new Promise((resolve, reject) => {
332332
try {
333-
const request = this.database!.transaction([table], 'readwrite')
333+
const request = this.database
334+
?.transaction([table], 'readwrite')
334335
.objectStore(table)
335336
.put(key);
336-
request.onsuccess = () => {
337-
resolve(key);
338-
};
339-
request.onerror = (e) => {
340-
Log.error('Database PUT Transaction Error:', e);
341-
reject(e);
342-
};
337+
338+
if (request) {
339+
request.onsuccess = () => {
340+
resolve(key);
341+
};
342+
request.onerror = (e) => {
343+
Log.error('Database PUT Transaction Error:', e);
344+
reject(e);
345+
};
346+
}
343347
} catch (e) {
344348
Log.error('Database PUT Error:', e);
345349
reject(e);

src/shared/services/OneSignalEvent.ts

+1-1
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,7 @@ export default class OneSignalEvent {
2929
static async trigger(eventName: string, data?: any, emitter?: Emitter) {
3030
if (!Utils.contains(SILENT_EVENTS, eventName)) {
3131
const displayData = data;
32-
let env = Utils.capitalize(SdkEnvironment.getWindowEnv().toString());
32+
const env = Utils.capitalize(SdkEnvironment.getWindowEnv().toString());
3333

3434
if (displayData || displayData === false) {
3535
Log.debug(`(${env}) » ${eventName}:`, displayData);

src/sw/serviceWorker/ServiceWorker.ts

+2-2
Original file line numberDiff line numberDiff line change
@@ -193,7 +193,7 @@ export class ServiceWorker {
193193
static setupMessageListeners() {
194194
ServiceWorker.workerMessenger.on(
195195
WorkerMessengerCommand.WorkerVersion,
196-
(_) => {
196+
() => {
197197
Log.debug('[Service Worker] Received worker version message.');
198198
ServiceWorker.workerMessenger.broadcast(
199199
WorkerMessengerCommand.WorkerVersion,
@@ -241,7 +241,7 @@ export class ServiceWorker {
241241
);
242242
ServiceWorker.workerMessenger.on(
243243
WorkerMessengerCommand.AmpSubscriptionState,
244-
async (_appConfigBundle: any) => {
244+
async () => {
245245
Log.debug('[Service Worker] Received AMP subscription state message.');
246246
const pushSubscription =
247247
await self.registration.pushManager.getSubscription();

0 commit comments

Comments
 (0)