Skip to content

Commit

Permalink
Merge pull request #1183 from OneSignal/send-self-local-2
Browse files Browse the repository at this point in the history
Change the sendSelfNotification method to use local push functionality
  • Loading branch information
rgomezp authored Jul 15, 2024
2 parents 30bf21e + 49f8f7f commit 24b3ece
Show file tree
Hide file tree
Showing 6 changed files with 65 additions and 47 deletions.
12 changes: 12 additions & 0 deletions express_webpack/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -154,6 +154,17 @@
})
}

function sendSelfNotification() {
OneSignal.push(function() {
OneSignal.sendSelfNotification('Title', 'message', `https://localhost:4001/?app_id=${appId}`, 'https://t3.ftcdn.net/jpg/03/08/73/34/360_F_308733458_QBzwMVu8ZzdGEp9Wwq1fAYaDgtP3UVwl.jpg', { test: 'foo' }, [{
id: 'like-button',
text: 'Like',
icon: 'https://image.similarpng.com/very-thumbnail/2020/06/Icon-like-button-transparent-PNG.png',
url: 'https://onesignal.com'
}]);
});
}

</script>
<head>
<meta charset="utf-8">
Expand Down Expand Up @@ -189,6 +200,7 @@ <h1>OneSignal WebSDK Sandbox</h1>
<button onclick="javascript:showSmsSlidedown();">Show Sms Slidedown</button>
<button onclick="javascript:showEmailSlidedown();">Show Email Slidedown</button>
<button onclick="javascript:showSmsAndEmailSlidedown();">Show Sms & Email Slidedown</button>
<button onclick="javascript:sendSelfNotification();">Send Self Notification</button>
<br />
<br />
<div class='onesignal-customlink-container'></div>
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@
"jest": "jest --coverage"
},
"config": {
"sdkVersion": "151605"
"sdkVersion": "151606"
},
"repository": {
"type": "git",
Expand Down
58 changes: 48 additions & 10 deletions src/OneSignal.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ import {
awaitOneSignalInitAndSupported,
executeCallback,
getConsoleStyle,
getPlatformNotificationIcon,
isValidEmail,
logMethodCall,
} from './utils';
Expand Down Expand Up @@ -713,16 +714,16 @@ export default class OneSignal {
/**
* @PublicApi
*/
static async sendSelfNotification(title: string = 'OneSignal Test Message',
message: string = 'This is an example notification.',
url: string = `${new URL(location.href).origin}?_osp=do_not_open`,
icon: URL,
data: Map<String, any>,
buttons: Array<NotificationActionButton>): Promise<void> {
static async sendSelfNotification(title = 'OneSignal Test Message',
message = 'This is an example notification.',
url = `${new URL(location.href).origin}?_osp=do_not_open`,
icon?: string,
data?: Record<string, any>,
buttons?: Array<any>): Promise<void> {
await awaitOneSignalInitAndSupported();
logMethodCall('sendSelfNotification', title, message, url, icon, data, buttons);
const appConfig = await Database.getAppConfig();
const subscription = await Database.getSubscription();

if (!appConfig.appId)
throw new InvalidStateError(InvalidStateReason.MissingAppId);
if (!(await OneSignal.isPushNotificationsEnabled()))
Expand All @@ -731,11 +732,48 @@ export default class OneSignal {
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 = [];

if (subscription.deviceId) {
await OneSignalApi.sendNotification(appConfig.appId, [subscription.deviceId], { en : title }, { en : message },
url, icon, data, buttons);
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
}

this.context.serviceWorkerManager.getRegistration().then(async (registration) => {
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);
});
}

/**
Expand Down
4 changes: 0 additions & 4 deletions src/OneSignalApi.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,10 +17,6 @@ export default class OneSignalApi {
return OneSignalApiShared.updatePlayer(appId, playerId, options);
}

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: Function) {
JSONP(url, null, fn);
}
Expand Down
23 changes: 0 additions & 23 deletions src/OneSignalApiShared.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,29 +21,6 @@ export default class OneSignalApiShared {
return OneSignalApiBase.put(`players/${playerId}`, { app_id: appId, ...options });
}

static sendNotification(appId: string, playerIds: Array<string>, titles, contents, url, icon, data, buttons) {
var 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 createUser(deviceRecord: DeviceRecord): Promise<string | null> {
const serializedDeviceRecord = deviceRecord.serialize();
Utils.enforceAppId(serializedDeviceRecord.app_id);
Expand Down
13 changes: 4 additions & 9 deletions src/helpers/EventHelper.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import Event from '../Event';
import LimitStore from '../LimitStore';
import OneSignalApiShared from '../OneSignalApiShared';
import Database from '../services/Database';
import { ContextSWInterface } from "../models/ContextSW";
import Log from '../libraries/Log';
Expand Down Expand Up @@ -84,8 +83,6 @@ export default class EventHelper {
}
EventHelper.sendingOrSentWelcomeNotification = true;

const { deviceId } = await Database.getSubscription();
const { appId } = await Database.getAppConfig();
let title =
welcome_notification_opts !== undefined &&
welcome_notification_opts['title'] !== undefined &&
Expand All @@ -108,13 +105,11 @@ export default class EventHelper {
message = BrowserUtils.decodeHtmlEntities(message);

Log.debug('Sending welcome notification.');
OneSignalApiShared.sendNotification(
appId,
[deviceId],
{ en: title },
{ en: message },
OneSignal.sendSelfNotification(
title,
message,
url,
null,
undefined,
{ __isOneSignalWelcomeNotification: true },
undefined
);
Expand Down

0 comments on commit 24b3ece

Please sign in to comment.