Skip to content

Commit

Permalink
Fix: Initializing in readonly if the user has not subscribed to notif…
Browse files Browse the repository at this point in the history
…ications & on Logout remove the listeners (#2528)
  • Loading branch information
AndiAkasha authored Jan 23, 2025
1 parent 5ab3cf5 commit 1963f1a
Show file tree
Hide file tree
Showing 4 changed files with 62 additions and 42 deletions.
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import React from 'react';
import { useRootComponentProps, withProviders } from '@akashaorg/ui-core-hooks';
import { useNotifications, useRootComponentProps, withProviders } from '@akashaorg/ui-core-hooks';
import { BellAlert } from '@akashaorg/design-system-core/lib/components/Icon/akasha-icons';

import { NotificationEvents, type UIEventData } from '@akashaorg/typings/lib/ui';
Expand All @@ -19,6 +19,7 @@ const RoundedNotificationButton = () => {
const uiEventsRef = React.useRef(uiEvents);
const [snoozeNotifications, setSnoozeNotifications] = React.useState(false);
const [hasNewNotifications, setHasNewNotifications] = React.useState(false);
const { previouslyEnabled } = useNotifications();
// check if snooze notification option has already been set
React.useEffect(() => {
if (window.localStorage) {
Expand Down Expand Up @@ -80,7 +81,9 @@ const RoundedNotificationButton = () => {
await sdk.services.common.notification.listenToNotificationEvents();
};

init();
if (previouslyEnabled) {
init();
}

return () => {
if (subSDK) {
Expand Down
21 changes: 12 additions & 9 deletions libs/hooks/src/use-notifications.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,16 +22,19 @@ export function useNotifications() {
const [readOnlyMode, setReadOnlyMode] = useState(false);
const [waitingForSignature, setWaitingForSignature] = useState(false);

// Initialise notificaitons readOnly client (without signature)
// Initialise notifications readOnly client (without signature)
useEffect(() => {
sdk.services.common.notification
.initialize({ readonly: true })
.then(() => {
setReadOnlyMode(true);
})
.catch(error => {
console.error(error);
});
// if the user has already enabled notifications before
if (previouslyEnabled) {
sdk.services.common.notification
.initialize({ readonly: true })
.then(() => {
setReadOnlyMode(true);
})
.catch(error => {
console.error(error);
});
}
}, []);

const enableNotifications = async () => {
Expand Down
5 changes: 5 additions & 0 deletions libs/sdk/src/auth/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ import { DIDSession } from 'did-session';
import type { DagJWS } from 'dids';
import type { JWE } from 'did-jwt';
import { Eip1193Provider } from 'ethers';
import NotificationService from '../common/notification/notification';

// in memory atm
const devKeys: { pubKey: string; addedAt: string; name?: string }[] = [];
Expand All @@ -52,6 +53,7 @@ class AWF_Auth {
private _gql: Gql;
private _lit: Lit;
private _ceramic: CeramicService;
private _notificationService: NotificationService;
private sessKey;
private currentUser?: CurrentUser;
private _lockSignIn?: boolean;
Expand All @@ -71,6 +73,7 @@ class AWF_Auth {
@inject(TYPES.Gql) gql: Gql,
@inject(TYPES.Lit) lit: Lit,
@inject(TYPES.Ceramic) ceramic: CeramicService,
@inject(TYPES.Notification) notificationService: NotificationService,
) {
this._db = db;
this._web3 = web3;
Expand All @@ -80,6 +83,7 @@ class AWF_Auth {
this._gql = gql;
this._lit = lit;
this._ceramic = ceramic;
this._notificationService = notificationService;
}

/**
Expand Down Expand Up @@ -321,6 +325,7 @@ class AWF_Auth {
await this._ceramic.disconnect();
await this._gql.setContextViewerID('');
await this._web3.disconnect();
await this._notificationService.disconnect();
await this._lit.disconnect();
await this._gql.resetCache();
// notify appLoader on sign out
Expand Down
71 changes: 40 additions & 31 deletions libs/sdk/src/common/notification/notification.ts
Original file line number Diff line number Diff line change
Expand Up @@ -106,39 +106,41 @@ class NotificationService {
* @throws {Error} If `notificationsClient` is not initialized in read mode.
*/
async listenToNotificationEvents() {
// Initialize a notification stream using the notifications client.
this._notificationsStream = await this.notificationsClient.initStream(
[CONSTANTS.STREAM.NOTIF],
{
filter: {
channels: [this._notificationChannelId],
if (!this._notificationsStream) {
// Initialize a notification stream using the notifications client.
this._notificationsStream = await this.notificationsClient.initStream(
[CONSTANTS.STREAM.NOTIF],
{
filter: {
channels: [this._notificationChannelId],
},
},
},
);
// Listen for incoming notifications on the specified stream.
this._notificationsStream.on(CONSTANTS.STREAM.NOTIF, (data: any) => {
// Set new notifications badge
this._globalChannel.next({
data: {},
event: NOTIFICATION_EVENTS.NEW_NOTIFICATIONS,
});

if (Notification.permission == 'granted') {
// Extract notification data and create a browser Notification instance.
const notification = new Notification(data?.message?.notification.body, {
body: data?.message?.notification.body,
icon: data?.channel?.icon,
data: data?.message?.payload,
);
// Listen for incoming notifications on the specified stream.
this._notificationsStream.on(CONSTANTS.STREAM.NOTIF, (data: any) => {
// Set new notifications badge
this._globalChannel.next({
data: {},
event: NOTIFICATION_EVENTS.NEW_NOTIFICATIONS,
});
// Add a click event listener to the notification.
notification.onclick = (event: any) => {
event.preventDefault();
window.open(data?.message?.payload?.cta || data?.channel?.url, '_blank');
};
}
});

await this._notificationsStream.connect();
if (Notification.permission == 'granted') {
// Extract notification data and create a browser Notification instance.
const notification = new Notification(data?.message?.notification.body, {
body: data?.message?.notification.body,
icon: data?.channel?.icon,
data: data?.message?.payload,
});
// Add a click event listener to the notification.
notification.onclick = (event: any) => {
event.preventDefault();
window.open(data?.message?.payload?.cta || data?.channel?.url, '_blank');
};
}
});

await this._notificationsStream.connect();
}
}

/**
Expand All @@ -152,6 +154,13 @@ class NotificationService {
this._notificationsStream = undefined;
}
}
/**
* Disconnect to notifications events and set _pushClient to undefined
*/
async disconnect() {
await this.stopListeningToNotificationEvents();
this._pushClient = undefined;
}
/**
* Retrieves the settings of notification channel.
*
Expand Down Expand Up @@ -191,7 +200,7 @@ class NotificationService {
const channelSubscriptionInfo = subscriptions.find(
subscription => subscription.channel === this._notificationChannelId,
);
if (!channelSubscriptionInfo) return null;
if (!channelSubscriptionInfo) return [];

// Parse the response
const result = ChannelUserSettingsSchema.safeParse(channelSubscriptionInfo);
Expand Down

0 comments on commit 1963f1a

Please sign in to comment.