(settings[s.key] = v)}
+ onChange={(v) => (settings[s.key] = v)}
note={
s.warning.enabled ? (
<>
@@ -277,8 +289,8 @@ function EquicordSettings() {
value: "hud",
},
]}
- select={v => (settings.macosVibrancyStyle = v)}
- isSelected={v => settings.macosVibrancyStyle === v}
+ select={(v) => (settings.macosVibrancyStyle = v)}
+ isSelected={(v) => settings.macosVibrancyStyle === v}
serialize={identity}
/>
>
@@ -324,7 +336,7 @@ function DiscordInviteCard({ invite, image }: DiscordInviteProps) {
{
+ onClick={async (e) => {
e.preventDefault();
openInviteModal(invite).catch(() =>
showToast("Invalid or expired invite"),
diff --git a/src/equicordplugins/ViewRawVariant/index.tsx b/src/equicordplugins/ViewRawVariant/index.tsx
index b0e47313..fc29d2d4 100644
--- a/src/equicordplugins/ViewRawVariant/index.tsx
+++ b/src/equicordplugins/ViewRawVariant/index.tsx
@@ -60,7 +60,7 @@ function cleanMessage(msg: CustomMessage) {
}
function openViewRawModal(obj: any, type: string, isMessage?: boolean) {
- const key = openModal(props => (
+ const key = openModal((props) => (
@@ -134,16 +134,16 @@ export default definePlugin({
"Copy/View raw content of any message, channel, or guild, but show in the right click menu.",
authors: [Devs.KingFish, Devs.Ven, Devs.rad, Devs.ImLvna, Devs.Kyuuhachi],
contextMenus: {
- "guild-context": makeContextCallback("guild", val =>
+ "guild-context": makeContextCallback("guild", (val) =>
openViewRawModal(val, "Guild"),
),
- "channel-context": makeContextCallback("channel", val =>
+ "channel-context": makeContextCallback("channel", (val) =>
openViewRawModal(val, "Channel"),
),
- "user-context": makeContextCallback("user", val =>
+ "user-context": makeContextCallback("user", (val) =>
openViewRawModal(val, "User"),
),
- message: makeContextCallback("message", val =>
+ message: makeContextCallback("message", (val) =>
openViewRawModal(cleanMessage(val), "Message", true),
),
},
diff --git a/src/equicordplugins/grammarFix/index.ts b/src/equicordplugins/grammarFix/index.ts
index b0d8cd16..0ec7d6f7 100644
--- a/src/equicordplugins/grammarFix/index.ts
+++ b/src/equicordplugins/grammarFix/index.ts
@@ -28,19 +28,19 @@ const settings = definePluginSettings({
},
});
-const getPresend = dictionary => {
+const getPresend = (dictionary) => {
const presendObject: SendListener = (_, msg) => {
msg.content = msg.content.trim();
if (!msg.content.includes("```") && /\w/.test(msg.content.charAt(0))) {
if (settings.store.autoWordReplacement) {
const re = new RegExp(
`(^|(?<=[^A-Z0-9]+))(${Object.keys(dictionary)
- .map(k => k.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"))
+ .map((k) => k.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"))
.join("|")})((?=[^A-Z0-9]+)|$)`,
"gi",
);
if (re !== null) {
- msg.content = msg.content.replace(re, match => {
+ msg.content = msg.content.replace(re, (match) => {
return dictionary[match.toLowerCase()] || match;
});
}
@@ -62,7 +62,7 @@ const getPresend = dictionary => {
// Ensure sentences are capitalized after punctuation
if (settings.store.autoCapitalization) {
- msg.content = msg.content.replace(/([.!?])\s*(\w)/g, match =>
+ msg.content = msg.content.replace(/([.!?])\s*(\w)/g, (match) =>
match.toUpperCase(),
);
diff --git a/src/equicordplugins/messageLoggerEnhanced/LoggedMessageManager.ts b/src/equicordplugins/messageLoggerEnhanced/LoggedMessageManager.ts
index e83a30e6..8b5127ee 100644
--- a/src/equicordplugins/messageLoggerEnhanced/LoggedMessageManager.ts
+++ b/src/equicordplugins/messageLoggerEnhanced/LoggedMessageManager.ts
@@ -16,29 +16,260 @@
* along with this program. If not, see .
*/
-import { Flogger, settings } from ".";
-import { addMessageIDB, db, DBMessageStatus, deleteMessagesBulkIDB, getOldestMessagesIDB } from "./db";
-import { LoggedMessage, LoggedMessageJSON } from "./types";
-import { cleanupMessage } from "./utils";
-import { cacheMessageImages } from "./utils/saveImage";
+import { createStore } from "@api/DataStore";
+import { DataStore } from "@api/index";
+import { Settings } from "@api/Settings";
-export const addMessage = async (message: LoggedMessage | LoggedMessageJSON, status: DBMessageStatus) => {
- if (settings.store.saveImages && status === DBMessageStatus.DELETED)
+import { Flogger, Native, settings } from ".";
+import { LoggedMessage, LoggedMessageIds, LoggedMessageJSON, LoggedMessages, MessageRecord } from "./types";
+import { cleanupMessage, getNative, sortMessagesByDate } from "./utils";
+import { cacheMessageImages, deleteMessageImages } from "./utils/saveImage";
+
+export const defaultLoggedMessages = { deletedMessages: {}, editedMessages: {}, };
+
+export const LOGGED_MESSAGES_KEY = "logged-messages-hi";
+export const MessageLoggerStore = createStore("MessageLoggerData", "MessageLoggerStore");
+
+// this gets used by the logs modal. logs modal should only use saved messages not messages that are being processed
+// also hasMessageInLogs should only check saved messages not the ones that are being processed
+export let savedLoggedMessages: LoggedMessages = { ...defaultLoggedMessages };
+
+export let loggedMessages: LoggedMessages = { ...defaultLoggedMessages };
+
+(async () => {
+ try {
+ const Native = getNative();
+ const res = await Native.getLogsFromFs();
+ if (res != null) {
+ Flogger.log("Got logged messages from native wont be checking DataStore");
+ const cleaned = await cleanMessages(res, Native);
+ loggedMessages = cleaned;
+ savedLoggedMessages = cleaned;
+ return;
+ }
+
+ if (IS_WEB) {
+ Flogger.log("hii. no point in checking DataStore if. we already did up there ^^");
+ return;
+ }
+
+ const data = await DataStore.get(LOGGED_MESSAGES_KEY, MessageLoggerStore);
+
+ if (data == null) {
+ Flogger.log("No logged messages in DataStore");
+ return;
+ }
+
+ Flogger.log("Loading logged messages from DataStore and writing to native");
+ Native.writeLogs(JSON.stringify(data));
+
+ loggedMessages = data;
+ savedLoggedMessages = res;
+ } catch (error) {
+ console.error("Error loading logged messages from the store:", error);
+ }
+})();
+
+// api
+
+export const saveLoggedMessages = async () => {
+ if (settings.store.saveMessages) {
+ await Native.writeLogs(JSON.stringify(loggedMessages));
+ }
+ savedLoggedMessages = loggedMessages;
+};
+
+export const addMessage = async (message: LoggedMessage | LoggedMessageJSON, key: keyof LoggedMessageIds, isBulk = false) => {
+ if (settings.store.saveImages && key === "deletedMessages")
await cacheMessageImages(message);
const finalMessage = cleanupMessage(message);
+ loggedMessages[message.id] = { message: finalMessage };
- await addMessageIDB(finalMessage, status);
+ if (!loggedMessages[key][message.channel_id])
+ loggedMessages[key][message.channel_id] = [];
- if (settings.store.messageLimit > 0) {
- const currentMessageCount = await db.count("messages");
- if (currentMessageCount > settings.store.messageLimit) {
- const messagesToDelete = currentMessageCount - settings.store.messageLimit;
- if (messagesToDelete <= 0 || messagesToDelete >= settings.store.messageLimit) return;
+ if (!loggedMessages[key][message.channel_id].includes(message.id))
+ loggedMessages[key][message.channel_id].push(message.id);
- const oldestMessages = await getOldestMessagesIDB(messagesToDelete);
+ // if limit is negative or 0 there is no limit
+ if (settings.store.messageLimit > 0 && (Object.keys(loggedMessages).length - 2) > settings.store.messageLimit)
+ await deleteOldestMessageWithoutSaving(loggedMessages);
- Flogger.info(`Deleting ${messagesToDelete} oldest messages`);
- await deleteMessagesBulkIDB(oldestMessages.map(m => m.message_id));
+ if (!isBulk)
+ await saveLoggedMessages();
+};
+
+
+export const removeFromKey = (
+ message_id: string,
+ channel_id: string,
+ loggedMessages: LoggedMessages,
+ key: keyof LoggedMessageIds,
+) => {
+ if (loggedMessages[key][channel_id]) {
+ loggedMessages[key][channel_id] = loggedMessages[key][channel_id].filter(msgid => msgid !== message_id);
+
+ if (loggedMessages[key][channel_id].length === 0) {
+ delete loggedMessages[key][channel_id];
}
}
};
+
+function removeLogWithoutSaving(messageId: string, loggedMessages: LoggedMessages) {
+ const record = loggedMessages[messageId];
+ if (record) {
+ const channel_id = record.message?.channel_id;
+
+ if (channel_id != null) {
+ removeFromKey(messageId, channel_id, loggedMessages, "editedMessages");
+ removeFromKey(messageId, channel_id, loggedMessages, "deletedMessages");
+ }
+
+ delete loggedMessages[messageId];
+ }
+
+ return loggedMessages;
+}
+
+
+
+export async function removeLogs(ids: string[]) {
+ for (const msgId of ids) {
+ removeLogWithoutSaving(msgId, loggedMessages);
+ }
+ await saveLoggedMessages();
+}
+
+export async function removeLog(id: string) {
+ const record = loggedMessages[id];
+
+ if (record?.message)
+ deleteMessageImages(record.message);
+
+ removeLogWithoutSaving(id, loggedMessages);
+
+ await saveLoggedMessages();
+
+}
+
+export async function clearLogs() {
+ await Native.writeLogs(JSON.stringify(defaultLoggedMessages));
+ loggedMessages = defaultLoggedMessages;
+ savedLoggedMessages = defaultLoggedMessages;
+}
+
+
+// utils
+
+export const hasMessageInLogs = (messageId: string) => {
+ const bruh = Object.values(savedLoggedMessages)
+ .filter(m => !Array.isArray(m)) as MessageRecord[];
+
+ return bruh.find(m => m.message?.id === messageId);
+};
+
+export const hasLogs = async () => {
+ const hasDeletedMessages = Object.keys(loggedMessages.deletedMessages).length > 0;
+ const hasEditedMessages = Object.keys(loggedMessages.editedMessages).length > 0;
+
+ const hasMessages = Object.keys(loggedMessages).filter(m => m !== "editedMessages" && m !== "deletedMessages").length > 0;
+
+ if (hasDeletedMessages && hasEditedMessages && hasMessages) return true;
+
+ return false;
+};
+
+export function findLoggedChannelByMessageIdSync(messageId: string, loggedMessages: LoggedMessages, key: keyof LoggedMessageIds) {
+ for (const channelId in loggedMessages[key]) {
+ if (loggedMessages[key][channelId].includes(messageId)) return channelId;
+ }
+
+ return null;
+}
+
+export async function findLoggedChannelByMessage(messageId: string, key?: keyof LoggedMessageIds): Promise<[string | null, keyof LoggedMessageIds]> {
+
+ if (!key) {
+ const id1 = findLoggedChannelByMessageIdSync(messageId, loggedMessages, "deletedMessages");
+ if (id1) return [id1, "deletedMessages"];
+ const id2 = findLoggedChannelByMessageIdSync(messageId, loggedMessages, "editedMessages");
+ return [id2, "editedMessages"];
+ }
+
+ return [findLoggedChannelByMessageIdSync(messageId, loggedMessages, key), key];
+}
+
+
+export function getOldestMessage(loggedMessageIds: LoggedMessages) {
+ const messags = Object.values(loggedMessageIds)
+ .filter(m => !Array.isArray(m) && m.message != null) as MessageRecord[];
+
+ const sortedMessages = messags.sort((a, b) => sortMessagesByDate(a.message.timestamp, b.message.timestamp));
+
+ const oldestMessage = sortedMessages[sortedMessages.length - 1];
+
+ return oldestMessage ?? null;
+}
+
+export function getMessage(channelId: string, messageId: string) {
+ const messags = Object.values(savedLoggedMessages)
+ .filter(m => !Array.isArray(m) && m.message != null) as MessageRecord[];
+
+ return messags.find(m => m.message.channel_id === channelId && m.message.id === messageId);
+}
+
+export async function deleteOldestMessageWithoutSaving(loggedMessages: LoggedMessages) {
+ const oldestMessage = getOldestMessage(loggedMessages);
+ if (!oldestMessage || !oldestMessage.message) {
+ console.warn("couldnt find oldest message. oldestMessage == null || oldestMessage.message == null");
+ return loggedMessages;
+ }
+
+ const { message } = oldestMessage;
+
+ const [channelId, key] = await findLoggedChannelByMessage(message.id);
+
+ if (!channelId || !key) {
+ console.warn("couldnt find oldest message. channelId =", channelId, " key =", key);
+ return loggedMessages;
+ }
+
+ removeLogWithoutSaving(message.id, loggedMessages);
+ // console.log("removing", message);
+
+ return loggedMessages;
+}
+
+async function cleanMessages(loggedMessages: LoggedMessages, _Native: any = Native) {
+ try {
+ const cleaned = { ...loggedMessages };
+
+ if (IS_WEB) return cleaned;
+
+ const messageRecords = Object.values(cleaned)
+ .filter(m => !Array.isArray(m)) as MessageRecord[];
+
+ let hasChanged = false;
+ for (const messageRecord of messageRecords) {
+ const { message } = messageRecord;
+
+ if (message?.attachments) {
+ for (const attachment of message.attachments) {
+ if (attachment.blobUrl) {
+ hasChanged = true;
+ delete attachment.blobUrl;
+ }
+ }
+ }
+ }
+
+ if (hasChanged)
+ await _Native.writeLogs(Settings.plugins.MessageLoggerEnhanced.logsDir, JSON.stringify(cleaned));
+
+ return cleaned;
+
+ } catch (err) {
+ Flogger.error("Error cleaning messages:", err);
+ return loggedMessages;
+ }
+}
diff --git a/src/equicordplugins/messageLoggerEnhanced/components/LogsModal.tsx b/src/equicordplugins/messageLoggerEnhanced/components/LogsModal.tsx
index 85186594..c7b76caf 100644
--- a/src/equicordplugins/messageLoggerEnhanced/components/LogsModal.tsx
+++ b/src/equicordplugins/messageLoggerEnhanced/components/LogsModal.tsx
@@ -1,26 +1,37 @@
/*
- * Vencord, a Discord client mod
- * Copyright (c) 2024 Vendicated and contributors
- * SPDX-License-Identifier: GPL-3.0-or-later
- */
+ * 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 .
+*/
import { classNameFactory } from "@api/Styles";
-import { Flex } from "@components/Flex";
-import { InfoIcon } from "@components/Icons";
import { openUserProfile } from "@utils/discord";
import { copyWithToast } from "@utils/misc";
import { closeAllModals, ModalContent, ModalFooter, ModalHeader, ModalProps, ModalRoot, ModalSize, openModal } from "@utils/modal";
-import { LazyComponent } from "@utils/react";
+import { LazyComponent, useAwaiter } from "@utils/react";
import { find, findByCode, findByCodeLazy } from "@webpack";
-import { Alerts, Button, ChannelStore, ContextMenuApi, FluxDispatcher, Menu, NavigationRouter, React, TabBar, Text, TextInput, Tooltip, useMemo, useRef, useState } from "@webpack/common";
+import { Alerts, Button, ChannelStore, ContextMenuApi, FluxDispatcher, Menu, NavigationRouter, React, TabBar, Text, TextInput, useCallback, useMemo, useRef, useState } from "@webpack/common";
import { User } from "discord-types/general";
-import { clearMessagesIDB, DBMessageRecord, deleteMessageIDB, deleteMessagesBulkIDB } from "../db";
import { settings } from "../index";
-import { LoggedMessage, LoggedMessageJSON } from "../types";
-import { messageJsonToMessageClass } from "../utils";
-import { importLogs } from "../utils/settingsUtils";
-import { useMessages } from "./hooks";
+import { clearLogs, defaultLoggedMessages, removeLog, removeLogs, savedLoggedMessages } from "../LoggedMessageManager";
+import { LoggedMessage, LoggedMessageJSON, LoggedMessages } from "../types";
+import { isGhostPinged, messageJsonToMessageClass, sortMessagesByDate } from "../utils";
+import { doesMatch, parseQuery } from "../utils/parseQuery";
+
+
export interface MessagePreviewProps {
className: string;
@@ -56,7 +67,7 @@ const ChildrenAccessories = LazyComponent(() => findByCode("c
const cl = classNameFactory("msg-logger-modal-");
-export enum LogTabs {
+enum LogTabs {
DELETED = "Deleted",
EDITED = "Edited",
GHOST_PING = "Ghost Pinged"
@@ -68,14 +79,73 @@ interface Props {
}
export function LogsModal({ modalProps, initalQuery }: Props) {
+ const [x, setX] = useState(0);
+ const forceUpdate = () => setX(e => e + 1);
+
+ const [logs, _, pending] = useAwaiter(async () => savedLoggedMessages, {
+ fallbackValue: defaultLoggedMessages as LoggedMessages,
+ deps: [x]
+ });
const [currentTab, setCurrentTab] = useState(LogTabs.DELETED);
const [queryEh, setQuery] = useState(initalQuery ?? "");
const [sortNewest, setSortNewest] = useState(settings.store.sortNewest);
- const [numDisplayedMessages, setNumDisplayedMessages] = useState(settings.store.messagesToDisplayAtOnceInLogs);
+ const [numDisplayedMessages, setNumDisplayedMessages] = useState(50);
const contentRef = useRef(null);
- const { messages, total, statusTotal, pending, reset } = useMessages(queryEh, currentTab, sortNewest, numDisplayedMessages);
+ const handleLoadMore = useCallback(() => {
+ setNumDisplayedMessages(prevNum => prevNum + 50);
+ }, []);
+
+ // Flogger.log(logs, _, pending, contentRef);
+
+ // Flogger.time("hi");
+ const messages: string[][] = currentTab === LogTabs.DELETED || currentTab === LogTabs.GHOST_PING
+ ? Object.values(logs?.deletedMessages ?? {})
+ : Object.values(logs?.editedMessages ?? {});
+
+ const flattendAndfilteredAndSortedMessages = useMemo(() => {
+ const { success, type, id, negate, query } = parseQuery(queryEh);
+
+ if (query === "" && !success) {
+ const result = messages
+ .flat()
+ .filter(m => currentTab === LogTabs.GHOST_PING ? isGhostPinged(logs[m].message!) : true)
+ .sort(sortMessagesByDate);
+ return sortNewest ? result : result.reverse();
+ }
+
+ const result = messages
+ .flat()
+ .filter(m =>
+ currentTab === LogTabs.GHOST_PING
+ ? isGhostPinged(logs[m].message)
+ : true
+ )
+ .filter(m =>
+ logs[m]?.message != null &&
+ (
+ success === false
+ ? true
+ : negate
+ ? !doesMatch(type!, id!, logs[m].message!)
+ : doesMatch(type!, id!, logs[m].message!)
+ )
+ )
+ .filter(m =>
+ logs[m]?.message?.content?.toLowerCase()?.includes(query.toLowerCase()) ??
+ logs[m].message?.editHistory?.map(m => m.content?.toLowerCase()).includes(query.toLowerCase())
+ )
+ .sort(sortMessagesByDate);
+
+ return sortNewest ? result : result.reverse();
+ }, [currentTab, logs, queryEh, sortNewest]);
+
+ const visibleMessages = flattendAndfilteredAndSortedMessages.slice(0, numDisplayedMessages);
+
+ const canLoadMore = numDisplayedMessages < flattendAndfilteredAndSortedMessages.length;
+
+ // Flogger.timeEnd("hi");
return (
@@ -87,7 +157,7 @@ export function LogsModal({ modalProps, initalQuery }: Props) {
selectedItem={currentTab}
onItemSelect={e => {
setCurrentTab(e);
- setNumDisplayedMessages(settings.store.messagesToDisplayAtOnceInLogs);
+ setNumDisplayedMessages(50);
contentRef.current?.firstElementChild?.scrollTo(0, 0);
// forceUpdate();
}}
@@ -118,23 +188,21 @@ export function LogsModal({ modalProps, initalQuery }: Props) {
- {messages != null && total === 0 && (
-
- )}
-
- {!pending && messages != null && (
- = settings.store.messagesToDisplayAtOnceInLogs}
- tab={currentTab}
- sortNewest={sortNewest}
- reset={reset}
- handleLoadMore={() => setNumDisplayedMessages(e => e + settings.store.messagesToDisplayAtOnceInLogs)}
- />
- )}
+ {
+ pending || logs == null || messages.length === 0
+ ?
+ : (
+
+ )
+ }
}
@@ -148,8 +216,8 @@ export function LogsModal({ modalProps, initalQuery }: Props) {
confirmColor: Button.Colors.RED,
cancelText: "Cancel",
onConfirm: async () => {
- await clearMessagesIDB();
- reset();
+ await clearLogs();
+ forceUpdate();
}
})}
@@ -159,16 +227,16 @@ export function LogsModal({ modalProps, initalQuery }: Props) {
Alerts.show({
title: "Clear Logs",
- body: `Are you sure you want to clear ${messages.length} logs`,
+ body: `Are you sure you want to clear ${visibleMessages.length} logs`,
confirmText: "Clear",
confirmColor: Button.Colors.RED,
cancelText: "Cancel",
onConfirm: async () => {
- await deleteMessagesBulkIDB(messages.map(e => e.message_id));
- reset();
+ await removeLogs(visibleMessages);
+ forceUpdate();
}
})}
>
@@ -194,27 +262,28 @@ export function LogsModal({ modalProps, initalQuery }: Props) {
}
interface LogContentProps {
+ logs: LoggedMessages,
sortNewest: boolean;
tab: LogTabs;
- visibleMessages: DBMessageRecord[];
+ visibleMessages: string[];
canLoadMore: boolean;
- reset: () => void;
+ forceUpdate: () => void;
handleLoadMore: () => void;
}
-function LogsContent({ visibleMessages, canLoadMore, sortNewest, tab, reset, handleLoadMore }: LogContentProps) {
+function LogsContent({ logs, visibleMessages, canLoadMore, sortNewest, tab, forceUpdate, handleLoadMore }: LogContentProps) {
if (visibleMessages.length === 0)
return ;
return (
{visibleMessages
- .map(({ message }, i) => (
+ .map((id, i) => (
))}
{
@@ -261,35 +330,12 @@ function NoResults({ tab }: { tab: LogTabs; }) {
);
}
-function EmptyLogs({ hasQuery, reset: forceUpdate }: { hasQuery: boolean; reset: () => void; }) {
+function EmptyLogs() {
return (
-
-
-
- Empty eh
-
-
- {!hasQuery && (
- <>
-
- {({ onMouseEnter, onMouseLeave }) => (
-
-
-
- )}
-
-
- importLogs().then(() => forceUpdate())}>
- Import Logs
-
- >
- )}
-
+
+ Empty eh
+
);
@@ -298,13 +344,11 @@ function EmptyLogs({ hasQuery, reset: forceUpdate }: { hasQuery: boolean; reset:
interface LMessageProps {
log: { message: LoggedMessageJSON; };
isGroupStart: boolean,
- reset: () => void;
+ forceUpdate: () => void;
}
-function LMessage({ log, isGroupStart, reset, }: LMessageProps) {
+function LMessage({ log, isGroupStart, forceUpdate, }: LMessageProps) {
const message = useMemo(() => messageJsonToMessageClass(log), [log]);
- // console.log(message);
-
if (!message) return null;
return (
@@ -326,6 +370,7 @@ function LMessage({ log, isGroupStart, reset, }: LMessageProps) {
closeAllModals();
}}
/>
+
- deleteMessageIDB(log.message.id).then(() => reset())
+ removeLog(log.message.id)
+ .then(() => {
+ forceUpdate();
+ })
}
/>
@@ -430,8 +478,6 @@ function isGroupStart(
) {
if (!currentMessage || !previousMessage) return true;
- if (currentMessage.id === previousMessage.id) return true;
-
const [newestMessage, oldestMessage] = sortNewest
? [previousMessage, currentMessage]
: [currentMessage, previousMessage];
diff --git a/src/equicordplugins/messageLoggerEnhanced/components/hooks.ts b/src/equicordplugins/messageLoggerEnhanced/components/hooks.ts
deleted file mode 100644
index fad128cf..00000000
--- a/src/equicordplugins/messageLoggerEnhanced/components/hooks.ts
+++ /dev/null
@@ -1,109 +0,0 @@
-/*
- * Vencord, a Discord client mod
- * Copyright (c) 2024 Vendicated and contributors
- * SPDX-License-Identifier: GPL-3.0-or-later
- */
-
-import { useEffect, useState } from "@webpack/common";
-
-import { countMessagesByStatusIDB, countMessagesIDB, DBMessageRecord, DBMessageStatus, getDateStortedMessagesByStatusIDB } from "../db";
-import { doesMatch, tokenizeQuery } from "../utils/parseQuery";
-import { LogTabs } from "./LogsModal";
-
-function useDebouncedValue(value: T, delay: number): T {
- const [debouncedValue, setDebouncedValue] = useState(value);
-
- useEffect(() => {
- const handler = setTimeout(() => {
- setDebouncedValue(value);
- }, delay);
-
- return () => {
- clearTimeout(handler);
- };
- }, [value, delay]);
-
- return debouncedValue;
-}
-
-// this is so shit
-export function useMessages(query: string, currentTab: LogTabs, sortNewest: boolean, numDisplayedMessages: number) {
- // only for initial load
- const [pending, setPending] = useState(true);
- const [messages, setMessages] = useState([]);
- const [statusTotal, setStatusTotal] = useState(0);
- const [total, setTotal] = useState(0);
-
- const debouncedQuery = useDebouncedValue(query, 300);
-
- useEffect(() => {
- countMessagesIDB().then(x => setTotal(x));
- }, [pending]);
-
- useEffect(() => {
- let isMounted = true;
-
- const loadMessages = async () => {
- const status = getStatus(currentTab);
-
- if (debouncedQuery === "") {
- const [messages, statusTotal] = await Promise.all([
- getDateStortedMessagesByStatusIDB(sortNewest, numDisplayedMessages, status),
- countMessagesByStatusIDB(status),
- ]);
-
-
- if (isMounted) {
- setMessages(messages);
- setStatusTotal(statusTotal);
- }
-
- setPending(false);
- } else {
- const allMessages = await getDateStortedMessagesByStatusIDB(sortNewest, Number.MAX_SAFE_INTEGER, status);
- const { queries, rest } = tokenizeQuery(debouncedQuery);
-
- const filteredMessages = allMessages.filter(record => {
- for (const query of queries) {
- const matching = doesMatch(query.key, query.value, record.message);
- if (query.negate ? matching : !matching) {
- return false;
- }
- }
-
- return rest.every(r =>
- record.message.content.toLowerCase().includes(r.toLowerCase())
- );
- });
-
- if (isMounted) {
- setMessages(filteredMessages);
- setStatusTotal(Number.MAX_SAFE_INTEGER);
- }
- setPending(false);
- }
- };
-
- loadMessages();
-
- return () => {
- isMounted = false;
- };
-
- }, [debouncedQuery, sortNewest, numDisplayedMessages, currentTab, pending]);
-
-
- return { messages, statusTotal, total, pending, reset: () => setPending(true) };
-}
-
-
-function getStatus(currentTab: LogTabs) {
- switch (currentTab) {
- case LogTabs.DELETED:
- return DBMessageStatus.DELETED;
- case LogTabs.EDITED:
- return DBMessageStatus.EDITED;
- default:
- return DBMessageStatus.GHOST_PINGED;
- }
-}
diff --git a/src/equicordplugins/messageLoggerEnhanced/db.ts b/src/equicordplugins/messageLoggerEnhanced/db.ts
deleted file mode 100644
index 90b850fa..00000000
--- a/src/equicordplugins/messageLoggerEnhanced/db.ts
+++ /dev/null
@@ -1,199 +0,0 @@
-/*
- * Vencord, a Discord client mod
- * Copyright (c) 2024 Vendicated and contributors
- * SPDX-License-Identifier: GPL-3.0-or-later
- */
-
-import { LoggedMessageJSON } from "./types";
-import { getMessageStatus } from "./utils";
-import { DB_NAME, DB_VERSION } from "./utils/constants";
-import { DBSchema, IDBPDatabase, openDB } from "./utils/idb";
-import { getAttachmentBlobUrl } from "./utils/saveImage";
-
-export enum DBMessageStatus {
- DELETED = "DELETED",
- EDITED = "EDITED",
- GHOST_PINGED = "GHOST_PINGED",
-}
-
-export interface DBMessageRecord {
- message_id: string;
- channel_id: string;
- status: DBMessageStatus;
- message: LoggedMessageJSON;
-}
-
-export interface MLIDB extends DBSchema {
- messages: {
- key: string;
- value: DBMessageRecord;
- indexes: {
- by_channel_id: string;
- by_status: DBMessageStatus;
- by_timestamp: string;
- by_timestamp_and_message_id: [string, string];
- };
- };
-
-}
-
-export let db: IDBPDatabase;
-export const cachedMessages = new Map();
-
-// this is probably not the best way to do this
-async function cacheRecords(records: DBMessageRecord[]) {
- for (const r of records) {
- cacheRecord(r);
-
- for (const att of r.message.attachments) {
- const blobUrl = await getAttachmentBlobUrl(att);
- if (blobUrl) {
- att.url = blobUrl + "#";
- att.proxy_url = blobUrl + "#";
- }
- }
- }
- return records;
-}
-
-async function cacheRecord(record?: DBMessageRecord | null) {
- if (!record) return record;
-
- cachedMessages.set(record.message_id, record.message);
- return record;
-}
-
-export async function initIDB() {
- db = await openDB(DB_NAME, DB_VERSION, {
- upgrade(db) {
- const messageStore = db.createObjectStore("messages", { keyPath: "message_id" });
- messageStore.createIndex("by_channel_id", "channel_id");
- messageStore.createIndex("by_status", "status");
- messageStore.createIndex("by_timestamp", "message.timestamp");
- messageStore.createIndex("by_timestamp_and_message_id", ["channel_id", "message.timestamp"]);
- }
- });
-}
-initIDB();
-
-export async function hasMessageIDB(message_id: string) {
- return cachedMessages.has(message_id) || (await db.count("messages", message_id)) > 0;
-}
-
-export async function countMessagesIDB() {
- return db.count("messages");
-}
-
-export async function countMessagesByStatusIDB(status: DBMessageStatus) {
- return db.countFromIndex("messages", "by_status", status);
-}
-
-export async function getAllMessagesIDB() {
- return cacheRecords(await db.getAll("messages"));
-}
-
-export async function getMessagesForChannelIDB(channel_id: string) {
- return cacheRecords(await db.getAllFromIndex("messages", "by_channel_id", channel_id));
-}
-
-export async function getMessageIDB(message_id: string) {
- return cacheRecord(await db.get("messages", message_id));
-}
-
-export async function getMessagesByStatusIDB(status: DBMessageStatus) {
- return cacheRecords(await db.getAllFromIndex("messages", "by_status", status));
-}
-
-export async function getOldestMessagesIDB(limit: number) {
- return cacheRecords(await db.getAllFromIndex("messages", "by_timestamp", undefined, limit));
-}
-
-export async function getDateStortedMessagesByStatusIDB(newest: boolean, limit: number, status: DBMessageStatus) {
- const tx = db.transaction("messages", "readonly");
- const { store } = tx;
- const index = store.index("by_status");
-
- const direction = newest ? "prev" : "next";
- const cursor = await index.openCursor(IDBKeyRange.only(status), direction);
-
- if (!cursor) {
- console.log("No messages found");
- return [];
- }
-
- const messages: DBMessageRecord[] = [];
- for await (const c of cursor) {
- messages.push(c.value);
- if (messages.length >= limit) break;
- }
-
- return cacheRecords(messages);
-}
-
-export async function getMessagesByChannelAndAfterTimestampIDB(channel_id: string, start: string) {
- const tx = db.transaction("messages", "readonly");
- const { store } = tx;
- const index = store.index("by_timestamp_and_message_id");
-
- const cursor = await index.openCursor(IDBKeyRange.bound([channel_id, start], [channel_id, "\uffff"]));
-
- if (!cursor) {
- console.log("No messages found in range");
- return [];
- }
-
- const messages: DBMessageRecord[] = [];
- for await (const c of cursor) {
- messages.push(c.value);
- }
-
- return cacheRecords(messages);
-}
-
-export async function addMessageIDB(message: LoggedMessageJSON, status: DBMessageStatus) {
- await db.put("messages", {
- channel_id: message.channel_id,
- message_id: message.id,
- status,
- message,
- });
-
- cachedMessages.set(message.id, message);
-}
-
-export async function addMessagesBulkIDB(messages: LoggedMessageJSON[], status?: DBMessageStatus) {
- const tx = db.transaction("messages", "readwrite");
- const { store } = tx;
-
- await Promise.all([
- ...messages.map(message => store.add({
- channel_id: message.channel_id,
- message_id: message.id,
- status: status ?? getMessageStatus(message),
- message,
- })),
- tx.done
- ]);
-
- messages.forEach(message => cachedMessages.set(message.id, message));
-}
-
-
-export async function deleteMessageIDB(message_id: string) {
- await db.delete("messages", message_id);
-
- cachedMessages.delete(message_id);
-}
-
-export async function deleteMessagesBulkIDB(message_ids: string[]) {
- const tx = db.transaction("messages", "readwrite");
- const { store } = tx;
-
- await Promise.all([...message_ids.map(id => store.delete(id)), tx.done]);
- message_ids.forEach(id => cachedMessages.delete(id));
-}
-
-export async function clearMessagesIDB() {
- await db.clear("messages");
- cachedMessages.clear();
-}
diff --git a/src/equicordplugins/messageLoggerEnhanced/index.tsx b/src/equicordplugins/messageLoggerEnhanced/index.tsx
index be5b837b..7e7aff12 100644
--- a/src/equicordplugins/messageLoggerEnhanced/index.tsx
+++ b/src/equicordplugins/messageLoggerEnhanced/index.tsx
@@ -1,37 +1,51 @@
/*
- * Vencord, a Discord client mod
- * Copyright (c) 2024 Vendicated and contributors
- * SPDX-License-Identifier: GPL-3.0-or-later
- */
+ * 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 .
+*/
-export const VERSION = "4.0.0";
+export const VERSION = "3.0.0";
export const Native = getNative();
import "./styles.css";
+import { NavContextMenuPatchCallback } from "@api/ContextMenu";
+import { definePluginSettings, Settings } from "@api/Settings";
import ErrorBoundary from "@components/ErrorBoundary";
import { Devs } from "@utils/constants";
import { Logger } from "@utils/Logger";
-import definePlugin from "@utils/types";
+import definePlugin, { OptionType } from "@utils/types";
import { findByPropsLazy } from "@webpack";
-import { FluxDispatcher, MessageStore, React, UserStore } from "@webpack/common";
+import { Alerts, Button, FluxDispatcher, Menu, MessageActions, MessageStore, React, Toasts, UserStore } from "@webpack/common";
+import { ImageCacheDir, LogsDir } from "./components/FolderSelectInput";
import { OpenLogsButton } from "./components/LogsButton";
import { openLogModal } from "./components/LogsModal";
-import * as idb from "./db";
-import { addMessage } from "./LoggedMessageManager";
+import { addMessage, loggedMessages, MessageLoggerStore, removeLog } from "./LoggedMessageManager";
import * as LoggedMessageManager from "./LoggedMessageManager";
-import { settings } from "./settings";
-import { FetchMessagesResponse, LoadMessagePayload, LoggedMessage, LoggedMessageJSON, MessageCreatePayload, MessageDeleteBulkPayload, MessageDeletePayload, MessageUpdatePayload } from "./types";
-import { cleanUpCachedMessage, cleanupUserObject, getNative, isGhostPinged, mapTimestamp, messageJsonToMessageClass, reAddDeletedMessages } from "./utils";
-import { removeContextMenuBindings, setupContextMenuPatches } from "./utils/contextMenu";
+import { LoadMessagePayload, LoggedAttachment, LoggedMessage, LoggedMessageJSON, MessageCreatePayload, MessageDeleteBulkPayload, MessageDeletePayload, MessageUpdatePayload } from "./types";
+import { addToXAndRemoveFromOpposite, cleanUpCachedMessage, cleanupUserObject, doesBlobUrlExist, getNative, isGhostPinged, ListType, mapEditHistory, messageJsonToMessageClass, reAddDeletedMessages, removeFromX } from "./utils";
+import { DEFAULT_IMAGE_CACHE_DIR } from "./utils/constants";
import { shouldIgnore } from "./utils/index";
import { LimitedMap } from "./utils/LimitedMap";
import { doesMatch } from "./utils/parseQuery";
import * as imageUtils from "./utils/saveImage";
import * as ImageManager from "./utils/saveImage/ImageManager";
-export { settings };
+import { downloadLoggedMessages } from "./utils/settingsUtils";
+
export const Flogger = new Logger("MessageLoggerEnhanced", "#f26c6c");
@@ -45,7 +59,7 @@ const handledMessageIds = new Set();
async function messageDeleteHandler(payload: MessageDeletePayload & { isBulk: boolean; }) {
if (payload.mlDeleted) {
if (settings.store.permanentlyRemoveLogByDefault)
- await idb.deleteMessageIDB(payload.id);
+ await removeLog(payload.id);
return;
}
@@ -68,8 +82,6 @@ async function messageDeleteHandler(payload: MessageDeletePayload & { isBulk: bo
message = { ...cacheSentMessages.get(`${payload.channelId},${payload.id}`), deleted: true } as LoggedMessageJSON;
}
- const ghostPinged = isGhostPinged(message as any);
-
if (
shouldIgnore({
channelId: message?.channel_id ?? payload.channelId,
@@ -77,7 +89,7 @@ async function messageDeleteHandler(payload: MessageDeletePayload & { isBulk: bo
authorId: message?.author?.id,
bot: message?.bot || message?.author?.bot,
flags: message?.flags,
- ghostPinged,
+ ghostPinged: isGhostPinged(message as any),
isCachedByUs: (message as LoggedMessageJSON).ourCache
})
) {
@@ -93,10 +105,7 @@ async function messageDeleteHandler(payload: MessageDeletePayload & { isBulk: bo
if (message == null || message.channel_id == null || !message.deleted) return;
// Flogger.log("ADDING MESSAGE (DELETED)", message);
- if (payload.isBulk)
- return message;
-
- await addMessage(message, ghostPinged ? idb.DBMessageStatus.GHOST_PINGED : idb.DBMessageStatus.DELETED);
+ await addMessage(message, "deletedMessages", payload.isBulk ?? false);
}
finally {
handledMessageIds.delete(payload.id);
@@ -105,13 +114,10 @@ async function messageDeleteHandler(payload: MessageDeletePayload & { isBulk: bo
async function messageDeleteBulkHandler({ channelId, guildId, ids }: MessageDeleteBulkPayload) {
// is this bad? idk man
- const messages = [] as LoggedMessageJSON[];
for (const id of ids) {
- const msg = await messageDeleteHandler({ type: "MESSAGE_DELETE", channelId, guildId, id, isBulk: true });
- if (msg) messages.push(msg as LoggedMessageJSON);
+ await messageDeleteHandler({ type: "MESSAGE_DELETE", channelId, guildId, id, isBulk: true });
}
-
- await idb.addMessagesBulkIDB(messages);
+ await LoggedMessageManager.saveLoggedMessages();
}
async function messageUpdateHandler(payload: MessageUpdatePayload) {
@@ -148,7 +154,7 @@ async function messageUpdateHandler(payload: MessageUpdatePayload) {
...(cachedMessage.editHistory ?? []),
{
content: cachedMessage.content,
- timestamp: (new Date()).toISOString()
+ timestamp: new Date().toISOString()
}
]
};
@@ -160,7 +166,7 @@ async function messageUpdateHandler(payload: MessageUpdatePayload) {
if (message == null || message.channel_id == null || message.editHistory == null || message.editHistory.length === 0) return;
// Flogger.log("ADDING MESSAGE (EDITED)", message, payload);
- await addMessage(message, idb.DBMessageStatus.EDITED);
+ await addMessage(message, "editedMessages");
}
function messageCreateHandler(payload: MessageCreatePayload) {
@@ -180,86 +186,412 @@ function messageCreateHandler(payload: MessageCreatePayload) {
// Flogger.log(`cached\nkey:${payload.message.channel_id},${payload.message.id}\nvalue:`, payload.message);
}
-async function processMessageFetch(response: FetchMessagesResponse) {
- try {
- if (!response.ok || response.body.length === 0) {
- Flogger.error("Failed to fetch messages", response);
- return;
+// also stolen from mlv2
+function messageLoadSuccess(payload: LoadMessagePayload) {
+ const deletedMessages = loggedMessages.deletedMessages[payload.channelId];
+ const editedMessages = loggedMessages.editedMessages[payload.channelId];
+ const recordIDs: string[] = [...(deletedMessages || []), ...(editedMessages || [])];
+
+
+ for (let i = 0; i < payload.messages.length; ++i) {
+ const recievedMessage = payload.messages[i];
+ const record = loggedMessages[recievedMessage.id];
+
+ if (record == null || record.message == null) continue;
+
+ if (record.message.editHistory!.length !== 0) {
+ payload.messages[i].editHistory = record.message.editHistory;
}
- const firstMessage = response.body[response.body.length - 1];
- // console.time("fetching messages from idb");
- const messages = await idb.getMessagesByChannelAndAfterTimestampIDB(firstMessage.channel_id, firstMessage.timestamp);
- // console.timeEnd("fetching messages from idb");
-
- if (!messages.length) return;
-
- const deletedMessages = messages.filter(m => m.status === idb.DBMessageStatus.DELETED);
-
- for (const recivedMessage of response.body) {
- const record = messages.find(m => m.message_id === recivedMessage.id);
-
- if (record == null) continue;
-
- if (record.message.editHistory && record.message.editHistory.length > 0) {
- recivedMessage.editHistory = record.message.editHistory;
- }
- }
-
- const fetchUser = (id: string) => UserStore.getUser(id) || response.body.find(e => e.author.id === id);
-
- for (let i = 0, len = messages.length; i < len; i++) {
- const record = messages[i];
- if (!record) continue;
-
- const { message } = record;
-
- for (let j = 0, len2 = message.mentions.length; j < len2; j++) {
- const user = message.mentions[j];
- const cachedUser = fetchUser((user as any).id || user);
- if (cachedUser) (message.mentions[j] as any) = cleanupUserObject(cachedUser);
- }
-
- const author = fetchUser(message.author.id);
- if (!author) continue;
- (message.author as any) = cleanupUserObject(author);
- }
-
- response.body.extra = deletedMessages.map(m => m.message);
-
- } catch (e) {
- Flogger.error("Failed to fetch messages", e);
}
+
+ const fetchUser = (id: string) => UserStore.getUser(id) || payload.messages.find(e => e.author.id === id);
+
+ for (let i = 0, len = recordIDs.length; i < len; i++) {
+ const id = recordIDs[i];
+ if (!loggedMessages[id]) continue;
+ const { message } = loggedMessages[id] as { message: LoggedMessageJSON; };
+
+ for (let j = 0, len2 = message.mentions.length; j < len2; j++) {
+ const user = message.mentions[j];
+ const cachedUser = fetchUser((user as any).id || user);
+ if (cachedUser) (message.mentions[j] as any) = cleanupUserObject(cachedUser);
+ }
+
+ const author = fetchUser(message.author.id);
+ if (!author) continue;
+ (message.author as any) = cleanupUserObject(author);
+ }
+
+ reAddDeletedMessages(payload.messages, deletedMessages, !payload.hasMoreAfter && !payload.isBefore, !payload.hasMoreBefore && !payload.isAfter);
}
+export const settings = definePluginSettings({
+ saveMessages: {
+ default: true,
+ type: OptionType.BOOLEAN,
+ description: "Wether to save the deleted and edited messages.",
+ },
+
+ saveImages: {
+ type: OptionType.BOOLEAN,
+ description: "Save deleted messages",
+ default: false
+ },
+
+ sortNewest: {
+ default: true,
+ type: OptionType.BOOLEAN,
+ description: "Sort logs by newest.",
+ },
+
+ cacheMessagesFromServers: {
+ default: false,
+ type: OptionType.BOOLEAN,
+ description: "Usually message logger only logs from whitelisted ids and dms, enabling this would mean it would log messages from all servers as well. Note that this may cause the cache to exceed its limit, resulting in some messages being missed. If you are in a lot of servers, this may significantly increase the chances of messages being logged, which can result in a large message record and the inclusion of irrelevant messages.",
+ },
+
+ ignoreBots: {
+ type: OptionType.BOOLEAN,
+ description: "Whether to ignore messages by bots",
+ default: false,
+ onChange() {
+ // we will be handling the ignoreBots now (enabled or not) so the original messageLogger shouldnt
+ Settings.plugins.MessageLogger.ignoreBots = false;
+ }
+ },
+
+ ignoreSelf: {
+ type: OptionType.BOOLEAN,
+ description: "Whether to ignore messages by yourself",
+ default: false,
+ onChange() {
+ Settings.plugins.MessageLogger.ignoreSelf = false;
+ }
+ },
+
+ ignoreMutedGuilds: {
+ default: false,
+ type: OptionType.BOOLEAN,
+ description: "Messages in muted guilds will not be logged. Whitelisted users/channels in muted guilds will still be logged."
+ },
+
+ ignoreMutedCategories: {
+ default: false,
+ type: OptionType.BOOLEAN,
+ description: "Messages in channels belonging to muted categories will not be logged. Whitelisted users/channels in muted guilds will still be logged."
+ },
+
+ ignoreMutedChannels: {
+ default: false,
+ type: OptionType.BOOLEAN,
+ description: "Messages in muted channels will not be logged. Whitelisted users/channels in muted guilds will still be logged."
+ },
+
+ alwaysLogDirectMessages: {
+ default: true,
+ type: OptionType.BOOLEAN,
+ description: "Always log DMs",
+ },
+
+ alwaysLogCurrentChannel: {
+ default: true,
+ type: OptionType.BOOLEAN,
+ description: "Always log current selected channel. Blacklisted channels/users will still be ignored.",
+ },
+
+ permanentlyRemoveLogByDefault: {
+ default: false,
+ type: OptionType.BOOLEAN,
+ description: "Equicord's base MessageLogger remove log button wiil delete logs permanently",
+ },
+
+ hideMessageFromMessageLoggers: {
+ default: false,
+ type: OptionType.BOOLEAN,
+ description: "When enabled, a context menu button will be added to messages to allow you to delete messages without them being logged by other loggers. Might not be safe, use at your own risk."
+ },
+
+ ShowLogsButton: {
+ default: true,
+ type: OptionType.BOOLEAN,
+ description: "Toggle to whenever show the toolbox or not",
+ restartNeeded: true,
+ },
+
+ hideMessageFromMessageLoggersDeletedMessage: {
+ default: "redacted eh",
+ type: OptionType.STRING,
+ description: "The message content to replace the message with when using the hide message from message loggers feature.",
+ },
+
+ messageLimit: {
+ default: 200,
+ type: OptionType.NUMBER,
+ description: "Maximum number of messages to save. Older messages are deleted when the limit is reached. 0 means there is no limit"
+ },
+
+ imagesLimit: {
+ default: 100,
+ type: OptionType.NUMBER,
+ description: "Maximum number of images to save. Older images are deleted when the limit is reached. 0 means there is no limit"
+ },
+
+ cacheLimit: {
+ default: 1000,
+ type: OptionType.NUMBER,
+ description: "Maximum number of messages to store in the cache. Older messages are deleted when the limit is reached. This helps reduce memory usage and improve performance. 0 means there is no limit",
+ },
+
+ whitelistedIds: {
+ default: "",
+ type: OptionType.STRING,
+ description: "Whitelisted server, channel, or user IDs."
+ },
+
+ blacklistedIds: {
+ default: "",
+ type: OptionType.STRING,
+ description: "Blacklisted server, channel, or user IDs."
+ },
+
+ imageCacheDir: {
+ type: OptionType.COMPONENT,
+ description: "Select saved images directory",
+ component: ErrorBoundary.wrap(ImageCacheDir) as any
+ },
+
+ logsDir: {
+ type: OptionType.COMPONENT,
+ description: "Select logs directory",
+ component: ErrorBoundary.wrap(LogsDir) as any
+ },
+
+ exportLogs: {
+ type: OptionType.COMPONENT,
+ description: "Export Logs From IndexedDB",
+ component: () =>
+
+ Export Logs
+
+ },
+ openLogs: {
+ type: OptionType.COMPONENT,
+ description: "Open Logs",
+ component: () =>
+ openLogModal()}>
+ Open Logs
+
+ },
+ openImageCacheFolder: {
+ type: OptionType.COMPONENT,
+ description: "Opens the image cache directory",
+ component: () =>
+ Native.showItemInFolder(settings.store.imageCacheDir)}
+ >
+ Open Image Cache Folder
+
+ },
+
+ clearLogs: {
+ type: OptionType.COMPONENT,
+ description: "Clear Logs",
+ component: () =>
+ Alerts.show({
+ title: "Clear Logs",
+ body: "Are you sure you want to clear all logs?",
+ confirmColor: Button.Colors.RED,
+ confirmText: "Clear",
+ cancelText: "Cancel",
+ onConfirm: () => {
+ LoggedMessageManager.clearLogs();
+ },
+ })}
+ >
+ Clear Logs
+
+ },
+
+});
+
+const idFunctions = {
+ Server: props => props?.guild?.id,
+ User: props => props?.message?.author?.id || props?.user?.id,
+ Channel: props => props.message?.channel_id || props.channel?.id
+} as const;
+
+type idKeys = keyof typeof idFunctions;
+
+function renderListOption(listType: ListType, IdType: idKeys, props: any) {
+ const id = idFunctions[IdType](props);
+ if (!id) return null;
+
+ const isBlocked = settings.store[listType].includes(id);
+ const oppositeListType = listType === "blacklistedIds" ? "whitelistedIds" : "blacklistedIds";
+ const isOppositeBlocked = settings.store[oppositeListType].includes(id);
+ const list = listType === "blacklistedIds" ? "Blacklist" : "Whitelist";
+
+ const addToList = () => addToXAndRemoveFromOpposite(listType, id);
+ const removeFromList = () => removeFromX(listType, id);
+
+ return (
+
+ );
+}
+
+function renderOpenLogs(idType: idKeys, props: any) {
+ const id = idFunctions[idType](props);
+ if (!id) return null;
+
+ return (
+ openLogModal(`${idType.toLowerCase()}:${id}`)}
+ />
+ );
+}
+
+const contextMenuPath: NavContextMenuPatchCallback = (children, props) => {
+ if (!props) return;
+
+ if (!children.some(child => child?.props?.id === "message-logger")) {
+ children.push(
+ ,
+
+
+ openLogModal()}
+ />
+
+ {Object.keys(idFunctions).map(IdType => renderOpenLogs(IdType as idKeys, props))}
+
+
+
+ {Object.keys(idFunctions).map(IdType => (
+
+ {renderListOption("blacklistedIds", IdType as idKeys, props)}
+ {renderListOption("whitelistedIds", IdType as idKeys, props)}
+
+ ))}
+
+ {
+ props.navId === "message"
+ && (props.message?.deleted || props.message?.editHistory?.length > 0)
+ && (
+ <>
+
+
+ removeLog(props.message.id)
+ .then(() => {
+ if (props.message.deleted) {
+ FluxDispatcher.dispatch({
+ type: "MESSAGE_DELETE",
+ channelId: props.message.channel_id,
+ id: props.message.id,
+ mlDeleted: true
+ });
+ } else {
+ props.message.editHistory = [];
+ }
+ }).catch(() => Toasts.show({
+ type: Toasts.Type.FAILURE,
+ message: "Failed to remove message",
+ id: Toasts.genId()
+ }))
+
+ }
+ />
+ >
+ )
+ }
+
+ {
+ settings.store.hideMessageFromMessageLoggers
+ && props.navId === "message"
+ && props.message?.author?.id === UserStore.getCurrentUser().id
+ && props.message?.deleted === false
+ && (
+ <>
+
+ {
+ await MessageActions.deleteMessage(props.message.channel_id, props.message.id);
+ MessageActions._sendMessage(props.message.channel_id, {
+ "content": settings.store.hideMessageFromMessageLoggersDeletedMessage,
+ "tts": false,
+ "invalidEmojis": [],
+ "validNonShortcutEmojis": []
+ }, { nonce: props.message.id });
+ }}
+
+ />
+ >
+ )
+ }
+
+
+ );
+ }
+};
+
export default definePlugin({
name: "MessageLoggerEnhanced",
authors: [Devs.Aria],
- description: "G'day",
+ description: "logs messages, images, and ghost pings",
dependencies: ["MessageLogger"],
-
+ contextMenus: {
+ "message": contextMenuPath,
+ "channel-context": contextMenuPath,
+ "user-context": contextMenuPath,
+ "guild-context": contextMenuPath,
+ "gdm-context": contextMenuPath
+ },
patches: [
{
- find: "_tryFetchMessagesCached",
- replacement: [
- {
- match: /(?<=\.get\({url.+?then\()(\i)=>\(/,
- replace: "async $1=>(await $self.processMessageFetch($1),"
- },
- {
- match: /(?<=type:"LOAD_MESSAGES_SUCCESS",.{1,100})messages:(\i)/,
- replace: "get messages() {return $self.coolReAddDeletedMessages($1, this);}"
- }
-
- ]
+ find: '"MessageStore"',
+ replacement: {
+ match: /(getOrCreate\(\i\);)(\i=\i\.loadComplete.*?}\),)/,
+ replace: "$1$self.messageLoadSuccess(arguments[0]);$2"
+ }
},
{
find: "THREAD_STARTER_MESSAGE?null===",
replacement: {
- match: / deleted:\i\.deleted, editHistory:\i\.editHistory,/,
- replace: "deleted:$self.getDeleted(...arguments), editHistory:$self.getEdited(...arguments),"
+ match: /interactionData:null!=.{0,50}.interaction_data/,
+ replace: "deleted:$self.getDeleted(...arguments), editHistory:$self.getEdited(...arguments)"
}
},
+
{
find: "toolbar:function",
predicate: () => settings.store.ShowLogsButton,
@@ -277,15 +609,20 @@ export default definePlugin({
}
},
- // https://regex101.com/r/S3IVGm/1
- // fix vidoes failing because there are no thumbnails
+ // https://regex101.com/r/TMV1vY/1
{
- find: ".handleImageLoad)",
+ find: ".removeMosaicItemHoverButton",
replacement: {
- match: /(componentDidMount\(\){)(.{1,150}===(.+?)\.LOADING)/,
- replace:
- "$1if(this.props?.src?.startsWith('blob:') && this.props?.item?.type === 'VIDEO')" +
- "return this.setState({readyState: $3.READY});$2"
+ match: /(\i=(\i)=>{)(.+?isSingleMosaicItem)/,
+ replace: "$1 let forceUpdate=Vencord.Util.useForceUpdater();$self.patchAttachments($2,forceUpdate);$3"
+ }
+ },
+
+ {
+ find: "handleImageLoad)",
+ replacement: {
+ match: /(render\(\){)(.{1,100}zoomThumbnailPlaceholder)/,
+ replace: "$1$self.checkImage(this);$2"
}
},
@@ -331,29 +668,15 @@ export default definePlugin({
];
},
- processMessageFetch,
+ messageLoadSuccess,
+ store: MessageLoggerStore,
openLogModal,
doesMatch,
- reAddDeletedMessages,
LoggedMessageManager,
ImageManager,
imageUtils,
- idb,
- coolReAddDeletedMessages: (messages: LoggedMessageJSON[] & { extra: LoggedMessageJSON[]; }, payload: LoadMessagePayload) => {
- try {
- if (messages.extra)
- reAddDeletedMessages(messages, messages.extra, !payload.hasMoreAfter && !payload.isBefore, !payload.hasMoreBefore && !payload.isAfter);
- }
- catch (e) {
- Flogger.error("Failed to re-add deleted messages", e);
- }
- finally {
- return messages;
- }
- },
-
- isDeletedMessage: (id: string) => cacheSentMessages.get(id)?.deleted ?? false,
+ isDeletedMessage: (id: string) => loggedMessages.deletedMessages[id] != null,
getDeleted(m1, m2) {
const deleted = m2?.deleted;
@@ -364,12 +687,53 @@ export default definePlugin({
getEdited(m1, m2) {
const editHistory = m2?.editHistory;
if (editHistory == null && m1?.editHistory != null && m1.editHistory.length > 0)
- return m1.editHistory.map(mapTimestamp);
+ return m1.editHistory.map(mapEditHistory);
return editHistory;
},
+ attachments: new Map(),
+ patchAttachments(props: { attachment: LoggedAttachment, message: LoggedMessage; }, forceUpdate: () => void) {
+ const { attachment, message } = props;
+ if (!message?.deleted || !LoggedMessageManager.hasMessageInLogs(message.id))
+ return; // Flogger.log("ignoring", message.id);
+
+ if (this.attachments.has(attachment.id))
+ return props.attachment = this.attachments.get(attachment.id)!; // Flogger.log("blobUrl already exists");
+
+ imageUtils.getAttachmentBlobUrl(attachment).then((blobUrl: string | null) => {
+ if (blobUrl == null) {
+ Flogger.error("image not found. for message.id =", message.id, blobUrl);
+ return;
+ }
+ Flogger.log("Got blob url for message.id =", message.id, blobUrl);
+ // we need to copy because changing this will change the attachment for the message in the logs
+ const attachmentCopy = { ...attachment };
+
+ attachmentCopy.oldUrl = attachment.url;
+
+ const finalBlobUrl = blobUrl + "#";
+ attachmentCopy.blobUrl = finalBlobUrl;
+ attachmentCopy.url = finalBlobUrl;
+ attachmentCopy.proxy_url = finalBlobUrl;
+ this.attachments.set(attachment.id, attachmentCopy);
+ forceUpdate();
+ });
+
+ },
+
+ async checkImage(instance: any) {
+ if (!instance.props.isBad && instance.state?.readyState !== "READY" && instance.props?.src?.startsWith("blob:")) {
+ if (await doesBlobUrlExist(instance.props.src)) {
+ Flogger.log("image exists", instance.props.src);
+ return instance.setState(e => ({ ...e, readyState: "READY" }));
+ }
+
+ instance.props.isBad = true;
+ }
+ },
+
flux: {
- "MESSAGE_DELETE": messageDeleteHandler as any,
+ "MESSAGE_DELETE": messageDeleteHandler,
"MESSAGE_DELETE_BULK": messageDeleteBulkHandler,
"MESSAGE_UPDATE": messageUpdateHandler,
"MESSAGE_CREATE": messageCreateHandler
@@ -377,11 +741,10 @@ export default definePlugin({
async start() {
this.oldGetMessage = oldGetMessage = MessageStore.getMessage;
-
// we have to do this because the original message logger fetches the message from the store now
MessageStore.getMessage = (channelId: string, messageId: string) => {
- const MLMessage = idb.cachedMessages.get(messageId);
- if (MLMessage) return messageJsonToMessageClass({ message: MLMessage });
+ const MLMessage = LoggedMessageManager.getMessage(channelId, messageId);
+ if (MLMessage?.message) return messageJsonToMessageClass(MLMessage);
return this.oldGetMessage(channelId, messageId);
};
@@ -391,13 +754,9 @@ export default definePlugin({
const { imageCacheDir, logsDir } = await Native.getSettings();
settings.store.imageCacheDir = imageCacheDir;
settings.store.logsDir = logsDir;
-
- setupContextMenuPatches();
},
stop() {
- removeContextMenuBindings();
MessageStore.getMessage = this.oldGetMessage;
}
});
-
diff --git a/src/equicordplugins/messageLoggerEnhanced/native/index.ts b/src/equicordplugins/messageLoggerEnhanced/native/index.ts
index 5b4d310f..ce7291cf 100644
--- a/src/equicordplugins/messageLoggerEnhanced/native/index.ts
+++ b/src/equicordplugins/messageLoggerEnhanced/native/index.ts
@@ -7,15 +7,12 @@
import { readdir, readFile, unlink, writeFile } from "node:fs/promises";
import path from "node:path";
-import { DATA_DIR } from "@main/utils/constants";
+import { Queue } from "@utils/Queue";
import { dialog, IpcMainInvokeEvent, shell } from "electron";
+import { DATA_DIR } from "../../../main/utils/constants";
import { getSettings, saveSettings } from "./settings";
-export * from "./updater";
-
-import { LoggedAttachment } from "../types";
-import { LOGS_DATA_FILENAME } from "../utils/constants";
-import { ensureDirectoryExists, getAttachmentIdFromFilename, sleep } from "./utils";
+import { ensureDirectoryExists, getAttachmentIdFromFilename } from "./utils";
export { getSettings };
@@ -56,13 +53,7 @@ export async function init(_event: IpcMainInvokeEvent) {
export async function getImageNative(_event: IpcMainInvokeEvent, attachmentId: string): Promise {
const imagePath = nativeSavedImages.get(attachmentId);
if (!imagePath) return null;
-
- try {
- return await readFile(imagePath);
- } catch (error: any) {
- console.error(error);
- return null;
- }
+ return await readFile(imagePath);
}
export async function writeImageNative(_event: IpcMainInvokeEvent, filename: string, content: Uint8Array) {
@@ -90,11 +81,24 @@ export async function deleteFileNative(_event: IpcMainInvokeEvent, attachmentId:
await unlink(imagePath);
}
+const LOGS_DATA_FILENAME = "message-logger-logs.json";
+const dataWriteQueue = new Queue();
+
+export async function getLogsFromFs(_event: IpcMainInvokeEvent) {
+ const logsDir = await getLogsDir();
+
+ await ensureDirectoryExists(logsDir);
+ try {
+ return JSON.parse(await readFile(path.join(logsDir, LOGS_DATA_FILENAME), "utf-8"));
+ } catch { }
+
+ return null;
+}
export async function writeLogs(_event: IpcMainInvokeEvent, contents: string) {
const logsDir = await getLogsDir();
- writeFile(path.join(logsDir, LOGS_DATA_FILENAME), contents);
+ dataWriteQueue.push(() => writeFile(path.join(logsDir, LOGS_DATA_FILENAME), contents));
}
@@ -133,68 +137,3 @@ export async function chooseDir(event: IpcMainInvokeEvent, logKey: "logsDir" | "
export async function showItemInFolder(_event: IpcMainInvokeEvent, filePath: string) {
shell.showItemInFolder(filePath);
}
-
-export async function chooseFile(_event: IpcMainInvokeEvent, title: string, filters: Electron.FileFilter[], defaultPath?: string) {
- const res = await dialog.showOpenDialog({ title, filters, properties: ["openFile"], defaultPath });
- const [path] = res.filePaths;
-
- if (!path) throw Error("Invalid file");
-
- return await readFile(path, "utf-8");
-}
-
-// doing it in native because you can only fetch images from the renderer
-// other types of files will cause cors issues
-export async function downloadAttachment(_event: IpcMainInvokeEvent, attachemnt: LoggedAttachment, attempts = 0, useOldUrl = false): Promise<{ error: string | null; path: string | null; }> {
- try {
- if (!attachemnt?.url || !attachemnt.oldUrl || !attachemnt?.id || !attachemnt?.fileExtension)
- return { error: "Invalid Attachment", path: null };
-
- if (attachemnt.id.match(/[\\/.]/)) {
- return { error: "Invalid Attachment ID", path: null };
- }
-
- const existingImage = nativeSavedImages.get(attachemnt.id);
- if (existingImage)
- return {
- error: null,
- path: existingImage
- };
-
- const res = await fetch(useOldUrl ? attachemnt.oldUrl : attachemnt.url);
-
- if (res.status !== 200) {
- if (res.status === 404 || res.status === 403)
- return { error: `Failed to get attachment ${attachemnt.id} for caching, error code ${res.status}`, path: null };
-
- attempts++;
- if (attempts > 3) {
- return {
- error: `Failed to get attachment ${attachemnt.id} for caching. too many attempts, error code ${res.status}`,
- path: null,
- };
- }
-
- await sleep(1000);
- return downloadAttachment(_event, attachemnt, attempts, res.status === 415);
- }
-
- const ab = await res.arrayBuffer();
- const imageCacheDir = await getImageCacheDir();
- await ensureDirectoryExists(imageCacheDir);
-
- const finalPath = path.join(imageCacheDir, `${attachemnt.id}${attachemnt.fileExtension}`);
- await writeFile(finalPath, Buffer.from(ab));
-
- nativeSavedImages.set(attachemnt.id, finalPath);
-
- return {
- error: null,
- path: finalPath
- };
-
- } catch (error: any) {
- console.error(error);
- return { error: error.message, path: null };
- }
-}
diff --git a/src/equicordplugins/messageLoggerEnhanced/native/settings.ts b/src/equicordplugins/messageLoggerEnhanced/native/settings.ts
index f8798983..df541844 100644
--- a/src/equicordplugins/messageLoggerEnhanced/native/settings.ts
+++ b/src/equicordplugins/messageLoggerEnhanced/native/settings.ts
@@ -47,4 +47,3 @@ async function getSettingsFilePath() {
return mlSettingsDir;
}
-
diff --git a/src/equicordplugins/messageLoggerEnhanced/native/updater.ts b/src/equicordplugins/messageLoggerEnhanced/native/updater.ts
deleted file mode 100644
index 9055fc96..00000000
--- a/src/equicordplugins/messageLoggerEnhanced/native/updater.ts
+++ /dev/null
@@ -1,134 +0,0 @@
-/*
- * Vencord, a Discord client mod
- * Copyright (c) 2024 Vendicated and contributors
- * SPDX-License-Identifier: GPL-3.0-or-later
- */
-
-import { execFile as cpExecFile, ExecFileOptions } from "node:child_process";
-
-import { readdir } from "fs/promises";
-import { join } from "path";
-import { promisify } from "util";
-
-import type { GitResult } from "../types";
-import { memoize } from "../utils/memoize";
-
-const execFile = promisify(cpExecFile);
-
-const isFlatpak = process.platform === "linux" && Boolean(process.env.FLATPAK_ID?.includes("discordapp") || process.env.FLATPAK_ID?.includes("Discord"));
-if (process.platform === "darwin") process.env.PATH = `/usr/local/bin:${process.env.PATH}`;
-
-
-const VENCORD_USER_PLUGIN_DIR = join(__dirname, "..", "src", "userplugins");
-const getCwd = memoize(async () => {
- const dirs = await readdir(VENCORD_USER_PLUGIN_DIR, { withFileTypes: true });
-
- for (const dir of dirs) {
- if (!dir.isDirectory()) continue;
-
- const pluginDir = join(VENCORD_USER_PLUGIN_DIR, dir.name);
- const files = await readdir(pluginDir);
-
- if (files.includes("LoggedMessageManager.ts")) return join(VENCORD_USER_PLUGIN_DIR, dir.name);
- }
-
- return;
-});
-
-async function git(...args: string[]): Promise {
- const opts: ExecFileOptions = { cwd: await getCwd(), shell: true };
-
- try {
- let result;
- if (isFlatpak) {
- result = await execFile("flatpak-spawn", ["--host", "git", ...args], opts);
- } else {
- result = await execFile("git", args, opts);
- }
-
- return { value: result.stdout.trim(), stderr: result.stderr, ok: true };
- } catch (error: any) {
- return {
- ok: false,
- cmd: error.cmd as string,
- message: error.stderr as string,
- error
- };
- }
-}
-
-export async function update() {
- return await git("pull");
-}
-
-export async function getCommitHash() {
- return await git("rev-parse", "HEAD");
-}
-
-export interface GitInfo {
- repo: string;
- gitHash: string;
-}
-
-export async function getRepoInfo(): Promise {
- const res = await git("remote", "get-url", "origin");
- if (!res.ok) {
- return res;
- }
-
- const gitHash = await getCommitHash();
- if (!gitHash.ok) {
- return gitHash;
- }
-
- return {
- ok: true,
- value: {
- repo: res.value
- .replace(/git@(.+):/, "https://$1/")
- .replace(/\.git$/, ""),
- gitHash: gitHash.value
- }
- };
-}
-
-export interface Commit {
- hash: string;
- longHash: string;
- message: string;
- author: string;
-}
-
-export async function getNewCommits(): Promise {
- const branch = await git("branch", "--show-current");
- if (!branch.ok) {
- return branch;
- }
-
- const logFormat = "%H;%an;%s";
- const branchRange = `HEAD..origin/${branch.value}`;
-
- try {
- await git("fetch");
-
- const logOutput = await git("log", `--format="${logFormat}"`, branchRange);
-
- if (!logOutput.ok) {
- return logOutput;
- }
-
- if (logOutput.value.trim() === "") {
- return { ok: true, value: [] };
- }
-
- const commitLines = logOutput.value.trim().split("\n");
- const commits: Commit[] = commitLines.map(line => {
- const [hash, author, ...rest] = line.split(";");
- return { longHash: hash, hash: hash.slice(0, 7), author, message: rest.join(";") } satisfies Commit;
- });
-
- return { ok: true, value: commits };
- } catch (error: any) {
- return { ok: false, cmd: error.cmd, message: error.message, error };
- }
-}
diff --git a/src/equicordplugins/messageLoggerEnhanced/native/utils.ts b/src/equicordplugins/messageLoggerEnhanced/native/utils.ts
index 691747f0..d54462cd 100644
--- a/src/equicordplugins/messageLoggerEnhanced/native/utils.ts
+++ b/src/equicordplugins/messageLoggerEnhanced/native/utils.ts
@@ -24,5 +24,3 @@ export async function ensureDirectoryExists(cacheDir: string) {
export function getAttachmentIdFromFilename(filename: string) {
return path.parse(filename).name;
}
-
-export const sleep = (ms: number) => new Promise(resolve => setTimeout(resolve, ms));
diff --git a/src/equicordplugins/messageLoggerEnhanced/settings.tsx b/src/equicordplugins/messageLoggerEnhanced/settings.tsx
deleted file mode 100644
index 7479fa6b..00000000
--- a/src/equicordplugins/messageLoggerEnhanced/settings.tsx
+++ /dev/null
@@ -1,242 +0,0 @@
-/*
- * Vencord, a Discord client mod
- * Copyright (c) 2024 Vendicated and contributors
- * SPDX-License-Identifier: GPL-3.0-or-later
- */
-
-import { definePluginSettings } from "@api/Settings";
-import ErrorBoundary from "@components/ErrorBoundary";
-import { OptionType } from "@utils/types";
-import { Alerts, Button } from "@webpack/common";
-import { Settings } from "Vencord";
-
-import { Native } from ".";
-import { ImageCacheDir, LogsDir } from "./components/FolderSelectInput";
-import { openLogModal } from "./components/LogsModal";
-import { clearMessagesIDB } from "./db";
-import { DEFAULT_IMAGE_CACHE_DIR } from "./utils/constants";
-import { exportLogs, importLogs } from "./utils/settingsUtils";
-
-export const settings = definePluginSettings({
- saveMessages: {
- default: true,
- type: OptionType.BOOLEAN,
- description: "Wether to save the deleted and edited messages.",
- },
-
- saveImages: {
- type: OptionType.BOOLEAN,
- description: "Save deleted attachments.",
- default: false
- },
-
- sortNewest: {
- default: true,
- type: OptionType.BOOLEAN,
- description: "Sort logs by newest.",
- },
-
- cacheMessagesFromServers: {
- default: false,
- type: OptionType.BOOLEAN,
- description: "Usually message logger only logs from whitelisted ids and dms, enabling this would mean it would log messages from all servers as well. Note that this may cause the cache to exceed its limit, resulting in some messages being missed. If you are in a lot of servers, this may significantly increase the chances of messages being logged, which can result in a large message record and the inclusion of irrelevant messages.",
- },
-
- autoCheckForUpdates: {
- default: true,
- type: OptionType.BOOLEAN,
- description: "Automatically check for updates on startup.",
- },
-
- ignoreBots: {
- type: OptionType.BOOLEAN,
- description: "Whether to ignore messages by bots",
- default: false,
- onChange() {
- // we will be handling the ignoreBots now (enabled or not) so the original messageLogger shouldnt
- Settings.plugins.MessageLogger.ignoreBots = false;
- }
- },
-
- ignoreSelf: {
- type: OptionType.BOOLEAN,
- description: "Whether to ignore messages by yourself",
- default: false,
- onChange() {
- Settings.plugins.MessageLogger.ignoreSelf = false;
- }
- },
-
- ignoreMutedGuilds: {
- default: false,
- type: OptionType.BOOLEAN,
- description: "Messages in muted guilds will not be logged. Whitelisted users/channels in muted guilds will still be logged."
- },
-
- ignoreMutedCategories: {
- default: false,
- type: OptionType.BOOLEAN,
- description: "Messages in channels belonging to muted categories will not be logged. Whitelisted users/channels in muted guilds will still be logged."
- },
-
- ignoreMutedChannels: {
- default: false,
- type: OptionType.BOOLEAN,
- description: "Messages in muted channels will not be logged. Whitelisted users/channels in muted guilds will still be logged."
- },
-
- alwaysLogDirectMessages: {
- default: true,
- type: OptionType.BOOLEAN,
- description: "Always log DMs",
- },
-
- alwaysLogCurrentChannel: {
- default: true,
- type: OptionType.BOOLEAN,
- description: "Always log current selected channel. Blacklisted channels/users will still be ignored.",
- },
-
- permanentlyRemoveLogByDefault: {
- default: false,
- type: OptionType.BOOLEAN,
- description: "Vencord's base MessageLogger remove log button wiil delete logs permanently",
- },
-
- hideMessageFromMessageLoggers: {
- default: false,
- type: OptionType.BOOLEAN,
- description: "When enabled, a context menu button will be added to messages to allow you to delete messages without them being logged by other loggers. Might not be safe, use at your own risk."
- },
-
- ShowLogsButton: {
- default: true,
- type: OptionType.BOOLEAN,
- description: "Toggle to whenever show the toolbox or not",
- restartNeeded: true,
- },
-
- messagesToDisplayAtOnceInLogs: {
- default: 100,
- type: OptionType.NUMBER,
- description: "Number of messages to display at once in logs & number of messages to load when loading more messages in logs.",
- },
-
- hideMessageFromMessageLoggersDeletedMessage: {
- default: "redacted eh",
- type: OptionType.STRING,
- description: "The message content to replace the message with when using the hide message from message loggers feature.",
- },
-
- messageLimit: {
- default: 200,
- type: OptionType.NUMBER,
- description: "Maximum number of messages to save. Older messages are deleted when the limit is reached. 0 means there is no limit"
- },
-
- attachmentSizeLimitInMegabytes: {
- default: 12,
- type: OptionType.NUMBER,
- description: "Maximum size of an attachment in megabytes to save. Attachments larger than this size will not be saved."
- },
-
- attachmentFileExtensions: {
- default: "png,jpg,jpeg,gif,webp,mp4,webm,mp3,ogg,wav",
- type: OptionType.STRING,
- description: "Comma separated list of file extensions to save. Attachments with file extensions not in this list will not be saved. Leave empty to save all attachments."
- },
-
- cacheLimit: {
- default: 1000,
- type: OptionType.NUMBER,
- description: "Maximum number of messages to store in the cache. Older messages are deleted when the limit is reached. This helps reduce memory usage and improve performance. 0 means there is no limit",
- },
-
- whitelistedIds: {
- default: "",
- type: OptionType.STRING,
- description: "Whitelisted server, channel, or user IDs."
- },
-
- blacklistedIds: {
- default: "",
- type: OptionType.STRING,
- description: "Blacklisted server, channel, or user IDs."
- },
-
- imageCacheDir: {
- type: OptionType.COMPONENT,
- description: "Select saved images directory",
- component: ErrorBoundary.wrap(ImageCacheDir) as any
- },
-
- logsDir: {
- type: OptionType.COMPONENT,
- description: "Select logs directory",
- component: ErrorBoundary.wrap(LogsDir) as any
- },
-
- importLogs: {
- type: OptionType.COMPONENT,
- description: "Import Logs From File",
- component: () =>
-
- Import Logs
-
- },
-
- exportLogs: {
- type: OptionType.COMPONENT,
- description: "Export Logs From IndexedDB",
- component: () =>
-
- Export Logs
-
- },
-
- openLogs: {
- type: OptionType.COMPONENT,
- description: "Open Logs",
- component: () =>
- openLogModal()}>
- Open Logs
-
- },
- openImageCacheFolder: {
- type: OptionType.COMPONENT,
- description: "Opens the image cache directory",
- component: () =>
- Native.showItemInFolder(settings.store.imageCacheDir)}
- >
- Open Image Cache Folder
-
- },
-
- clearLogs: {
- type: OptionType.COMPONENT,
- description: "Clear Logs",
- component: () =>
- Alerts.show({
- title: "Clear Logs",
- body: "Are you sure you want to clear all logs?",
- confirmColor: Button.Colors.RED,
- confirmText: "Clear",
- cancelText: "Cancel",
- onConfirm: () => {
- clearMessagesIDB();
- },
- })}
- >
- Clear Logs
-
- },
-
-});
diff --git a/src/equicordplugins/messageLoggerEnhanced/styles.css b/src/equicordplugins/messageLoggerEnhanced/styles.css
index 97d1cada..3b5987b4 100644
--- a/src/equicordplugins/messageLoggerEnhanced/styles.css
+++ b/src/equicordplugins/messageLoggerEnhanced/styles.css
@@ -11,14 +11,6 @@
height: 100%;
}
-.msg-logger-modal-info-icon {
- position: absolute;
- top: -24px;
- right: -24px;
- color: var(--interactive-normal);
- cursor: pointer;
-}
-
.msg-logger-modal-header {
flex-direction: column;
@@ -43,11 +35,12 @@
height: 100%;
}
-.msg-logger-modal-header > div:has(input) {
+.msg-logger-modal-header>div:has(input) {
width: 100%;
}
.msg-logger-modal-tab-bar-item {
+ margin-right: 32px;
padding-bottom: 16px;
margin-bottom: -2px;
}
@@ -62,7 +55,7 @@
color: var(--interactive-normal);
}
-:is(.vc-log-toolbox-btn:hover, .vc-log-toolbox-btn[class*="selected"]) svg {
+:is(.vc-log-toolbox-btn:hover, .vc-log-toolbox-btn[class*='selected']) svg {
color: var(--interactive-active);
}
@@ -83,3 +76,31 @@
margin: 6px;
padding: 4px 8px;
}
+
+.vc-updater-modal-content {
+ padding: 1rem 2rem;
+}
+
+div[class*="messagelogger-deleted"] [class*="contents"] > :is(div, h1, h2, h3, p) {
+ color: var(--text-normal) !important;
+}
+
+/* Markdown title highlighting */
+div[class*="messagelogger-deleted"] [class*="contents"] :is(h1, h2, h3) {
+ color: var(--text-normal) !important;
+}
+
+/* Bot "thinking" text highlighting */
+div[class*="messagelogger-deleted"] [class*="colorStandard"] {
+ color: var(--text-normal) !important;
+}
+
+/* Embed highlighting */
+div[class*="messagelogger-deleted"] article :is(div, span, h1, h2, h3, p) {
+ color: var(--text-normal) !important;
+}
+
+div[class*="messagelogger-deleted"] a {
+ color: var(--text-link) !important;
+ text-decoration: underline;
+}
diff --git a/src/equicordplugins/messageLoggerEnhanced/types.ts b/src/equicordplugins/messageLoggerEnhanced/types.ts
index 371c48b2..eeed3af8 100644
--- a/src/equicordplugins/messageLoggerEnhanced/types.ts
+++ b/src/equicordplugins/messageLoggerEnhanced/types.ts
@@ -24,7 +24,6 @@ export interface LoggedAttachment extends MessageAttachment {
blobUrl?: string;
nativefileSystem?: boolean;
oldUrl?: string;
- oldProxyUrl?: string;
}
export type RefrencedMessage = LoggedMessageJSON & { message_id: string; };
@@ -92,27 +91,6 @@ export interface LoadMessagePayload {
isStale: boolean;
}
-export interface FetchMessagesResponse {
- ok: boolean;
- headers: Headers;
- body: LoggedMessageJSON[] & {
- extra?: LoggedMessageJSON[];
- };
- text: string;
- status: number;
-}
-
-export interface PatchAttachmentItem {
- uniqueId: string;
- originalItem: LoggedAttachment;
- type: string;
- downloadUrl: string;
- height: number;
- width: number;
- spoiler: boolean;
- contentType: string;
-}
-
export interface AttachmentData {
messageId: string;
attachmentId: string;
diff --git a/src/equicordplugins/messageLoggerEnhanced/utils/LimitedMap.ts b/src/equicordplugins/messageLoggerEnhanced/utils/LimitedMap.ts
index 38ee9e09..f8f2aa48 100644
--- a/src/equicordplugins/messageLoggerEnhanced/utils/LimitedMap.ts
+++ b/src/equicordplugins/messageLoggerEnhanced/utils/LimitedMap.ts
@@ -25,7 +25,10 @@ export class LimitedMap {
set(key: K, value: V) {
if (settings.store.cacheLimit > 0 && this.map.size >= settings.store.cacheLimit) {
// delete the first entry
- this.map.delete(this.map.keys().next().value);
+ const firstKey = this.map.keys().next().value;
+ if (firstKey !== undefined) {
+ this.map.delete(firstKey);
+ }
}
this.map.set(key, value);
}
diff --git a/src/equicordplugins/messageLoggerEnhanced/utils/cleanUp.ts b/src/equicordplugins/messageLoggerEnhanced/utils/cleanUp.ts
index 7f47ff36..13e5a112 100644
--- a/src/equicordplugins/messageLoggerEnhanced/utils/cleanUp.ts
+++ b/src/equicordplugins/messageLoggerEnhanced/utils/cleanUp.ts
@@ -33,7 +33,7 @@ export function cleanupMessage(message: any, removeDetails: boolean = true): Log
ret.guildId = ret.guild_id ?? getGuildIdByChannel(ret.channel_id);
ret.embeds = (ret.embeds ?? []).map(cleanupEmbed);
ret.deleted = ret.deleted ?? false;
- ret.deletedTimestamp = ret.deleted ? (new Date()).toISOString() : undefined;
+ ret.deletedTimestamp = ret.deleted ? new Date().toISOString() : undefined;
ret.editHistory = ret.editHistory ?? [];
if (ret.type === 19) {
ret.message_reference = message.message_reference || message.messageReference;
diff --git a/src/equicordplugins/messageLoggerEnhanced/utils/constants.ts b/src/equicordplugins/messageLoggerEnhanced/utils/constants.ts
index 7fe6a219..1d217ec0 100644
--- a/src/equicordplugins/messageLoggerEnhanced/utils/constants.ts
+++ b/src/equicordplugins/messageLoggerEnhanced/utils/constants.ts
@@ -17,7 +17,3 @@
*/
export const DEFAULT_IMAGE_CACHE_DIR = "savedImages";
-
-export const DB_NAME = "MessageLoggerIDB";
-export const DB_VERSION = 1;
-export const LOGS_DATA_FILENAME = "message-logger-logs.json";
diff --git a/src/equicordplugins/messageLoggerEnhanced/utils/contextMenu.tsx b/src/equicordplugins/messageLoggerEnhanced/utils/contextMenu.tsx
deleted file mode 100644
index e33ea2b9..00000000
--- a/src/equicordplugins/messageLoggerEnhanced/utils/contextMenu.tsx
+++ /dev/null
@@ -1,171 +0,0 @@
-/*
- * Vencord, a Discord client mod
- * Copyright (c) 2024 Vendicated and contributors
- * SPDX-License-Identifier: GPL-3.0-or-later
- */
-
-import { addContextMenuPatch, NavContextMenuPatchCallback, removeContextMenuPatch } from "@api/ContextMenu";
-import { FluxDispatcher, Menu, MessageActions, React, Toasts, UserStore } from "@webpack/common";
-
-import { openLogModal } from "../components/LogsModal";
-import { deleteMessageIDB } from "../db";
-import { settings } from "../index";
-import { addToXAndRemoveFromOpposite, ListType, removeFromX } from ".";
-
-const idFunctions = {
- Server: props => props?.guild?.id,
- User: props => props?.message?.author?.id || props?.user?.id,
- Channel: props => props.message?.channel_id || props.channel?.id
-} as const;
-
-type idKeys = keyof typeof idFunctions;
-
-function renderListOption(listType: ListType, IdType: idKeys, props: any) {
- const id = idFunctions[IdType](props);
- if (!id) return null;
-
- const isBlocked = settings.store[listType].includes(id);
- const oppositeListType = listType === "blacklistedIds" ? "whitelistedIds" : "blacklistedIds";
- const isOppositeBlocked = settings.store[oppositeListType].includes(id);
- const list = listType === "blacklistedIds" ? "Blacklist" : "Whitelist";
-
- const addToList = () => addToXAndRemoveFromOpposite(listType, id);
- const removeFromList = () => removeFromX(listType, id);
-
- return (
-
- );
-}
-
-function renderOpenLogs(idType: idKeys, props: any) {
- const id = idFunctions[idType](props);
- if (!id) return null;
-
- return (
- openLogModal(`${idType.toLowerCase()}:${id}`)}
- />
- );
-}
-
-export const contextMenuPath: NavContextMenuPatchCallback = (children, props) => {
- if (!props) return;
-
- if (!children.some(child => child?.props?.id === "message-logger")) {
- children.push(
- ,
-
-
- openLogModal()}
- />
-
- {Object.keys(idFunctions).map(IdType => renderOpenLogs(IdType as idKeys, props))}
-
-
-
- {Object.keys(idFunctions).map(IdType => (
-
- {renderListOption("blacklistedIds", IdType as idKeys, props)}
- {renderListOption("whitelistedIds", IdType as idKeys, props)}
-
- ))}
-
- {
- props.navId === "message"
- && (props.message?.deleted || props.message?.editHistory?.length > 0)
- && (
- <>
-
-
- deleteMessageIDB(props.message.id)
- .then(() => {
- if (props.message.deleted) {
- FluxDispatcher.dispatch({
- type: "MESSAGE_DELETE",
- channelId: props.message.channel_id,
- id: props.message.id,
- mlDeleted: true
- });
- } else {
- props.message.editHistory = [];
- }
- }).catch(() => Toasts.show({
- type: Toasts.Type.FAILURE,
- message: "Failed to remove message",
- id: Toasts.genId()
- }))
-
- }
- />
- >
- )
- }
-
- {
- settings.store.hideMessageFromMessageLoggers
- && props.navId === "message"
- && props.message?.author?.id === UserStore.getCurrentUser().id
- && props.message?.deleted === false
- && (
- <>
-
- {
- await MessageActions.deleteMessage(props.message.channel_id, props.message.id);
- MessageActions._sendMessage(props.message.channel_id, {
- "content": settings.store.hideMessageFromMessageLoggersDeletedMessage,
- "tts": false,
- "invalidEmojis": [],
- "validNonShortcutEmojis": []
- }, { nonce: props.message.id });
- }}
-
- />
- >
- )
- }
-
-
- );
- }
-};
-
-export const setupContextMenuPatches = () => {
- addContextMenuPatch("message", contextMenuPath);
- addContextMenuPatch("channel-context", contextMenuPath);
- addContextMenuPatch("user-context", contextMenuPath);
- addContextMenuPatch("guild-context", contextMenuPath);
- addContextMenuPatch("gdm-context", contextMenuPath);
-};
-
-export const removeContextMenuBindings = () => {
- removeContextMenuPatch("message", contextMenuPath);
- removeContextMenuPatch("channel-context", contextMenuPath);
- removeContextMenuPatch("user-context", contextMenuPath);
- removeContextMenuPatch("guild-context", contextMenuPath);
- removeContextMenuPatch("gdm-context", contextMenuPath);
-};
diff --git a/src/equicordplugins/messageLoggerEnhanced/utils/freedom/importMeToPreload.ts b/src/equicordplugins/messageLoggerEnhanced/utils/freedom/importMeToPreload.ts
new file mode 100644
index 00000000..37fd6070
--- /dev/null
+++ b/src/equicordplugins/messageLoggerEnhanced/utils/freedom/importMeToPreload.ts
@@ -0,0 +1,19 @@
+/*
+ * 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 .
+*/
+
+//! hi this file is now usless. but ill keep it here just in case some people forgot to remove it from the preload.ts
diff --git a/src/equicordplugins/messageLoggerEnhanced/utils/idb/LICENSE b/src/equicordplugins/messageLoggerEnhanced/utils/idb/LICENSE
deleted file mode 100644
index f8b22cee..00000000
--- a/src/equicordplugins/messageLoggerEnhanced/utils/idb/LICENSE
+++ /dev/null
@@ -1,6 +0,0 @@
-ISC License (ISC)
-Copyright (c) 2016, Jake Archibald
-
-Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies.
-
-THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
diff --git a/src/equicordplugins/messageLoggerEnhanced/utils/idb/async-iterators.ts b/src/equicordplugins/messageLoggerEnhanced/utils/idb/async-iterators.ts
deleted file mode 100644
index 97709e37..00000000
--- a/src/equicordplugins/messageLoggerEnhanced/utils/idb/async-iterators.ts
+++ /dev/null
@@ -1,78 +0,0 @@
-/* eslint-disable simple-header/header */
-
-import { IDBPCursor, IDBPIndex, IDBPObjectStore } from "./entry.js";
-import { Func, instanceOfAny } from "./util.js";
-import { replaceTraps, reverseTransformCache, unwrap } from "./wrap-idb-value.js";
-
-const advanceMethodProps = ["continue", "continuePrimaryKey", "advance"];
-const methodMap: { [s: string]: Func; } = {};
-const advanceResults = new WeakMap>();
-const ittrProxiedCursorToOriginalProxy = new WeakMap();
-
-const cursorIteratorTraps: ProxyHandler = {
- get(target, prop) {
- if (!advanceMethodProps.includes(prop as string)) return target[prop];
-
- let cachedFunc = methodMap[prop as string];
-
- if (!cachedFunc) {
- cachedFunc = methodMap[prop as string] = function (
- this: IDBPCursor,
- ...args: any
- ) {
- advanceResults.set(
- this,
- (ittrProxiedCursorToOriginalProxy.get(this) as any)[prop](...args),
- );
- };
- }
-
- return cachedFunc;
- },
-};
-
-async function* iterate(
- this: IDBPObjectStore | IDBPIndex | IDBPCursor,
- ...args: any[]
-): AsyncIterableIterator {
- // tslint:disable-next-line:no-this-assignment
- let cursor: typeof this | null = this;
-
- if (!(cursor instanceof IDBCursor)) {
- cursor = await (cursor as IDBPObjectStore | IDBPIndex).openCursor(...args);
- }
-
- if (!cursor) return;
-
- cursor = cursor as IDBPCursor;
- const proxiedCursor = new Proxy(cursor, cursorIteratorTraps);
- ittrProxiedCursorToOriginalProxy.set(proxiedCursor, cursor);
- // Map this double-proxy back to the original, so other cursor methods work.
- reverseTransformCache.set(proxiedCursor, unwrap(cursor));
-
- while (cursor) {
- yield proxiedCursor;
- // If one of the advancing methods was not called, call continue().
- cursor = await (advanceResults.get(proxiedCursor) || cursor.continue());
- advanceResults.delete(proxiedCursor);
- }
-}
-
-function isIteratorProp(target: any, prop: number | string | symbol) {
- return (
- (prop === Symbol.asyncIterator &&
- instanceOfAny(target, [IDBIndex, IDBObjectStore, IDBCursor])) ||
- (prop === "iterate" && instanceOfAny(target, [IDBIndex, IDBObjectStore]))
- );
-}
-
-replaceTraps(oldTraps => ({
- ...oldTraps,
- get(target, prop, receiver) {
- if (isIteratorProp(target, prop)) return iterate;
- return oldTraps.get!(target, prop, receiver);
- },
- has(target, prop) {
- return isIteratorProp(target, prop) || oldTraps.has!(target, prop);
- },
-}));
diff --git a/src/equicordplugins/messageLoggerEnhanced/utils/idb/database-extras.ts b/src/equicordplugins/messageLoggerEnhanced/utils/idb/database-extras.ts
deleted file mode 100644
index 26e6a7e8..00000000
--- a/src/equicordplugins/messageLoggerEnhanced/utils/idb/database-extras.ts
+++ /dev/null
@@ -1,75 +0,0 @@
-/* eslint-disable simple-header/header */
-
-import { IDBPDatabase, IDBPIndex } from "./entry.js";
-import { Func } from "./util.js";
-import { replaceTraps } from "./wrap-idb-value.js";
-
-const readMethods = ["get", "getKey", "getAll", "getAllKeys", "count"];
-const writeMethods = ["put", "add", "delete", "clear"];
-const cachedMethods = new Map();
-
-function getMethod(
- target: any,
- prop: string | number | symbol,
-): Func | undefined {
- if (
- !(
- target instanceof IDBDatabase &&
- !(prop in target) &&
- typeof prop === "string"
- )
- ) {
- return;
- }
-
- if (cachedMethods.get(prop)) return cachedMethods.get(prop);
-
- const targetFuncName: string = prop.replace(/FromIndex$/, "");
- const useIndex = prop !== targetFuncName;
- const isWrite = writeMethods.includes(targetFuncName);
-
- if (
- // Bail if the target doesn't exist on the target. Eg, getAll isn't in Edge.
- !(targetFuncName in (useIndex ? IDBIndex : IDBObjectStore).prototype) ||
- !(isWrite || readMethods.includes(targetFuncName))
- ) {
- return;
- }
-
- const method = async function (
- this: IDBPDatabase,
- storeName: string,
- ...args: any[]
- ) {
- // isWrite ? 'readwrite' : undefined gzipps better, but fails in Edge :(
- const tx = this.transaction(storeName, isWrite ? "readwrite" : "readonly");
- let target:
- | typeof tx.store
- | IDBPIndex =
- tx.store;
- if (useIndex) target = target.index(args.shift());
-
- // Must reject if op rejects.
- // If it's a write operation, must reject if tx.done rejects.
- // Must reject with op rejection first.
- // Must resolve with op value.
- // Must handle both promises (no unhandled rejections)
- return (
- await Promise.all([
- (target as any)[targetFuncName](...args),
- isWrite && tx.done,
- ])
- )[0];
- };
-
- cachedMethods.set(prop, method);
- return method;
-}
-
-replaceTraps(oldTraps => ({
- ...oldTraps,
- get: (target, prop, receiver) =>
- getMethod(target, prop) || oldTraps.get!(target, prop, receiver),
- has: (target, prop) =>
- !!getMethod(target, prop) || oldTraps.has!(target, prop),
-}));
diff --git a/src/equicordplugins/messageLoggerEnhanced/utils/idb/entry.ts b/src/equicordplugins/messageLoggerEnhanced/utils/idb/entry.ts
deleted file mode 100644
index c22ff4ff..00000000
--- a/src/equicordplugins/messageLoggerEnhanced/utils/idb/entry.ts
+++ /dev/null
@@ -1,1142 +0,0 @@
-/* eslint-disable simple-header/header */
-
-import { wrap } from "./wrap-idb-value.js";
-
-export interface OpenDBCallbacks {
- /**
- * Called if this version of the database has never been opened before. Use it to specify the
- * schema for the database.
- *
- * @param database A database instance that you can use to add/remove stores and indexes.
- * @param oldVersion Last version of the database opened by the user.
- * @param newVersion Whatever new version you provided.
- * @param transaction The transaction for this upgrade.
- * This is useful if you need to get data from other stores as part of a migration.
- * @param event The event object for the associated 'upgradeneeded' event.
- */
- upgrade?(
- database: IDBPDatabase,
- oldVersion: number,
- newVersion: number | null,
- transaction: IDBPTransaction<
- DBTypes,
- StoreNames[],
- "versionchange"
- >,
- event: IDBVersionChangeEvent,
- ): void;
- /**
- * Called if there are older versions of the database open on the origin, so this version cannot
- * open.
- *
- * @param currentVersion Version of the database that's blocking this one.
- * @param blockedVersion The version of the database being blocked (whatever version you provided to `openDB`).
- * @param event The event object for the associated `blocked` event.
- */
- blocked?(
- currentVersion: number,
- blockedVersion: number | null,
- event: IDBVersionChangeEvent,
- ): void;
- /**
- * Called if this connection is blocking a future version of the database from opening.
- *
- * @param currentVersion Version of the open database (whatever version you provided to `openDB`).
- * @param blockedVersion The version of the database that's being blocked.
- * @param event The event object for the associated `versionchange` event.
- */
- blocking?(
- currentVersion: number,
- blockedVersion: number | null,
- event: IDBVersionChangeEvent,
- ): void;
- /**
- * Called if the browser abnormally terminates the connection.
- * This is not called when `db.close()` is called.
- */
- terminated?(): void;
-}
-
-/**
- * Open a database.
- *
- * @param name Name of the database.
- * @param version Schema version.
- * @param callbacks Additional callbacks.
- */
-export function openDB(
- name: string,
- version?: number,
- { blocked, upgrade, blocking, terminated }: OpenDBCallbacks = {},
-): Promise> {
- const request = indexedDB.open(name, version);
- const openPromise = wrap(request) as Promise>;
-
- if (upgrade) {
- request.addEventListener("upgradeneeded", event => {
- upgrade(
- wrap(request.result) as IDBPDatabase,
- event.oldVersion,
- event.newVersion,
- wrap(request.transaction!) as unknown as IDBPTransaction<
- DBTypes,
- StoreNames[],
- "versionchange"
- >,
- event,
- );
- });
- }
-
- if (blocked) {
- request.addEventListener("blocked", event =>
- blocked(
- // Casting due to https://github.com/microsoft/TypeScript-DOM-lib-generator/pull/1405
- (event as IDBVersionChangeEvent).oldVersion,
- (event as IDBVersionChangeEvent).newVersion,
- event as IDBVersionChangeEvent,
- ),
- );
- }
-
- openPromise
- .then(db => {
- if (terminated) db.addEventListener("close", () => terminated());
- if (blocking) {
- db.addEventListener("versionchange", event =>
- blocking(event.oldVersion, event.newVersion, event),
- );
- }
- })
- .catch(() => { });
-
- return openPromise;
-}
-
-export interface DeleteDBCallbacks {
- /**
- * Called if there are connections to this database open, so it cannot be deleted.
- *
- * @param currentVersion Version of the database that's blocking the delete operation.
- * @param event The event object for the associated `blocked` event.
- */
- blocked?(currentVersion: number, event: IDBVersionChangeEvent): void;
-}
-
-/**
- * Delete a database.
- *
- * @param name Name of the database.
- */
-export function deleteDB(
- name: string,
- { blocked }: DeleteDBCallbacks = {},
-): Promise {
- const request = indexedDB.deleteDatabase(name);
-
- if (blocked) {
- request.addEventListener("blocked", event =>
- blocked(
- // Casting due to https://github.com/microsoft/TypeScript-DOM-lib-generator/pull/1405
- (event as IDBVersionChangeEvent).oldVersion,
- event as IDBVersionChangeEvent,
- ),
- );
- }
-
- return wrap(request).then(() => undefined);
-}
-
-export { unwrap, wrap } from "./wrap-idb-value.js";
-
-// === The rest of this file is type defs ===
-type KeyToKeyNoIndex = {
- [K in keyof T]: string extends K ? never : number extends K ? never : K;
-};
-type ValuesOf = T extends { [K in keyof T]: infer U } ? U : never;
-type KnownKeys = ValuesOf>;
-
-type Omit = Pick>;
-
-export interface DBSchema {
- [s: string]: DBSchemaValue;
-}
-
-interface IndexKeys {
- [s: string]: IDBValidKey;
-}
-
-interface DBSchemaValue {
- key: IDBValidKey;
- value: any;
- indexes?: IndexKeys;
-}
-
-/**
- * Extract known object store names from the DB schema type.
- *
- * @template DBTypes DB schema type, or unknown if the DB isn't typed.
- */
-export type StoreNames =
- DBTypes extends DBSchema ? KnownKeys : string;
-
-/**
- * Extract database value types from the DB schema type.
- *
- * @template DBTypes DB schema type, or unknown if the DB isn't typed.
- * @template StoreName Names of the object stores to get the types of.
- */
-export type StoreValue<
- DBTypes extends DBSchema | unknown,
- StoreName extends StoreNames,
-> = DBTypes extends DBSchema ? DBTypes[StoreName]["value"] : any;
-
-/**
- * Extract database key types from the DB schema type.
- *
- * @template DBTypes DB schema type, or unknown if the DB isn't typed.
- * @template StoreName Names of the object stores to get the types of.
- */
-export type StoreKey<
- DBTypes extends DBSchema | unknown,
- StoreName extends StoreNames,
-> = DBTypes extends DBSchema ? DBTypes[StoreName]["key"] : IDBValidKey;
-
-/**
- * Extract the names of indexes in certain object stores from the DB schema type.
- *
- * @template DBTypes DB schema type, or unknown if the DB isn't typed.
- * @template StoreName Names of the object stores to get the types of.
- */
-export type IndexNames<
- DBTypes extends DBSchema | unknown,
- StoreName extends StoreNames,
-> = DBTypes extends DBSchema ? keyof DBTypes[StoreName]["indexes"] : string;
-
-/**
- * Extract the types of indexes in certain object stores from the DB schema type.
- *
- * @template DBTypes DB schema type, or unknown if the DB isn't typed.
- * @template StoreName Names of the object stores to get the types of.
- * @template IndexName Names of the indexes to get the types of.
- */
-export type IndexKey<
- DBTypes extends DBSchema | unknown,
- StoreName extends StoreNames,
- IndexName extends IndexNames,
-> = DBTypes extends DBSchema
- ? IndexName extends keyof DBTypes[StoreName]["indexes"]
- ? DBTypes[StoreName]["indexes"][IndexName]
- : IDBValidKey
- : IDBValidKey;
-
-type CursorSource<
- DBTypes extends DBSchema | unknown,
- TxStores extends ArrayLike>,
- StoreName extends StoreNames,
- IndexName extends IndexNames | unknown,
- Mode extends IDBTransactionMode = "readonly",
-> = IndexName extends IndexNames
- ? IDBPIndex
- : IDBPObjectStore;
-
-type CursorKey<
- DBTypes extends DBSchema | unknown,
- StoreName extends StoreNames,
- IndexName extends IndexNames | unknown,
-> = IndexName extends IndexNames
- ? IndexKey
- : StoreKey;
-
-type IDBPDatabaseExtends = Omit<
- IDBDatabase,
- "createObjectStore" | "deleteObjectStore" | "transaction" | "objectStoreNames"
->;
-
-/**
- * A variation of DOMStringList with precise string types
- */
-export interface TypedDOMStringList extends DOMStringList {
- contains(string: T): boolean;
- item(index: number): T | null;
- [index: number]: T;
- [Symbol.iterator](): ArrayIterator;
-}
-
-interface IDBTransactionOptions {
- /**
- * The durability of the transaction.
- *
- * The default is "default". Using "relaxed" provides better performance, but with fewer
- * guarantees. Web applications are encouraged to use "relaxed" for ephemeral data such as caches
- * or quickly changing records, and "strict" in cases where reducing the risk of data loss
- * outweighs the impact to performance and power.
- */
- durability?: "default" | "strict" | "relaxed";
-}
-
-export interface IDBPDatabase
- extends IDBPDatabaseExtends {
- /**
- * The names of stores in the database.
- */
- readonly objectStoreNames: TypedDOMStringList>;
- /**
- * Creates a new object store.
- *
- * Throws a "InvalidStateError" DOMException if not called within an upgrade transaction.
- */
- createObjectStore>(
- name: Name,
- optionalParameters?: IDBObjectStoreParameters,
- ): IDBPObjectStore<
- DBTypes,
- ArrayLike>,
- Name,
- "versionchange"
- >;
- /**
- * Deletes the object store with the given name.
- *
- * Throws a "InvalidStateError" DOMException if not called within an upgrade transaction.
- */
- deleteObjectStore(name: StoreNames): void;
- /**
- * Start a new transaction.
- *
- * @param storeNames The object store(s) this transaction needs.
- * @param mode
- * @param options
- */
- transaction<
- Name extends StoreNames,
- Mode extends IDBTransactionMode = "readonly",
- >(
- storeNames: Name,
- mode?: Mode,
- options?: IDBTransactionOptions,
- ): IDBPTransaction;
- transaction<
- Names extends ArrayLike>,
- Mode extends IDBTransactionMode = "readonly",
- >(
- storeNames: Names,
- mode?: Mode,
- options?: IDBTransactionOptions,
- ): IDBPTransaction;
-
- // Shortcut methods
-
- /**
- * Add a value to a store.
- *
- * Rejects if an item of a given key already exists in the store.
- *
- * This is a shortcut that creates a transaction for this single action. If you need to do more
- * than one action, create a transaction instead.
- *
- * @param storeName Name of the store.
- * @param value
- * @param key
- */
- add>(
- storeName: Name,
- value: StoreValue,
- key?: StoreKey | IDBKeyRange,
- ): Promise>;
- /**
- * Deletes all records in a store.
- *
- * This is a shortcut that creates a transaction for this single action. If you need to do more
- * than one action, create a transaction instead.
- *
- * @param storeName Name of the store.
- */
- clear(name: StoreNames): Promise;
- /**
- * Retrieves the number of records matching the given query in a store.
- *
- * This is a shortcut that creates a transaction for this single action. If you need to do more
- * than one action, create a transaction instead.
- *
- * @param storeName Name of the store.
- * @param key
- */
- count>(
- storeName: Name,
- key?: StoreKey | IDBKeyRange | null,
- ): Promise;
- /**
- * Retrieves the number of records matching the given query in an index.
- *
- * This is a shortcut that creates a transaction for this single action. If you need to do more
- * than one action, create a transaction instead.
- *
- * @param storeName Name of the store.
- * @param indexName Name of the index within the store.
- * @param key
- */
- countFromIndex<
- Name extends StoreNames,
- IndexName extends IndexNames,
- >(
- storeName: Name,
- indexName: IndexName,
- key?: IndexKey | IDBKeyRange | null,
- ): Promise;
- /**
- * Deletes records in a store matching the given query.
- *
- * This is a shortcut that creates a transaction for this single action. If you need to do more
- * than one action, create a transaction instead.
- *
- * @param storeName Name of the store.
- * @param key
- */
- delete>(
- storeName: Name,
- key: StoreKey | IDBKeyRange,
- ): Promise;
- /**
- * Retrieves the value of the first record in a store matching the query.
- *
- * Resolves with undefined if no match is found.
- *
- * This is a shortcut that creates a transaction for this single action. If you need to do more
- * than one action, create a transaction instead.
- *
- * @param storeName Name of the store.
- * @param query
- */
- get>(
- storeName: Name,
- query: StoreKey | IDBKeyRange,
- ): Promise | undefined>;
- /**
- * Retrieves the value of the first record in an index matching the query.
- *
- * Resolves with undefined if no match is found.
- *
- * This is a shortcut that creates a transaction for this single action. If you need to do more
- * than one action, create a transaction instead.
- *
- * @param storeName Name of the store.
- * @param indexName Name of the index within the store.
- * @param query
- */
- getFromIndex<
- Name extends StoreNames,
- IndexName extends IndexNames,
- >(
- storeName: Name,
- indexName: IndexName,
- query: IndexKey | IDBKeyRange,
- ): Promise | undefined>;
- /**
- * Retrieves all values in a store that match the query.
- *
- * This is a shortcut that creates a transaction for this single action. If you need to do more
- * than one action, create a transaction instead.
- *
- * @param storeName Name of the store.
- * @param query
- * @param count Maximum number of values to return.
- */
- getAll>(
- storeName: Name,
- query?: StoreKey | IDBKeyRange | null,
- count?: number,
- ): Promise[]>;
- /**
- * Retrieves all values in an index that match the query.
- *
- * This is a shortcut that creates a transaction for this single action. If you need to do more
- * than one action, create a transaction instead.
- *
- * @param storeName Name of the store.
- * @param indexName Name of the index within the store.
- * @param query
- * @param count Maximum number of values to return.
- */
- getAllFromIndex<
- Name extends StoreNames,
- IndexName extends IndexNames,
- >(
- storeName: Name,
- indexName: IndexName,
- query?: IndexKey | IDBKeyRange | null,
- count?: number,
- ): Promise[]>;
- /**
- * Retrieves the keys of records in a store matching the query.
- *
- * This is a shortcut that creates a transaction for this single action. If you need to do more
- * than one action, create a transaction instead.
- *
- * @param storeName Name of the store.
- * @param query
- * @param count Maximum number of keys to return.
- */
- getAllKeys>(
- storeName: Name,
- query?: StoreKey | IDBKeyRange | null,
- count?: number,
- ): Promise[]>;
- /**
- * Retrieves the keys of records in an index matching the query.
- *
- * This is a shortcut that creates a transaction for this single action. If you need to do more
- * than one action, create a transaction instead.
- *
- * @param storeName Name of the store.
- * @param indexName Name of the index within the store.
- * @param query
- * @param count Maximum number of keys to return.
- */
- getAllKeysFromIndex<
- Name extends StoreNames,
- IndexName extends IndexNames,
- >(
- storeName: Name,
- indexName: IndexName,
- query?: IndexKey | IDBKeyRange | null,
- count?: number,
- ): Promise[]>;
- /**
- * Retrieves the key of the first record in a store that matches the query.
- *
- * Resolves with undefined if no match is found.
- *
- * This is a shortcut that creates a transaction for this single action. If you need to do more
- * than one action, create a transaction instead.
- *
- * @param storeName Name of the store.
- * @param query
- */
- getKey>(
- storeName: Name,
- query: StoreKey | IDBKeyRange,
- ): Promise | undefined>;
- /**
- * Retrieves the key of the first record in an index that matches the query.
- *
- * Resolves with undefined if no match is found.
- *
- * This is a shortcut that creates a transaction for this single action. If you need to do more
- * than one action, create a transaction instead.
- *
- * @param storeName Name of the store.
- * @param indexName Name of the index within the store.
- * @param query
- */
- getKeyFromIndex<
- Name extends StoreNames,
- IndexName extends IndexNames,
- >(
- storeName: Name,
- indexName: IndexName,
- query: IndexKey | IDBKeyRange,
- ): Promise | undefined>;
- /**
- * Put an item in the database.
- *
- * Replaces any item with the same key.
- *
- * This is a shortcut that creates a transaction for this single action. If you need to do more
- * than one action, create a transaction instead.
- *
- * @param storeName Name of the store.
- * @param value
- * @param key
- */
- put>(
- storeName: Name,
- value: StoreValue,
- key?: StoreKey | IDBKeyRange,
- ): Promise>;
-}
-
-type IDBPTransactionExtends = Omit<
- IDBTransaction,
- "db" | "objectStore" | "objectStoreNames"
->;
-
-export interface IDBPTransaction<
- DBTypes extends DBSchema | unknown = unknown,
- TxStores extends ArrayLike> = ArrayLike<
- StoreNames
- >,
- Mode extends IDBTransactionMode = "readonly",
-> extends IDBPTransactionExtends {
- /**
- * The transaction's mode.
- */
- readonly mode: Mode;
- /**
- * The names of stores in scope for this transaction.
- */
- readonly objectStoreNames: TypedDOMStringList;
- /**
- * The transaction's connection.
- */
- readonly db: IDBPDatabase;
- /**
- * Promise for the completion of this transaction.
- */
- readonly done: Promise;
- /**
- * The associated object store, if the transaction covers a single store, otherwise undefined.
- */
- readonly store: TxStores[1] extends undefined
- ? IDBPObjectStore
- : undefined;
- /**
- * Returns an IDBObjectStore in the transaction's scope.
- */
- objectStore(
- name: StoreName,
- ): IDBPObjectStore;
-}
-
-type IDBPObjectStoreExtends = Omit<
- IDBObjectStore,
- | "transaction"
- | "add"
- | "clear"
- | "count"
- | "createIndex"
- | "delete"
- | "get"
- | "getAll"
- | "getAllKeys"
- | "getKey"
- | "index"
- | "openCursor"
- | "openKeyCursor"
- | "put"
- | "indexNames"
->;
-
-export interface IDBPObjectStore<
- DBTypes extends DBSchema | unknown = unknown,
- TxStores extends ArrayLike> = ArrayLike<
- StoreNames
- >,
- StoreName extends StoreNames = StoreNames,
- Mode extends IDBTransactionMode = "readonly",
-> extends IDBPObjectStoreExtends {
- /**
- * The names of indexes in the store.
- */
- readonly indexNames: TypedDOMStringList>;
- /**
- * The associated transaction.
- */
- readonly transaction: IDBPTransaction;
- /**
- * Add a value to the store.
- *
- * Rejects if an item of a given key already exists in the store.
- */
- add: Mode extends "readonly"
- ? undefined
- : (
- value: StoreValue,
- key?: StoreKey | IDBKeyRange,
- ) => Promise>;
- /**
- * Deletes all records in store.
- */
- clear: Mode extends "readonly" ? undefined : () => Promise;
- /**
- * Retrieves the number of records matching the given query.
- */
- count(
- key?: StoreKey | IDBKeyRange | null,
- ): Promise;
- /**
- * Creates a new index in store.
- *
- * Throws an "InvalidStateError" DOMException if not called within an upgrade transaction.
- */
- createIndex: Mode extends "versionchange"
- ? >(
- name: IndexName,
- keyPath: string | string[],
- options?: IDBIndexParameters,
- ) => IDBPIndex
- : undefined;
- /**
- * Deletes records in store matching the given query.
- */
- delete: Mode extends "readonly"
- ? undefined
- : (key: StoreKey | IDBKeyRange) => Promise;
- /**
- * Retrieves the value of the first record matching the query.
- *
- * Resolves with undefined if no match is found.
- */
- get(
- query: StoreKey | IDBKeyRange,
- ): Promise | undefined>;
- /**
- * Retrieves all values that match the query.
- *
- * @param query
- * @param count Maximum number of values to return.
- */
- getAll(
- query?: StoreKey | IDBKeyRange | null,
- count?: number,
- ): Promise[]>;
- /**
- * Retrieves the keys of records matching the query.
- *
- * @param query
- * @param count Maximum number of keys to return.
- */
- getAllKeys(
- query?: StoreKey | IDBKeyRange | null,
- count?: number,
- ): Promise[]>;
- /**
- * Retrieves the key of the first record that matches the query.
- *
- * Resolves with undefined if no match is found.
- */
- getKey(
- query: StoreKey | IDBKeyRange,
- ): Promise | undefined>;
- /**
- * Get a query of a given name.
- */
- index>(
- name: IndexName,
- ): IDBPIndex;
- /**
- * Opens a cursor over the records matching the query.
- *
- * Resolves with null if no matches are found.
- *
- * @param query If null, all records match.
- * @param direction
- */
- openCursor(
- query?: StoreKey | IDBKeyRange | null,
- direction?: IDBCursorDirection,
- ): Promise | null>;
- /**
- * Opens a cursor over the keys matching the query.
- *
- * Resolves with null if no matches are found.
- *
- * @param query If null, all records match.
- * @param direction
- */
- openKeyCursor(
- query?: StoreKey | IDBKeyRange | null,
- direction?: IDBCursorDirection,
- ): Promise | null>;
- /**
- * Put an item in the store.
- *
- * Replaces any item with the same key.
- */
- put: Mode extends "readonly"
- ? undefined
- : (
- value: StoreValue,
- key?: StoreKey | IDBKeyRange,
- ) => Promise>;
- /**
- * Iterate over the store.
- */
- [Symbol.asyncIterator](): AsyncIterableIterator<
- IDBPCursorWithValueIteratorValue<
- DBTypes,
- TxStores,
- StoreName,
- unknown,
- Mode
- >
- >;
- /**
- * Iterate over the records matching the query.
- *
- * @param query If null, all records match.
- * @param direction
- */
- iterate(
- query?: StoreKey | IDBKeyRange | null,
- direction?: IDBCursorDirection,
- ): AsyncIterableIterator<
- IDBPCursorWithValueIteratorValue<
- DBTypes,
- TxStores,
- StoreName,
- unknown,
- Mode
- >
- >;
-}
-
-type IDBPIndexExtends = Omit<
- IDBIndex,
- | "objectStore"
- | "count"
- | "get"
- | "getAll"
- | "getAllKeys"
- | "getKey"
- | "openCursor"
- | "openKeyCursor"
->;
-
-export interface IDBPIndex<
- DBTypes extends DBSchema | unknown = unknown,
- TxStores extends ArrayLike> = ArrayLike<
- StoreNames
- >,
- StoreName extends StoreNames = StoreNames,
- IndexName extends IndexNames = IndexNames<
- DBTypes,
- StoreName
- >,
- Mode extends IDBTransactionMode = "readonly",
-> extends IDBPIndexExtends {
- /**
- * The IDBObjectStore the index belongs to.
- */
- readonly objectStore: IDBPObjectStore;
-
- /**
- * Retrieves the number of records matching the given query.
- */
- count(
- key?: IndexKey | IDBKeyRange | null,
- ): Promise;
- /**
- * Retrieves the value of the first record matching the query.
- *
- * Resolves with undefined if no match is found.
- */
- get(
- query: IndexKey | IDBKeyRange,
- ): Promise | undefined>;
- /**
- * Retrieves all values that match the query.
- *
- * @param query
- * @param count Maximum number of values to return.
- */
- getAll(
- query?: IndexKey | IDBKeyRange | null,
- count?: number,
- ): Promise[]>;
- /**
- * Retrieves the keys of records matching the query.
- *
- * @param query
- * @param count Maximum number of keys to return.
- */
- getAllKeys(
- query?: IndexKey | IDBKeyRange | null,
- count?: number,
- ): Promise[]>;
- /**
- * Retrieves the key of the first record that matches the query.
- *
- * Resolves with undefined if no match is found.
- */
- getKey(
- query: IndexKey | IDBKeyRange,
- ): Promise | undefined>;
- /**
- * Opens a cursor over the records matching the query.
- *
- * Resolves with null if no matches are found.
- *
- * @param query If null, all records match.
- * @param direction
- */
- openCursor(
- query?: IndexKey | IDBKeyRange | null,
- direction?: IDBCursorDirection,
- ): Promise | null>;
- /**
- * Opens a cursor over the keys matching the query.
- *
- * Resolves with null if no matches are found.
- *
- * @param query If null, all records match.
- * @param direction
- */
- openKeyCursor(
- query?: IndexKey | IDBKeyRange | null,
- direction?: IDBCursorDirection,
- ): Promise | null>;
- /**
- * Iterate over the index.
- */
- [Symbol.asyncIterator](): AsyncIterableIterator<
- IDBPCursorWithValueIteratorValue<
- DBTypes,
- TxStores,
- StoreName,
- IndexName,
- Mode
- >
- >;
- /**
- * Iterate over the records matching the query.
- *
- * Resolves with null if no matches are found.
- *
- * @param query If null, all records match.
- * @param direction
- */
- iterate(
- query?: IndexKey | IDBKeyRange | null,
- direction?: IDBCursorDirection,
- ): AsyncIterableIterator<
- IDBPCursorWithValueIteratorValue<
- DBTypes,
- TxStores,
- StoreName,
- IndexName,
- Mode
- >
- >;
-}
-
-type IDBPCursorExtends = Omit<
- IDBCursor,
- | "key"
- | "primaryKey"
- | "source"
- | "advance"
- | "continue"
- | "continuePrimaryKey"
- | "delete"
- | "update"
->;
-
-export interface IDBPCursor<
- DBTypes extends DBSchema | unknown = unknown,
- TxStores extends ArrayLike> = ArrayLike<
- StoreNames
- >,
- StoreName extends StoreNames = StoreNames,
- IndexName extends IndexNames | unknown = unknown,
- Mode extends IDBTransactionMode = "readonly",
-> extends IDBPCursorExtends {
- /**
- * The key of the current index or object store item.
- */
- readonly key: CursorKey;
- /**
- * The key of the current object store item.
- */
- readonly primaryKey: StoreKey;
- /**
- * Returns the IDBObjectStore or IDBIndex the cursor was opened from.
- */
- readonly source: CursorSource;
- /**
- * Advances the cursor a given number of records.
- *
- * Resolves to null if no matching records remain.
- */
- advance(this: T, count: number): Promise;
- /**
- * Advance the cursor by one record (unless 'key' is provided).
- *
- * Resolves to null if no matching records remain.
- *
- * @param key Advance to the index or object store with a key equal to or greater than this value.
- */
- continue(
- this: T,
- key?: CursorKey,
- ): Promise;
- /**
- * Advance the cursor by given keys.
- *
- * The operation is 'and' – both keys must be satisfied.
- *
- * Resolves to null if no matching records remain.
- *
- * @param key Advance to the index or object store with a key equal to or greater than this value.
- * @param primaryKey and where the object store has a key equal to or greater than this value.
- */
- continuePrimaryKey(
- this: T,
- key: CursorKey,
- primaryKey: StoreKey,
- ): Promise;
- /**
- * Delete the current record.
- */
- delete: Mode extends "readonly" ? undefined : () => Promise;
- /**
- * Updated the current record.
- */
- update: Mode extends "readonly"
- ? undefined
- : (
- value: StoreValue,
- ) => Promise>;
- /**
- * Iterate over the cursor.
- */
- [Symbol.asyncIterator](): AsyncIterableIterator<
- IDBPCursorIteratorValue
- >;
-}
-
-type IDBPCursorIteratorValueExtends<
- DBTypes extends DBSchema | unknown = unknown,
- TxStores extends ArrayLike> = ArrayLike<
- StoreNames
- >,
- StoreName extends StoreNames = StoreNames,
- IndexName extends IndexNames | unknown = unknown,
- Mode extends IDBTransactionMode = "readonly",
-> = Omit<
- IDBPCursor,
- "advance" | "continue" | "continuePrimaryKey"
->;
-
-export interface IDBPCursorIteratorValue<
- DBTypes extends DBSchema | unknown = unknown,
- TxStores extends ArrayLike> = ArrayLike<
- StoreNames
- >,
- StoreName extends StoreNames = StoreNames,
- IndexName extends IndexNames | unknown = unknown,
- Mode extends IDBTransactionMode = "readonly",
-> extends IDBPCursorIteratorValueExtends<
- DBTypes,
- TxStores,
- StoreName,
- IndexName,
- Mode
-> {
- /**
- * Advances the cursor a given number of records.
- */
- advance(this: T, count: number): void;
- /**
- * Advance the cursor by one record (unless 'key' is provided).
- *
- * @param key Advance to the index or object store with a key equal to or greater than this value.
- */
- continue(this: T, key?: CursorKey): void;
- /**
- * Advance the cursor by given keys.
- *
- * The operation is 'and' – both keys must be satisfied.
- *
- * @param key Advance to the index or object store with a key equal to or greater than this value.
- * @param primaryKey and where the object store has a key equal to or greater than this value.
- */
- continuePrimaryKey(
- this: T,
- key: CursorKey,
- primaryKey: StoreKey,
- ): void;
-}
-
-export interface IDBPCursorWithValue<
- DBTypes extends DBSchema | unknown = unknown,
- TxStores extends ArrayLike> = ArrayLike<
- StoreNames
- >,
- StoreName extends StoreNames = StoreNames,
- IndexName extends IndexNames | unknown = unknown,
- Mode extends IDBTransactionMode = "readonly",
-> extends IDBPCursor {
- /**
- * The value of the current item.
- */
- readonly value: StoreValue;
- /**
- * Iterate over the cursor.
- */
- [Symbol.asyncIterator](): AsyncIterableIterator<
- IDBPCursorWithValueIteratorValue<
- DBTypes,
- TxStores,
- StoreName,
- IndexName,
- Mode
- >
- >;
-}
-
-// Some of that sweeeeet Java-esque naming.
-type IDBPCursorWithValueIteratorValueExtends<
- DBTypes extends DBSchema | unknown = unknown,
- TxStores extends ArrayLike> = ArrayLike<
- StoreNames
- >,
- StoreName extends StoreNames = StoreNames,
- IndexName extends IndexNames | unknown = unknown,
- Mode extends IDBTransactionMode = "readonly",
-> = Omit<
- IDBPCursorWithValue,
- "advance" | "continue" | "continuePrimaryKey"
->;
-
-export interface IDBPCursorWithValueIteratorValue<
- DBTypes extends DBSchema | unknown = unknown,
- TxStores extends ArrayLike> = ArrayLike<
- StoreNames
- >,
- StoreName extends StoreNames = StoreNames,
- IndexName extends IndexNames | unknown = unknown,
- Mode extends IDBTransactionMode = "readonly",
-> extends IDBPCursorWithValueIteratorValueExtends<
- DBTypes,
- TxStores,
- StoreName,
- IndexName,
- Mode
-> {
- /**
- * Advances the cursor a given number of records.
- */
- advance(this: T, count: number): void;
- /**
- * Advance the cursor by one record (unless 'key' is provided).
- *
- * @param key Advance to the index or object store with a key equal to or greater than this value.
- */
- continue(this: T, key?: CursorKey): void;
- /**
- * Advance the cursor by given keys.
- *
- * The operation is 'and' – both keys must be satisfied.
- *
- * @param key Advance to the index or object store with a key equal to or greater than this value.
- * @param primaryKey and where the object store has a key equal to or greater than this value.
- */
- continuePrimaryKey(
- this: T,
- key: CursorKey,
- primaryKey: StoreKey,
- ): void;
-}
diff --git a/src/equicordplugins/messageLoggerEnhanced/utils/idb/index.ts b/src/equicordplugins/messageLoggerEnhanced/utils/idb/index.ts
deleted file mode 100644
index 4bc654a1..00000000
--- a/src/equicordplugins/messageLoggerEnhanced/utils/idb/index.ts
+++ /dev/null
@@ -1,5 +0,0 @@
-/* eslint-disable simple-header/header */
-
-export * from "./entry.js";
-import "./database-extras.js";
-import "./async-iterators.js";
diff --git a/src/equicordplugins/messageLoggerEnhanced/utils/idb/util.ts b/src/equicordplugins/messageLoggerEnhanced/utils/idb/util.ts
deleted file mode 100644
index 5de6907f..00000000
--- a/src/equicordplugins/messageLoggerEnhanced/utils/idb/util.ts
+++ /dev/null
@@ -1,9 +0,0 @@
-/* eslint-disable simple-header/header */
-
-export type Constructor = new (...args: any[]) => any;
-export type Func = (...args: any[]) => any;
-
-export const instanceOfAny = (
- object: any,
- constructors: Constructor[],
-): boolean => constructors.some(c => object instanceof c);
diff --git a/src/equicordplugins/messageLoggerEnhanced/utils/idb/wrap-idb-value.ts b/src/equicordplugins/messageLoggerEnhanced/utils/idb/wrap-idb-value.ts
deleted file mode 100644
index 748b0ae5..00000000
--- a/src/equicordplugins/messageLoggerEnhanced/utils/idb/wrap-idb-value.ts
+++ /dev/null
@@ -1,227 +0,0 @@
-/* eslint-disable simple-header/header */
-
-import {
- IDBPCursor,
- IDBPCursorWithValue,
- IDBPDatabase,
- IDBPIndex,
- IDBPObjectStore,
- IDBPTransaction,
-} from "./entry.js";
-import { Constructor, Func, instanceOfAny } from "./util.js";
-
-let idbProxyableTypes: Constructor[];
-let cursorAdvanceMethods: Func[];
-
-// This is a function to prevent it throwing up in node environments.
-function getIdbProxyableTypes(): Constructor[] {
- return (
- idbProxyableTypes ||
- (idbProxyableTypes = [
- IDBDatabase,
- IDBObjectStore,
- IDBIndex,
- IDBCursor,
- IDBTransaction,
- ])
- );
-}
-
-// This is a function to prevent it throwing up in node environments.
-function getCursorAdvanceMethods(): Func[] {
- return (
- cursorAdvanceMethods ||
- (cursorAdvanceMethods = [
- IDBCursor.prototype.advance,
- IDBCursor.prototype.continue,
- IDBCursor.prototype.continuePrimaryKey,
- ])
- );
-}
-
-const transactionDoneMap: WeakMap<
- IDBTransaction,
- Promise
-> = new WeakMap();
-const transformCache = new WeakMap();
-export const reverseTransformCache = new WeakMap();
-
-function promisifyRequest(request: IDBRequest): Promise {
- const promise = new Promise