MessageLogger: add context menu option to clear channel history (#2008)

Co-authored-by: vee <vendicated@riseup.net>
This commit is contained in:
Nickyux 2024-06-07 23:28:17 +02:00 committed by GitHub
parent 1bc9a800a6
commit 29c65948b4
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
2 changed files with 70 additions and 53 deletions

View file

@ -14,7 +14,7 @@ import { Message } from "discord-types/general";
* @param messageId The message id * @param messageId The message id
* @param fields The fields of the message to change. Leave empty if you just want to re-render * @param fields The fields of the message to change. Leave empty if you just want to re-render
*/ */
export function updateMessage(channelId: string, messageId: string, fields?: Partial<Message>) { export function updateMessage(channelId: string, messageId: string, fields?: Partial<Message & Record<string, any>>) {
const channelMessageCache = MessageCache.getOrCreate(channelId); const channelMessageCache = MessageCache.getOrCreate(channelId);
if (!channelMessageCache.has(messageId)) return; if (!channelMessageCache.has(messageId)) return;

View file

@ -18,7 +18,8 @@
import "./messageLogger.css"; import "./messageLogger.css";
import { NavContextMenuPatchCallback } from "@api/ContextMenu"; import { findGroupChildrenByChildId, NavContextMenuPatchCallback } from "@api/ContextMenu";
import { updateMessage } from "@api/MessageUpdater";
import { Settings } from "@api/Settings"; import { Settings } from "@api/Settings";
import { disableStyle, enableStyle } from "@api/Styles"; import { disableStyle, enableStyle } from "@api/Styles";
import ErrorBoundary from "@components/ErrorBoundary"; import ErrorBoundary from "@components/ErrorBoundary";
@ -26,11 +27,17 @@ import { Devs } from "@utils/constants";
import { Logger } from "@utils/Logger"; import { Logger } from "@utils/Logger";
import definePlugin, { OptionType } from "@utils/types"; import definePlugin, { OptionType } from "@utils/types";
import { findByPropsLazy } from "@webpack"; import { findByPropsLazy } from "@webpack";
import { ChannelStore, FluxDispatcher, i18n, Menu, Parser, Timestamp, UserStore } from "@webpack/common"; import { ChannelStore, FluxDispatcher, i18n, Menu, MessageStore, Parser, Timestamp, UserStore, useStateFromStores } from "@webpack/common";
import { Message } from "discord-types/general";
import overlayStyle from "./deleteStyleOverlay.css?managed"; import overlayStyle from "./deleteStyleOverlay.css?managed";
import textStyle from "./deleteStyleText.css?managed"; import textStyle from "./deleteStyleText.css?managed";
interface MLMessage extends Message {
deleted?: boolean;
editHistory?: { timestamp: Date; content: string; }[];
}
const styles = findByPropsLazy("edited", "communicationDisabled", "isSystemMessage"); const styles = findByPropsLazy("edited", "communicationDisabled", "isSystemMessage");
function addDeleteStyle() { function addDeleteStyle() {
@ -89,22 +96,63 @@ const patchMessageContextMenu: NavContextMenuPatchCallback = (children, props) =
)); ));
}; };
const patchChannelContextMenu: NavContextMenuPatchCallback = (children, { channel }) => {
const messages = MessageStore.getMessages(channel?.id) as MLMessage[];
if (!messages?.some(msg => msg.deleted || msg.editHistory?.length)) return;
const group = findGroupChildrenByChildId("mark-channel-read", children) ?? children;
group.push(
<Menu.MenuItem
id="vc-ml-clear-channel"
label="Clear Message Log"
color="danger"
action={() => {
messages.forEach(msg => {
if (msg.deleted)
FluxDispatcher.dispatch({
type: "MESSAGE_DELETE",
channelId: channel.id,
id: msg.id,
mlDeleted: true
});
else
updateMessage(channel.id, msg.id, {
editHistory: []
});
});
}}
/>
);
};
export default definePlugin({ export default definePlugin({
name: "MessageLogger", name: "MessageLogger",
description: "Temporarily logs deleted and edited messages.", description: "Temporarily logs deleted and edited messages.",
authors: [Devs.rushii, Devs.Ven, Devs.AutumnVN], authors: [Devs.rushii, Devs.Ven, Devs.AutumnVN, Devs.Nickyux],
dependencies: ["MessageUpdaterAPI"],
contextMenus: { contextMenus: {
"message": patchMessageContextMenu "message": patchMessageContextMenu,
"channel-context": patchChannelContextMenu,
"user-context": patchChannelContextMenu,
"gdm-context": patchChannelContextMenu
}, },
start() { start() {
addDeleteStyle(); addDeleteStyle();
}, },
renderEdit(edit: { timestamp: any, content: string; }) { renderEdits: ErrorBoundary.wrap(({ message: { id: messageId, channel_id: channelId } }: { message: Message; }) => {
const message = useStateFromStores(
[MessageStore],
() => MessageStore.getMessage(channelId, messageId) as MLMessage,
null,
(oldMsg, newMsg) => oldMsg.editHistory === newMsg.editHistory
);
return ( return (
<ErrorBoundary noop> <>
{message.editHistory?.map(edit => (
<div className="messagelogger-edited"> <div className="messagelogger-edited">
{Parser.parse(edit.content)} {Parser.parse(edit.content)}
<Timestamp <Timestamp
@ -115,9 +163,10 @@ export default definePlugin({
<span className={styles.edited}>{" "}({i18n.Messages.MESSAGE_EDITED})</span> <span className={styles.edited}>{" "}({i18n.Messages.MESSAGE_EDITED})</span>
</Timestamp> </Timestamp>
</div> </div>
</ErrorBoundary> ))}
</>
); );
}, }, { noop: true }),
makeEdit(newMessage: any, oldMessage: any): any { makeEdit(newMessage: any, oldMessage: any): any {
return { return {
@ -222,11 +271,9 @@ export default definePlugin({
(message.channel_id === "1026515880080842772" && message.author?.id === "1017176847865352332"); (message.channel_id === "1026515880080842772" && message.author?.id === "1017176847865352332");
}, },
// Based on canary 63b8f1b4f2025213c5cf62f0966625bee3d53136
patches: [ patches: [
{ {
// MessageStore // MessageStore
// Module 171447
find: '"MessageStore"', find: '"MessageStore"',
replacement: [ replacement: [
{ {
@ -271,7 +318,6 @@ export default definePlugin({
{ {
// Message domain model // Message domain model
// Module 451
find: "}addReaction(", find: "}addReaction(",
replacement: [ replacement: [
{ {
@ -285,14 +331,8 @@ export default definePlugin({
{ {
// Updated message transformer(?) // Updated message transformer(?)
// Module 819525
find: "THREAD_STARTER_MESSAGE?null===", find: "THREAD_STARTER_MESSAGE?null===",
replacement: [ replacement: [
// {
// // DEBUG: Log the params of the target function to the patch below
// match: /function N\(e,t\){/,
// replace: "function L(e,t){console.log('pre-transform', e, t);"
// },
{ {
// Pass through editHistory & deleted & original attachments to the "edited message" transformer // Pass through editHistory & deleted & original attachments to the "edited message" transformer
match: /(?<=null!=\i\.edited_timestamp\)return )\i\(\i,\{reactions:(\i)\.reactions.{0,50}\}\)/, match: /(?<=null!=\i\.edited_timestamp\)return )\i\(\i,\{reactions:(\i)\.reactions.{0,50}\}\)/,
@ -300,11 +340,6 @@ export default definePlugin({
"Object.assign($&,{ deleted:$1.deleted, editHistory:$1.editHistory, attachments:$1.attachments })" "Object.assign($&,{ deleted:$1.deleted, editHistory:$1.editHistory, attachments:$1.attachments })"
}, },
// {
// // DEBUG: Log the params of the target function to the patch below
// match: /function R\(e\){/,
// replace: "function R(e){console.log('after-edit-transform', arguments);"
// },
{ {
// Construct new edited message and add editHistory & deleted (ref above) // Construct new edited message and add editHistory & deleted (ref above)
// Pass in custom data to attachment parser to mark attachments deleted as well // Pass in custom data to attachment parser to mark attachments deleted as well
@ -335,7 +370,6 @@ export default definePlugin({
{ {
// Attachment renderer // Attachment renderer
// Module 96063
find: ".removeMosaicItemHoverButton", find: ".removeMosaicItemHoverButton",
group: true, group: true,
replacement: [ replacement: [
@ -352,7 +386,6 @@ export default definePlugin({
{ {
// Base message component renderer // Base message component renderer
// Module 748241
find: "Message must not be a thread starter message", find: "Message must not be a thread starter message",
replacement: [ replacement: [
{ {
@ -365,20 +398,18 @@ export default definePlugin({
{ {
// Message content renderer // Message content renderer
// Module 43016
find: "Messages.MESSAGE_EDITED,\")\"", find: "Messages.MESSAGE_EDITED,\")\"",
replacement: [ replacement: [
{ {
// Render editHistory in the deepest div for message content // Render editHistory in the deepest div for message content
match: /(\)\("div",\{id:.+?children:\[)/, match: /(\)\("div",\{id:.+?children:\[)/,
replace: "$1 (arguments[0].message.editHistory?.length > 0 ? arguments[0].message.editHistory.map(edit => $self.renderEdit(edit)) : null), " replace: "$1 (!!arguments[0].message.editHistory?.length && $self.renderEdits(arguments[0])),"
} }
] ]
}, },
{ {
// ReferencedMessageStore // ReferencedMessageStore
// Module 778667
find: '"ReferencedMessageStore"', find: '"ReferencedMessageStore"',
replacement: [ replacement: [
{ {
@ -394,7 +425,6 @@ export default definePlugin({
{ {
// Message context base menu // Message context base menu
// Module 600300
find: "useMessageMenu:", find: "useMessageMenu:",
replacement: [ replacement: [
{ {
@ -404,18 +434,5 @@ export default definePlugin({
} }
] ]
} }
// {
// // MessageStore caching internals
// // Module 819525
// find: "e.getOrCreate=function(t)",
// replacement: [
// // {
// // // DEBUG: log getOrCreate return values from MessageStore caching internals
// // match: /getOrCreate=function(.+?)return/,
// // replace: "getOrCreate=function$1console.log('getOrCreate',n);return"
// // }
// ]
// }
] ]
}); });