fixed notifications

This commit is contained in:
PhilReact 2024-11-01 00:19:24 +02:00
parent 58d7fb5e9e
commit 4b65471139

View File

@ -10,6 +10,8 @@ import {
uint8ArrayToObject, uint8ArrayToObject,
} from "./backgroundFunctions/encryption"; } from "./backgroundFunctions/encryption";
import { PUBLIC_NOTIFICATION_CODE_FIRST_SECRET_KEY } from "./constants/codes"; import { PUBLIC_NOTIFICATION_CODE_FIRST_SECRET_KEY } from "./constants/codes";
import ShortUniqueId from "short-unique-id";
import Base58 from "./deps/Base58"; import Base58 from "./deps/Base58";
import { import {
base64ToUint8Array, base64ToUint8Array,
@ -90,8 +92,11 @@ import {
import { getData, removeKeysAndLogout, storeData } from "./utils/chromeStorage"; import { getData, removeKeysAndLogout, storeData } from "./utils/chromeStorage";
import {BackgroundFetch} from '@transistorsoft/capacitor-background-fetch'; import {BackgroundFetch} from '@transistorsoft/capacitor-background-fetch';
import { LocalNotifications } from '@capacitor/local-notifications'; import { LocalNotifications } from '@capacitor/local-notifications';
const uid = new ShortUniqueId({ length: 9, dictionary: 'number' });
const generateId = ()=> {
return parseInt(uid.rnd())
}
LocalNotifications.requestPermissions().then(permission => { LocalNotifications.requestPermissions().then(permission => {
if (permission.display === 'granted') { if (permission.display === 'granted') {
console.log("Notifications enabled"); console.log("Notifications enabled");
@ -394,12 +399,7 @@ const handleNotificationDirect = async (directs) => {
(newestLatestTimestamp && (newestLatestTimestamp &&
newestLatestTimestamp?.timestamp > oldestLatestTimestamp?.timestamp) newestLatestTimestamp?.timestamp > oldestLatestTimestamp?.timestamp)
) { ) {
const notificationId = const notificationId = generateId()
"chat_notification_" +
Date.now() +
"_type=direct" +
`_from=${newestLatestTimestamp.address}`;
LocalNotifications.schedule({ LocalNotifications.schedule({
notifications: [ notifications: [
{ {
@ -409,6 +409,10 @@ const handleNotificationDirect = async (directs) => {
body: "You have received a new direct message", body: "You have received a new direct message",
id: notificationId, id: notificationId,
schedule: { at: new Date(Date.now() + 1000) }, // 1 second from now schedule: { at: new Date(Date.now() + 1000) }, // 1 second from now
extra: {
type: 'direct',
from: newestLatestTimestamp.address
}
} }
] ]
}); });
@ -430,11 +434,8 @@ const handleNotificationDirect = async (directs) => {
); );
}); });
const notificationId = const notificationId = generateId()
"chat_notification_" +
Date.now() +
"_type=direct" +
`_from=${newestLatestTimestamp.address}`;
LocalNotifications.schedule({ LocalNotifications.schedule({
notifications: [ notifications: [
{ {
@ -442,6 +443,10 @@ const handleNotificationDirect = async (directs) => {
body: "You have received a new direct message", body: "You have received a new direct message",
id: notificationId, id: notificationId,
schedule: { at: new Date(Date.now() + 1000) }, // 1 second from now schedule: { at: new Date(Date.now() + 1000) }, // 1 second from now
extra: {
type: 'direct',
from: ""
}
} }
] ]
}); });
@ -560,18 +565,15 @@ const handleNotification = async (groups) => {
const dataWithUpdates = groups.filter( const dataWithUpdates = groups.filter(
(group) => group?.sender !== address && !mutedGroups.includes(group.groupId) (group) => group?.sender !== address && !mutedGroups.includes(group.groupId)
); );
try { try {
if (isDisableNotifications) return; if (isDisableNotifications) return;
if (!data || data?.length === 0) return; if (!data || data?.length === 0) return;
isFocused = await checkWebviewFocus(); isFocused = await checkWebviewFocus();
if (isFocused) { if (isFocused) {
throw new Error("isFocused"); throw new Error("isFocused");
} }
const newActiveChats = data; const newActiveChats = data;
const oldActiveChats = await getChatHeads(); const oldActiveChats = await getChatHeads();
let results = []; let results = [];
let newestLatestTimestamp; let newestLatestTimestamp;
let oldestLatestTimestamp; let oldestLatestTimestamp;
@ -608,14 +610,10 @@ const handleNotification = async (groups) => {
if ( if (
!newestLatestTimestamp?.data || !newestLatestTimestamp?.data ||
!isExtMsg(newestLatestTimestamp?.data) !isExtMsg(newestLatestTimestamp?.data)
) ) return;
return;
const notificationId = generateId()
const notificationId =
"chat_notification_" +
Date.now() +
"_type=group" +
`_from=${newestLatestTimestamp.groupId}`;
LocalNotifications.schedule({ LocalNotifications.schedule({
notifications: [ notifications: [
@ -624,6 +622,10 @@ const handleNotification = async (groups) => {
body: `You have received a new message from ${newestLatestTimestamp?.groupName}`, body: `You have received a new message from ${newestLatestTimestamp?.groupName}`,
id: notificationId, id: notificationId,
schedule: { at: new Date(Date.now() + 1000) }, // 1 second from now schedule: { at: new Date(Date.now() + 1000) }, // 1 second from now
extra: {
type: 'group',
from: newestLatestTimestamp?.groupId
}
} }
] ]
}); });
@ -647,7 +649,7 @@ const handleNotification = async (groups) => {
); );
}); });
const notificationId = "chat_notification_" + Date.now(); const notificationId = generateId()
LocalNotifications.schedule({ LocalNotifications.schedule({
notifications: [ notifications: [
@ -656,6 +658,10 @@ const handleNotification = async (groups) => {
body: "You have received a new message from one of your groups", body: "You have received a new message from one of your groups",
id: notificationId, id: notificationId,
schedule: { at: new Date(Date.now() + 1000) }, // 1 second from now schedule: { at: new Date(Date.now() + 1000) }, // 1 second from now
extra: {
type: 'group',
from: ""
}
} }
] ]
}); });
@ -735,12 +741,23 @@ export async function getSaveWallet() {
export async function clearAllNotifications() { export async function clearAllNotifications() {
// const notifications = await chrome.notifications.getAll(); try {
// for (const notificationId of Object.keys(notifications)) { // Get all pending notifications
// await chrome.notifications.clear(notificationId); const pending = await LocalNotifications.getPending();
// } const notificationIds = pending.notifications.map((notification) => ({ id: notification.id }));
}
// Cancel all pending notifications if any are found
if (notificationIds.length > 0) {
await LocalNotifications.cancel({ notifications: notificationIds });
}
// Call this to clear any displayed notifications from the system tray
await LocalNotifications.removeAllListeners();
} catch (error) {
console.error("Error clearing notifications:", error);
}
}
export async function getUserInfo() { export async function getUserInfo() {
const wallet = await getSaveWallet(); const wallet = await getSaveWallet();
const address = wallet.address0; const address = wallet.address0;
@ -2913,11 +2930,8 @@ export const checkNewMessages = async () => {
let isDisableNotifications = await getUserSettings({key: 'disable-push-notifications'}) || false let isDisableNotifications = await getUserSettings({key: 'disable-push-notifications'}) || false
if (newAnnouncements.length > 0 && !mutedGroups.includes(newAnnouncements[0]?.groupId) && !isDisableNotifications) { if (newAnnouncements.length > 0 && !mutedGroups.includes(newAnnouncements[0]?.groupId) && !isDisableNotifications) {
const notificationId = const notificationId = generateId()
"chat_notification_" +
Date.now() +
"_type=group-announcement" +
`_from=${newAnnouncements[0]?.groupId}`;
LocalNotifications.schedule({ LocalNotifications.schedule({
@ -2927,6 +2941,10 @@ export const checkNewMessages = async () => {
body: `You have received a new announcement from ${newAnnouncements[0]?.groupName}`, body: `You have received a new announcement from ${newAnnouncements[0]?.groupName}`,
id: notificationId, id: notificationId,
schedule: { at: new Date(Date.now() + 1000) }, // 1 second from now schedule: { at: new Date(Date.now() + 1000) }, // 1 second from now
extra: {
type: 'group',
from: newAnnouncements[0]?.groupId
}
} }
] ]
}); });
@ -3058,14 +3076,10 @@ export const checkThreads = async (bringBack) => {
chrome.storage.local.set({ [`threadactivity-${address}`]: dataString }); chrome.storage.local.set({ [`threadactivity-${address}`]: dataString });
if (newAnnouncements.length > 0) { if (newAnnouncements.length > 0) {
const notificationId =
"chat_notification_" + const notificationId = generateId()
Date.now() +
"_type=thread-post" +
`_data=${JSON.stringify(newAnnouncements[0])}`;
let isDisableNotifications = await getUserSettings({key: 'disable-push-notifications'}) || false let isDisableNotifications = await getUserSettings({key: 'disable-push-notifications'}) || false
if(!isDisableNotifications){ if(!isDisableNotifications){
LocalNotifications.schedule({ LocalNotifications.schedule({
notifications: [ notifications: [
{ {
@ -3073,12 +3087,16 @@ export const checkThreads = async (bringBack) => {
body: `New post in ${newAnnouncements[0]?.thread?.threadData?.title}`, body: `New post in ${newAnnouncements[0]?.thread?.threadData?.title}`,
id: notificationId, id: notificationId,
schedule: { at: new Date(Date.now() + 1000) }, // 1 second from now schedule: { at: new Date(Date.now() + 1000) }, // 1 second from now
extra: {
type: 'thread-post',
from: ""
}
} }
] ]
}); });
} }
} }
const savedtimestampAfter = await getTimestampGroupAnnouncement(); const savedtimestampAfter = await getTimestampGroupAnnouncement();
window.postMessage({ window.postMessage({
action: "SET_GROUP_ANNOUNCEMENTS", action: "SET_GROUP_ANNOUNCEMENTS",
@ -3116,32 +3134,29 @@ BackgroundFetch.configure({
LocalNotifications.addListener('localNotificationActionPerformed', async (notification) => { LocalNotifications.addListener('localNotificationActionPerformed', async (event) => {
const notificationId = notification.notification.id;
// Check the type of notification by parsing notificationId // Access nested properties based on your screenshot
const isDirect = notificationId.includes('_type=direct_'); const extraData = event.notification?.extra;
const isGroup = notificationId.includes('_type=group_'); const type = extraData?.type;
const isGroupAnnouncement = notificationId.includes('_type=group-announcement_'); const from = extraData?.from;
const isNewThreadPost = notificationId.includes('_type=thread-post_');
// Determine notification type based on `type` field
if (type === 'direct') {
window.postMessage({ action: "NOTIFICATION_OPEN_DIRECT", payload: { from } }, "*");
} else if (type === 'group') {
window.postMessage({ action: "NOTIFICATION_OPEN_GROUP", payload: { from } }, "*");
} else if (type === 'group-announcement') {
window.postMessage({ action: "NOTIFICATION_OPEN_ANNOUNCEMENT_GROUP", payload: { from } }, "*");
} else if (type === 'thread-post') {
window.postMessage({ action: "NOTIFICATION_OPEN_THREAD_NEW_POST", payload: { data: extraData?.data } }, "*");
}
// Handle specific notification types // Clear all notifications
if (isDirect) { try {
const fromValue = notificationId.split('_from=')[1]; await clearAllNotifications();
} catch (error) {
window.postMessage({ action: "NOTIFICATION_OPEN_DIRECT", payload: { from: fromValue } }, "*"); console.error("Error clearing notifications:", error);
} else if (isGroup) {
const fromValue = notificationId.split('_from=')[1];
window.postMessage({ action: "NOTIFICATION_OPEN_GROUP", payload: { from: fromValue } }, "*");
} else if (isGroupAnnouncement) {
const fromValue = notificationId.split('_from=')[1];
window.postMessage({ action: "NOTIFICATION_OPEN_ANNOUNCEMENT_GROUP", payload: { from: fromValue } }, "*");
} else if (isNewThreadPost) {
const dataValue = notificationId.split('_data=')[1];
const dataParsed = JSON.parse(dataValue);
window.postMessage({ action: "NOTIFICATION_OPEN_THREAD_NEW_POST", payload: { data: dataParsed } }, "*");
} }
}); });