From 5e056b9af37741dc4c7f3f79a4b48667f9a1d364 Mon Sep 17 00:00:00 2001 From: Federico Terzi Date: Mon, 27 Nov 2023 19:57:29 +0000 Subject: [PATCH] use new URL in `subscribeSafariPromptPermission` Due to changes in our API, the `appId` is now required in the URL used by `subscribeSafariPromptPermission`. In instances where the new URL is not usable, we fallback to the legacy URL with an additional request. This ensures compatibility with both the updated and legacy API endpoints. --- src/managers/SubscriptionManager.ts | 45 +++++++++++++++++++---------- 1 file changed, 30 insertions(+), 15 deletions(-) diff --git a/src/managers/SubscriptionManager.ts b/src/managers/SubscriptionManager.ts index 6ebe25ed3..bb6421f37 100644 --- a/src/managers/SubscriptionManager.ts +++ b/src/managers/SubscriptionManager.ts @@ -51,6 +51,7 @@ export type SubscriptionStateServiceWorkerNotIntalled = export class SubscriptionManager { private context: ContextSWInterface; private config: SubscriptionManagerConfig; + private safariPermissionPromptFailed = false; constructor(context: ContextSWInterface, config: SubscriptionManagerConfig) { this.context = context; @@ -258,23 +259,36 @@ export class SubscriptionManager { return !!deviceId; } - private subscribeSafariPromptPermission(): Promise { - return new Promise(resolve => { - window.safari.pushNotification.requestPermission( + private async subscribeSafariPromptPermission(): Promise { + const requestPermission = (url: string) => { + return new Promise((resolve) => { + window.safari.pushNotification.requestPermission( + url, + this.config.safariWebId, + { app_id: this.config.appId }, + (response) => { + if (response && response.deviceToken) { + resolve(response.deviceToken.toLowerCase()); + } else { + resolve(null); + } + }, + ); + }); + }; + + if (!this.safariPermissionPromptFailed) { + return requestPermission( + `${SdkEnvironment.getOneSignalApiUrl().toString()}/safari/apps/${ + this.config.appId + }`, + ); + } else { + // If last attempt failed, retry with the legacy URL + return requestPermission( `${SdkEnvironment.getOneSignalApiUrl().toString()}/safari`, - this.config.safariWebId, - { - app_id: this.config.appId - }, - response => { - if ((response as any).deviceToken) { - resolve((response as any).deviceToken.toLowerCase()); - } else { - resolve(null); - } - } ); - }); + } } private async subscribeSafari(): Promise { @@ -308,6 +322,7 @@ export class SubscriptionManager { if (deviceToken) { pushSubscriptionDetails.setFromSafariSubscription(deviceToken); } else { + this.safariPermissionPromptFailed = true; throw new SubscriptionError(SubscriptionErrorReason.InvalidSafariSetup); } return pushSubscriptionDetails;