From a01ee40591f7a1e49b903b24a5ab2a6b278b34a2 Mon Sep 17 00:00:00 2001 From: Nuckyz <61953774+Nuckyz@users.noreply.github.com> Date: Wed, 19 Jun 2024 23:49:42 -0300 Subject: [PATCH 01/27] Clean-up related additions to mangled exports --- src/api/SettingsStores.ts | 69 --------------- src/api/UserSettingDefinitions.ts | 83 +++++++++++++++++++ src/api/index.ts | 7 +- ...gsStores.ts => userSettingsDefinitions.ts} | 21 +++-- src/plugins/betterRoleContext/index.tsx | 6 +- src/plugins/customRPC/index.tsx | 7 +- src/plugins/gameActivityToggle/index.tsx | 6 +- src/plugins/ignoreActivities/index.tsx | 6 +- src/plugins/messageLinkEmbeds/index.tsx | 6 +- src/utils/discord.tsx | 2 +- src/webpack/common/index.ts | 2 +- src/webpack/common/types/index.d.ts | 1 - src/webpack/common/types/settingsStores.ts | 11 --- src/webpack/common/types/utils.d.ts | 2 +- .../{settingsStores.ts => userSettings.ts} | 0 15 files changed, 120 insertions(+), 109 deletions(-) delete mode 100644 src/api/SettingsStores.ts create mode 100644 src/api/UserSettingDefinitions.ts rename src/plugins/_api/{settingsStores.ts => userSettingsDefinitions.ts} (52%) delete mode 100644 src/webpack/common/types/settingsStores.ts rename src/webpack/common/{settingsStores.ts => userSettings.ts} (100%) diff --git a/src/api/SettingsStores.ts b/src/api/SettingsStores.ts deleted file mode 100644 index 18139e4e6..000000000 --- a/src/api/SettingsStores.ts +++ /dev/null @@ -1,69 +0,0 @@ -/* - * 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 { proxyLazy } from "@utils/lazy"; -import { Logger } from "@utils/Logger"; -import { findModuleId, proxyLazyWebpack, wreq } from "@webpack"; - -import { Settings } from "./Settings"; - -interface Setting { - /** - * Get the setting value - */ - getSetting(): T; - /** - * Update the setting value - * @param value The new value - */ - updateSetting(value: T | ((old: T) => T)): Promise; - /** - * React hook for automatically updating components when the setting is updated - */ - useSetting(): T; - settingsStoreApiGroup: string; - settingsStoreApiName: string; -} - -export const SettingsStores: Array> | undefined = proxyLazyWebpack(() => { - const modId = findModuleId('"textAndImages","renderSpoilers"') as any; - if (modId == null) return new Logger("SettingsStoreAPI").error("Didn't find stores module."); - - const mod = wreq(modId); - if (mod == null) return; - - return Object.values(mod).filter((s: any) => s?.settingsStoreApiGroup) as any; -}); - -/** - * Get the store for a setting - * @param group The setting group - * @param name The name of the setting - */ -export function getSettingStore(group: string, name: string): Setting | undefined { - if (!Settings.plugins.SettingsStoreAPI.enabled) throw new Error("Cannot use SettingsStoreAPI without setting as dependency."); - - return SettingsStores?.find(s => s?.settingsStoreApiGroup === group && s?.settingsStoreApiName === name); -} - -/** - * getSettingStore but lazy - */ -export function getSettingStoreLazy(group: string, name: string) { - return proxyLazy(() => getSettingStore(group, name)); -} diff --git a/src/api/UserSettingDefinitions.ts b/src/api/UserSettingDefinitions.ts new file mode 100644 index 000000000..7a2ed5be9 --- /dev/null +++ b/src/api/UserSettingDefinitions.ts @@ -0,0 +1,83 @@ +/* + * 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 { proxyLazy } from "@utils/lazy"; +import { Logger } from "@utils/Logger"; +import { findModuleId, proxyLazyWebpack, wreq } from "@webpack"; + +import { Settings } from "./Settings"; + +interface UserSettingDefinition { + /** + * Get the setting value + */ + getSetting(): T; + /** + * Update the setting value + * @param value The new value + */ + updateSetting(value: T): Promise; + /** + * Update the setting value + * @param value A callback that accepts the old value as the first argument, and returns the new value + */ + updateSetting(value: (old: T) => T): Promise; + /** + * Stateful React hook for this setting value + */ + useSetting(): T; + userSettingDefinitionsAPIGroup: string; + userSettingDefinitionsAPIName: string; +} + +export const UserSettingsDefinitions: Record> | undefined = proxyLazyWebpack(() => { + const modId = findModuleId('"textAndImages","renderSpoilers"'); + if (modId == null) return new Logger("UserSettingDefinitionsAPI").error("Didn't find settings definitions module."); + + return wreq(modId as any); +}); + +/** + * Get the definition for a setting. + * + * @param group The setting group + * @param name The name of the setting + */ +export function getUserSettingDefinition(group: string, name: string): UserSettingDefinition | undefined { + if (!Settings.plugins.UserSettingDefinitionsAPI.enabled) throw new Error("Cannot use UserSettingDefinitionsAPI without setting as dependency."); + + for (const key in UserSettingsDefinitions) { + const userSettingDefinition = UserSettingsDefinitions[key]; + + if (userSettingDefinition.userSettingDefinitionsAPIGroup === group && userSettingDefinition.userSettingDefinitionsAPIName === name) { + return userSettingDefinition; + } + } +} + +/** + * {@link getUserSettingDefinition}, lazy. + * + * Get the definition for a setting. + * + * @param group The setting group + * @param name The name of the setting + */ +export function getUserSettingDefinitionLazy(group: string, name: string) { + return proxyLazy(() => getUserSettingDefinition(group, name)); +} diff --git a/src/api/index.ts b/src/api/index.ts index 737e06d60..5f8233d21 100644 --- a/src/api/index.ts +++ b/src/api/index.ts @@ -31,8 +31,8 @@ import * as $Notices from "./Notices"; import * as $Notifications from "./Notifications"; import * as $ServerList from "./ServerList"; import * as $Settings from "./Settings"; -import * as $SettingsStores from "./SettingsStores"; import * as $Styles from "./Styles"; +import * as $UserSettingDefinitions from "./UserSettingDefinitions"; /** * An API allowing you to listen to Message Clicks or run your own logic @@ -118,4 +118,7 @@ export const ChatButtons = $ChatButtons; */ export const MessageUpdater = $MessageUpdater; -export const SettingsStores = $SettingsStores; +/** + * An API allowing you to get the definition for an user setting + */ +export const UserSettingDefinitions = $UserSettingDefinitions; diff --git a/src/plugins/_api/settingsStores.ts b/src/plugins/_api/userSettingsDefinitions.ts similarity index 52% rename from src/plugins/_api/settingsStores.ts rename to src/plugins/_api/userSettingsDefinitions.ts index a888532ee..5577a1723 100644 --- a/src/plugins/_api/settingsStores.ts +++ b/src/plugins/_api/userSettingsDefinitions.ts @@ -20,23 +20,30 @@ import { Devs } from "@utils/constants"; import definePlugin from "@utils/types"; export default definePlugin({ - name: "SettingsStoreAPI", - description: "Patches Discord's SettingsStores to expose their group and name", + name: "UserSettingDefinitionsAPI", + description: "Patches Discord's UserSettingDefinitions to expose their group and name.", authors: [Devs.Nuckyz], patches: [ { find: ",updateSetting:", replacement: [ + // Main setting definition { - match: /(?<=INFREQUENT_USER_ACTION.{0,20}),useSetting:/, - replace: ",settingsStoreApiGroup:arguments[0],settingsStoreApiName:arguments[1]$&" + match: /(?<=INFREQUENT_USER_ACTION.{0,20},)useSetting:/, + replace: "userSettingDefinitionsAPIGroup:arguments[0],userSettingDefinitionsAPIName:arguments[1],$&" }, - // some wrapper. just make it copy the group and name + // Selective wrapper { - match: /updateSetting:.{0,20}shouldSync/, - replace: "settingsStoreApiGroup:arguments[0].settingsStoreApiGroup,settingsStoreApiName:arguments[0].settingsStoreApiName,$&" + match: /updateSetting:.{0,100}SELECTIVELY_SYNCED_USER_SETTINGS_UPDATE/, + replace: "userSettingDefinitionsAPIGroup:arguments[0].userSettingDefinitionsAPIGroup,userSettingDefinitionsAPIName:arguments[0].userSettingDefinitionsAPIName,$&" + }, + // Override wrapper + { + match: /updateSetting:.{0,60}USER_SETTINGS_OVERRIDE_CLEAR/, + replace: "userSettingDefinitionsAPIGroup:arguments[0].userSettingDefinitionsAPIGroup,userSettingDefinitionsAPIName:arguments[0].userSettingDefinitionsAPIName,$&" } + ] } ] diff --git a/src/plugins/betterRoleContext/index.tsx b/src/plugins/betterRoleContext/index.tsx index d69e188c0..77be0e2b0 100644 --- a/src/plugins/betterRoleContext/index.tsx +++ b/src/plugins/betterRoleContext/index.tsx @@ -5,7 +5,7 @@ */ import { definePluginSettings } from "@api/Settings"; -import { getSettingStoreLazy } from "@api/SettingsStores"; +import { getUserSettingDefinitionLazy } from "@api/UserSettingDefinitions"; import { ImageIcon } from "@components/Icons"; import { Devs } from "@utils/constants"; import { getCurrentGuild, openImageModal } from "@utils/discord"; @@ -15,7 +15,7 @@ import { Clipboard, GuildStore, Menu, PermissionStore } from "@webpack/common"; const GuildSettingsActions = findByPropsLazy("open", "selectRole", "updateGuild"); -const DeveloperMode = getSettingStoreLazy("appearance", "developerMode")!; +const DeveloperMode = getUserSettingDefinitionLazy("appearance", "developerMode")!; function PencilIcon() { return ( @@ -65,7 +65,7 @@ export default definePlugin({ name: "BetterRoleContext", description: "Adds options to copy role color / edit role / view role icon when right clicking roles in the user profile", authors: [Devs.Ven, Devs.goodbee], - dependencies: ["SettingsStoreAPI"], + dependencies: ["UserSettingDefinitionsAPI"], settings, diff --git a/src/plugins/customRPC/index.tsx b/src/plugins/customRPC/index.tsx index 7e4e9a938..ed2de9b4d 100644 --- a/src/plugins/customRPC/index.tsx +++ b/src/plugins/customRPC/index.tsx @@ -17,7 +17,7 @@ */ import { definePluginSettings, Settings } from "@api/Settings"; -import { getSettingStoreLazy } from "@api/SettingsStores"; +import { getUserSettingDefinitionLazy } from "@api/UserSettingDefinitions"; import { ErrorCard } from "@components/ErrorCard"; import { Link } from "@components/Link"; import { Devs } from "@utils/constants"; @@ -33,8 +33,7 @@ const useProfileThemeStyle = findByCodeLazy("profileThemeStyle:", "--profile-gra const ActivityComponent = findComponentByCodeLazy("onOpenGameProfile"); const ActivityClassName = findByPropsLazy("activity", "buttonColor"); -const ShowCurrentGame = getSettingStoreLazy("status", "showCurrentGame")!; - +const ShowCurrentGame = getUserSettingDefinitionLazy("status", "showCurrentGame")!; async function getApplicationAsset(key: string): Promise { if (/https?:\/\/(cdn|media)\.discordapp\.(com|net)\/attachments\//.test(key)) return "mp:" + key.replace(/https?:\/\/(cdn|media)\.discordapp\.(com|net)\//, ""); @@ -394,7 +393,7 @@ export default definePlugin({ name: "CustomRPC", description: "Allows you to set a custom rich presence.", authors: [Devs.captain, Devs.AutumnVN, Devs.nin0dev], - dependencies: ["SettingsStoreAPI"], + dependencies: ["UserSettingDefinitionsAPI"], start: setRpc, stop: () => setRpc(true), settings, diff --git a/src/plugins/gameActivityToggle/index.tsx b/src/plugins/gameActivityToggle/index.tsx index 4e2a390d6..e7353a5d9 100644 --- a/src/plugins/gameActivityToggle/index.tsx +++ b/src/plugins/gameActivityToggle/index.tsx @@ -17,8 +17,8 @@ */ import { definePluginSettings } from "@api/Settings"; -import { getSettingStoreLazy } from "@api/SettingsStores"; import { disableStyle, enableStyle } from "@api/Styles"; +import { getUserSettingDefinitionLazy } from "@api/UserSettingDefinitions"; import ErrorBoundary from "@components/ErrorBoundary"; import { Devs } from "@utils/constants"; import definePlugin, { OptionType } from "@utils/types"; @@ -28,7 +28,7 @@ import style from "./style.css?managed"; const Button = findComponentByCodeLazy("Button.Sizes.NONE,disabled:"); -const ShowCurrentGame = getSettingStoreLazy("status", "showCurrentGame")!; +const ShowCurrentGame = getUserSettingDefinitionLazy("status", "showCurrentGame")!; function makeIcon(showCurrentGame?: boolean) { const { oldIcon } = settings.use(["oldIcon"]); @@ -87,7 +87,7 @@ export default definePlugin({ name: "GameActivityToggle", description: "Adds a button next to the mic and deafen button to toggle game activity.", authors: [Devs.Nuckyz, Devs.RuukuLada], - dependencies: ["SettingsStoreAPI"], + dependencies: ["UserSettingDefinitionsAPI"], settings, patches: [ diff --git a/src/plugins/ignoreActivities/index.tsx b/src/plugins/ignoreActivities/index.tsx index 6e34c79f3..431cd3e04 100644 --- a/src/plugins/ignoreActivities/index.tsx +++ b/src/plugins/ignoreActivities/index.tsx @@ -6,7 +6,7 @@ import * as DataStore from "@api/DataStore"; import { definePluginSettings, Settings } from "@api/Settings"; -import { getSettingStoreLazy } from "@api/SettingsStores"; +import { getUserSettingDefinitionLazy } from "@api/UserSettingDefinitions"; import ErrorBoundary from "@components/ErrorBoundary"; import { Flex } from "@components/Flex"; import { Devs } from "@utils/constants"; @@ -28,7 +28,7 @@ interface IgnoredActivity { const RunningGameStore = findStoreLazy("RunningGameStore"); -const ShowCurrentGame = getSettingStoreLazy("status", "showCurrentGame")!; +const ShowCurrentGame = getUserSettingDefinitionLazy("status", "showCurrentGame")!; function ToggleIcon(activity: IgnoredActivity, tooltipText: string, path: string, fill: string) { return ( @@ -208,7 +208,7 @@ export default definePlugin({ name: "IgnoreActivities", authors: [Devs.Nuckyz], description: "Ignore activities from showing up on your status ONLY. You can configure which ones are specifically ignored from the Registered Games and Activities tabs, or use the general settings below.", - dependencies: ["SettingsStoreAPI"], + dependencies: ["UserSettingDefinitionsAPI"], settings, diff --git a/src/plugins/messageLinkEmbeds/index.tsx b/src/plugins/messageLinkEmbeds/index.tsx index 70681fb28..9fefc82a2 100644 --- a/src/plugins/messageLinkEmbeds/index.tsx +++ b/src/plugins/messageLinkEmbeds/index.tsx @@ -19,7 +19,7 @@ import { addAccessory, removeAccessory } from "@api/MessageAccessories"; import { updateMessage } from "@api/MessageUpdater"; import { definePluginSettings } from "@api/Settings"; -import { getSettingStoreLazy } from "@api/SettingsStores"; +import { getUserSettingDefinitionLazy } from "@api/UserSettingDefinitions"; import ErrorBoundary from "@components/ErrorBoundary"; import { Devs } from "@utils/constants.js"; import { classes } from "@utils/misc"; @@ -54,7 +54,7 @@ const ChannelMessage = findComponentByCodeLazy("childrenExecutedCommand:", ".hid const SearchResultClasses = findByPropsLazy("message", "searchResult"); const EmbedClasses = findByPropsLazy("embedAuthorIcon", "embedAuthor", "embedAuthor"); -const MessageDisplayCompact = getSettingStoreLazy("textAndImages", "messageDisplayCompact")!; +const MessageDisplayCompact = getUserSettingDefinitionLazy("textAndImages", "messageDisplayCompact")!; const messageLinkRegex = /(? } - // FIXME: wtf is this? do we need to pass some proper component?? + // Don't render forward message button renderForwardComponent={() => null} shouldHideMediaOptions={false} shouldAnimate diff --git a/src/webpack/common/index.ts b/src/webpack/common/index.ts index 5da3cc68b..4193330cb 100644 --- a/src/webpack/common/index.ts +++ b/src/webpack/common/index.ts @@ -20,9 +20,9 @@ export * from "./classes"; export * from "./components"; export * from "./menu"; export * from "./react"; -export * from "./settingsStores"; export * from "./stores"; export * as ComponentTypes from "./types/components.d"; export * as MenuTypes from "./types/menu.d"; export * as UtilTypes from "./types/utils.d"; +export * from "./userSettings"; export * from "./utils"; diff --git a/src/webpack/common/types/index.d.ts b/src/webpack/common/types/index.d.ts index 01c968553..a536cdcf1 100644 --- a/src/webpack/common/types/index.d.ts +++ b/src/webpack/common/types/index.d.ts @@ -21,6 +21,5 @@ export * from "./components"; export * from "./fluxEvents"; export * from "./i18nMessages"; export * from "./menu"; -export * from "./settingsStores"; export * from "./stores"; export * from "./utils"; diff --git a/src/webpack/common/types/settingsStores.ts b/src/webpack/common/types/settingsStores.ts deleted file mode 100644 index 5453ca352..000000000 --- a/src/webpack/common/types/settingsStores.ts +++ /dev/null @@ -1,11 +0,0 @@ -/* - * Vencord, a Discord client mod - * Copyright (c) 2024 Vendicated and contributors - * SPDX-License-Identifier: GPL-3.0-or-later - */ - -export interface SettingsStore { - getSetting(): T; - updateSetting(value: T): void; - useSetting(): T; -} diff --git a/src/webpack/common/types/utils.d.ts b/src/webpack/common/types/utils.d.ts index 7f6249be6..ee3f69944 100644 --- a/src/webpack/common/types/utils.d.ts +++ b/src/webpack/common/types/utils.d.ts @@ -82,7 +82,7 @@ interface RestRequestData { retries?: number; } -export type RestAPI = Record<"delete" | "get" | "patch" | "post" | "put", (data: RestRequestData) => Promise>; +export type RestAPI = Record<"del" | "get" | "patch" | "post" | "put", (data: RestRequestData) => Promise>; export type Permissions = "CREATE_INSTANT_INVITE" | "KICK_MEMBERS" diff --git a/src/webpack/common/settingsStores.ts b/src/webpack/common/userSettings.ts similarity index 100% rename from src/webpack/common/settingsStores.ts rename to src/webpack/common/userSettings.ts From ceaaf9ab8a3bb87494573a8442f31cc4a2396bbf Mon Sep 17 00:00:00 2001 From: Nuckyz <61953774+Nuckyz@users.noreply.github.com> Date: Thu, 20 Jun 2024 01:00:07 -0300 Subject: [PATCH 02/27] Reporter: Test mapMangledModule --- src/debug/runReporter.ts | 15 ++++++++++++--- src/webpack/webpack.ts | 4 +++- 2 files changed, 15 insertions(+), 4 deletions(-) diff --git a/src/debug/runReporter.ts b/src/debug/runReporter.ts index 6c7a2a03f..ddd5e5f18 100644 --- a/src/debug/runReporter.ts +++ b/src/debug/runReporter.ts @@ -39,9 +39,8 @@ async function runReporter() { } if (searchType === "waitForStore") method = "findStore"; + let result: any; try { - let result: any; - if (method === "proxyLazyWebpack" || method === "LazyComponentWebpack") { const [factory] = args; result = factory(); @@ -50,16 +49,26 @@ async function runReporter() { result = await Webpack.extractAndLoadChunks(code, matcher); if (result === false) result = null; + } else if (method === "mapMangledModule") { + const [code, mapper] = args; + + result = Webpack.mapMangledModule(code, mapper); + if (Object.keys(result).length !== Object.keys(mapper).length) throw new Error("Webpack Find Fail"); } else { // @ts-ignore result = Webpack[method](...args); } - if (result == null || (result.$$vencordInternal != null && result.$$vencordInternal() == null)) throw "a rock at ben shapiro"; + if (result == null || (result.$$vencordInternal != null && result.$$vencordInternal() == null)) throw new Error("Webpack Find Fail"); } catch (e) { let logMessage = searchType; if (method === "find" || method === "proxyLazyWebpack" || method === "LazyComponentWebpack") logMessage += `(${args[0].toString().slice(0, 147)}...)`; else if (method === "extractAndLoadChunks") logMessage += `([${args[0].map(arg => `"${arg}"`).join(", ")}], ${args[1].toString()})`; + else if (method === "mapMangledModule") { + const failedMappings = Object.keys(args[1]).filter(key => result?.[key] == null); + + logMessage += `("${args[0]}", {\n${failedMappings.map(mapping => `\t${mapping}: ${args[1][mapping].toString().slice(0, 147)}...`).join(",\n")}\n})`; + } else logMessage += `(${args.map(arg => `"${arg}"`).join(", ")})`; ReporterLogger.log("Webpack Find Fail:", logMessage); diff --git a/src/webpack/webpack.ts b/src/webpack/webpack.ts index b536063e8..f776ab1c3 100644 --- a/src/webpack/webpack.ts +++ b/src/webpack/webpack.ts @@ -279,7 +279,7 @@ export function findModuleFactory(...code: string[]) { return wreq.m[id]; } -export const lazyWebpackSearchHistory = [] as Array<["find" | "findByProps" | "findByCode" | "findStore" | "findComponent" | "findComponentByCode" | "findExportedComponent" | "waitFor" | "waitForComponent" | "waitForStore" | "proxyLazyWebpack" | "LazyComponentWebpack" | "extractAndLoadChunks", any[]]>; +export const lazyWebpackSearchHistory = [] as Array<["find" | "findByProps" | "findByCode" | "findStore" | "findComponent" | "findComponentByCode" | "findExportedComponent" | "waitFor" | "waitForComponent" | "waitForStore" | "proxyLazyWebpack" | "LazyComponentWebpack" | "extractAndLoadChunks" | "mapMangledModule", any[]]>; /** * This is just a wrapper around {@link proxyLazy} to make our reporter test for your webpack finds. @@ -483,6 +483,8 @@ export const mapMangledModule = traceFunction("mapMangledModule", function mapMa * }) */ export function mapMangledModuleLazy(code: string, mappers: Record): Record { + if (IS_REPORTER) lazyWebpackSearchHistory.push(["mapMangledModule", [code, mappers]]); + return proxyLazy(() => mapMangledModule(code, mappers)); } From a43d5d595a8b23e36125228d2784cd4baeec056b Mon Sep 17 00:00:00 2001 From: Vendicated Date: Thu, 20 Jun 2024 19:48:37 +0200 Subject: [PATCH 03/27] Plugin Page: add indicator for excluded plugins --- scripts/build/build.mjs | 20 ++- scripts/build/common.mjs | 59 +++++++-- scripts/generatePluginList.ts | 2 +- src/components/PluginSettings/index.tsx | 154 ++++++++++++++--------- src/modules.d.ts | 1 + src/plugins/appleMusic.desktop/index.tsx | 2 +- src/plugins/xsOverlay.desktop/index.ts | 2 +- 7 files changed, 156 insertions(+), 84 deletions(-) diff --git a/scripts/build/build.mjs b/scripts/build/build.mjs index fcf56f66c..817c2cec3 100755 --- a/scripts/build/build.mjs +++ b/scripts/build/build.mjs @@ -21,7 +21,7 @@ import esbuild from "esbuild"; import { readdir } from "fs/promises"; import { join } from "path"; -import { BUILD_TIMESTAMP, commonOpts, exists, globPlugins, IS_DEV, IS_REPORTER, IS_STANDALONE, IS_UPDATER_DISABLED, VERSION, watch } from "./common.mjs"; +import { BUILD_TIMESTAMP, commonOpts, exists, globPlugins, IS_DEV, IS_REPORTER, IS_STANDALONE, IS_UPDATER_DISABLED, resolvePluginName, VERSION, watch } from "./common.mjs"; const defines = { IS_STANDALONE, @@ -76,22 +76,20 @@ const globNativesPlugin = { for (const dir of pluginDirs) { const dirPath = join("src", dir); if (!await exists(dirPath)) continue; - const plugins = await readdir(dirPath); - for (const p of plugins) { - const nativePath = join(dirPath, p, "native.ts"); - const indexNativePath = join(dirPath, p, "native/index.ts"); + const plugins = await readdir(dirPath, { withFileTypes: true }); + for (const file of plugins) { + const fileName = file.name; + const nativePath = join(dirPath, fileName, "native.ts"); + const indexNativePath = join(dirPath, fileName, "native/index.ts"); if (!(await exists(nativePath)) && !(await exists(indexNativePath))) continue; - const nameParts = p.split("."); - const namePartsWithoutTarget = nameParts.length === 1 ? nameParts : nameParts.slice(0, -1); - // pluginName.thing.desktop -> PluginName.thing - const cleanPluginName = p[0].toUpperCase() + namePartsWithoutTarget.join(".").slice(1); + const pluginName = await resolvePluginName(dirPath, file); const mod = `p${i}`; - code += `import * as ${mod} from "./${dir}/${p}/native";\n`; - natives += `${JSON.stringify(cleanPluginName)}:${mod},\n`; + code += `import * as ${mod} from "./${dir}/${fileName}/native";\n`; + natives += `${JSON.stringify(pluginName)}:${mod},\n`; i++; } } diff --git a/scripts/build/common.mjs b/scripts/build/common.mjs index eb7ab905b..c46a559a7 100644 --- a/scripts/build/common.mjs +++ b/scripts/build/common.mjs @@ -53,6 +53,32 @@ export const banner = { `.trim() }; +const PluginDefinitionNameMatcher = /definePlugin\(\{\s*(["'])?name\1:\s*(["'`])(.+?)\2/; +/** + * @param {string} base + * @param {import("fs").Dirent} dirent + */ +export async function resolvePluginName(base, dirent) { + const fullPath = join(base, dirent.name); + const content = dirent.isFile() + ? await readFile(fullPath, "utf-8") + : await (async () => { + for (const file of ["index.ts", "index.tsx"]) { + try { + return await readFile(join(fullPath, file), "utf-8"); + } catch { + continue; + } + } + throw new Error(`Invalid plugin ${fullPath}: could not resolve entry point`); + })(); + + return PluginDefinitionNameMatcher.exec(content)?.[3] + ?? (() => { + throw new Error(`Invalid plugin ${fullPath}: must contain definePlugin call with simple string name property as first property`); + })(); +} + export async function exists(path) { return await access(path, FsConstants.F_OK) .then(() => true) @@ -88,14 +114,16 @@ export const globPlugins = kind => ({ build.onLoad({ filter, namespace: "import-plugins" }, async () => { const pluginDirs = ["plugins/_api", "plugins/_core", "plugins", "userplugins"]; let code = ""; - let plugins = "\n"; - let meta = "\n"; + let pluginsCode = "\n"; + let metaCode = "\n"; + let excludedCode = "\n"; let i = 0; for (const dir of pluginDirs) { const userPlugin = dir === "userplugins"; - if (!await exists(`./src/${dir}`)) continue; - const files = await readdir(`./src/${dir}`, { withFileTypes: true }); + const fullDir = `./src/${dir}`; + if (!await exists(fullDir)) continue; + const files = await readdir(fullDir, { withFileTypes: true }); for (const file of files) { const fileName = file.name; if (fileName.startsWith("_") || fileName.startsWith(".")) continue; @@ -104,23 +132,30 @@ export const globPlugins = kind => ({ const target = getPluginTarget(fileName); if (target && !IS_REPORTER) { - if (target === "dev" && !watch) continue; - if (target === "web" && kind === "discordDesktop") continue; - if (target === "desktop" && kind === "web") continue; - if (target === "discordDesktop" && kind !== "discordDesktop") continue; - if (target === "vencordDesktop" && kind !== "vencordDesktop") continue; + const excluded = + (target === "dev" && !IS_DEV) || + (target === "web" && kind === "discordDesktop") || + (target === "desktop" && kind === "web") || + (target === "discordDesktop" && kind !== "discordDesktop") || + (target === "vencordDesktop" && kind !== "vencordDesktop"); + + if (excluded) { + const name = await resolvePluginName(fullDir, file); + excludedCode += `${JSON.stringify(name)}:${JSON.stringify(target)},\n`; + continue; + } } const folderName = `src/${dir}/${fileName}`.replace(/^src\/plugins\//, ""); const mod = `p${i}`; code += `import ${mod} from "./${dir}/${fileName.replace(/\.tsx?$/, "")}";\n`; - plugins += `[${mod}.name]:${mod},\n`; - meta += `[${mod}.name]:${JSON.stringify({ folderName, userPlugin })},\n`; // TODO: add excluded plugins to display in the UI? + pluginsCode += `[${mod}.name]:${mod},\n`; + metaCode += `[${mod}.name]:${JSON.stringify({ folderName, userPlugin })},\n`; // TODO: add excluded plugins to display in the UI? i++; } } - code += `export default {${plugins}};export const PluginMeta={${meta}};`; + code += `export default {${pluginsCode}};export const PluginMeta={${metaCode}};export const ExcludedPlugins={${excludedCode}};`; return { contents: code, resolveDir: "./src" diff --git a/scripts/generatePluginList.ts b/scripts/generatePluginList.ts index e8aa33a46..3d7c16c01 100644 --- a/scripts/generatePluginList.ts +++ b/scripts/generatePluginList.ts @@ -39,7 +39,7 @@ interface PluginData { hasCommands: boolean; required: boolean; enabledByDefault: boolean; - target: "discordDesktop" | "vencordDesktop" | "web" | "dev"; + target: "discordDesktop" | "vencordDesktop" | "desktop" | "web" | "dev"; filePath: string; } diff --git a/src/components/PluginSettings/index.tsx b/src/components/PluginSettings/index.tsx index 978d2e85a..c659e7838 100644 --- a/src/components/PluginSettings/index.tsx +++ b/src/components/PluginSettings/index.tsx @@ -35,9 +35,9 @@ import { openModalLazy } from "@utils/modal"; import { useAwaiter } from "@utils/react"; import { Plugin } from "@utils/types"; import { findByPropsLazy } from "@webpack"; -import { Alerts, Button, Card, Forms, lodash, Parser, React, Select, Text, TextInput, Toasts, Tooltip } from "@webpack/common"; +import { Alerts, Button, Card, Forms, lodash, Parser, React, Select, Text, TextInput, Toasts, Tooltip, useMemo } from "@webpack/common"; -import Plugins from "~plugins"; +import Plugins, { ExcludedPlugins } from "~plugins"; // Avoid circular dependency const { startDependenciesRecursive, startPlugin, stopPlugin } = proxyLazy(() => require("../../plugins")); @@ -177,6 +177,37 @@ const enum SearchStatus { NEW } +function ExcludedPluginsList({ search }: { search: string; }) { + const matchingExcludedPlugins = Object.entries(ExcludedPlugins) + .filter(([name]) => name.toLowerCase().includes(search)); + + const ExcludedReasons: Record<"web" | "discordDesktop" | "vencordDesktop" | "desktop" | "dev", string> = { + desktop: "Discord Desktop app or Vesktop", + discordDesktop: "Discord Desktop app", + vencordDesktop: "Vesktop app", + web: "Vesktop app and the Web version of Discord", + dev: "Developer version of Vencord" + }; + + return ( + + {matchingExcludedPlugins.length + ? <> + Are you looking for: +
    + {matchingExcludedPlugins.map(([name, reason]) => ( +
  • + {name}: Only available on the {ExcludedReasons[reason]} +
  • + ))} +
+ + : "No plugins meet the search criteria." + } +
+ ); +} + export default function PluginSettings() { const settings = useSettings(); const changes = React.useMemo(() => new ChangeList(), []); @@ -215,26 +246,27 @@ export default function PluginSettings() { return o; }, []); - const sortedPlugins = React.useMemo(() => Object.values(Plugins) + const sortedPlugins = useMemo(() => Object.values(Plugins) .sort((a, b) => a.name.localeCompare(b.name)), []); const [searchValue, setSearchValue] = React.useState({ value: "", status: SearchStatus.ALL }); + const search = searchValue.value.toLowerCase(); const onSearch = (query: string) => setSearchValue(prev => ({ ...prev, value: query })); const onStatusChange = (status: SearchStatus) => setSearchValue(prev => ({ ...prev, status })); const pluginFilter = (plugin: typeof Plugins[keyof typeof Plugins]) => { - const enabled = settings.plugins[plugin.name]?.enabled; - if (enabled && searchValue.status === SearchStatus.DISABLED) return false; - if (!enabled && searchValue.status === SearchStatus.ENABLED) return false; - if (searchValue.status === SearchStatus.NEW && !newPlugins?.includes(plugin.name)) return false; - if (!searchValue.value.length) return true; + const { status } = searchValue; + const enabled = Vencord.Plugins.isPluginEnabled(plugin.name); + if (enabled && status === SearchStatus.DISABLED) return false; + if (!enabled && status === SearchStatus.ENABLED) return false; + if (status === SearchStatus.NEW && !newPlugins?.includes(plugin.name)) return false; + if (!search.length) return true; - const v = searchValue.value.toLowerCase(); return ( - plugin.name.toLowerCase().includes(v) || - plugin.description.toLowerCase().includes(v) || - plugin.tags?.some(t => t.toLowerCase().includes(v)) + plugin.name.toLowerCase().includes(search) || + plugin.description.toLowerCase().includes(search) || + plugin.tags?.some(t => t.toLowerCase().includes(search)) ); }; @@ -255,54 +287,48 @@ export default function PluginSettings() { return lodash.isEqual(newPlugins, sortedPluginNames) ? [] : newPlugins; })); - type P = JSX.Element | JSX.Element[]; - let plugins: P, requiredPlugins: P; - if (sortedPlugins?.length) { - plugins = []; - requiredPlugins = []; + const plugins = [] as JSX.Element[]; + const requiredPlugins = [] as JSX.Element[]; - const showApi = searchValue.value === "API"; - for (const p of sortedPlugins) { - if (p.hidden || (!p.options && p.name.endsWith("API") && !showApi)) - continue; + const showApi = searchValue.value.includes("API"); + for (const p of sortedPlugins) { + if (p.hidden || (!p.options && p.name.endsWith("API") && !showApi)) + continue; - if (!pluginFilter(p)) continue; + if (!pluginFilter(p)) continue; - const isRequired = p.required || depMap[p.name]?.some(d => settings.plugins[d].enabled); + const isRequired = p.required || depMap[p.name]?.some(d => settings.plugins[d].enabled); - if (isRequired) { - const tooltipText = p.required - ? "This plugin is required for Vencord to function." - : makeDependencyList(depMap[p.name]?.filter(d => settings.plugins[d].enabled)); - - requiredPlugins.push( - - {({ onMouseLeave, onMouseEnter }) => ( - changes.handleChange(name)} - disabled={true} - plugin={p} - /> - )} - - ); - } else { - plugins.push( - changes.handleChange(name)} - disabled={false} - plugin={p} - isNew={newPlugins?.includes(p.name)} - key={p.name} - /> - ); - } + if (isRequired) { + const tooltipText = p.required + ? "This plugin is required for Vencord to function." + : makeDependencyList(depMap[p.name]?.filter(d => settings.plugins[d].enabled)); + requiredPlugins.push( + + {({ onMouseLeave, onMouseEnter }) => ( + changes.handleChange(name)} + disabled={true} + plugin={p} + key={p.name} + /> + )} + + ); + } else { + plugins.push( + changes.handleChange(name)} + disabled={false} + plugin={p} + isNew={newPlugins?.includes(p.name)} + key={p.name} + /> + ); } - } else { - plugins = requiredPlugins = No plugins meet search criteria.; } return ( @@ -333,9 +359,18 @@ export default function PluginSettings() { Plugins -
- {plugins} -
+ {plugins.length || requiredPlugins.length + ? ( +
+ {plugins.length + ? plugins + : No plugins meet the search criteria. + } +
+ ) + : + } + @@ -343,7 +378,10 @@ export default function PluginSettings() { Required Plugins
- {requiredPlugins} + {requiredPlugins.length + ? requiredPlugins + : No plugins meet the search criteria. + }
); diff --git a/src/modules.d.ts b/src/modules.d.ts index 70ffcfb91..7566a5bf4 100644 --- a/src/modules.d.ts +++ b/src/modules.d.ts @@ -26,6 +26,7 @@ declare module "~plugins" { folderName: string; userPlugin: boolean; }>; + export const ExcludedPlugins: Record; } declare module "~pluginNatives" { diff --git a/src/plugins/appleMusic.desktop/index.tsx b/src/plugins/appleMusic.desktop/index.tsx index 0d81204e9..6fa989cdd 100644 --- a/src/plugins/appleMusic.desktop/index.tsx +++ b/src/plugins/appleMusic.desktop/index.tsx @@ -9,7 +9,7 @@ import { Devs } from "@utils/constants"; import definePlugin, { OptionType, PluginNative, ReporterTestable } from "@utils/types"; import { ApplicationAssetUtils, FluxDispatcher, Forms } from "@webpack/common"; -const Native = VencordNative.pluginHelpers.AppleMusic as PluginNative; +const Native = VencordNative.pluginHelpers.AppleMusicRichPresence as PluginNative; interface ActivityAssets { large_image?: string; diff --git a/src/plugins/xsOverlay.desktop/index.ts b/src/plugins/xsOverlay.desktop/index.ts index a68373a6a..b42d20210 100644 --- a/src/plugins/xsOverlay.desktop/index.ts +++ b/src/plugins/xsOverlay.desktop/index.ts @@ -136,7 +136,7 @@ const settings = definePluginSettings({ }, }); -const Native = VencordNative.pluginHelpers.XsOverlay as PluginNative; +const Native = VencordNative.pluginHelpers.XSOverlay as PluginNative; export default definePlugin({ name: "XSOverlay", From a5be1873ba45066d982c8fbdae1f6b68cd303fb7 Mon Sep 17 00:00:00 2001 From: vishnyanetchereshnya <151846235+vishnyanetchereshnya@users.noreply.github.com> Date: Thu, 20 Jun 2024 23:47:15 +0300 Subject: [PATCH 04/27] [Plugin] NotesSearcher Allows you to open modal with all of your notes and search throught them by UserID, Note text and Global/Username if user is cached --- src/plugins/notesSearcher/README.md | 8 + .../notesSearcher/components/Icons.tsx | 76 +++ .../components/NotesDataButton.tsx | 27 + .../components/NotesDataModal.tsx | 514 ++++++++++++++++++ src/plugins/notesSearcher/data.ts | 101 ++++ src/plugins/notesSearcher/index.tsx | 70 +++ src/plugins/notesSearcher/settings.tsx | 16 + src/plugins/notesSearcher/styles.css | 296 ++++++++++ 8 files changed, 1108 insertions(+) create mode 100644 src/plugins/notesSearcher/README.md create mode 100644 src/plugins/notesSearcher/components/Icons.tsx create mode 100644 src/plugins/notesSearcher/components/NotesDataButton.tsx create mode 100644 src/plugins/notesSearcher/components/NotesDataModal.tsx create mode 100644 src/plugins/notesSearcher/data.ts create mode 100644 src/plugins/notesSearcher/index.tsx create mode 100644 src/plugins/notesSearcher/settings.tsx create mode 100644 src/plugins/notesSearcher/styles.css diff --git a/src/plugins/notesSearcher/README.md b/src/plugins/notesSearcher/README.md new file mode 100644 index 000000000..960415fd3 --- /dev/null +++ b/src/plugins/notesSearcher/README.md @@ -0,0 +1,8 @@ +# NotesSearcher + +Allows you to open modal with all of your notes and search throught them by UserID, Note text and Global/Username if user is cached + +## Preview + +![preview](https://i.imgur.com/FJl4W13.png) +![preview](https://i.imgur.com/nCyP8Uf.png) diff --git a/src/plugins/notesSearcher/components/Icons.tsx b/src/plugins/notesSearcher/components/Icons.tsx new file mode 100644 index 000000000..90543feb1 --- /dev/null +++ b/src/plugins/notesSearcher/components/Icons.tsx @@ -0,0 +1,76 @@ +/* + * Vencord, a Discord client mod + * Copyright (c) 2024 Vendicated and contributors + * SPDX-License-Identifier: GPL-3.0-or-later + */ + +import { LazyComponent } from "@utils/lazyReact"; +import { React } from "@webpack/common"; + +export const NotesDataIcon = LazyComponent(() => React.memo(() => { + return ( + + + + ); +})); + +export const SaveIcon = LazyComponent(() => React.memo(() => { + return ( + + + + ); +})); + +export const DeleteIcon = LazyComponent(() => React.memo(() => { + return ( + + + + ); +})); + +export const RefreshIcon = LazyComponent(() => React.memo(() => { + return ( + + + + ); +})); + +export const PopupIcon = LazyComponent(() => React.memo(() => { + return ( + + + + + ); +})); + +export const CrossIcon = LazyComponent(() => React.memo(() => { + return ( + + + + + ); +})); + +export const ProblemIcon = LazyComponent(() => React.memo(() => { + return ( + + + + + ); +})); + +export const SuccessIcon = LazyComponent(() => React.memo(() => { + return ( + + + + + ); +})); diff --git a/src/plugins/notesSearcher/components/NotesDataButton.tsx b/src/plugins/notesSearcher/components/NotesDataButton.tsx new file mode 100644 index 000000000..030e43dfa --- /dev/null +++ b/src/plugins/notesSearcher/components/NotesDataButton.tsx @@ -0,0 +1,27 @@ +/* + * Vencord, a Discord client mod + * Copyright (c) 2024 Vendicated and contributors + * SPDX-License-Identifier: GPL-3.0-or-later + */ + +import { LazyComponent } from "@utils/react"; +import { filters, find } from "@webpack"; + +import { NotesDataIcon } from "./Icons"; +import { openNotesDataModal } from "./NotesDataModal"; + +const HeaderBarIcon = LazyComponent(() => { + const filter = filters.byCode(".HEADER_BAR_BADGE"); + return find(m => m.Icon && filter(m.Icon)).Icon; +}); + +export function OpenNotesDataButton() { + return ( + openNotesDataModal()} + tooltip={"Open Notes Data"} + icon={NotesDataIcon} + /> + ); +} diff --git a/src/plugins/notesSearcher/components/NotesDataModal.tsx b/src/plugins/notesSearcher/components/NotesDataModal.tsx new file mode 100644 index 000000000..fbdb68bab --- /dev/null +++ b/src/plugins/notesSearcher/components/NotesDataModal.tsx @@ -0,0 +1,514 @@ +/* + * Vencord, a Discord client mod + * Copyright (c) 2024 Vendicated and contributors + * SPDX-License-Identifier: GPL-3.0-or-later + */ + +import { classNameFactory } from "@api/Styles"; +import { openPrivateChannel, openUserProfile } from "@utils/discord"; +import { copyWithToast } from "@utils/misc"; +import { + closeModal, ModalCloseButton, ModalContent, ModalHeader, ModalProps, ModalRoot, openModal +} from "@utils/modal"; +import { LazyComponent, useAwaiter } from "@utils/react"; +import { Alerts, Avatar, Button, ContextMenuApi, Menu, Popout, React, RelationshipStore, Select, Text, TextArea, TextInput, Tooltip, useCallback, useMemo, useReducer, UserUtils, useState } from "@webpack/common"; + +import { cacheUsers, getRunning, NotesMap, putNote, setupStates, stopCacheProcess, updateNote, usersCache } from "../data"; +import { CrossIcon, DeleteIcon, PopupIcon, ProblemIcon, RefreshIcon, SaveIcon, SuccessIcon } from "./Icons"; + +const cl = classNameFactory("vc-notes-searcher-modal-"); + +const enum SearchStatus { + ALL, + FRIENDS, + BLOCKED, +} + +const filterByUserDetails = (userId: string, query: string) => { + if (userId.includes(query)) return true; + + const user = usersCache.get(userId); + + if (!user) return false; + + return user.globalName?.includes(query) || user.username.includes(query); +}; + +// looks like a shit but I didn't know better way to do it +let RefreshNotesDataEx: () => void | undefined; + +export const refreshNotesData = () => { + if (!RefreshNotesDataEx) return; + + RefreshNotesDataEx(); +}; + +export function NotesDataModal({ modalProps, close }: { + modalProps: ModalProps; + close(): void; +}) { + const [shouldShow, setShouldShow] = useState(false); + + const [searchValue, setSearchValue] = useState({ query: "", status: SearchStatus.ALL }); + + const onSearch = (query: string) => setSearchValue(prev => ({ ...prev, query })); + const onStatusChange = (status: SearchStatus) => setSearchValue(prev => ({ ...prev, status })); + + const [usersNotesData, refreshNotesData] = useReducer(() => { + return Array.from(NotesMap); + }, Array.from(NotesMap)); + + RefreshNotesDataEx = refreshNotesData; + + const filteredNotes = useMemo(() => { + const { query, status } = searchValue; + + if (query === "" && status === SearchStatus.ALL) { + return usersNotesData; + } + + return usersNotesData + .filter(([userId, userNotes]) => { + return ( + status === SearchStatus.FRIENDS ? + RelationshipStore.isFriend(userId) && + ( + query === "" || + ( + filterByUserDetails(userId, query) || + userNotes.toLowerCase().includes(query.toLowerCase()) + ) + ) + : + status === SearchStatus.BLOCKED ? + RelationshipStore.isBlocked(userId) && + ( + query === "" || + ( + filterByUserDetails(userId, query) || + userNotes.toLowerCase().includes(query.toLowerCase()) + ) + ) + : + query === "" || + ( + filterByUserDetails(userId, query) || + userNotes.toLowerCase().includes(query.toLowerCase()) + ) + ); + }); + }, [usersNotesData, searchValue]); + + const [visibleNotesNum, setVisibleNotesNum] = useState(10); + + const loadMore = useCallback(() => { + setVisibleNotesNum(prevNum => prevNum + 10); + }, []); + + const visibleNotes = filteredNotes.slice(0, visibleNotesNum); + + const canLoadMore = visibleNotesNum < filteredNotes.length; + + return ( + + + Notes Data + +
+