Equicord/src/api/Notifications/notificationLog.tsx
V 2f1c6a37fc
fix many bugs found by Claude (#4436)
Fixes:
- Webpack Patcher: incorrect patch error handling could lead to some functional patches not being applied 
- CommandsAPI: subcommands were impossible to unregister
- useAwaiter: on error, the value was set to null even if a fallbackValue was specified, violating the type contract
- Patcher: build check boolean logic was grouped incorrectly due to missing parantheses
- CustomCommands: commands weren't unregistered on stop, leading to error when enabling, disabling & re-renabling the plugin
- Notification Log: delete was by timestamp instead of ID and non-atomic
- FixSpotifyEmbeds: settings listener was registered inside browser-window-created event handler, leading to duplicate listeners
- CustomRPC: changing activity type or timestamp didn't update the RPC
- CopyStickerLinks: message patch had non-sense code, just removed it
- XSOverlay: UDP socket wasn't closed on stop
- VoiceMessages: Web recorder never closed the mic media stream, which continues showing the OS mic indicator
- PictureInPicture: Video clone wasn't properly cleaned up, which leaked memory
- Themes (Extension version): theme object urls were never cleaned up, which leaked memory on theme change
- Themes (Extension version): Upload Theme button hitbox was only the text, not the whole button. Also added Drag & Drop from file manager support
- Dearrow: toggling for one embed flipped the global dearrow by default setting
- Extension Installer: the zip extract function was vulnerable to path traversal, although we only ever used this for React DevTools obtained via https so it has low impact
- FileWatchers: ensure always properly cleaned up
- components/Link: mutated props which is a very bad practice

All fixes are human written, only the audit was done by Claude Fable (thanks for ur tokens, Zere).
2026-07-26 17:07:47 +02:00

201 lines
6.4 KiB
TypeScript

/*
* Vencord, a modification for Discord's desktop app
* Copyright (c) 2023 Vendicated and contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
import * as DataStore from "@api/DataStore";
import { Settings } from "@api/Settings";
import { openNotificationSettingsModal } from "@components/settings/tabs/vencord/NotificationSettings";
import { classNameFactory } from "@utils/css";
import { useAwaiter } from "@utils/react";
import { RenderModalProps } from "@vencord/discord-types";
import { ConfirmModal, Forms, ListScrollerThin, Modal, openModal, React, Timestamp, useEffect, useReducer, useState } from "@webpack/common";
import { nanoid } from "nanoid";
import type { DispatchWithoutAction } from "react";
import NotificationComponent from "./NotificationComponent";
import type { NotificationData } from "./Notifications";
interface PersistentNotificationData extends Pick<NotificationData, "title" | "body" | "image" | "icon" | "color"> {
timestamp: number;
id: string;
}
const KEY = "notification-log";
const getLog = async () => {
const log = await DataStore.get(KEY) as PersistentNotificationData[] | undefined;
return log ?? [];
};
const cl = classNameFactory("vc-notification-log-");
const signals = new Set<DispatchWithoutAction>();
export async function persistNotification(notification: NotificationData) {
if (notification.noPersist) return;
const limit = Settings.notifications.logLimit;
if (limit === 0) return;
await DataStore.update(KEY, (old: PersistentNotificationData[] | undefined) => {
const log = old ?? [];
// Omit stuff we don't need
const {
onClick, onClose, richBody, permanent, noPersist, dismissOnClick,
...pureNotification
} = notification;
log.unshift({
...pureNotification,
timestamp: Date.now(),
id: nanoid()
});
if (log.length > limit && limit !== 200)
log.length = limit;
return log;
});
signals.forEach(x => x());
}
export async function deleteNotification(id: string) {
let found = false;
await DataStore.update(KEY, (old: PersistentNotificationData[] | undefined) => {
const log = old ?? [];
const index = log.findIndex(x => x.id === id);
if (index === -1) return log;
log.splice(index, 1);
found = true;
return log;
});
if (found)
signals.forEach(x => x());
}
export function useLogs() {
const [signal, setSignal] = useReducer(x => x + 1, 0);
useEffect(() => {
signals.add(setSignal);
return () => void signals.delete(setSignal);
}, []);
const [log, _, pending] = useAwaiter(getLog, {
fallbackValue: [],
deps: [signal]
});
return [log, pending] as const;
}
function NotificationEntry({ data }: { data: PersistentNotificationData; }) {
const [removing, setRemoving] = useState(false);
return (
<div className={cl("wrapper", { removing })}>
<NotificationComponent
{...data}
permanent={true}
dismissOnClick={false}
onClose={() => {
if (removing) return;
setRemoving(true);
setTimeout(() => deleteNotification(data.id), 200);
}}
richBody={
<div className={cl("body-wrapper")}>
<div className={cl("body")}>{data.body}</div>
<Timestamp timestamp={new Date(data.timestamp)} className={cl("timestamp")} />
</div>
}
/>
</div >
);
}
export function NotificationLog({ log, pending }: { log: PersistentNotificationData[], pending: boolean; }) {
if (!log.length && !pending)
return (
<div>
<div className={cl("empty")} />
<Forms.FormText style={{ textAlign: "center" }}>
No notifications yet
</Forms.FormText>
</div>
);
return (
<ListScrollerThin
className={cl("container")}
sections={[log.length]}
sectionHeight={0}
rowHeight={120}
renderSection={() => null}
renderRow={item => <NotificationEntry data={log[item.row]} key={log[item.row].id} />}
/>
);
}
function LogModal(props: RenderModalProps) {
const [log, pending] = useLogs();
return (
<Modal
{...props}
size="xl"
title="Notification Log"
actions={[
{
text: "Notification Settings",
variant: "primary",
onClick: openNotificationSettingsModal
},
{
text: "Clear Notification Log",
variant: "critical-primary",
disabled: !log.length,
onClick() {
openModal(props =>
<ConfirmModal
{...props}
title="Are you sure?"
subtitle={`This will permanently remove ${log.length} notification${log.length === 1 ? "" : "s"}. This action cannot be undone.`}
confirmText="Do it!"
onConfirm={async () => {
await DataStore.set(KEY, []);
signals.forEach(x => x());
}}
/>
);
}
}
]}
>
<NotificationLog log={log} pending={pending} />
</Modal>
);
}
export function openNotificationLogModal() {
openModal(props => <LogModal {...props} />);
}