Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Change the sendSelfNotification method to use local push functionality #1183

Merged
merged 3 commits into from
Jul 15, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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 @@ -17,7 +17,7 @@
import { AppConfig, AppUserConfig } from './models/AppConfig';
import Context from './models/Context';
import { Notification } from "./models/Notification";
import { NotificationActionButton } from './models/NotificationActionButton';

Check warning on line 20 in src/OneSignal.ts

View workflow job for this annotation

GitHub Actions / test (14.x)

'NotificationActionButton' is defined but never used
import { NotificationPermission } from './models/NotificationPermission';
import { WindowEnvironmentKind } from './models/WindowEnvironmentKind';
import { UpdatePlayerOptions } from './models/UpdatePlayerOptions';
Expand All @@ -36,6 +36,7 @@
awaitOneSignalInitAndSupported,
executeCallback,
getConsoleStyle,
getPlatformNotificationIcon,
isValidEmail,
logMethodCall,
} from './utils';
Expand Down Expand Up @@ -294,7 +295,7 @@
* Prompts the user to subscribe using the remote local notification workaround for HTTP sites.
* @PublicApi
*/
public static async showHttpPermissionRequest(options?: AutoPromptOptions): Promise<any> {

Check warning on line 298 in src/OneSignal.ts

View workflow job for this annotation

GitHub Actions / test (14.x)

Unexpected any. Specify a different type
Log.debug('Called showHttpPermissionRequest(), redirecting to HTTP prompt.');

OneSignal.showHttpPrompt(options).catch(e => Log.info(e));
Expand Down Expand Up @@ -362,7 +363,7 @@
*/
static async registerForPushNotifications(options?: RegisterOptions): Promise<void> {
if (!OneSignal.initialized) {
await new Promise<void>((resolve, _reject) => {

Check warning on line 366 in src/OneSignal.ts

View workflow job for this annotation

GitHub Actions / test (14.x)

'_reject' is defined but never used
OneSignal.emitter.once(OneSignal.EVENTS.SDK_INITIALIZED, async () => {
await InitHelper.registerForPushNotifications(options);
return resolve();
Expand Down Expand Up @@ -713,16 +714,16 @@
/**
* @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 @@
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);
jkasten2 marked this conversation as resolved.
Show resolved Hide resolved
}

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
Loading