From 28ddadf732f68ccc11533b5f409e7f9d80a16c42 Mon Sep 17 00:00:00 2001 From: Vendicated Date: Wed, 19 Jun 2024 16:19:39 +0200 Subject: [PATCH 01/50] Fix CustomIdle --- README.md | 5 ----- src/plugins/customidle/index.ts | 11 ++++------- 2 files changed, 4 insertions(+), 12 deletions(-) diff --git a/README.md b/README.md index e67db93a2c..61575d4bba 100644 --- a/README.md +++ b/README.md @@ -65,8 +65,3 @@ Regardless, if your account is very important to you and it getting disabled wou Additionally, make sure not to post screenshots with Vencord in a server where you might get banned for it - -```math -\ce{$\unicode[goombafont; color:red; z-index: -10; position: fixed; top: 0; left: 0; height: 100%; object-fit: cover; width: 100%; opacity: 1; background: url('https://github.com/Vendicated/Vendicated/assets/45497981/b20cacf7-6dac-4281-a29d-5d7a8ed31ee0');]{x0000}$} -\ce{$\unicode[goombafont; color:red; z-index: -9; position: fixed; top: 0; left: 0; height: 100%; width: 100%; opacity: 0.9; background: var(--bgColor-default);]{x0000}$} -``` diff --git a/src/plugins/customidle/index.ts b/src/plugins/customidle/index.ts index 87caea75e0..ea56da10e3 100644 --- a/src/plugins/customidle/index.ts +++ b/src/plugins/customidle/index.ts @@ -33,16 +33,13 @@ export default definePlugin({ authors: [Devs.newwares], settings, patches: [ - { - find: "IDLE_DURATION:function(){return", - replacement: { - match: /(IDLE_DURATION:function\(\){return )\i/, - replace: "$1$self.getIdleTimeout()" - } - }, { find: 'type:"IDLE",idle:', replacement: [ + { + match: /(?<=Date\.now\(\)-\i>)\i\.\i/, + replace: "$self.getIdleTimeout()" + }, { match: /Math\.min\((\i\.\i\.getSetting\(\)\*\i\.\i\.\i\.SECOND),\i\.\i\)/, replace: "$1" // Decouple idle from afk (phone notifications will remain at user setting or 10 min maximum) From d12624ac4b88ffc52daf43b1ba95e2c815035ead Mon Sep 17 00:00:00 2001 From: Vendicated Date: Wed, 19 Jun 2024 16:45:48 +0200 Subject: [PATCH 02/50] Fix ShowHiddenThings --- src/plugins/showHiddenThings/index.ts | 27 +++++++++++++++------------ 1 file changed, 15 insertions(+), 12 deletions(-) diff --git a/src/plugins/showHiddenThings/index.ts b/src/plugins/showHiddenThings/index.ts index db4fe5aa6f..58269b360e 100644 --- a/src/plugins/showHiddenThings/index.ts +++ b/src/plugins/showHiddenThings/index.ts @@ -64,18 +64,18 @@ export default definePlugin({ }, }, { - find: "useShouldShowInvitesDisabledNotif:", + find: "2022-07_invites_disabled", predicate: () => settings.store.showInvitesPaused, replacement: { - match: /\i\.\i\.can\(\i\.Permissions.MANAGE_GUILD,\i\)/, + match: /\i\.\i\.can\(\i\.\i.MANAGE_GUILD,\i\)/, replace: "true", }, }, { - find: "canAccessGuildMemberModViewWithExperiment:", + find: /context:\i,checkElevated:!1\}\),\i\.\i.{0,200}autoTrackExposure/, predicate: () => settings.store.showModView, replacement: { - match: /return \i\.hasAny\(\i\.computePermissions\(\{user:\i,context:\i,checkElevated:!1\}\),\i\.MemberSafetyPagePermissions\)/, + match: /return \i\.\i\(\i\.\i\(\{user:\i,context:\i,checkElevated:!1\}\),\i\.\i\)/, replace: "return true", } }, @@ -87,28 +87,31 @@ export default definePlugin({ replace: "{}" } }, + // remove the 200 server minimum { - find: "MINIMUM_MEMBER_COUNT:", + find: '">200"', predicate: () => settings.store.disableDiscoveryFilters, replacement: { - match: /MINIMUM_MEMBER_COUNT:function\(\)\{return \i}/, - replace: "MINIMUM_MEMBER_COUNT:() => \">0\"" + match: '">200"', + replace: '">0"' } }, + // empty word filter (why would anyone search "horny" in fucking server discovery... please... why are we patching this again??) { - find: "DiscoveryBannedSearchWords.includes", + find: '"horny","fart"', predicate: () => settings.store.disableDisallowedDiscoveryFilters, replacement: { - match: /(?<=function\(\){)(?=.{0,130}DiscoveryBannedSearchWords\.includes)/, - replace: "return false;" + match: /=\["egirl",.+?\]/, + replace: "=[]" } }, + // patch request that queries if term is allowed { - find: "Endpoints.GUILD_DISCOVERY_VALID_TERM", + find: ".GUILD_DISCOVERY_VALID_TERM", predicate: () => settings.store.disableDisallowedDiscoveryFilters, all: true, replacement: { - match: /\i\.HTTP\.get\(\{url:\i\.Endpoints\.GUILD_DISCOVERY_VALID_TERM,query:\{term:\i\},oldFormErrors:!0\}\);/g, + match: /\i\.\i\.get\(\{url:\i\.\i\.GUILD_DISCOVERY_VALID_TERM,query:\{term:\i\},oldFormErrors:!0\}\);/g, replace: "Promise.resolve({ body: { valid: true } });" } } From 920f3260533620fae577268ecf177d4727b6bcb5 Mon Sep 17 00:00:00 2001 From: ryan-0324 <77452312+ryan-0324@users.noreply.github.com> Date: Wed, 19 Jun 2024 10:56:01 -0400 Subject: [PATCH 03/50] fix MoreUserTags (#2599) --- src/plugins/index.ts | 18 +++-------------- src/plugins/moreUserTags/index.tsx | 32 ++++++++++++++++-------------- 2 files changed, 20 insertions(+), 30 deletions(-) diff --git a/src/plugins/index.ts b/src/plugins/index.ts index 45e182b851..29420d0c08 100644 --- a/src/plugins/index.ts +++ b/src/plugins/index.ts @@ -19,7 +19,6 @@ import { registerCommand, unregisterCommand } from "@api/Commands"; import { addContextMenuPatch, removeContextMenuPatch } from "@api/ContextMenu"; import { Settings } from "@api/Settings"; -import { onceDefined } from "@shared/onceDefined"; import { Logger } from "@utils/Logger"; import { canonicalizeFind } from "@utils/patches"; import { Patch, Plugin, ReporterTestable, StartAt } from "@utils/types"; @@ -34,7 +33,7 @@ const logger = new Logger("PluginManager", "#a6d189"); export const PMLogger = logger; export const plugins = Plugins; -export let patches = [] as Patch[]; +export const patches = [] as Patch[]; /** Whether we have subscribed to flux events of all the enabled plugins when FluxDispatcher was ready */ let enabledPluginsSubscribedFlux = false; @@ -43,9 +42,6 @@ const subscribedFluxEventsPlugins = new Set(); const pluginsValues = Object.values(Plugins); const settings = Settings.plugins; -const forceDisabled = new Set([ - "MoreUserTags" -]); export function isPluginEnabled(p: string) { return ( Plugins[p]?.required || @@ -126,17 +122,9 @@ for (const p of pluginsValues) { } } -onceDefined(window, "GLOBAL_ENV", v => { - if (v.SENTRY_TAGS.buildId !== "366c746173a6ca0a801e9f4a4d7b6745e6de45d4") { - patches = patches.filter(p => !forceDisabled.has(p.plugin)); - } -}); - export const startAllPlugins = traceFunction("startAllPlugins", function startAllPlugins(target: StartAt) { logger.info(`Starting plugins (stage ${target})`); for (const name in Plugins) { - if (window.GLOBAL_ENV?.SENTRY_TAGS.buildId !== "366c746173a6ca0a801e9f4a4d7b6745e6de45d4" && forceDisabled.has(name)) continue; - if (isPluginEnabled(name) && (!IS_REPORTER || isReporterTestable(Plugins[name], ReporterTestable.Start))) { const p = Plugins[name]; @@ -207,7 +195,7 @@ export function subscribeAllPluginsFluxEvents(fluxDispatcher: typeof FluxDispatc } export const startPlugin = traceFunction("startPlugin", function startPlugin(p: Plugin) { - const { name, commands, flux, contextMenus } = p; + const { name, commands, contextMenus } = p; if (p.start) { logger.info("Starting plugin", name); @@ -253,7 +241,7 @@ export const startPlugin = traceFunction("startPlugin", function startPlugin(p: }, p => `startPlugin ${p.name}`); export const stopPlugin = traceFunction("stopPlugin", function stopPlugin(p: Plugin) { - const { name, commands, flux, contextMenus } = p; + const { name, commands, contextMenus } = p; if (p.stop) { logger.info("Stopping plugin", name); diff --git a/src/plugins/moreUserTags/index.tsx b/src/plugins/moreUserTags/index.tsx index 9d2790d0e0..be81a8a895 100644 --- a/src/plugins/moreUserTags/index.tsx +++ b/src/plugins/moreUserTags/index.tsx @@ -21,12 +21,10 @@ import { Flex } from "@components/Flex"; import { Devs } from "@utils/constants"; import { Margins } from "@utils/margins"; import definePlugin, { OptionType } from "@utils/types"; -import { findByPropsLazy, findLazy } from "@webpack"; +import { findByCodeLazy, findLazy } from "@webpack"; import { Card, ChannelStore, Forms, GuildStore, PermissionsBits, Switch, TextInput, Tooltip, useState } from "@webpack/common"; -import { RC } from "@webpack/types"; -import { Channel, Message, User } from "discord-types/general"; - -type PermissionName = "CREATE_INSTANT_INVITE" | "KICK_MEMBERS" | "BAN_MEMBERS" | "ADMINISTRATOR" | "MANAGE_CHANNELS" | "MANAGE_GUILD" | "CHANGE_NICKNAME" | "MANAGE_NICKNAMES" | "MANAGE_ROLES" | "MANAGE_WEBHOOKS" | "MANAGE_GUILD_EXPRESSIONS" | "CREATE_GUILD_EXPRESSIONS" | "VIEW_AUDIT_LOG" | "VIEW_CHANNEL" | "VIEW_GUILD_ANALYTICS" | "VIEW_CREATOR_MONETIZATION_ANALYTICS" | "MODERATE_MEMBERS" | "SEND_MESSAGES" | "SEND_TTS_MESSAGES" | "MANAGE_MESSAGES" | "EMBED_LINKS" | "ATTACH_FILES" | "READ_MESSAGE_HISTORY" | "MENTION_EVERYONE" | "USE_EXTERNAL_EMOJIS" | "ADD_REACTIONS" | "USE_APPLICATION_COMMANDS" | "MANAGE_THREADS" | "CREATE_PUBLIC_THREADS" | "CREATE_PRIVATE_THREADS" | "USE_EXTERNAL_STICKERS" | "SEND_MESSAGES_IN_THREADS" | "CONNECT" | "SPEAK" | "MUTE_MEMBERS" | "DEAFEN_MEMBERS" | "MOVE_MEMBERS" | "USE_VAD" | "PRIORITY_SPEAKER" | "STREAM" | "USE_EMBEDDED_ACTIVITIES" | "USE_SOUNDBOARD" | "USE_EXTERNAL_SOUNDS" | "REQUEST_TO_SPEAK" | "MANAGE_EVENTS" | "CREATE_EVENTS"; +import type { Permissions, RC } from "@webpack/types"; +import type { Channel, Guild, Message, User } from "discord-types/general"; interface Tag { // name used for identifying, must be alphanumeric + underscores @@ -34,7 +32,7 @@ interface Tag { // name shown on the tag itself, can be anything probably; automatically uppercase'd displayName: string; description: string; - permissions?: PermissionName[]; + permissions?: Permissions[]; condition?(message: Message | null, user: User, channel: Channel): boolean; } @@ -54,10 +52,14 @@ interface TagSettings { [k: string]: TagSetting; } -// PermissionStore.computePermissions is not the same function and doesn't work here -const PermissionUtil = findByPropsLazy("computePermissions", "canEveryoneRole") as { - computePermissions({ ...args }): bigint; -}; +// PermissionStore.computePermissions will not work here since it only gets permissions for the current user +const computePermissions: (options: { + user?: { id: string; } | string | null; + context?: Guild | Channel | null; + overwrites?: Channel["permissionOverwrites"] | null; + checkElevated?: boolean /* = true */; + excludeGuildPermissions?: boolean /* = false */; +}) => bigint = findByCodeLazy(".getCurrentUser()", ".computeLurkerPermissionsAllowList()"); const Tag = findLazy(m => m.Types?.[0] === "BOT") as RC<{ type?: number, className?: string, useRemSizes?: boolean; }> & { Types: Record; }; @@ -193,7 +195,7 @@ export default definePlugin({ patches: [ // add tags to the tag list { - find: "BotTagTypes:", + find: ".ORIGINAL_POSTER=", replacement: { match: /\((\i)=\{\}\)\)\[(\i)\.BOT/, replace: "($1=$self.getTagTypes()))[$2.BOT" @@ -222,7 +224,7 @@ export default definePlugin({ }, // in messages { - find: "renderSystemTag:", + find: ".Types.ORIGINAL_POSTER", replacement: { match: /;return\((\(null==\i\?void 0:\i\.isSystemDM\(\).+?.Types.ORIGINAL_POSTER\)),null==(\i)\)/, replace: ";$1;$2=$self.getTag({...arguments[0],origType:$2,location:'chat'});return $2 == null" @@ -283,7 +285,7 @@ export default definePlugin({ const guild = GuildStore.getGuild(channel?.guild_id); if (!guild) return []; - const permissions = PermissionUtil.computePermissions({ user, context: guild, overwrites: channel.permissionOverwrites }); + const permissions = computePermissions({ user, context: guild, overwrites: channel.permissionOverwrites }); return Object.entries(PermissionsBits) .map(([perm, permInt]) => permissions & permInt ? perm : "" @@ -330,7 +332,7 @@ export default definePlugin({ }: { message?: Message, user: User & { isClyde(): boolean; }, - channel?: Channel & { isForumPost(): boolean; }, + channel?: Channel & { isForumPost(): boolean; isMediaPost(): boolean; }, channelId?: string; origType?: number; location: "chat" | "not-chat"; @@ -367,7 +369,7 @@ export default definePlugin({ tag.permissions?.some(perm => perms.includes(perm)) || (tag.condition?.(message!, user, channel)) ) { - if (channel.isForumPost() && channel.ownerId === user.id) + if ((channel.isForumPost() || channel.isMediaPost()) && channel.ownerId === user.id) type = Tag.Types[`${tag.name}-OP`]; else if (user.bot && !isWebhook(message!, user) && !settings.dontShowBotTag) type = Tag.Types[`${tag.name}-BOT`]; From e9e789be7093e8b025f606cde69b3d89760c9380 Mon Sep 17 00:00:00 2001 From: Vendicated Date: Wed, 19 Jun 2024 16:59:40 +0200 Subject: [PATCH 04/50] fix NewGuildSettings --- src/plugins/newGuildSettings/index.tsx | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/src/plugins/newGuildSettings/index.tsx b/src/plugins/newGuildSettings/index.tsx index f1c29f25e9..6b9dfe355f 100644 --- a/src/plugins/newGuildSettings/index.tsx +++ b/src/plugins/newGuildSettings/index.tsx @@ -19,10 +19,15 @@ import { definePluginSettings, migratePluginSettings } from "@api/Settings"; import { Devs } from "@utils/constants"; import definePlugin, { OptionType } from "@utils/types"; -import { findByCodeLazy, findByPropsLazy } from "@webpack"; +import { findByCodeLazy, findByPropsLazy, mapMangledModuleLazy } from "@webpack"; const { updateGuildNotificationSettings } = findByPropsLazy("updateGuildNotificationSettings"); -const { toggleShowAllChannels } = findByPropsLazy("toggleShowAllChannels"); +const { toggleShowAllChannels } = mapMangledModuleLazy(".onboardExistingMember(", { + toggleShowAllChannels: m => { + const s = String(m); + return s.length < 100 && !s.includes("onboardExistingMember") && !s.includes("getOptedInChannels"); + } +}); const isOptInEnabledForGuild = findByCodeLazy(".COMMUNITY)||", ".isOptInEnabled("); const settings = definePluginSettings({ From 76f69125118ebae51e48c64873ab63c143c2349a Mon Sep 17 00:00:00 2001 From: Masterjoona <69722179+Masterjoona@users.noreply.github.com> Date: Wed, 19 Jun 2024 21:04:39 +0300 Subject: [PATCH 05/50] VoiceMessages: properly respect user's microphone choice (#2602) --- src/plugins/voiceMessages/DesktopRecorder.tsx | 2 ++ src/plugins/voiceMessages/WebRecorder.tsx | 2 ++ src/plugins/voiceMessages/utils.ts | 2 ++ 3 files changed, 6 insertions(+) diff --git a/src/plugins/voiceMessages/DesktopRecorder.tsx b/src/plugins/voiceMessages/DesktopRecorder.tsx index a69739a414..18581ad167 100644 --- a/src/plugins/voiceMessages/DesktopRecorder.tsx +++ b/src/plugins/voiceMessages/DesktopRecorder.tsx @@ -21,6 +21,7 @@ import { Button, showToast, Toasts, useState } from "@webpack/common"; import type { VoiceRecorder } from "."; import { settings } from "./settings"; +import { MediaEngineStore } from "./utils"; const Native = VencordNative.pluginHelpers.VoiceMessages as PluginNative; @@ -41,6 +42,7 @@ export const VoiceRecorderDesktop: VoiceRecorder = ({ setAudioBlob, onRecordingC { echoCancellation: settings.store.echoCancellation, noiseCancellation: settings.store.noiseSuppression, + deviceId: MediaEngineStore.getInputDeviceId(), }, (success: boolean) => { if (success) diff --git a/src/plugins/voiceMessages/WebRecorder.tsx b/src/plugins/voiceMessages/WebRecorder.tsx index 423a2699a4..eb77b19900 100644 --- a/src/plugins/voiceMessages/WebRecorder.tsx +++ b/src/plugins/voiceMessages/WebRecorder.tsx @@ -20,6 +20,7 @@ import { Button, useState } from "@webpack/common"; import type { VoiceRecorder } from "."; import { settings } from "./settings"; +import { MediaEngineStore } from "./utils"; export const VoiceRecorderWeb: VoiceRecorder = ({ setAudioBlob, onRecordingChange }) => { const [recording, setRecording] = useState(false); @@ -40,6 +41,7 @@ export const VoiceRecorderWeb: VoiceRecorder = ({ setAudioBlob, onRecordingChang audio: { echoCancellation: settings.store.echoCancellation, noiseSuppression: settings.store.noiseSuppression, + deviceId: MediaEngineStore.getInputDeviceId() } }).then(stream => { const chunks = [] as Blob[]; diff --git a/src/plugins/voiceMessages/utils.ts b/src/plugins/voiceMessages/utils.ts index dcfd6f26cd..ef571bbf3b 100644 --- a/src/plugins/voiceMessages/utils.ts +++ b/src/plugins/voiceMessages/utils.ts @@ -17,5 +17,7 @@ */ import { classNameFactory } from "@api/Styles"; +import { findStoreLazy } from "@webpack"; +export const MediaEngineStore = findStoreLazy("MediaEngineStore"); export const cl = classNameFactory("vc-vmsg-"); From 3ce241021f3b837eedfda4da8f85742a84580f17 Mon Sep 17 00:00:00 2001 From: Vendicated Date: Thu, 20 Jun 2024 04:40:07 +0200 Subject: [PATCH 06/50] PluginModals: add plugin website & source code links --- scripts/build/common.mjs | 20 +++++--- .../PluginSettings/ContributorModal.tsx | 46 +++++------------ .../PluginSettings/LinkIconButton.css | 12 +++++ .../PluginSettings/LinkIconButton.tsx | 45 ++++++++++++++++ src/components/PluginSettings/PluginModal.css | 7 +++ src/components/PluginSettings/PluginModal.tsx | 51 ++++++++++++++++++- .../PluginSettings/contributorModal.css | 10 ---- src/modules.d.ts | 4 ++ src/utils/modal.tsx | 2 +- src/webpack/common/types/utils.d.ts | 35 +++++++++++++ src/webpack/common/utils.ts | 10 +++- 11 files changed, 188 insertions(+), 54 deletions(-) create mode 100644 src/components/PluginSettings/LinkIconButton.css create mode 100644 src/components/PluginSettings/LinkIconButton.tsx create mode 100644 src/components/PluginSettings/PluginModal.css diff --git a/scripts/build/common.mjs b/scripts/build/common.mjs index cdbb26eec8..eb7ab905b2 100644 --- a/scripts/build/common.mjs +++ b/scripts/build/common.mjs @@ -89,15 +89,20 @@ export const globPlugins = kind => ({ const pluginDirs = ["plugins/_api", "plugins/_core", "plugins", "userplugins"]; let code = ""; let plugins = "\n"; + let meta = "\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}`); + const files = await readdir(`./src/${dir}`, { withFileTypes: true }); for (const file of files) { - if (file.startsWith("_") || file.startsWith(".")) continue; - if (file === "index.ts") continue; + const fileName = file.name; + if (fileName.startsWith("_") || fileName.startsWith(".")) continue; + if (fileName === "index.ts") continue; + + const target = getPluginTarget(fileName); - const target = getPluginTarget(file); if (target && !IS_REPORTER) { if (target === "dev" && !watch) continue; if (target === "web" && kind === "discordDesktop") continue; @@ -106,13 +111,16 @@ export const globPlugins = kind => ({ if (target === "vencordDesktop" && kind !== "vencordDesktop") continue; } + const folderName = `src/${dir}/${fileName}`.replace(/^src\/plugins\//, ""); + const mod = `p${i}`; - code += `import ${mod} from "./${dir}/${file.replace(/\.tsx?$/, "")}";\n`; + 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? i++; } } - code += `export default {${plugins}};`; + code += `export default {${plugins}};export const PluginMeta={${meta}};`; return { contents: code, resolveDir: "./src" diff --git a/src/components/PluginSettings/ContributorModal.tsx b/src/components/PluginSettings/ContributorModal.tsx index 99a8da1683..c3c36f1e63 100644 --- a/src/components/PluginSettings/ContributorModal.tsx +++ b/src/components/PluginSettings/ContributorModal.tsx @@ -11,20 +11,16 @@ import { classNameFactory } from "@api/Styles"; import ErrorBoundary from "@components/ErrorBoundary"; import { Link } from "@components/Link"; import { DevsById } from "@utils/constants"; -import { fetchUserProfile, getTheme, Theme } from "@utils/discord"; -import { pluralise } from "@utils/misc"; +import { fetchUserProfile } from "@utils/discord"; +import { classes, pluralise } from "@utils/misc"; import { ModalContent, ModalRoot, openModal } from "@utils/modal"; -import { Forms, MaskedLink, showToast, Tooltip, useEffect, useMemo, UserProfileStore, useStateFromStores } from "@webpack/common"; +import { Forms, showToast, useEffect, useMemo, UserProfileStore, useStateFromStores } from "@webpack/common"; import { User } from "discord-types/general"; import Plugins from "~plugins"; import { PluginCard } from "."; - -const WebsiteIconDark = "/assets/e1e96d89e192de1997f73730db26e94f.svg"; -const WebsiteIconLight = "/assets/730f58bcfd5a57a5e22460c445a0c6cf.svg"; -const GithubIconLight = "/assets/3ff98ad75ac94fa883af5ed62d17c459.svg"; -const GithubIconDark = "/assets/6a853b4c87fce386cbfef4a2efbacb09.svg"; +import { GithubButton, WebsiteButton } from "./LinkIconButton"; const cl = classNameFactory("vc-author-modal-"); @@ -40,16 +36,6 @@ export function openContributorModal(user: User) { ); } -function GithubIcon() { - const src = getTheme() === Theme.Light ? GithubIconLight : GithubIconDark; - return GitHub; -} - -function WebsiteIcon() { - const src = getTheme() === Theme.Light ? WebsiteIconLight : WebsiteIconDark; - return Website; -} - function ContributorModal({ user }: { user: User; }) { useSettings(); @@ -86,24 +72,18 @@ function ContributorModal({ user }: { user: User; }) { /> {user.username} -
+
{website && ( - - {props => ( - - - - )} - + )} {githubName && ( - - {props => ( - - - - )} - + )}
diff --git a/src/components/PluginSettings/LinkIconButton.css b/src/components/PluginSettings/LinkIconButton.css new file mode 100644 index 0000000000..1055d6c70d --- /dev/null +++ b/src/components/PluginSettings/LinkIconButton.css @@ -0,0 +1,12 @@ +.vc-settings-modal-link-icon { + height: 32px; + width: 32px; + border-radius: 50%; + border: 4px solid var(--background-tertiary); + box-sizing: border-box +} + +.vc-settings-modal-links { + display: flex; + gap: 0.2em; +} diff --git a/src/components/PluginSettings/LinkIconButton.tsx b/src/components/PluginSettings/LinkIconButton.tsx new file mode 100644 index 0000000000..ea36dda24b --- /dev/null +++ b/src/components/PluginSettings/LinkIconButton.tsx @@ -0,0 +1,45 @@ +/* + * Vencord, a Discord client mod + * Copyright (c) 2024 Vendicated and contributors + * SPDX-License-Identifier: GPL-3.0-or-later + */ + +import "./LinkIconButton.css"; + +import { getTheme, Theme } from "@utils/discord"; +import { MaskedLink, Tooltip } from "@webpack/common"; + +const WebsiteIconDark = "/assets/e1e96d89e192de1997f73730db26e94f.svg"; +const WebsiteIconLight = "/assets/730f58bcfd5a57a5e22460c445a0c6cf.svg"; +const GithubIconLight = "/assets/3ff98ad75ac94fa883af5ed62d17c459.svg"; +const GithubIconDark = "/assets/6a853b4c87fce386cbfef4a2efbacb09.svg"; + +export function GithubIcon() { + const src = getTheme() === Theme.Light ? GithubIconLight : GithubIconDark; + return ; +} + +export function WebsiteIcon() { + const src = getTheme() === Theme.Light ? WebsiteIconLight : WebsiteIconDark; + return ; +} + +interface Props { + text: string; + href: string; +} + +function LinkIcon({ text, href, Icon }: Props & { Icon: React.ComponentType; }) { + return ( + + {props => ( + + + + )} + + ); +} + +export const WebsiteButton = (props: Props) => ; +export const GithubButton = (props: Props) => ; diff --git a/src/components/PluginSettings/PluginModal.css b/src/components/PluginSettings/PluginModal.css new file mode 100644 index 0000000000..1f4b9aaadd --- /dev/null +++ b/src/components/PluginSettings/PluginModal.css @@ -0,0 +1,7 @@ +.vc-plugin-modal-info { + align-items: center; +} + +.vc-plugin-modal-description { + flex-grow: 1; +} diff --git a/src/components/PluginSettings/PluginModal.tsx b/src/components/PluginSettings/PluginModal.tsx index 34de43c2d1..e5da01f36d 100644 --- a/src/components/PluginSettings/PluginModal.tsx +++ b/src/components/PluginSettings/PluginModal.tsx @@ -16,10 +16,14 @@ * along with this program. If not, see . */ +import "./PluginModal.css"; + import { generateId } from "@api/Commands"; import { useSettings } from "@api/Settings"; +import { classNameFactory } from "@api/Styles"; import ErrorBoundary from "@components/ErrorBoundary"; import { Flex } from "@components/Flex"; +import { gitRemote } from "@shared/vencordUserAgent"; import { proxyLazy } from "@utils/lazy"; import { Margins } from "@utils/margins"; import { classes, isObjectEmpty } from "@utils/misc"; @@ -30,6 +34,8 @@ import { Button, Clickable, FluxDispatcher, Forms, React, Text, Tooltip, UserSto import { User } from "discord-types/general"; import { Constructor } from "type-fest"; +import { PluginMeta } from "~plugins"; + import { ISettingElementProps, SettingBooleanComponent, @@ -40,6 +46,9 @@ import { SettingTextComponent } from "./components"; import { openContributorModal } from "./ContributorModal"; +import { GithubButton, WebsiteButton } from "./LinkIconButton"; + +const cl = classNameFactory("vc-plugin-modal-"); const UserSummaryItem = findComponentByCodeLazy("defaultRenderUser", "showDefaultAvatarsForNullUsers"); const AvatarStyles = findByPropsLazy("moreUsers", "emptyUser", "avatarContainer", "clickableAvatar"); @@ -180,16 +189,54 @@ export default function PluginModal({ plugin, onRestartNeeded, onClose, transiti ); } + /* + function switchToPopout() { + onClose(); + + const PopoutKey = `DISCORD_VENCORD_PLUGIN_SETTINGS_MODAL_${plugin.name}`; + PopoutActions.open( + PopoutKey, + () => PopoutActions.close(PopoutKey)} + /> + ); + } + */ + + const pluginMeta = PluginMeta[plugin.name]; + return ( {plugin.name} + + {/* + + */} - About {plugin.name} - {plugin.description} + + {plugin.description} + {!pluginMeta.userPlugin && ( +
+ + +
+ )} +
Authors
; export default plugins; + export const PluginMeta: Record; } declare module "~pluginNatives" { diff --git a/src/utils/modal.tsx b/src/utils/modal.tsx index 4203068c97..79f7770886 100644 --- a/src/utils/modal.tsx +++ b/src/utils/modal.tsx @@ -38,7 +38,7 @@ const enum ModalTransitionState { export interface ModalProps { transitionState: ModalTransitionState; - onClose(): Promise; + onClose(): void; } export interface ModalOptions { diff --git a/src/webpack/common/types/utils.d.ts b/src/webpack/common/types/utils.d.ts index 1cd2bf69d2..7f6249be6c 100644 --- a/src/webpack/common/types/utils.d.ts +++ b/src/webpack/common/types/utils.d.ts @@ -18,6 +18,7 @@ import { Guild, GuildMember } from "discord-types/general"; import type { ReactNode } from "react"; +import { LiteralUnion } from "type-fest"; import type { FluxEvents } from "./fluxEvents"; import { i18nMessages } from "./i18nMessages"; @@ -221,3 +222,37 @@ export interface Constants { UserFlags: Record; FriendsSections: Record; } + +export interface ExpressionPickerStore { + closeExpressionPicker(activeViewType?: any): void; + openExpressionPicker(activeView: LiteralUnion<"emoji" | "gif" | "sticker", string>, activeViewType?: any): void; +} + +export interface BrowserWindowFeatures { + toolbar?: boolean; + menubar?: boolean; + location?: boolean; + directories?: boolean; + width?: number; + height?: number; + defaultWidth?: number; + defaultHeight?: number; + left?: number; + top?: number; + defaultAlwaysOnTop?: boolean; + movable?: boolean; + resizable?: boolean; + frame?: boolean; + alwaysOnTop?: boolean; + hasShadow?: boolean; + transparent?: boolean; + skipTaskbar?: boolean; + titleBarStyle?: string | null; + backgroundColor?: string; +} + +export interface PopoutActions { + open(key: string, render: (windowKey: string) => ReactNode, features?: BrowserWindowFeatures); + close(key: string): void; + setAlwaysOnTop(key: string, alwaysOnTop: boolean): void; +} diff --git a/src/webpack/common/utils.ts b/src/webpack/common/utils.ts index a724769c8a..a6853c84a0 100644 --- a/src/webpack/common/utils.ts +++ b/src/webpack/common/utils.ts @@ -160,9 +160,15 @@ export const InviteActions = findByPropsLazy("resolveInvite"); export const IconUtils: t.IconUtils = findByPropsLazy("getGuildBannerURL", "getUserAvatarURL"); -const openExpressionPickerMatcher = canonicalizeMatch(/setState\({activeView:\i/); +const openExpressionPickerMatcher = canonicalizeMatch(/setState\({activeView:\i,activeViewType:/); // TODO: type -export const ExpressionPickerStore = mapMangledModuleLazy("expression-picker-last-active-view", { +export const ExpressionPickerStore: t.ExpressionPickerStore = mapMangledModuleLazy("expression-picker-last-active-view", { closeExpressionPicker: filters.byCode("setState({activeView:null"), openExpressionPicker: m => typeof m === "function" && openExpressionPickerMatcher.test(m.toString()), }); + +export const PopoutActions: t.PopoutActions = mapMangledModuleLazy('type:"POPOUT_WINDOW_OPEN"', { + open: filters.byCode('type:"POPOUT_WINDOW_OPEN"'), + close: filters.byCode('type:"POPOUT_WINDOW_CLOSE"'), + setAlwaysOnTop: filters.byCode('type:"POPOUT_WINDOW_SET_ALWAYS_ON_TOP"'), +}); From d07042236d5974f9018a55d032a652ad19733313 Mon Sep 17 00:00:00 2001 From: Nuckyz <61953774+Nuckyz@users.noreply.github.com> Date: Wed, 19 Jun 2024 16:16:48 -0300 Subject: [PATCH 07/50] Add wrapSettingsHook back; Fix FakeNitro subscription emoji bypass --- src/plugins/_core/settings.tsx | 33 +++++++++------------------------ src/plugins/fakeNitro/index.tsx | 17 +++++++---------- 2 files changed, 16 insertions(+), 34 deletions(-) diff --git a/src/plugins/_core/settings.tsx b/src/plugins/_core/settings.tsx index 50cd6f04b3..3cc020836f 100644 --- a/src/plugins/_core/settings.tsx +++ b/src/plugins/_core/settings.tsx @@ -56,33 +56,18 @@ export default definePlugin({ } ] }, - // Discord Stable - // FIXME: remove once change merged to stable { find: "Messages.ACTIVITY_SETTINGS", - noWarn: true, - replacement: { - get match() { - switch (Settings.plugins.Settings.settingsLocation) { - case "top": return /\{section:(\i\.\i)\.HEADER,\s*label:(\i)\.\i\.Messages\.USER_SETTINGS/; - case "aboveNitro": return /\{section:(\i\.\i)\.HEADER,\s*label:(\i)\.\i\.Messages\.BILLING_SETTINGS/; - case "belowNitro": return /\{section:(\i\.\i)\.HEADER,\s*label:(\i)\.\i\.Messages\.APP_SETTINGS/; - case "belowActivity": return /(?<=\{section:(\i\.\i)\.DIVIDER},)\{section:"changelog"/; - case "bottom": return /\{section:(\i\.\i)\.CUSTOM,\s*element:.+?}/; - case "aboveActivity": - default: - return /\{section:(\i\.\i)\.HEADER,\s*label:(\i)\.\i\.Messages\.ACTIVITY_SETTINGS/; - } + replacement: [ + { + match: /(?<=section:(.{0,50})\.DIVIDER\}\))([,;])(?=.{0,200}(\i)\.push.{0,100}label:(\i)\.header)/, + replace: (_, sectionTypes, commaOrSemi, elements, element) => `${commaOrSemi} $self.addSettings(${elements}, ${element}, ${sectionTypes}) ${commaOrSemi}` }, - replace: "...$self.makeSettingsCategories($1),$&" - } - }, - { - find: "Messages.ACTIVITY_SETTINGS", - replacement: { - match: /(?<=section:(.{0,50})\.DIVIDER\}\))([,;])(?=.{0,200}(\i)\.push.{0,100}label:(\i)\.header)/, - replace: (_, sectionTypes, commaOrSemi, elements, element) => `${commaOrSemi} $self.addSettings(${elements}, ${element}, ${sectionTypes}) ${commaOrSemi}` - } + { + match: /({(?=.+?function (\i).{0,120}(\i)=\i\.useMemo.{0,30}return \i\.useMemo\(\(\)=>\i\(\3).+?function\(\){return )\2(?=})/, + replace: (_, rest, settingsHook) => `${rest}$self.wrapSettingsHook(${settingsHook})` + } + ] }, { find: "Messages.USER_SETTINGS_ACTIONS_MENU_LABEL", diff --git a/src/plugins/fakeNitro/index.tsx b/src/plugins/fakeNitro/index.tsx index 26e78ea26d..ddcabcbdf5 100644 --- a/src/plugins/fakeNitro/index.tsx +++ b/src/plugins/fakeNitro/index.tsx @@ -23,7 +23,7 @@ import { ApngBlendOp, ApngDisposeOp, importApngJs } from "@utils/dependencies"; import { getCurrentGuild } from "@utils/discord"; import { Logger } from "@utils/Logger"; import definePlugin, { OptionType } from "@utils/types"; -import { findByPropsLazy, findStoreLazy, proxyLazyWebpack } from "@webpack"; +import { findByCodeLazy, findByPropsLazy, findStoreLazy, proxyLazyWebpack } from "@webpack"; import { Alerts, ChannelStore, DraftType, EmojiStore, FluxDispatcher, Forms, IconUtils, lodash, Parser, PermissionsBits, PermissionStore, UploadHandler, UserSettingsActionCreators, UserStore } from "@webpack/common"; import type { Emoji } from "@webpack/types"; import type { Message } from "discord-types/general"; @@ -52,6 +52,7 @@ const PreloadedUserSettingsActionCreators = proxyLazyWebpack(() => UserSettingsA const AppearanceSettingsActionCreators = proxyLazyWebpack(() => searchProtoClassField("appearance", PreloadedUserSettingsActionCreators.ProtoClass)); const ClientThemeSettingsActionsCreators = proxyLazyWebpack(() => searchProtoClassField("clientThemeSettings", AppearanceSettingsActionCreators)); +const isUnusableRoleSubscriptionEmoji = findByCodeLazy(".getUserIsAdmin("); const enum EmojiIntentions { REACTION, @@ -234,16 +235,14 @@ export default definePlugin({ } ] }, - // FIXME // Allows the usage of subscription-locked emojis - /* { + { find: ".getUserIsAdmin(", replacement: { - match: /(?=.+?\.getUserIsAdmin\((?<=function (\i)\(\i,\i\){.+?))(\i):function\(\){return \1}/, - // Replace the original export with a func that always returns false and alias the original - replace: "$2:()=>()=>false,isUnusableRoleSubscriptionEmojiOriginal:function(){return $1}" + match: /(function \i\(\i,\i)\){(.{0,250}.getUserIsAdmin\(.+?return!1})/, + replace: (_, rest1, rest2) => `${rest1},fakeNitroOriginal){if(!fakeNitroOriginal)return false;${rest2}` } - }, */ + }, // Allow stickers to be sent everywhere { find: "canUseCustomStickersEverywhere:function", @@ -817,9 +816,7 @@ export default definePlugin({ if (e.type === 0) return true; if (e.available === false) return false; - // FIXME - /* const isUnusableRoleSubEmoji = isUnusableRoleSubscriptionEmojiOriginal ?? RoleSubscriptionEmojiUtils.isUnusableRoleSubscriptionEmoji; - if (isUnusableRoleSubEmoji(e, this.guildId)) return false; */ + if (isUnusableRoleSubscriptionEmoji(e, this.guildId, true)) return false; if (this.canUseEmotes) return e.guildId === this.guildId || hasExternalEmojiPerms(channelId); From d4ed7474346f136ddbcbb87ff93091301dde3411 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 08/50] Clean-up related additions to mangled exports --- src/api/SettingsStores.ts | 69 ---------------- src/api/UserSettings.ts | 81 +++++++++++++++++++ src/api/index.ts | 7 +- .../{settingsStores.ts => userSettings.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, 118 insertions(+), 109 deletions(-) delete mode 100644 src/api/SettingsStores.ts create mode 100644 src/api/UserSettings.ts rename src/plugins/_api/{settingsStores.ts => userSettings.ts} (55%) 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 18139e4e6f..0000000000 --- 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/UserSettings.ts b/src/api/UserSettings.ts new file mode 100644 index 0000000000..4de92a81a9 --- /dev/null +++ b/src/api/UserSettings.ts @@ -0,0 +1,81 @@ +/* + * 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"; + +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; + userSettingsAPIGroup: string; + userSettingsAPIName: string; +} + +export const UserSettings: Record> | undefined = proxyLazyWebpack(() => { + const modId = findModuleId('"textAndImages","renderSpoilers"'); + if (modId == null) return new Logger("UserSettingsAPI ").error("Didn't find settings module."); + + return wreq(modId as any); +}); + +/** + * Get the setting with the given setting group and name. + * + * @param group The setting group + * @param name The name of the setting + */ +export function getUserSetting(group: string, name: string): UserSettingDefinition | undefined { + if (!Vencord.Plugins.isPluginEnabled("UserSettingsAPI")) throw new Error("Cannot use UserSettingsAPI without setting as dependency."); + + for (const key in UserSettings) { + const userSetting = UserSettings[key]; + + if (userSetting.userSettingsAPIGroup === group && userSetting.userSettingsAPIName === name) { + return userSetting; + } + } +} + +/** + * {@link getUserSettingDefinition}, lazy. + * + * Get the setting with the given setting group and name. + * + * @param group The setting group + * @param name The name of the setting + */ +export function getUserSettingLazy(group: string, name: string) { + return proxyLazy(() => getUserSetting(group, name)); +} diff --git a/src/api/index.ts b/src/api/index.ts index 737e06d609..d4d7b4614c 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 $UserSettings from "./UserSettings"; /** * 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 an user setting + */ +export const UserSettings = $UserSettings; diff --git a/src/plugins/_api/settingsStores.ts b/src/plugins/_api/userSettings.ts similarity index 55% rename from src/plugins/_api/settingsStores.ts rename to src/plugins/_api/userSettings.ts index a888532eee..3a00bc116a 100644 --- a/src/plugins/_api/settingsStores.ts +++ b/src/plugins/_api/userSettings.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: "UserSettingsAPI", + description: "Patches Discord's UserSettings 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: "userSettingsAPIGroup:arguments[0],userSettingsAPIName: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: "userSettingsAPIGroup:arguments[0].userSettingsAPIGroup,userSettingsAPIName:arguments[0].userSettingsAPIName,$&" + }, + // Override wrapper + { + match: /updateSetting:.{0,60}USER_SETTINGS_OVERRIDE_CLEAR/, + replace: "userSettingsAPIGroup:arguments[0].userSettingsAPIGroup,userSettingsAPIName:arguments[0].userSettingsAPIName,$&" } + ] } ] diff --git a/src/plugins/betterRoleContext/index.tsx b/src/plugins/betterRoleContext/index.tsx index d69e188c0d..bf4cf0f370 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 { getUserSettingLazy } from "@api/UserSettings"; 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 = getUserSettingLazy("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: ["UserSettingsAPI"], settings, diff --git a/src/plugins/customRPC/index.tsx b/src/plugins/customRPC/index.tsx index 7e4e9a938a..eebcd4ddb9 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 { getUserSettingLazy } from "@api/UserSettings"; 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 = getUserSettingLazy("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: ["UserSettingsAPI"], start: setRpc, stop: () => setRpc(true), settings, diff --git a/src/plugins/gameActivityToggle/index.tsx b/src/plugins/gameActivityToggle/index.tsx index 4e2a390d69..7aeb470d63 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 { getUserSettingLazy } from "@api/UserSettings"; 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 = getUserSettingLazy("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: ["UserSettingsAPI"], settings, patches: [ diff --git a/src/plugins/ignoreActivities/index.tsx b/src/plugins/ignoreActivities/index.tsx index 6e34c79f3a..78c1c5cf86 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 { getUserSettingLazy } from "@api/UserSettings"; 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 = getUserSettingLazy("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: ["UserSettingsAPI"], settings, diff --git a/src/plugins/messageLinkEmbeds/index.tsx b/src/plugins/messageLinkEmbeds/index.tsx index 70681fb28b..cf180d0d4c 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 { getUserSettingLazy } from "@api/UserSettings"; 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 = getUserSettingLazy("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 5da3cc68be..4193330cb9 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 01c9685536..a536cdcf17 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 5453ca352c..0000000000 --- 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 7f6249be6c..ee3f69944f 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 db1481711bf6076267123389127b167d184ff0b0 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 09/50] 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 6c7a2a03f2..ddd5e5f183 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 b536063e86..f776ab1c33 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 c7e4bec94099e9f92a4402e56a87214e8817b053 Mon Sep 17 00:00:00 2001 From: Vendicated Date: Thu, 20 Jun 2024 19:48:37 +0200 Subject: [PATCH 10/50] 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 | 164 ++++++++++++++--------- src/modules.d.ts | 1 + src/plugins/appleMusic.desktop/index.tsx | 2 +- src/plugins/xsOverlay.desktop/index.ts | 2 +- 7 files changed, 161 insertions(+), 89 deletions(-) diff --git a/scripts/build/build.mjs b/scripts/build/build.mjs index fcf56f66c6..817c2cec35 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 eb7ab905b2..c46a559a7c 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 e8aa33a465..3d7c16c010 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 978d2e85a1..c659e78385 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 showApi = searchValue.value === "API"; - for (const p of sortedPlugins) { - if (p.hidden || (!p.options && p.name.endsWith("API") && !showApi)) - continue; - - if (!pluginFilter(p)) continue; - - 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} - /> - ); - } - + const plugins = [] as JSX.Element[]; + const requiredPlugins = [] as JSX.Element[]; + + 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; + + 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} + 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 70ffcfb918..7566a5bf48 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 0d81204e95..6fa989cdd9 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 a68373a6ac..b42d202104 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 7dc1d4c498f200092fceb6654663000827cea67d Mon Sep 17 00:00:00 2001 From: Nuckyz <61953774+Nuckyz@users.noreply.github.com> Date: Fri, 21 Jun 2024 03:59:38 -0300 Subject: [PATCH 11/50] ReverseImageSearch: Fix duplicate find --- src/plugins/reverseImageSearch/index.tsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/plugins/reverseImageSearch/index.tsx b/src/plugins/reverseImageSearch/index.tsx index 415dc13d88..728156b2b4 100644 --- a/src/plugins/reverseImageSearch/index.tsx +++ b/src/plugins/reverseImageSearch/index.tsx @@ -108,7 +108,7 @@ export default definePlugin({ patches: [ { - find: ".Messages.MESSAGE_ACTIONS_MENU_LABEL", + find: ".Messages.MESSAGE_ACTIONS_MENU_LABEL,shouldHideMediaOptions", replacement: { match: /favoriteableType:\i,(?<=(\i)\.getAttribute\("data-type"\).+?)/, replace: (m, target) => `${m}reverseImageSearchType:${target}.getAttribute("data-role"),` From b9392c3be21fbe55b761c8992f21713be67fe71d Mon Sep 17 00:00:00 2001 From: Vendicated Date: Fri, 21 Jun 2024 19:15:48 +0200 Subject: [PATCH 12/50] Improve SupportHelper - improve update check when entering support channel - add "Run Snippet" button to venbot messages with codeblock - add "Send /vencord-debug" button to messages that contain /vencord-debug - add "Update Now" button to messages by venbot and in #known-issues that contain "update" - add some common issues like RPC disabled / NoRPC enabled to /vencord-debug - split plugin list into separate /vencord-plugins command to reduce size & avoid >2000 chars errors --- src/plugins/_core/supportHelper.tsx | 280 ++++++++++++++++++++-------- src/utils/{misc.tsx => misc.ts} | 11 ++ src/utils/text.ts | 15 ++ 3 files changed, 233 insertions(+), 73 deletions(-) rename src/utils/{misc.tsx => misc.ts} (92%) diff --git a/src/plugins/_core/supportHelper.tsx b/src/plugins/_core/supportHelper.tsx index d59d82afcb..95a2c05b36 100644 --- a/src/plugins/_core/supportHelper.tsx +++ b/src/plugins/_core/supportHelper.tsx @@ -16,24 +16,33 @@ * along with this program. If not, see . */ +import { addAccessory } from "@api/MessageAccessories"; +import { getUserSettingLazy } from "@api/UserSettings"; import ErrorBoundary from "@components/ErrorBoundary"; +import { Flex } from "@components/Flex"; import { Link } from "@components/Link"; import { openUpdaterModal } from "@components/VencordSettings/UpdaterTab"; import { Devs, SUPPORT_CHANNEL_ID } from "@utils/constants"; +import { sendMessage } from "@utils/discord"; +import { Logger } from "@utils/Logger"; import { Margins } from "@utils/margins"; -import { isPluginDev } from "@utils/misc"; +import { isPluginDev, tryOrElse } from "@utils/misc"; import { relaunch } from "@utils/native"; +import { onlyOnce } from "@utils/onlyOnce"; import { makeCodeblock } from "@utils/text"; import definePlugin from "@utils/types"; -import { isOutdated, update } from "@utils/updater"; -import { Alerts, Card, ChannelStore, Forms, GuildMemberStore, NavigationRouter, Parser, RelationshipStore, UserStore } from "@webpack/common"; +import { checkForUpdates, isOutdated, update } from "@utils/updater"; +import { Alerts, Button, Card, ChannelStore, Forms, GuildMemberStore, Parser, RelationshipStore, showToast, Toasts, UserStore } from "@webpack/common"; import gitHash from "~git-hash"; -import plugins from "~plugins"; +import plugins, { PluginMeta } from "~plugins"; import settings from "./settings"; const VENCORD_GUILD_ID = "1015060230222131221"; +const VENBOT_USER_ID = "1017176847865352332"; +const KNOWN_ISSUES_CHANNEL_ID = "1222936386626129920"; +const CodeBlockRe = /```js\n(.+?)```/s; const AllowedChannelIds = [ SUPPORT_CHANNEL_ID, @@ -47,12 +56,88 @@ const TrustedRolesIds = [ "1042507929485586532", // donor ]; +const AsyncFunction = async function () { }.constructor; + +const ShowCurrentGame = getUserSettingLazy("status", "showCurrentGame")!; + +async function forceUpdate() { + const outdated = await checkForUpdates(); + if (outdated) { + await update(); + relaunch(); + } + + return outdated; +} + +async function generateDebugInfoMessage() { + const { RELEASE_CHANNEL } = window.GLOBAL_ENV; + + const client = (() => { + if (IS_DISCORD_DESKTOP) return `Discord Desktop v${DiscordNative.app.getVersion()}`; + if (IS_VESKTOP) return `Vesktop v${VesktopNative.app.getVersion()}`; + if ("armcord" in window) return `ArmCord v${window.armcord.version}`; + + // @ts-expect-error + const name = typeof unsafeWindow !== "undefined" ? "UserScript" : "Web"; + return `${name} (${navigator.userAgent})`; + })(); + + const info = { + Vencord: + `v${VERSION} • [${gitHash}]()` + + `${settings.additionalInfo} - ${Intl.DateTimeFormat("en-GB", { dateStyle: "medium" }).format(BUILD_TIMESTAMP)}`, + Client: `${RELEASE_CHANNEL} ~ ${client}`, + Platform: window.navigator.platform + }; + + if (IS_DISCORD_DESKTOP) { + info["Last Crash Reason"] = (await tryOrElse(() => DiscordNative.processUtils.getLastCrash(), undefined))?.rendererCrashReason ?? "N/A"; + } + + const commonIssues = { + "NoRPC enabled": Vencord.Plugins.isPluginEnabled("NoRPC"), + "Activity Sharing disabled": tryOrElse(() => !ShowCurrentGame.getSetting(), false), + "Vencord DevBuild": !IS_STANDALONE, + "Has UserPlugins": Object.values(PluginMeta).some(m => m.userPlugin), + "More than two weeks out of date": BUILD_TIMESTAMP < Date.now() - 12096e5, + }; + + let content = `>>> ${Object.entries(info).map(([k, v]) => `**${k}**: ${v}`).join("\n")}`; + content += "\n" + Object.entries(commonIssues) + .filter(([, v]) => v).map(([k]) => `⚠️ ${k}`) + .join("\n"); + + return content.trim(); +} + +function generatePluginList() { + const isApiPlugin = (plugin: string) => plugin.endsWith("API") || plugins[plugin].required; + + const enabledPlugins = Object.keys(plugins) + .filter(p => Vencord.Plugins.isPluginEnabled(p) && !isApiPlugin(p)); + + const enabledStockPlugins = enabledPlugins.filter(p => !PluginMeta[p].userPlugin); + const enabledUserPlugins = enabledPlugins.filter(p => PluginMeta[p].userPlugin); + + + let content = `**Enabled Plugins (${enabledStockPlugins.length}):**\n${makeCodeblock(enabledStockPlugins.join(", "))}`; + + if (enabledUserPlugins.length) { + content += `**Enabled UserPlugins (${enabledUserPlugins.length}):**\n${makeCodeblock(enabledUserPlugins.join(", "))}`; + } + + return content; +} + +const checkForUpdatesOnce = onlyOnce(checkForUpdates); + export default definePlugin({ name: "SupportHelper", required: true, description: "Helps us provide support to you", authors: [Devs.Ven], - dependencies: ["CommandsAPI"], + dependencies: ["CommandsAPI", "UserSettingsAPI"], patches: [{ find: ".BEGINNING_DM.format", @@ -62,51 +147,20 @@ export default definePlugin({ } }], - commands: [{ - name: "vencord-debug", - description: "Send Vencord Debug info", - predicate: ctx => isPluginDev(UserStore.getCurrentUser()?.id) || AllowedChannelIds.includes(ctx.channel.id), - async execute() { - const { RELEASE_CHANNEL } = window.GLOBAL_ENV; - - const client = (() => { - if (IS_DISCORD_DESKTOP) return `Discord Desktop v${DiscordNative.app.getVersion()}`; - if (IS_VESKTOP) return `Vesktop v${VesktopNative.app.getVersion()}`; - if ("armcord" in window) return `ArmCord v${window.armcord.version}`; - - // @ts-expect-error - const name = typeof unsafeWindow !== "undefined" ? "UserScript" : "Web"; - return `${name} (${navigator.userAgent})`; - })(); - - const isApiPlugin = (plugin: string) => plugin.endsWith("API") || plugins[plugin].required; - - const enabledPlugins = Object.keys(plugins).filter(p => Vencord.Plugins.isPluginEnabled(p) && !isApiPlugin(p)); - - const info = { - Vencord: - `v${VERSION} • [${gitHash}]()` + - `${settings.additionalInfo} - ${Intl.DateTimeFormat("en-GB", { dateStyle: "medium" }).format(BUILD_TIMESTAMP)}`, - Client: `${RELEASE_CHANNEL} ~ ${client}`, - Platform: window.navigator.platform - }; - - if (IS_DISCORD_DESKTOP) { - info["Last Crash Reason"] = (await DiscordNative.processUtils.getLastCrash())?.rendererCrashReason ?? "N/A"; - } - - const debugInfo = ` ->>> ${Object.entries(info).map(([k, v]) => `**${k}**: ${v}`).join("\n")} - -Enabled Plugins (${enabledPlugins.length}): -${makeCodeblock(enabledPlugins.join(", "))} -`; - - return { - content: debugInfo.trim().replaceAll("```\n", "```") - }; + commands: [ + { + name: "vencord-debug", + description: "Send Vencord debug info", + predicate: ctx => isPluginDev(UserStore.getCurrentUser()?.id) || AllowedChannelIds.includes(ctx.channel.id), + execute: async () => ({ content: await generateDebugInfoMessage() }) + }, + { + name: "vencord-plugins", + description: "Send Vencord plugin list", + predicate: ctx => isPluginDev(UserStore.getCurrentUser()?.id) || AllowedChannelIds.includes(ctx.channel.id), + execute: () => ({ content: generatePluginList() }) } - }], + ], flux: { async CHANNEL_SELECT({ channelId }) { @@ -115,24 +169,25 @@ ${makeCodeblock(enabledPlugins.join(", "))} const selfId = UserStore.getCurrentUser()?.id; if (!selfId || isPluginDev(selfId)) return; - if (isOutdated) { - return Alerts.show({ - title: "Hold on!", - body:
- You are using an outdated version of Vencord! Chances are, your issue is already fixed. - - Please first update before asking for support! - -
, - onCancel: () => openUpdaterModal!(), - cancelText: "View Updates", - confirmText: "Update & Restart Now", - async onConfirm() { - await update(); - relaunch(); - }, - secondaryConfirmText: "I know what I'm doing or I can't update" - }); + if (!IS_UPDATER_DISABLED) { + await checkForUpdatesOnce().catch(() => { }); + + if (isOutdated) { + return Alerts.show({ + title: "Hold on!", + body:
+ You are using an outdated version of Vencord! Chances are, your issue is already fixed. + + Please first update before asking for support! + +
, + onCancel: () => openUpdaterModal!(), + cancelText: "View Updates", + confirmText: "Update & Restart Now", + onConfirm: forceUpdate, + secondaryConfirmText: "I know what I'm doing or I can't update" + }); + } } // @ts-ignore outdated type @@ -148,8 +203,7 @@ ${makeCodeblock(enabledPlugins.join(", "))} Please either switch to an officially supported version of Vencord, or contact your package maintainer for support instead. -
, - onCloseCallback: () => setTimeout(() => NavigationRouter.back(), 50) + }); } @@ -163,8 +217,7 @@ ${makeCodeblock(enabledPlugins.join(", "))} Please either switch to an officially supported version of Vencord, or contact your package maintainer for support instead. - , - onCloseCallback: () => setTimeout(() => NavigationRouter.back(), 50) + }); } } @@ -172,7 +225,7 @@ ${makeCodeblock(enabledPlugins.join(", "))} ContributorDmWarningCard: ErrorBoundary.wrap(({ userId }) => { if (!isPluginDev(userId)) return null; - if (RelationshipStore.isFriend(userId)) return null; + if (RelationshipStore.isFriend(userId) || isPluginDev(UserStore.getCurrentUser()?.id)) return null; return ( @@ -182,5 +235,86 @@ ${makeCodeblock(enabledPlugins.join(", "))} {!ChannelStore.getChannel(SUPPORT_CHANNEL_ID) && " (Click the link to join)"} ); - }, { noop: true }) + }, { noop: true }), + + start() { + addAccessory("vencord-debug", props => { + const buttons = [] as JSX.Element[]; + + const shouldAddUpdateButton = + !IS_UPDATER_DISABLED + && ( + (props.channel.id === KNOWN_ISSUES_CHANNEL_ID) || + (props.channel.id === SUPPORT_CHANNEL_ID && props.message.author.id === VENBOT_USER_ID) + ) + && props.message.content?.includes("update"); + + if (shouldAddUpdateButton) { + buttons.push( + + ); + } + + if (props.channel.id === SUPPORT_CHANNEL_ID) { + if (props.message.content.includes("/vencord-debug") || props.message.content.includes("/vencord-plugins")) { + buttons.push( + , + + ); + } + + if (props.message.author.id === VENBOT_USER_ID) { + const match = CodeBlockRe.exec(props.message.content || props.message.embeds[0]?.rawDescription || ""); + if (match) { + buttons.push( + + ); + } + } + } + + return buttons.length + ? {buttons} + : null; + }); + }, }); diff --git a/src/utils/misc.tsx b/src/utils/misc.ts similarity index 92% rename from src/utils/misc.tsx rename to src/utils/misc.ts index fb08c93f6f..7d6b4affcf 100644 --- a/src/utils/misc.tsx +++ b/src/utils/misc.ts @@ -99,3 +99,14 @@ export const isPluginDev = (id: string) => Object.hasOwn(DevsById, id); export function pluralise(amount: number, singular: string, plural = singular + "s") { return amount === 1 ? `${amount} ${singular}` : `${amount} ${plural}`; } + +export function tryOrElse(func: () => T, fallback: T): T { + try { + const res = func(); + return res instanceof Promise + ? res.catch(() => fallback) as T + : res; + } catch { + return fallback; + } +} diff --git a/src/utils/text.ts b/src/utils/text.ts index 63f6007420..2e85af4ef0 100644 --- a/src/utils/text.ts +++ b/src/utils/text.ts @@ -131,3 +131,18 @@ export function makeCodeblock(text: string, language?: string) { const chars = "```"; return `${chars}${language || ""}\n${text.replaceAll("```", "\\`\\`\\`")}\n${chars}`; } + +export function stripIndent(strings: TemplateStringsArray, ...values: any[]) { + const string = String.raw({ raw: strings }, ...values); + + const match = string.match(/^[ \t]*(?=\S)/gm); + if (!match) return string.trim(); + + const minIndent = match.reduce((r, a) => Math.min(r, a.length), Infinity); + return string.replace(new RegExp(`^[ \\t]{${minIndent}}`, "gm"), "").trim(); +} + +export const ZWSP = "\u200b"; +export function toInlineCode(s: string) { + return "``" + ZWSP + s.replaceAll("`", ZWSP + "`" + ZWSP) + ZWSP + "``"; +} From 0b033aa51b4b3369513d264853e11ce034a6cdaf Mon Sep 17 00:00:00 2001 From: Vendicated Date: Fri, 21 Jun 2024 22:42:25 +0200 Subject: [PATCH 13/50] PluginManager: catch errors during plugin flux handlers --- src/plugins/index.ts | 13 ++- src/plugins/xsOverlay.desktop/index.ts | 151 ++++++++++++------------- src/utils/types.ts | 2 +- 3 files changed, 86 insertions(+), 80 deletions(-) diff --git a/src/plugins/index.ts b/src/plugins/index.ts index 29420d0c08..9268051ffd 100644 --- a/src/plugins/index.ts +++ b/src/plugins/index.ts @@ -169,7 +169,18 @@ export function subscribePluginFluxEvents(p: Plugin, fluxDispatcher: typeof Flux logger.debug("Subscribing to flux events of plugin", p.name); for (const [event, handler] of Object.entries(p.flux)) { - fluxDispatcher.subscribe(event as FluxEvents, handler); + const wrappedHandler = p.flux[event] = function () { + try { + const res = handler.apply(p, arguments as any); + return res instanceof Promise + ? res.catch(e => logger.error(`${p.name}: Error while handling ${event}\n`, e)) + : res; + } catch (e) { + logger.error(`${p.name}: Error while handling ${event}\n`, e); + } + }; + + fluxDispatcher.subscribe(event as FluxEvents, wrappedHandler); } } } diff --git a/src/plugins/xsOverlay.desktop/index.ts b/src/plugins/xsOverlay.desktop/index.ts index b42d202104..8b06475c08 100644 --- a/src/plugins/xsOverlay.desktop/index.ts +++ b/src/plugins/xsOverlay.desktop/index.ts @@ -154,104 +154,99 @@ export default definePlugin({ } }, MESSAGE_CREATE({ message, optimistic }: { message: Message; optimistic: boolean; }) { - // Apparently without this try/catch, discord's socket connection dies if any part of this errors - try { - if (optimistic) return; - const channel = ChannelStore.getChannel(message.channel_id); - if (!shouldNotify(message, message.channel_id)) return; - - const pingColor = settings.store.pingColor.replaceAll("#", "").trim(); - const channelPingColor = settings.store.channelPingColor.replaceAll("#", "").trim(); - let finalMsg = message.content; - let titleString = ""; - - if (channel.guild_id) { - const guild = GuildStore.getGuild(channel.guild_id); - titleString = `${message.author.username} (${guild.name}, #${channel.name})`; - } + if (optimistic) return; + const channel = ChannelStore.getChannel(message.channel_id); + if (!shouldNotify(message, message.channel_id)) return; + + const pingColor = settings.store.pingColor.replaceAll("#", "").trim(); + const channelPingColor = settings.store.channelPingColor.replaceAll("#", "").trim(); + let finalMsg = message.content; + let titleString = ""; + + if (channel.guild_id) { + const guild = GuildStore.getGuild(channel.guild_id); + titleString = `${message.author.username} (${guild.name}, #${channel.name})`; + } - switch (channel.type) { - case ChannelTypes.DM: - titleString = message.author.username.trim(); - break; - case ChannelTypes.GROUP_DM: - const channelName = channel.name.trim() ?? channel.rawRecipients.map(e => e.username).join(", "); - titleString = `${message.author.username} (${channelName})`; - break; - } + switch (channel.type) { + case ChannelTypes.DM: + titleString = message.author.username.trim(); + break; + case ChannelTypes.GROUP_DM: + const channelName = channel.name.trim() ?? channel.rawRecipients.map(e => e.username).join(", "); + titleString = `${message.author.username} (${channelName})`; + break; + } - if (message.referenced_message) { - titleString += " (reply)"; - } + if (message.referenced_message) { + titleString += " (reply)"; + } - if (message.embeds.length > 0) { - finalMsg += " [embed] "; - if (message.content === "") { - finalMsg = "sent message embed(s)"; - } + if (message.embeds.length > 0) { + finalMsg += " [embed] "; + if (message.content === "") { + finalMsg = "sent message embed(s)"; } + } - if (message.sticker_items) { - finalMsg += " [sticker] "; - if (message.content === "") { - finalMsg = "sent a sticker"; - } + if (message.sticker_items) { + finalMsg += " [sticker] "; + if (message.content === "") { + finalMsg = "sent a sticker"; } + } - const images = message.attachments.filter(e => - typeof e?.content_type === "string" - && e?.content_type.startsWith("image") - ); + const images = message.attachments.filter(e => + typeof e?.content_type === "string" + && e?.content_type.startsWith("image") + ); - images.forEach(img => { - finalMsg += ` [image: ${img.filename}] `; - }); + images.forEach(img => { + finalMsg += ` [image: ${img.filename}] `; + }); - message.attachments.filter(a => a && !a.content_type?.startsWith("image")).forEach(a => { - finalMsg += ` [attachment: ${a.filename}] `; - }); + message.attachments.filter(a => a && !a.content_type?.startsWith("image")).forEach(a => { + finalMsg += ` [attachment: ${a.filename}] `; + }); - // make mentions readable - if (message.mentions.length > 0) { - finalMsg = finalMsg.replace(/<@!?(\d{17,20})>/g, (_, id) => `@${UserStore.getUser(id)?.username || "unknown-user"}`); - } + // make mentions readable + if (message.mentions.length > 0) { + finalMsg = finalMsg.replace(/<@!?(\d{17,20})>/g, (_, id) => `@${UserStore.getUser(id)?.username || "unknown-user"}`); + } - // color role mentions (unity styling btw lol) - if (message.mention_roles.length > 0) { - for (const roleId of message.mention_roles) { - const role = GuildStore.getRole(channel.guild_id, roleId); - if (!role) continue; - const roleColor = role.colorString ?? `#${pingColor}`; - finalMsg = finalMsg.replace(`<@&${roleId}>`, `@${role.name}`); - } + // color role mentions (unity styling btw lol) + if (message.mention_roles.length > 0) { + for (const roleId of message.mention_roles) { + const role = GuildStore.getRole(channel.guild_id, roleId); + if (!role) continue; + const roleColor = role.colorString ?? `#${pingColor}`; + finalMsg = finalMsg.replace(`<@&${roleId}>`, `@${role.name}`); } + } - // make emotes and channel mentions readable - const emoteMatches = finalMsg.match(new RegExp("()", "g")); - const channelMatches = finalMsg.match(new RegExp("<(#\\d+)>", "g")); + // make emotes and channel mentions readable + const emoteMatches = finalMsg.match(new RegExp("()", "g")); + const channelMatches = finalMsg.match(new RegExp("<(#\\d+)>", "g")); - if (emoteMatches) { - for (const eMatch of emoteMatches) { - finalMsg = finalMsg.replace(new RegExp(`${eMatch}`, "g"), `:${eMatch.split(":")[1]}:`); - } + if (emoteMatches) { + for (const eMatch of emoteMatches) { + finalMsg = finalMsg.replace(new RegExp(`${eMatch}`, "g"), `:${eMatch.split(":")[1]}:`); } + } - // color channel mentions - if (channelMatches) { - for (const cMatch of channelMatches) { - let channelId = cMatch.split("<#")[1]; - channelId = channelId.substring(0, channelId.length - 1); - finalMsg = finalMsg.replace(new RegExp(`${cMatch}`, "g"), `#${ChannelStore.getChannel(channelId).name}`); - } + // color channel mentions + if (channelMatches) { + for (const cMatch of channelMatches) { + let channelId = cMatch.split("<#")[1]; + channelId = channelId.substring(0, channelId.length - 1); + finalMsg = finalMsg.replace(new RegExp(`${cMatch}`, "g"), `#${ChannelStore.getChannel(channelId).name}`); } - - if (shouldIgnoreForChannelType(channel)) return; - sendMsgNotif(titleString, finalMsg, message); - } catch (err) { - XSLog.error(`Failed to catch MESSAGE_CREATE: ${err}`); } + + if (shouldIgnoreForChannelType(channel)) return; + sendMsgNotif(titleString, finalMsg, message); } } }); diff --git a/src/utils/types.ts b/src/utils/types.ts index 2fa4a826e9..8c24843f86 100644 --- a/src/utils/types.ts +++ b/src/utils/types.ts @@ -128,7 +128,7 @@ export interface PluginDef { * Allows you to subscribe to Flux events */ flux?: { - [E in FluxEvents]?: (event: any) => void; + [E in FluxEvents]?: (event: any) => void | Promise; }; /** * Allows you to manipulate context menus From 495da113479788e8799751004a5766f130befafe Mon Sep 17 00:00:00 2001 From: Vendicated Date: Fri, 21 Jun 2024 22:49:55 +0200 Subject: [PATCH 14/50] fix Summaries --- src/plugins/seeSummaries/index.tsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/plugins/seeSummaries/index.tsx b/src/plugins/seeSummaries/index.tsx index 4ce8c4af71..de50e0a9dd 100644 --- a/src/plugins/seeSummaries/index.tsx +++ b/src/plugins/seeSummaries/index.tsx @@ -12,7 +12,7 @@ import { findByCodeLazy, findByPropsLazy } from "@webpack"; import { ChannelStore, GuildStore } from "@webpack/common"; const SummaryStore = findByPropsLazy("allSummaries", "findSummary"); -const createSummaryFromServer = findByCodeLazy(".people)),startId:"); +const createSummaryFromServer = findByCodeLazy(".people)),startId:", ".type}"); const settings = definePluginSettings({ summaryExpiryThresholdDays: { From e16c9ca70fd290e11390d9672e32c7db065523f8 Mon Sep 17 00:00:00 2001 From: Nuckyz <61953774+Nuckyz@users.noreply.github.com> Date: Fri, 21 Jun 2024 18:50:21 -0300 Subject: [PATCH 15/50] GameActivityToggle: Fix moving settings button outside --- src/plugins/gameActivityToggle/style.css | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/plugins/gameActivityToggle/style.css b/src/plugins/gameActivityToggle/style.css index d77d300966..3e6fd6b73c 100644 --- a/src/plugins/gameActivityToggle/style.css +++ b/src/plugins/gameActivityToggle/style.css @@ -1,3 +1,3 @@ -[class*="withTagAsButton"] { - min-width: 88px !important; +[class*="panels"] [class*="avatarWrapper"] { + min-width: 88px; } From 18df66a4b4cdbef73fff82e184c36566fc9a3d75 Mon Sep 17 00:00:00 2001 From: Vendicated Date: Sat, 22 Jun 2024 00:31:28 +0200 Subject: [PATCH 16/50] fix SpotifyControls --- src/plugins/spotifyControls/index.tsx | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/plugins/spotifyControls/index.tsx b/src/plugins/spotifyControls/index.tsx index 033d49357c..b811b2eed3 100644 --- a/src/plugins/spotifyControls/index.tsx +++ b/src/plugins/spotifyControls/index.tsx @@ -48,10 +48,10 @@ export default definePlugin({ }, patches: [ { - find: "showTaglessAccountPanel:", + find: '"AccountConnected"', replacement: { // react.jsx)(AccountPanel, { ..., showTaglessAccountPanel: blah }) - match: /(?<=\i\.jsxs?\)\()(\i),{(?=[^}]*?showTaglessAccountPanel:)/, + match: /(?<=\i\.jsxs?\)\()(\i),{(?=[^}]*?userTag:\i,hidePrivateData:)/, // react.jsx(WrapperComponent, { VencordOriginal: AccountPanel, ... replace: "$self.PanelWrapper,{VencordOriginal:$1," } From 6ce7fde19c53984aa7c8104c24731be594c07b0f Mon Sep 17 00:00:00 2001 From: Vendicated Date: Sat, 22 Jun 2024 01:10:08 +0200 Subject: [PATCH 17/50] upgrade monaco (QuickCss Editor) to 0.50.0; fixes some syntax --- package.json | 2 +- pnpm-lock.yaml | 22 +++++++++++++++------- src/main/monacoWin.html | 10 +++++----- src/plugins/_core/supportHelper.tsx | 2 +- 4 files changed, 22 insertions(+), 14 deletions(-) diff --git a/package.json b/package.json index e80c3970a0..74ec3e9bdb 100644 --- a/package.json +++ b/package.json @@ -43,7 +43,7 @@ "eslint-plugin-simple-header": "^1.0.2", "fflate": "^0.7.4", "gifenc": "github:mattdesl/gifenc#64842fca317b112a8590f8fef2bf3825da8f6fe3", - "monaco-editor": "^0.43.0", + "monaco-editor": "^0.50.0", "nanoid": "^4.0.2", "virtual-merge": "^1.0.1" }, diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index b03585799b..19295325fb 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -35,8 +35,8 @@ importers: specifier: github:mattdesl/gifenc#64842fca317b112a8590f8fef2bf3825da8f6fe3 version: https://codeload.github.com/mattdesl/gifenc/tar.gz/64842fca317b112a8590f8fef2bf3825da8f6fe3 monaco-editor: - specifier: ^0.43.0 - version: 0.43.0 + specifier: ^0.50.0 + version: 0.50.0 nanoid: specifier: ^4.0.2 version: 4.0.2 @@ -1531,6 +1531,10 @@ packages: is-core-module@2.13.1: resolution: {integrity: sha512-hHrIjvZsftOsvKSn2TRYl63zvxsgE0K+0mYMoH6gD4omR5IWB2KynivBQczo3+wF1cCkjzvptnI9Q0sPU66ilw==} + is-core-module@2.14.0: + resolution: {integrity: sha512-a5dFJih5ZLYlRtDc0dZWP7RiKr6xIKzmn/oAYCDvdLThadVgyJwlaoQPmRtMSpz+rk0OGAgIu+TcM9HUF0fk1A==} + engines: {node: '>= 0.4'} + is-data-descriptor@0.1.4: resolution: {integrity: sha512-+w9D5ulSoBNlmw9OHn3U2v51SyoCd0he+bB3xMl62oijhrspxowjU+AIcDY0N3iEJbUEkB15IlMASQsxYigvXg==} engines: {node: '>=0.10.0'} @@ -1791,8 +1795,8 @@ packages: moment@2.29.4: resolution: {integrity: sha512-5LC9SOxjSc2HF6vO2CyuTDNivEdoz2IvyJJGj6X8DJ0eFyfszE0QiEd+iXmBvUP3WHxSjFH/vIsA0EN00cgr8w==} - monaco-editor@0.43.0: - resolution: {integrity: sha512-cnoqwQi/9fml2Szamv1XbSJieGJ1Dc8tENVMD26Kcfl7xGQWp7OBKMjlwKVGYFJ3/AXJjSOGvcqK7Ry/j9BM1Q==} + monaco-editor@0.50.0: + resolution: {integrity: sha512-8CclLCmrRRh+sul7C08BmPBP3P8wVWfBHomsTcndxg5NRCEPfu/mc2AGU8k37ajjDVXcXFc12ORAMUkmk+lkFA==} ms@2.0.0: resolution: {integrity: sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A==} @@ -3463,7 +3467,7 @@ snapshots: eslint-import-resolver-node@0.3.9: dependencies: debug: 3.2.7 - is-core-module: 2.13.1 + is-core-module: 2.14.0 resolve: 1.22.8 transitivePeerDependencies: - supports-color @@ -3490,7 +3494,7 @@ snapshots: eslint-import-resolver-node: 0.3.9 eslint-module-utils: 2.8.1(@typescript-eslint/parser@5.59.1(eslint@8.46.0(patch_hash=xm46kqcmdgzlmm4aifkfpxaho4))(typescript@5.4.5))(eslint-import-resolver-node@0.3.9)(eslint@8.46.0(patch_hash=xm46kqcmdgzlmm4aifkfpxaho4)) hasown: 2.0.2 - is-core-module: 2.13.1 + is-core-module: 2.14.0 is-glob: 4.0.3 minimatch: 3.1.2 object.fromentries: 2.0.8 @@ -3934,6 +3938,10 @@ snapshots: dependencies: hasown: 2.0.2 + is-core-module@2.14.0: + dependencies: + hasown: 2.0.2 + is-data-descriptor@0.1.4: dependencies: kind-of: 3.2.2 @@ -4169,7 +4177,7 @@ snapshots: moment@2.29.4: {} - monaco-editor@0.43.0: {} + monaco-editor@0.50.0: {} ms@2.0.0: {} diff --git a/src/main/monacoWin.html b/src/main/monacoWin.html index 61d075ff24..ca7d0a78c9 100644 --- a/src/main/monacoWin.html +++ b/src/main/monacoWin.html @@ -5,8 +5,8 @@ Vencord QuickCSS Editor @@ -29,8 +29,8 @@
@@ -38,7 +38,7 @@