From cdbeea3b675ff2d578e5e2214cc5a16ec18a9856 Mon Sep 17 00:00:00 2001 From: "|| Prof. - Xadk3!#0000 || @naryal2580" Date: Sat, 27 May 2023 18:23:15 +0530 Subject: [PATCH] latest? --- .eslintrc.json | 2 +- README.md | 15 +- browser/GMPolyfill.js | 73 ++--- package.json | 2 +- scripts/generatePluginList.ts | 19 +- src/Vencord.ts | 3 - src/api/ContextMenu.ts | 17 +- src/api/MessageEvents.ts | 13 +- src/api/index.ts | 5 + src/components/Icons.tsx | 148 ++++++++++ src/components/PluginSettings/PluginModal.tsx | 30 +- src/components/PluginSettings/index.tsx | 29 +- .../PluginSettings/userPopoutHideBotTag.css | 3 + ...RestoreTab.tsx => BackupAndRestoreTab.tsx} | 11 +- src/components/VencordSettings/CloudTab.tsx | 9 +- .../PatchHelperTab.tsx} | 13 +- src/components/VencordSettings/PluginsTab.tsx | 5 +- src/components/VencordSettings/ThemesTab.tsx | 15 +- .../{Updater.tsx => UpdaterTab.tsx} | 14 +- src/components/VencordSettings/VencordTab.tsx | 9 +- src/components/VencordSettings/index.tsx | 96 ------- .../VencordSettings/settingsStyles.css | 4 +- src/components/VencordSettings/shared.tsx | 51 ++++ src/components/iconStyles.css | 7 + src/components/index.ts | 21 -- src/plugins/apiBadges.tsx | 10 +- src/plugins/apiServerList.ts | 2 +- src/plugins/emoteCloner.tsx | 260 +++++++++++++----- src/plugins/experiments.tsx | 26 +- src/plugins/{fakeNitro.tsx => fakeNitro.ts} | 204 ++++++++++---- src/plugins/favEmojiFirst.ts | 83 ++++++ src/plugins/imageZoom/index.tsx | 2 + src/plugins/invisibleChat/index.tsx | 42 ++- src/plugins/lastfm.tsx | 5 +- src/plugins/messageClickActions.ts | 66 +++-- .../{moreUserTags.ts => moreUserTags.tsx} | 227 ++++++++++----- src/plugins/noReplyMention.tsx | 24 +- src/plugins/partyMode.ts | 105 +++++++ .../components/RolesAndUsersPermissions.tsx | 225 +++++++++++++++ .../components/UserPermissions.tsx | 197 +++++++++++++ .../permissionsViewer/components/icons.tsx | 58 ++++ src/plugins/permissionsViewer/index.tsx | 189 +++++++++++++ src/plugins/permissionsViewer/styles.css | 146 ++++++++++ src/plugins/permissionsViewer/utils.ts | 98 +++++++ src/plugins/platformIndicators.tsx | 47 ++-- .../components/PronounsChatComponent.tsx | 4 +- src/plugins/reverseImageSearch.tsx | 32 ++- src/plugins/reviewDB/Utils/Utils.tsx | 11 +- .../reviewDB/components/ReviewComponent.tsx | 22 +- .../reviewDB/components/ReviewsView.tsx | 19 +- src/plugins/reviewDB/entities/User.ts | 22 +- src/plugins/reviewDB/index.tsx | 60 +++- src/plugins/searchReply.tsx | 2 +- src/plugins/sendTimestamps/styles.css | 2 +- src/plugins/settings.tsx | 20 +- src/plugins/showConnections/VerifiedIcon.tsx | 38 +++ src/plugins/showConnections/index.tsx | 24 +- src/plugins/showConnections/styles.css | 6 + .../components/HiddenChannelLockScreen.tsx | 106 +++++-- src/plugins/showHiddenChannels/index.tsx | 19 +- src/plugins/showHiddenChannels/style.css | 35 ++- src/plugins/silentMessageToggle.tsx | 11 +- src/plugins/silentTyping.tsx | 2 +- .../spotifyControls/PlayerComponent.tsx | 5 + src/plugins/supportHelper.tsx | 4 +- src/plugins/textReplace.tsx | 6 +- src/plugins/translate/TranslateIcon.tsx | 78 ++++++ src/plugins/translate/TranslateModal.tsx | 101 +++++++ .../translate/TranslationAccessory.tsx | 62 +++++ src/plugins/translate/index.tsx | 90 ++++++ src/plugins/translate/languages.ts | 172 ++++++++++++ src/plugins/translate/settings.ts | 52 ++++ src/plugins/translate/styles.css | 37 +++ src/plugins/translate/utils.ts | 75 +++++ src/plugins/typingIndicator.tsx | 2 +- src/plugins/typingTweaks.tsx | 6 +- src/plugins/urbanDictionary.ts | 35 ++- src/plugins/usrbg/index.tsx | 12 +- src/plugins/uwuify.ts | 37 ++- src/plugins/validUser.tsx | 144 ++++++++++ src/plugins/vcNarrator.tsx | 7 +- src/plugins/viewIcons.tsx | 16 +- src/plugins/webContextMenus.web.ts | 6 +- src/utils/constants.ts | 45 ++- src/utils/discord.ts | 32 ++- src/utils/misc.tsx | 4 + src/utils/types.ts | 7 + src/webpack/common/components.ts | 5 +- src/webpack/common/stores.ts | 5 +- src/webpack/common/types/components.d.ts | 12 + src/webpack/common/types/menu.d.ts | 7 +- src/webpack/common/types/stores.d.ts | 101 +++++++ src/webpack/common/types/utils.d.ts | 45 +++ src/webpack/common/utils.ts | 2 + 94 files changed, 3605 insertions(+), 672 deletions(-) create mode 100644 src/components/Icons.tsx create mode 100644 src/components/PluginSettings/userPopoutHideBotTag.css rename src/components/VencordSettings/{BackupRestoreTab.tsx => BackupAndRestoreTab.tsx} (89%) rename src/components/{PatchHelper.tsx => VencordSettings/PatchHelperTab.tsx} (96%) rename src/components/VencordSettings/{Updater.tsx => UpdaterTab.tsx} (95%) delete mode 100644 src/components/VencordSettings/index.tsx create mode 100644 src/components/VencordSettings/shared.tsx create mode 100644 src/components/iconStyles.css delete mode 100644 src/components/index.ts rename src/plugins/{fakeNitro.tsx => fakeNitro.ts} (79%) create mode 100644 src/plugins/favEmojiFirst.ts rename src/plugins/{moreUserTags.ts => moreUserTags.tsx} (55%) create mode 100644 src/plugins/partyMode.ts create mode 100644 src/plugins/permissionsViewer/components/RolesAndUsersPermissions.tsx create mode 100644 src/plugins/permissionsViewer/components/UserPermissions.tsx create mode 100644 src/plugins/permissionsViewer/components/icons.tsx create mode 100644 src/plugins/permissionsViewer/index.tsx create mode 100644 src/plugins/permissionsViewer/styles.css create mode 100644 src/plugins/permissionsViewer/utils.ts create mode 100644 src/plugins/showConnections/VerifiedIcon.tsx create mode 100644 src/plugins/translate/TranslateIcon.tsx create mode 100644 src/plugins/translate/TranslateModal.tsx create mode 100644 src/plugins/translate/TranslationAccessory.tsx create mode 100644 src/plugins/translate/index.tsx create mode 100644 src/plugins/translate/languages.ts create mode 100644 src/plugins/translate/settings.ts create mode 100644 src/plugins/translate/styles.css create mode 100644 src/plugins/translate/utils.ts create mode 100644 src/plugins/validUser.tsx diff --git a/.eslintrc.json b/.eslintrc.json index aaaaaeb..e45e446 100644 --- a/.eslintrc.json +++ b/.eslintrc.json @@ -62,7 +62,7 @@ "indent": ["error", 4, { "SwitchCase": 1 }], "arrow-parens": ["error", "as-needed"], "eol-last": ["error", "always"], - "func-call-spacing": ["error", "never"], + "@typescript-eslint/func-call-spacing": ["error", "never"], "no-multi-spaces": "error", "no-trailing-spaces": "error", "no-whitespace-before-property": "error", diff --git a/README.md b/README.md index cc1c4bd..e1a70c6 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@ The cutest Discord client mod - Super easy to install (Download Installer, open, click install button, done) - 100+ plugins built in: [See a list](https://vencord.dev/plugins) - - Some highlights: SpotifyControls, GameActivityToggle, Experiments, NoTrack, MessageLogger, QuickReply, Free Emotes/Stickers, CustomCommands, ShowHiddenChannels, PronounDB + - Some highlights: SpotifyControls, MessageLogger, Experiments, GameActivityToggle, Translate, NoTrack, QuickReply, Free Emotes/Stickers, PermissionsViewer, CustomCommands, ShowHiddenChannels, PronounDB - Fairly lightweight despite the many inbuilt plugins - Excellent Browser Support: Run Vencord in your Browser via extension or UserScript - Works on any Discord branch: Stable, Canary or PTB all work (though for the best experience I recommend stable!) @@ -32,12 +32,21 @@ Click the below button to install Vencord to the Discord Desktop app Or use the [UserScript](https://raw.githubusercontent.com/Vencord/builds/main/Vencord.user.js) - Please note that the CSS Editor, Themes loaded from remote sources and co. will not work in the UserScript. Use the extension if you need any of those -## Installing our Desktop App +
+Alternative Downloads + +## Vencord Desktop + +> **Warning** +> This is an alternative app. It currently doesn't support screensharing or keybinds. If you just want to install to the normal Discord Desktop app, scroll up + As an alternative to the Discord Desktop app, Vencord also has its own standalone Desktop app that is snappier and lighter than Discord's official Desktop app. It is currently in beta and we have yet to implement some features like screensharing, but you can try the beta nonetheless [![Download Vencord Desktop](https://img.shields.io/github/v/release/Vencord/Desktop?label=Download%20Vencord%20Desktop&style=for-the-badge)](https://github.com/Vencord/Desktop#vencord-desktop) +
+ ## Join our Support/Community Server [![Vencord Discord Server](https://invidget.switchblade.xyz/D9uwnFnqmd?theme=dark)](https://discord.gg/D9uwnFnqmd) @@ -48,7 +57,7 @@ Discord is trademark of Discord Inc. and solely mentioned for the sake of descri Mention of it does not imply any affiliation with or endorsement by Discord Inc.
-Using Vencord violates Discord's terms of service +Using Vencord violates Discord's terms of service Client modifications are against Discord’s Terms of Service. diff --git a/browser/GMPolyfill.js b/browser/GMPolyfill.js index 1f74a7c..f880155 100644 --- a/browser/GMPolyfill.js +++ b/browser/GMPolyfill.js @@ -16,20 +16,6 @@ * along with this program. If not, see . */ -function fetchOptions(url) { - return new Promise((resolve, reject) => { - const opt = { - method: "OPTIONS", - url: url, - }; - opt.onload = resp => resolve(resp.responseHeaders); - opt.ontimeout = () => reject("fetch timeout"); - opt.onerror = () => reject("fetch error"); - opt.onabort = () => reject("fetch abort"); - GM_xmlhttpRequest(opt); - }); -} - function parseHeaders(headers) { if (!headers) return {}; @@ -52,21 +38,6 @@ function parseHeaders(headers) { return result; } -// returns true if CORS permits request -async function checkCors(url, method) { - const headers = parseHeaders(await fetchOptions(url)); - - const origin = headers["access-control-allow-origin"]; - if (origin !== "*" && origin !== window.location.origin) return false; - - const methods = headers["access-control-allow-methods"]?.toLowerCase() - .split(",") - .map(s => s.trim()); - if (methods && !methods.includes(method.toLowerCase())) return false; - - return true; -} - function blobTo(to, blob) { if (to === "arrayBuffer" && blob.arrayBuffer) return blob.arrayBuffer(); return new Promise((resolve, reject) => { @@ -80,31 +51,25 @@ function blobTo(to, blob) { function GM_fetch(url, opt) { return new Promise((resolve, reject) => { - checkCors(url, opt?.method || "GET") - .then(can => { - if (can) { - // https://www.tampermonkey.net/documentation.php?ext=dhdg#GM_xmlhttpRequest - const options = opt || {}; - options.url = url; - options.data = options.body; - options.responseType = "blob"; - options.onload = resp => { - var blob = resp.response; - resp.blob = () => Promise.resolve(blob); - resp.arrayBuffer = () => blobTo("arrayBuffer", blob); - resp.text = () => blobTo("text", blob); - resp.json = async () => JSON.parse(await blobTo("text", blob)); - resp.headers = new Headers(parseHeaders(resp.responseHeaders)); - resolve(resp); - }; - options.ontimeout = () => reject("fetch timeout"); - options.onerror = () => reject("fetch error"); - options.onabort = () => reject("fetch abort"); - GM_xmlhttpRequest(options); - } else { - reject("CORS issue"); - } - }); + // https://www.tampermonkey.net/documentation.php?ext=dhdg#GM_xmlhttpRequest + const options = opt || {}; + options.url = url; + options.data = options.body; + options.responseType = "blob"; + options.onload = resp => { + var blob = resp.response; + resp.blob = () => Promise.resolve(blob); + resp.arrayBuffer = () => blobTo("arrayBuffer", blob); + resp.text = () => blobTo("text", blob); + resp.json = async () => JSON.parse(await blobTo("text", blob)); + resp.headers = new Headers(parseHeaders(resp.responseHeaders)); + resp.ok = resp.status >= 200 && resp.status < 300; + resolve(resp); + }; + options.ontimeout = () => reject("fetch timeout"); + options.onerror = () => reject("fetch error"); + options.onabort = () => reject("fetch abort"); + GM_xmlhttpRequest(options); }); } export const fetch = GM_fetch; diff --git a/package.json b/package.json index e3b4360..b5e92ca 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "vencord", "private": "true", - "version": "1.2.0", + "version": "1.2.5", "description": "The cutest Discord client mod", "homepage": "https://github.com/Vendicated/Vencord#readme", "bugs": { diff --git a/scripts/generatePluginList.ts b/scripts/generatePluginList.ts index e4ae20a..87c32ab 100644 --- a/scripts/generatePluginList.ts +++ b/scripts/generatePluginList.ts @@ -19,7 +19,7 @@ import { Dirent, readdirSync, readFileSync, writeFileSync } from "fs"; import { access, readFile } from "fs/promises"; import { join } from "path"; -import { BigIntLiteral, createSourceFile, Identifier, isArrayLiteralExpression, isCallExpression, isExportAssignment, isIdentifier, isObjectLiteralExpression, isPropertyAccessExpression, isPropertyAssignment, isStringLiteral, isVariableStatement, NamedDeclaration, NodeArray, ObjectLiteralExpression, ScriptTarget, StringLiteral, SyntaxKind } from "typescript"; +import { BigIntLiteral, createSourceFile, Identifier, isArrayLiteralExpression, isCallExpression, isExportAssignment, isIdentifier, isObjectLiteralExpression, isPropertyAccessExpression, isPropertyAssignment, isSatisfiesExpression, isStringLiteral, isVariableStatement, NamedDeclaration, NodeArray, ObjectLiteralExpression, ScriptTarget, StringLiteral, SyntaxKind } from "typescript"; interface Dev { name: string; @@ -29,6 +29,7 @@ interface Dev { interface PluginData { name: string; description: string; + tags: string[]; authors: Dev[]; dependencies: string[]; hasPatches: boolean; @@ -65,9 +66,9 @@ function parseDevs() { const value = devsDeclaration.initializer.arguments[0]; - if (!isObjectLiteralExpression(value)) return; + if (!isSatisfiesExpression(value) || !isObjectLiteralExpression(value.expression)) throw new Error("Failed to parse devs: not an object literal"); - for (const prop of value.properties) { + for (const prop of value.expression.properties) { const name = (prop.name as Identifier).text; const value = isPropertyAssignment(prop) ? prop.initializer : prop; @@ -106,6 +107,7 @@ async function parseFile(fileName: string) { hasCommands: false, enabledByDefault: false, required: false, + tags: [] as string[] } as PluginData; for (const prop of pluginObj.properties) { @@ -128,7 +130,16 @@ async function parseFile(fileName: string) { if (!isArrayLiteralExpression(value)) throw fail("authors is not an array literal"); data.authors = value.elements.map(e => { if (!isPropertyAccessExpression(e)) throw fail("authors array contains non-property access expressions"); - return devs[getName(e)!]; + const d = devs[getName(e)!]; + if (!d) throw fail(`couldn't look up author ${getName(e)}`); + return d; + }); + break; + case "tags": + if (!isArrayLiteralExpression(value)) throw fail("tags is not an array literal"); + data.tags = value.elements.map(e => { + if (!isStringLiteral(e)) throw fail("tags array contains non-string literals"); + return e.text; }); break; case "dependencies": diff --git a/src/Vencord.ts b/src/Vencord.ts index 76719e5..a05ec53 100644 --- a/src/Vencord.ts +++ b/src/Vencord.ts @@ -37,8 +37,6 @@ import { checkForUpdates, update, UpdateLogger } from "./utils/updater"; import { onceReady } from "./webpack"; import { SettingsRouter } from "./webpack/common"; -export let Components: any; - async function syncSettings() { if ( Settings.cloud.settingsSync && // if it's enabled @@ -65,7 +63,6 @@ async function syncSettings() { async function init() { await onceReady; startAllPlugins(); - Components = await import("./components"); syncSettings(); diff --git a/src/api/ContextMenu.ts b/src/api/ContextMenu.ts index f1ebfdb..156ae20 100644 --- a/src/api/ContextMenu.ts +++ b/src/api/ContextMenu.ts @@ -25,14 +25,14 @@ type ContextMenuPatchCallbackReturn = (() => void) | void; * @param args Any arguments passed into making the context menu, like the guild, channel, user or message for example * @returns A callback which is only ran once used to modify the context menu elements (Use to avoid duplicates) */ -export type NavContextMenuPatchCallback = (children: Array, ...args: Array) => ContextMenuPatchCallbackReturn; +export type NavContextMenuPatchCallback = (children: Array, ...args: Array) => ContextMenuPatchCallbackReturn; /** * @param navId The navId of the context menu being patched * @param children The rendered context menu elements * @param args Any arguments passed into making the context menu, like the guild, channel, user or message for example * @returns A callback which is only ran once used to modify the context menu elements (Use to avoid duplicates) */ -export type GlobalContextMenuPatchCallback = (navId: string, children: Array, ...args: Array) => ContextMenuPatchCallbackReturn; +export type GlobalContextMenuPatchCallback = (navId: string, children: Array, ...args: Array) => ContextMenuPatchCallbackReturn; const ContextMenuLogger = new Logger("ContextMenu"); @@ -89,15 +89,18 @@ export function removeGlobalContextMenuPatch(patch: GlobalContextMenuPatchCallba } /** - * A helper function for finding the children array of a group nested inside a context menu based on the id of one of its childs - * @param id The id of the child + * A helper function for finding the children array of a group nested inside a context menu based on the id(s) of its children + * @param id The id of the child. If an array is specified, all ids will be tried * @param children The context menu children */ -export function findGroupChildrenByChildId(id: string, children: Array, _itemsArray?: Array): Array | null { +export function findGroupChildrenByChildId(id: string | string[], children: Array, _itemsArray?: Array): Array | null { for (const child of children) { if (child == null) continue; - if (child.props?.id === id) return _itemsArray ?? null; + if ( + (Array.isArray(id) && id.some(id => child.props?.id === id)) + || child.props?.id === id + ) return _itemsArray ?? null; let nextChildren = child.props?.children; if (nextChildren) { @@ -117,7 +120,7 @@ export function findGroupChildrenByChildId(id: string, children: Array; navId: string; - children: Array; + children: Array; "aria-label": string; onSelect: (() => void) | undefined; onClose: (callback: (...args: Array) => any) => void; diff --git a/src/api/MessageEvents.ts b/src/api/MessageEvents.ts index b597fea..341b4e6 100644 --- a/src/api/MessageEvents.ts +++ b/src/api/MessageEvents.ts @@ -18,24 +18,15 @@ import { Logger } from "@utils/Logger"; import { MessageStore } from "@webpack/common"; +import { CustomEmoji } from "@webpack/types"; import type { Channel, Message } from "discord-types/general"; import type { Promisable } from "type-fest"; const MessageEventsLogger = new Logger("MessageEvents", "#e5c890"); -export interface Emoji { - require_colons: boolean, - originalName: string, - animated: boolean; - guildId: string, - name: string, - url: string, - id: string, -} - export interface MessageObject { content: string, - validNonShortcutEmojis: Emoji[]; + validNonShortcutEmojis: CustomEmoji[]; invalidEmojis: any[]; tts: boolean; } diff --git a/src/api/index.ts b/src/api/index.ts index ba2978e..f2c47e5 100644 --- a/src/api/index.ts +++ b/src/api/index.ts @@ -28,6 +28,7 @@ import * as $MessagePopover from "./MessagePopover"; import * as $Notices from "./Notices"; import * as $Notifications from "./Notifications"; import * as $ServerList from "./ServerList"; +import * as $Settings from "./Settings"; import * as $SettingsStore from "./SettingsStore"; import * as $Styles from "./Styles"; @@ -86,6 +87,10 @@ export const MessageDecorations = $MessageDecorations; * An API allowing you to add components to member list users, in both DM's and servers */ export const MemberListDecorators = $MemberListDecorators; +/** + * An API allowing you to persist data + */ +export const Settings = $Settings; /** * An API allowing you to read, manipulate and automatically update components based on Discord settings */ diff --git a/src/components/Icons.tsx b/src/components/Icons.tsx new file mode 100644 index 0000000..4227fce --- /dev/null +++ b/src/components/Icons.tsx @@ -0,0 +1,148 @@ +/* + * 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 "./iconStyles.css"; + +import { classes } from "@utils/misc"; +import { i18n } from "@webpack/common"; +import type { PropsWithChildren, SVGProps } from "react"; + +interface BaseIconProps extends IconProps { + viewBox: string; +} + +interface IconProps extends SVGProps { + className?: string; + height?: number; + width?: number; +} + +function Icon({ height = 24, width = 24, className, children, viewBox, ...svgProps }: PropsWithChildren) { + return ( + + {children} + + ); +} + +/** + * Discord's link icon, as seen in the Message context menu "Copy Message Link" option + */ +export function LinkIcon({ height = 24, width = 24, className }: IconProps) { + return ( + + + + + + + ); +} + +/** + * Discord's copy icon, as seen in the user popout right of the username when clicking + * your own username in the bottom left user panel + */ +export function CopyIcon(props: IconProps) { + return ( + + + + + + + ); +} + +/** + * Discord's open external icon, as seen in the user profile connections + */ +export function OpenExternalIcon(props: IconProps) { + return ( + + + + ); +} + +export function ImageIcon(props: IconProps) { + return ( + + + + ); +} + +export function InfoIcon(props: IconProps) { + return ( + + + + ); +} + +export function OwnerCrownIcon(props: IconProps) { + return ( + + + + ); +} diff --git a/src/components/PluginSettings/PluginModal.tsx b/src/components/PluginSettings/PluginModal.tsx index c502873..7079ebf 100644 --- a/src/components/PluginSettings/PluginModal.tsx +++ b/src/components/PluginSettings/PluginModal.tsx @@ -18,6 +18,7 @@ import { generateId } from "@api/Commands"; import { useSettings } from "@api/Settings"; +import { disableStyle, enableStyle } from "@api/Styles"; import ErrorBoundary from "@components/ErrorBoundary"; import { Flex } from "@components/Flex"; import { proxyLazy } from "@utils/lazy"; @@ -40,6 +41,7 @@ import { SettingSliderComponent, SettingTextComponent } from "./components"; +import hideBotTagStyle from "./userPopoutHideBotTag.css?managed"; const UserSummaryItem = LazyComponent(() => findByCode("defaultRenderUser", "showDefaultAvatarsForNullUsers")); const AvatarStyles = findByPropsLazy("moreUsers", "emptyUser", "avatarContainer", "clickableAvatar"); @@ -50,11 +52,12 @@ interface PluginModalProps extends ModalProps { onRestartNeeded(): void; } -/** To stop discord making unwanted requests... */ -function makeDummyUser(user: { name: string, id: BigInt; }) { +function makeDummyUser(user: { username: string; id?: string; avatar?: string; }) { const newUser = new UserRecord({ - username: user.name, - id: generateId(), + username: user.username, + id: user.id ?? generateId(), + avatar: user.avatar, + /** To stop discord making unwanted requests... */ bot: true, }); FluxDispatcher.dispatch({ @@ -89,14 +92,27 @@ export default function PluginModal({ plugin, onRestartNeeded, onClose, transiti const hasSettings = Boolean(pluginSettings && plugin.options); React.useEffect(() => { + enableStyle(hideBotTagStyle); + + let originalUser: User; (async () => { for (const user of plugin.authors.slice(0, 6)) { const author = user.id - ? await UserUtils.fetchUser(`${user.id}`).catch(() => makeDummyUser(user)) - : makeDummyUser(user); + ? await UserUtils.fetchUser(`${user.id}`) + // only show name & pfp and no actions so users cannot harass plugin devs for support (send dms, add as friend, etc) + .then(u => (originalUser = u, makeDummyUser(u))) + .catch(() => makeDummyUser({ username: user.name })) + : makeDummyUser({ username: user.name }); + setAuthors(a => [...a, author]); } })(); + + return () => { + disableStyle(hideBotTagStyle); + if (originalUser) + FluxDispatcher.dispatch({ type: "USER_UPDATE", user: originalUser }); + }; }, []); async function saveAndClose() { @@ -129,6 +145,8 @@ export default function PluginModal({ plugin, onRestartNeeded, onClose, transiti return There are no settings for this plugin.; } else { const options = Object.entries(plugin.options).map(([key, setting]) => { + if (setting.hidden) return null; + function onChange(newValue: any) { setTempSettings(s => ({ ...s, [key]: newValue })); } diff --git a/src/components/PluginSettings/index.tsx b/src/components/PluginSettings/index.tsx index 7679c01..e1b36ef 100644 --- a/src/components/PluginSettings/index.tsx +++ b/src/components/PluginSettings/index.tsx @@ -20,20 +20,18 @@ import "./styles.css"; import * as DataStore from "@api/DataStore"; import { showNotice } from "@api/Notices"; -import { useSettings } from "@api/Settings"; +import { Settings, useSettings } from "@api/Settings"; import { classNameFactory } from "@api/Styles"; -import ErrorBoundary from "@components/ErrorBoundary"; import { Flex } from "@components/Flex"; -import { handleComponentFailed } from "@components/handleComponentFailed"; import { Badge } from "@components/PluginSettings/components"; import PluginModal from "@components/PluginSettings/PluginModal"; import { Switch } from "@components/Switch"; +import { SettingsTab } from "@components/VencordSettings/shared"; import { ChangeList } from "@utils/ChangeList"; import { Logger } from "@utils/Logger"; import { Margins } from "@utils/margins"; import { classes } from "@utils/misc"; import { openModalLazy } from "@utils/modal"; -import { onlyOnce } from "@utils/onlyOnce"; import { LazyComponent, useAwaiter } from "@utils/react"; import { Plugin } from "@utils/types"; import { findByCode, findByPropsLazy } from "@webpack"; @@ -96,7 +94,7 @@ interface PluginCardProps extends React.HTMLProps { } function PluginCard({ plugin, disabled, onRestartNeeded, onMouseEnter, onMouseLeave, isNew }: PluginCardProps) { - const settings = useSettings([`plugins.${plugin.name}.enabled`]).plugins[plugin.name]; + const settings = Settings.plugins[plugin.name]; const isEnabled = () => settings.enabled ?? false; @@ -179,7 +177,7 @@ enum SearchStatus { DISABLED } -export default ErrorBoundary.wrap(function PluginSettings() { +export default function PluginSettings() { const settings = useSettings(); const changes = React.useMemo(() => new ChangeList(), []); @@ -230,9 +228,12 @@ export default ErrorBoundary.wrap(function PluginSettings() { if (enabled && searchValue.status === SearchStatus.DISABLED) return false; if (!enabled && searchValue.status === SearchStatus.ENABLED) return false; if (!searchValue.value.length) return true; + + const v = searchValue.value.toLowerCase(); return ( - plugin.name.toLowerCase().includes(searchValue.value.toLowerCase()) || - plugin.description.toLowerCase().includes(searchValue.value.toLowerCase()) + plugin.name.toLowerCase().includes(v) || + plugin.description.toLowerCase().includes(v) || + plugin.tags?.some(t => t.toLowerCase().includes(v)) ); }; @@ -260,6 +261,9 @@ export default ErrorBoundary.wrap(function PluginSettings() { requiredPlugins = []; for (const p of sortedPlugins) { + if (!p.options && p.name.endsWith("API") && searchValue.value !== "API") + continue; + if (!pluginFilter(p)) continue; const isRequired = p.required || depMap[p.name]?.some(d => settings.plugins[d].enabled); @@ -300,7 +304,7 @@ export default ErrorBoundary.wrap(function PluginSettings() { } return ( - + @@ -339,12 +343,9 @@ export default ErrorBoundary.wrap(function PluginSettings() {
{requiredPlugins}
-
+ ); -}, { - message: "Failed to render the Plugin Settings. If this persists, try using the installer to reinstall!", - onError: onlyOnce(handleComponentFailed), -}); +} function makeDependencyList(deps: string[]) { return ( diff --git a/src/components/PluginSettings/userPopoutHideBotTag.css b/src/components/PluginSettings/userPopoutHideBotTag.css new file mode 100644 index 0000000..5e33e4b --- /dev/null +++ b/src/components/PluginSettings/userPopoutHideBotTag.css @@ -0,0 +1,3 @@ +[class|="userPopoutOuter"] [class*="botTag"] { + display: none; +} diff --git a/src/components/VencordSettings/BackupRestoreTab.tsx b/src/components/VencordSettings/BackupAndRestoreTab.tsx similarity index 89% rename from src/components/VencordSettings/BackupRestoreTab.tsx rename to src/components/VencordSettings/BackupAndRestoreTab.tsx index 1737470..a9a1c9f 100644 --- a/src/components/VencordSettings/BackupRestoreTab.tsx +++ b/src/components/VencordSettings/BackupAndRestoreTab.tsx @@ -16,16 +16,17 @@ * along with this program. If not, see . */ -import ErrorBoundary from "@components/ErrorBoundary"; import { Flex } from "@components/Flex"; import { Margins } from "@utils/margins"; import { classes } from "@utils/misc"; import { downloadSettingsBackup, uploadSettingsBackup } from "@utils/settingsSync"; -import { Button, Card, Forms, Text } from "@webpack/common"; +import { Button, Card, Text } from "@webpack/common"; + +import { SettingsTab, wrapTab } from "./shared"; function BackupRestoreTab() { return ( - + Warning @@ -59,8 +60,8 @@ function BackupRestoreTab() { Export Settings - + ); } -export default ErrorBoundary.wrap(BackupRestoreTab); +export default wrapTab(BackupRestoreTab, "Backup & Restore"); diff --git a/src/components/VencordSettings/CloudTab.tsx b/src/components/VencordSettings/CloudTab.tsx index 5e48a72..77e5298 100644 --- a/src/components/VencordSettings/CloudTab.tsx +++ b/src/components/VencordSettings/CloudTab.tsx @@ -19,13 +19,14 @@ import { showNotification } from "@api/Notifications"; import { Settings, useSettings } from "@api/Settings"; import { CheckedTextInput } from "@components/CheckedTextInput"; -import ErrorBoundary from "@components/ErrorBoundary"; import { Link } from "@components/Link"; import { authorizeCloud, cloudLogger, deauthorizeCloud, getCloudAuth, getCloudUrl } from "@utils/cloud"; import { Margins } from "@utils/margins"; import { deleteCloudSettings, getCloudSettings, putCloudSettings } from "@utils/settingsSync"; import { Alerts, Button, Forms, Switch, Tooltip } from "@webpack/common"; +import { SettingsTab, wrapTab } from "./shared"; + function validateUrl(url: string) { try { new URL(url); @@ -114,7 +115,7 @@ function CloudTab() { const settings = useSettings(["cloud.authenticated", "cloud.url"]); return ( - <> + Vencord comes with a cloud integration that adds goodies like settings sync across devices. @@ -157,8 +158,8 @@ function CloudTab() { - + ); } -export default ErrorBoundary.wrap(CloudTab); +export default wrapTab(CloudTab, "Cloud"); diff --git a/src/components/PatchHelper.tsx b/src/components/VencordSettings/PatchHelperTab.tsx similarity index 96% rename from src/components/PatchHelper.tsx rename to src/components/VencordSettings/PatchHelperTab.tsx index 6c95a8a..d5bd94c 100644 --- a/src/components/PatchHelper.tsx +++ b/src/components/VencordSettings/PatchHelperTab.tsx @@ -16,16 +16,16 @@ * along with this program. If not, see . */ +import { CheckedTextInput } from "@components/CheckedTextInput"; import { debounce } from "@utils/debounce"; import { Margins } from "@utils/margins"; import { canonicalizeMatch, canonicalizeReplace } from "@utils/patches"; import { makeCodeblock } from "@utils/text"; import { ReplaceFn } from "@utils/types"; import { search } from "@webpack"; -import { Button, Clipboard, Forms, Parser, React, Switch, Text, TextInput } from "@webpack/common"; +import { Button, Clipboard, Forms, Parser, React, Switch, TextInput } from "@webpack/common"; -import { CheckedTextInput } from "./CheckedTextInput"; -import ErrorBoundary from "./ErrorBoundary"; +import { SettingsTab, wrapTab } from "./shared"; // Do not include diff in non dev builds (side effects import) if (IS_DEV) { @@ -258,8 +258,7 @@ function PatchHelper() { } return ( - - Patch Helper + find Clipboard.copy(code)}>Copy to Clipboard )} - + ); } -export default IS_DEV ? ErrorBoundary.wrap(PatchHelper) : null; +export default IS_DEV ? wrapTab(PatchHelper, "PatchHelper") : null; diff --git a/src/components/VencordSettings/PluginsTab.tsx b/src/components/VencordSettings/PluginsTab.tsx index 04b5dc2..6a32095 100644 --- a/src/components/VencordSettings/PluginsTab.tsx +++ b/src/components/VencordSettings/PluginsTab.tsx @@ -16,7 +16,8 @@ * along with this program. If not, see . */ -import ErrorBoundary from "@components/ErrorBoundary"; import PluginSettings from "@components/PluginSettings"; -export default ErrorBoundary.wrap(PluginSettings); +import { wrapTab } from "./shared"; + +export default wrapTab(PluginSettings, "Plugins"); diff --git a/src/components/VencordSettings/ThemesTab.tsx b/src/components/VencordSettings/ThemesTab.tsx index 75fea34..79ddc50 100644 --- a/src/components/VencordSettings/ThemesTab.tsx +++ b/src/components/VencordSettings/ThemesTab.tsx @@ -17,13 +17,14 @@ */ import { useSettings } from "@api/Settings"; -import ErrorBoundary from "@components/ErrorBoundary"; import { Link } from "@components/Link"; import { Margins } from "@utils/margins"; import { useAwaiter } from "@utils/react"; import { findLazy } from "@webpack"; import { Card, Forms, React, TextArea } from "@webpack/common"; +import { SettingsTab, wrapTab } from "./shared"; + const TextAreaProps = findLazy(m => typeof m.textarea === "string"); function Validator({ link }: { link: string; }) { @@ -74,8 +75,8 @@ function Validators({ themeLinks }: { themeLinks: string[]; }) { ); } -export default ErrorBoundary.wrap(function () { - const settings = useSettings(); +function ThemesTab() { + const settings = useSettings(["themeLinks"]); const [themeText, setThemeText] = React.useState(settings.themeLinks.join("\n")); function onBlur() { @@ -89,7 +90,7 @@ export default ErrorBoundary.wrap(function () { } return ( - <> + Paste links to .theme.css files here One link per line @@ -124,6 +125,8 @@ export default ErrorBoundary.wrap(function () { onBlur={onBlur} /> - + ); -}); +} + +export default wrapTab(ThemesTab, "Themes"); diff --git a/src/components/VencordSettings/Updater.tsx b/src/components/VencordSettings/UpdaterTab.tsx similarity index 95% rename from src/components/VencordSettings/Updater.tsx rename to src/components/VencordSettings/UpdaterTab.tsx index 9345d27..4d0b86c 100644 --- a/src/components/VencordSettings/Updater.tsx +++ b/src/components/VencordSettings/UpdaterTab.tsx @@ -17,21 +17,20 @@ */ import { useSettings } from "@api/Settings"; -import ErrorBoundary from "@components/ErrorBoundary"; import { ErrorCard } from "@components/ErrorCard"; import { Flex } from "@components/Flex"; -import { handleComponentFailed } from "@components/handleComponentFailed"; import { Link } from "@components/Link"; import { Margins } from "@utils/margins"; import { classes } from "@utils/misc"; import { relaunch } from "@utils/native"; -import { onlyOnce } from "@utils/onlyOnce"; import { useAwaiter } from "@utils/react"; import { changes, checkForUpdates, getRepo, isNewer, update, updateError, UpdateLogger } from "@utils/updater"; import { Alerts, Button, Card, Forms, Parser, React, Switch, Toasts } from "@webpack/common"; import gitHash from "~git-hash"; +import { SettingsTab, wrapTab } from "./shared"; + function withDispatcher(dispatcher: React.Dispatch>, action: () => any) { return async () => { dispatcher(true); @@ -199,7 +198,7 @@ function Updater() { }; return ( - + Updater Settings Updates {isNewer ? : } - + ); } -export default IS_WEB ? null : ErrorBoundary.wrap(Updater, { - message: "Failed to render the Updater. If this persists, try using the installer to reinstall!", - onError: onlyOnce(handleComponentFailed), -}); +export default IS_WEB ? null : wrapTab(Updater, "Updater"); diff --git a/src/components/VencordSettings/VencordTab.tsx b/src/components/VencordSettings/VencordTab.tsx index 8c71821..1502bfa 100644 --- a/src/components/VencordSettings/VencordTab.tsx +++ b/src/components/VencordSettings/VencordTab.tsx @@ -21,7 +21,6 @@ import { openNotificationLogModal } from "@api/Notifications/notificationLog"; import { Settings, useSettings } from "@api/Settings"; import { classNameFactory } from "@api/Styles"; import DonateButton from "@components/DonateButton"; -import ErrorBoundary from "@components/ErrorBoundary"; import { ErrorCard } from "@components/ErrorCard"; import { Margins } from "@utils/margins"; import { identity } from "@utils/misc"; @@ -29,6 +28,8 @@ import { relaunch, showItemInFolder } from "@utils/native"; import { useAwaiter } from "@utils/react"; import { Button, Card, Forms, React, Select, Slider, Switch } from "@webpack/common"; +import { SettingsTab, wrapTab } from "./shared"; + const cl = classNameFactory("vc-settings-"); const DEFAULT_DONATE_IMAGE = "https://cdn.discordapp.com/emojis/1026533090627174460.png"; @@ -97,7 +98,7 @@ function VencordSettings() { ]; return ( - + @@ -153,7 +154,7 @@ function VencordSettings() { {typeof Notification !== "undefined" && } - + ); } @@ -263,4 +264,4 @@ function DonateCard({ image }: DonateCardProps) { ); } -export default ErrorBoundary.wrap(VencordSettings); +export default wrapTab(VencordSettings, "Vencord Settings"); diff --git a/src/components/VencordSettings/index.tsx b/src/components/VencordSettings/index.tsx deleted file mode 100644 index 6d65aa1..0000000 --- a/src/components/VencordSettings/index.tsx +++ /dev/null @@ -1,96 +0,0 @@ -/* - * Vencord, a modification for Discord's desktop app - * Copyright (c) 2022 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 "./settingsStyles.css"; - -import { classNameFactory } from "@api/Styles"; -import ErrorBoundary from "@components/ErrorBoundary"; -import { handleComponentFailed } from "@components/handleComponentFailed"; -import { isMobile } from "@utils/misc"; -import { onlyOnce } from "@utils/onlyOnce"; -import { Forms, SettingsRouter, TabBar, Text } from "@webpack/common"; - -import BackupRestoreTab from "./BackupRestoreTab"; -import CloudTab from "./CloudTab"; -import PluginsTab from "./PluginsTab"; -import ThemesTab from "./ThemesTab"; -import Updater from "./Updater"; -import VencordSettings from "./VencordTab"; - -const cl = classNameFactory("vc-settings-"); - -interface SettingsProps { - tab: string; -} - -interface SettingsTab { - name: string; - component?: React.ComponentType; -} - -const SettingsTabs: Record = { - VencordSettings: { name: "Vencord", component: () => }, - VencordPlugins: { name: "Plugins", component: () => }, - VencordThemes: { name: "Themes", component: () => }, - VencordUpdater: { name: "Updater" }, // Only show updater if IS_WEB is false - VencordCloud: { name: "Cloud", component: () => }, - VencordSettingsSync: { name: "Backup & Restore", component: () => } -}; - -if (!IS_WEB) SettingsTabs.VencordUpdater.component = () => Updater && ; - -function Settings(props: SettingsProps) { - const { tab = "VencordSettings" } = props; - - const CurrentTab = SettingsTabs[tab]?.component ?? null; - if (isMobile) { - return CurrentTab && ; - } - - return - Vencord Settings - - - {Object.entries(SettingsTabs).map(([key, { name, component }]) => { - if (!component) return null; - return - {name} - ; - })} - - - {CurrentTab && } - ; -} - -const onError = onlyOnce(handleComponentFailed); - -export default function (props: SettingsProps) { - return - - ; -} diff --git a/src/components/VencordSettings/settingsStyles.css b/src/components/VencordSettings/settingsStyles.css index 3652756..26988fd 100644 --- a/src/components/VencordSettings/settingsStyles.css +++ b/src/components/VencordSettings/settingsStyles.css @@ -29,14 +29,12 @@ .vc-settings-card { padding: 1em; margin-bottom: 1em; - margin-top: 1em; } .vc-backup-restore-card { background-color: var(--info-warning-background); border-color: var(--info-warning-foreground); color: var(--info-warning-text); - margin-top: 0; } .vc-settings-theme-links { @@ -59,7 +57,7 @@ } .vc-text-selectable, -.vc-text-selectable :not(a, button, a *, button *) { +.vc-text-selectable :not(a, button, a *, button *, input, input *) { /* make text selectable, silly discord makes the entirety of settings not selectable */ user-select: text; diff --git a/src/components/VencordSettings/shared.tsx b/src/components/VencordSettings/shared.tsx new file mode 100644 index 0000000..0d3910d --- /dev/null +++ b/src/components/VencordSettings/shared.tsx @@ -0,0 +1,51 @@ +/* + * 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 "./settingsStyles.css"; + +import ErrorBoundary from "@components/ErrorBoundary"; +import { handleComponentFailed } from "@components/handleComponentFailed"; +import { Margins } from "@utils/margins"; +import { onlyOnce } from "@utils/onlyOnce"; +import { Forms, Text } from "@webpack/common"; +import type { ComponentType, PropsWithChildren } from "react"; + +export function SettingsTab({ title, children }: PropsWithChildren<{ title: string; }>) { + return ( + + + {title} + + + {children} + + ); +} + +const onError = onlyOnce(handleComponentFailed); + +export function wrapTab(component: ComponentType, tab: string) { + return ErrorBoundary.wrap(component, { + message: `Failed to render the ${tab} tab. If this issue persists, try using the installer to reinstall!`, + onError, + }); +} diff --git a/src/components/iconStyles.css b/src/components/iconStyles.css new file mode 100644 index 0000000..ca4075d --- /dev/null +++ b/src/components/iconStyles.css @@ -0,0 +1,7 @@ +.vc-open-external-icon { + transform: rotate(45deg); +} + +.vc-owner-crown-icon { + color: var(--text-warning); +} diff --git a/src/components/index.ts b/src/components/index.ts deleted file mode 100644 index 3ee53b0..0000000 --- a/src/components/index.ts +++ /dev/null @@ -1,21 +0,0 @@ -/* - * Vencord, a modification for Discord's desktop app - * Copyright (c) 2022 Vendicated and contributors - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . -*/ - -export { default as PatchHelper } from "./PatchHelper"; -export { default as PluginSettings } from "./PluginSettings"; -export { default as VencordSettings } from "./VencordSettings"; diff --git a/src/plugins/apiBadges.tsx b/src/plugins/apiBadges.tsx index d9e97b2..5f44d98 100644 --- a/src/plugins/apiBadges.tsx +++ b/src/plugins/apiBadges.tsx @@ -24,15 +24,13 @@ import { Heart } from "@components/Heart"; import { Devs } from "@utils/constants"; import { Logger } from "@utils/Logger"; import { Margins } from "@utils/margins"; +import { isPluginDev } from "@utils/misc"; import { closeModal, Modals, openModal } from "@utils/modal"; import definePlugin from "@utils/types"; import { Forms, Toasts } from "@webpack/common"; const CONTRIBUTOR_BADGE = "https://cdn.discordapp.com/attachments/1033680203433660458/1092089947126780035/favicon.png"; -/** List of vencord contributor IDs */ -const contributorIds: string[] = Object.values(Devs).map(d => d.id.toString()); - const ContributorBadge: ProfileBadge = { description: "Vencord Contributor", image: CONTRIBUTOR_BADGE, @@ -43,7 +41,7 @@ const ContributorBadge: ProfileBadge = { transform: "scale(0.9)" // The image is a bit too big compared to default badges } }, - shouldShow: ({ user }) => contributorIds.includes(user.id), + shouldShow: ({ user }) => isPluginDev(user.id), link: "https://github.com/Vendicated/Vencord" }; @@ -82,8 +80,8 @@ export default definePlugin({ find: "Messages.PROFILE_USER_BADGES,role:", replacement: [ { - match: /null==\i\?void 0:(\i)\.getBadges\(\)/, - replace: (_, badgesMod) => `Vencord.Api.Badges._getBadges(arguments[0]).concat(${badgesMod}?.getBadges()??[])`, + match: /(?<=(\i)\.isTryItOutFlow,)(.{0,300})null==\i\?void 0:(\i)\.getBadges\(\)/, + replace: (_, props, restCode, badgesMod) => `vencordProps=${props},${restCode}Vencord.Api.Badges._getBadges(vencordProps).concat(${badgesMod}?.getBadges()??[])`, }, { // alt: "", aria-hidden: false, src: originalSrc diff --git a/src/plugins/apiServerList.ts b/src/plugins/apiServerList.ts index 77498ac..6585d38 100644 --- a/src/plugins/apiServerList.ts +++ b/src/plugins/apiServerList.ts @@ -32,7 +32,7 @@ export default definePlugin({ } }, { - find: "Messages.SERVERS", + find: "Messages.SERVERS,children", replacement: { match: /(Messages\.SERVERS,children:)(.+?default:return null\}\}\)\))/, replace: "$1Vencord.Api.ServerList.renderAll(Vencord.Api.ServerList.ServerListRenderPosition.In).concat($2)" diff --git a/src/plugins/emoteCloner.tsx b/src/plugins/emoteCloner.tsx index 0d65148..0900422 100644 --- a/src/plugins/emoteCloner.tsx +++ b/src/plugins/emoteCloner.tsx @@ -21,17 +21,101 @@ import { CheckedTextInput } from "@components/CheckedTextInput"; import { Devs } from "@utils/constants"; import { Logger } from "@utils/Logger"; import { Margins } from "@utils/margins"; -import { ModalContent, ModalHeader, ModalRoot, openModal } from "@utils/modal"; +import { ModalContent, ModalHeader, ModalRoot, openModalLazy } from "@utils/modal"; import definePlugin from "@utils/types"; -import { findByCodeLazy, findByPropsLazy } from "@webpack"; -import { Forms, GuildStore, Menu, PermissionStore, React, Toasts, Tooltip, UserStore } from "@webpack/common"; +import { findByCodeLazy, findStoreLazy } from "@webpack"; +import { EmojiStore, FluxDispatcher, Forms, GuildStore, Menu, PermissionStore, React, RestAPI, Toasts, Tooltip, UserStore } from "@webpack/common"; +import { Promisable } from "type-fest"; const MANAGE_EMOJIS_AND_STICKERS = 1n << 30n; -const GuildEmojiStore = findByPropsLazy("getGuilds", "getGuildEmoji"); +const StickersStore = findStoreLazy("StickersStore"); const uploadEmoji = findByCodeLazy('"EMOJI_UPLOAD_START"', "GUILD_EMOJIS("); -function getGuildCandidates(isAnimated: boolean) { +interface Sticker { + t: "Sticker"; + description: string; + format_type: number; + guild_id: string; + id: string; + name: string; + tags: string; + type: number; +} + +interface Emoji { + t: "Emoji"; + id: string; + name: string; + isAnimated: boolean; +} + +type Data = Emoji | Sticker; + +const StickerExt = [, "png", "png", "json", "gif"] as const; + +function getUrl(data: Data) { + if (data.t === "Emoji") + return `${location.protocol}//${window.GLOBAL_ENV.CDN_HOST}/emojis/${data.id}.${data.isAnimated ? "gif" : "png"}`; + + return `${location.origin}/stickers/${data.id}.${StickerExt[data.format_type]}`; +} + +async function fetchSticker(id: string) { + const cached = StickersStore.getStickerById(id); + if (cached) return cached; + + const { body } = await RestAPI.get({ + url: `/stickers/${id}` + }); + + FluxDispatcher.dispatch({ + type: "STICKER_FETCH_SUCCESS", + sticker: body + }); + + return body as Sticker; +} + +async function cloneSticker(guildId: string, sticker: Sticker) { + const data = new FormData(); + data.append("name", sticker.name); + data.append("tags", sticker.tags); + data.append("description", sticker.description); + data.append("file", await fetchBlob(getUrl(sticker))); + + const { body } = await RestAPI.post({ + url: `/guilds/${guildId}/stickers`, + body: data, + }); + + FluxDispatcher.dispatch({ + type: "GUILD_STICKERS_CREATE_SUCCESS", + guildId, + sticker: { + ...body, + user: UserStore.getCurrentUser() + } + }); +} + +async function cloneEmoji(guildId: string, emoji: Emoji) { + const data = await fetchBlob(getUrl(emoji)); + + const dataUrl = await new Promise(resolve => { + const reader = new FileReader(); + reader.onload = () => resolve(reader.result as string); + reader.readAsDataURL(data); + }); + + return uploadEmoji({ + guildId, + name: emoji.name.split("~")[0], + image: dataUrl + }); +} + +function getGuildCandidates(data: Data) { const meId = UserStore.getCurrentUser().id; return Object.values(GuildStore.getGuilds()).filter(g => { @@ -39,8 +123,12 @@ function getGuildCandidates(isAnimated: boolean) { BigInt(PermissionStore.getGuildPermissions({ id: g.id }) & MANAGE_EMOJIS_AND_STICKERS) === MANAGE_EMOJIS_AND_STICKERS; if (!canCreate) return false; + if (data.t === "Sticker") return true; + + const { isAnimated } = data as Emoji; + const emojiSlots = g.getMaxEmojiSlots(); - const { emojis } = GuildEmojiStore.getGuilds()[g.id]; + const { emojis } = EmojiStore.getGuilds()[g.id]; let count = 0; for (const emoji of emojis) @@ -49,33 +137,34 @@ function getGuildCandidates(isAnimated: boolean) { }).sort((a, b) => a.name.localeCompare(b.name)); } -async function doClone(guildId: string, id: string, name: string, isAnimated: boolean) { - const data = await fetch(`${location.protocol}//${window.GLOBAL_ENV.CDN_HOST}/emojis/${id}.${isAnimated ? "gif" : "png"}`) - .then(r => r.blob()); - const reader = new FileReader(); +async function fetchBlob(url: string) { + const res = await fetch(url); + if (!res.ok) + throw new Error(`Failed to fetch ${url} - ${res.status}`); - reader.onload = () => { - uploadEmoji({ - guildId, - name: name.split("~")[0], - image: reader.result - }).then(() => { - Toasts.show({ - message: `Successfully cloned ${name}!`, - type: Toasts.Type.SUCCESS, - id: Toasts.genId() - }); - }).catch((e: any) => { - new Logger("EmoteCloner").error("Failed to upload emoji", e); - Toasts.show({ - message: "Oopsie something went wrong :( Check console!!!", - type: Toasts.Type.FAILURE, - id: Toasts.genId() - }); + return res.blob(); +} + +async function doClone(guildId: string, data: Sticker | Emoji) { + try { + if (data.t === "Sticker") + await cloneSticker(guildId, data); + else + await cloneEmoji(guildId, data); + + Toasts.show({ + message: `Successfully cloned ${data.name} to ${GuildStore.getGuild(guildId)?.name ?? "your server"}!`, + type: Toasts.Type.SUCCESS, + id: Toasts.genId() }); - }; - - reader.readAsDataURL(data); + } catch (e) { + new Logger("EmoteCloner").error("Failed to clone", data.name, "to", guildId, e); + Toasts.show({ + message: "Oopsie something went wrong :( Check console!!!", + type: Toasts.Type.FAILURE, + id: Toasts.genId() + }); + } } const getFontSize = (s: string) => { @@ -86,22 +175,26 @@ const getFontSize = (s: string) => { const nameValidator = /^\w+$/i; -function CloneModal({ id, name: emojiName, isAnimated }: { id: string; name: string; isAnimated: boolean; }) { +function CloneModal({ data }: { data: Sticker | Emoji; }) { const [isCloning, setIsCloning] = React.useState(false); - const [name, setName] = React.useState(emojiName); + const [name, setName] = React.useState(data.name); const [x, invalidateMemo] = React.useReducer(x => x + 1, 0); - const guilds = React.useMemo(() => getGuildCandidates(isAnimated), [isAnimated, x]); + const guilds = React.useMemo(() => getGuildCandidates(data), [data.id, x]); return ( <> Custom Name { + data.name = v; + setName(v); + }} validate={v => - (v.length > 1 && v.length < 32 && nameValidator.test(v)) + (data.t === "Emoji" && v.length > 2 && v.length < 32 && nameValidator.test(v)) + || (data.t === "Sticker" && v.length > 2 && v.length < 30) || "Name must be between 2 and 32 characters and only contain alphanumeric characters" } /> @@ -135,7 +228,7 @@ function CloneModal({ id, name: emojiName, isAnimated }: { id: string; name: str }} onClick={isCloning ? void 0 : async () => { setIsCloning(true); - doClone(g.id, id, name, isAnimated).finally(() => { + doClone(g.id, data).finally(() => { invalidateMemo(); setIsCloning(false); }); @@ -175,32 +268,38 @@ function CloneModal({ id, name: emojiName, isAnimated }: { id: string; name: str ); } -function buildMenuItem(id: string, name: string, isAnimated: boolean) { +function buildMenuItem(type: "Emoji" | "Sticker", fetchData: () => Promisable>) { return ( - openModal(modalProps => ( - - - - Clone {name} - - - - - - )) + openModalLazy(async () => { + const res = await fetchData(); + const data = { t: type, ...res } as Sticker | Emoji; + const url = getUrl(data); + + return modalProps => ( + + + + Clone {data.name} + + + + + + ); + }) } /> ); @@ -213,28 +312,53 @@ function isGifUrl(url: string) { const messageContextMenuPatch: NavContextMenuPatchCallback = (children, props) => () => { const { favoriteableId, itemHref, itemSrc, favoriteableType } = props ?? {}; - if (!favoriteableId || favoriteableType !== "emoji") return; + if (!favoriteableId) return; - const match = props.message.content.match(RegExp(`|https://cdn\\.discordapp\\.com/emojis/${favoriteableId}\\.`)); - if (!match) return; - const name = match[1] ?? "FakeNitroEmoji"; + const menuItem = (() => { + switch (favoriteableType) { + case "emoji": + const match = props.message.content.match(RegExp(`|https://cdn\\.discordapp\\.com/emojis/${favoriteableId}\\.`)); + if (!match) return; + const name = match[1] ?? "FakeNitroEmoji"; - const group = findGroupChildrenByChildId("copy-link", children); - if (group) group.push(buildMenuItem(favoriteableId, name, isGifUrl(itemHref ?? itemSrc))); + return buildMenuItem("Emoji", () => ({ + id: favoriteableId, + name, + isAnimated: isGifUrl(itemHref ?? itemSrc) + })); + case "sticker": + const sticker = props.message.stickerItems.find(s => s.id === favoriteableId); + if (sticker?.format_type === 3 /* LOTTIE */) return; + + return buildMenuItem("Sticker", () => fetchSticker(favoriteableId)); + } + })(); + + if (menuItem) + findGroupChildrenByChildId("copy-link", children)?.push(menuItem); }; const expressionPickerPatch: NavContextMenuPatchCallback = (children, props: { target: HTMLElement; }) => () => { const { id, name, type } = props?.target?.dataset ?? {}; - if (!id || !name || type !== "emoji") return; + if (!id) return; - const firstChild = props.target.firstChild as HTMLImageElement; + if (type === "emoji" && name) { + const firstChild = props.target.firstChild as HTMLImageElement; - children.push(buildMenuItem(id, name, firstChild && isGifUrl(firstChild.src))); + children.push(buildMenuItem("Emoji", () => ({ + id, + name, + isAnimated: firstChild && isGifUrl(firstChild.src) + }))); + } else if (type === "sticker" && !props.target.className?.includes("lottieCanvas")) { + children.push(buildMenuItem("Sticker", () => fetchSticker(id))); + } }; export default definePlugin({ name: "EmoteCloner", - description: "Adds a Clone context menu item to emotes to clone them your own server", + description: "Allows you to clone Emotes & Stickers to your own server (right click them)", + tags: ["StickerCloner"], authors: [Devs.Ven, Devs.Nuckyz], start() { diff --git a/src/plugins/experiments.tsx b/src/plugins/experiments.tsx index ed29aa7..cc8309d 100644 --- a/src/plugins/experiments.tsx +++ b/src/plugins/experiments.tsx @@ -17,7 +17,10 @@ */ import { definePluginSettings } from "@api/Settings"; +import ErrorBoundary from "@components/ErrorBoundary"; +import { ErrorCard } from "@components/ErrorCard"; import { Devs } from "@utils/constants"; +import { Margins } from "@utils/margins"; import definePlugin, { OptionType } from "@utils/types"; import { findByPropsLazy } from "@webpack"; import { Forms, React } from "@webpack/common"; @@ -87,6 +90,13 @@ export default definePlugin({ match: /"staging"===window\.GLOBAL_ENV\.RELEASE_CHANNEL/, replace: "true" } + }, + { + find: 'H1,title:"Experiments"', + replacement: { + match: 'title:"Experiments",children:[', + replace: "$&$self.WarningCard()," + } } ], @@ -109,5 +119,19 @@ export default definePlugin({ ); - } + }, + + WarningCard: ErrorBoundary.wrap(() => ( + + Hold on!! + + + Experiments are unreleased Discord features. They might not work, or even break your client or get your account disabled. + + + + Only use experiments if you know what you're doing. Vencord is not responsible for any damage caused by enabling experiments. + + + ), { noop: true }) }); diff --git a/src/plugins/fakeNitro.tsx b/src/plugins/fakeNitro.ts similarity index 79% rename from src/plugins/fakeNitro.tsx rename to src/plugins/fakeNitro.ts index 52a9d25..34cd63b 100644 --- a/src/plugins/fakeNitro.tsx +++ b/src/plugins/fakeNitro.ts @@ -22,11 +22,12 @@ import { Devs } from "@utils/constants"; import { ApngBlendOp, ApngDisposeOp, getGifEncoder, importApngJs } from "@utils/dependencies"; import { getCurrentGuild } from "@utils/discord"; import { proxyLazy } from "@utils/lazy"; +import { Logger } from "@utils/Logger"; import definePlugin, { OptionType } from "@utils/types"; import { findByCodeLazy, findByPropsLazy, findLazy, findStoreLazy } from "@webpack"; -import { ChannelStore, FluxDispatcher, Parser, PermissionStore, UserStore } from "@webpack/common"; +import { ChannelStore, EmojiStore, FluxDispatcher, Parser, PermissionStore, UserStore } from "@webpack/common"; import type { Message } from "discord-types/general"; -import type { ReactNode } from "react"; +import type { ReactElement, ReactNode } from "react"; const DRAFT_TYPE = 0; const promptToUpload = findByCodeLazy("UPLOAD_FILE_LIMIT_ERROR"); @@ -38,8 +39,6 @@ const StickerStore = findStoreLazy("StickersStore") as { getAllGuildStickers(): Map; getStickerById(id: string): Sticker | undefined; }; -const EmojiStore = findStoreLazy("EmojiStore"); - function searchProtoClass(localName: string, parentProtoClass: any) { if (!parentProtoClass) return; @@ -57,7 +56,7 @@ const ClientThemeSettingsProto = proxyLazy(() => searchProtoClass("clientThemeSe const USE_EXTERNAL_EMOJIS = 1n << 18n; const USE_EXTERNAL_STICKERS = 1n << 37n; -enum EmojiIntentions { +const enum EmojiIntentions { REACTION = 0, STATUS = 1, COMMUNITY_CONTENT = 2, @@ -68,6 +67,14 @@ enum EmojiIntentions { SOUNDBOARD = 7 } +const enum StickerType { + PNG = 1, + APNG = 2, + LOTTIE = 3, + // don't think you can even have gif stickers but the docs have it + GIF = 4 +} + interface BaseSticker { available: boolean; description: string; @@ -173,6 +180,10 @@ export default definePlugin({ { match: /(&&!\i&&)!(\i)(?=\)return \i\.\i\.DISALLOW_EXTERNAL;)/, replace: (_, rest, canUseExternal) => `${rest}(!${canUseExternal}&&(typeof fakeNitroIntention==="undefined"||![${EmojiIntentions.CHAT},${EmojiIntentions.GUILD_STICKER_RELATED_EMOJI}].includes(fakeNitroIntention)))` + }, + { + match: /if\(!\i\.available/, + replace: m => `${m}&&(typeof fakeNitroIntention==="undefined"||![${EmojiIntentions.CHAT},${EmojiIntentions.GUILD_STICKER_RELATED_EMOJI}].includes(fakeNitroIntention))` } ] }, @@ -321,7 +332,7 @@ export default definePlugin({ }, handleProtoChange(proto: any, user: any) { - if ((!proto.appearance && !AppearanceSettingsProto) || !UserSettingsProtoStore) return; + if (proto == null || typeof proto === "string" || !UserSettingsProtoStore || (!proto.appearance && !AppearanceSettingsProto)) return; const premiumType: number = user?.premium_type ?? UserStore?.getCurrentUser()?.premiumType ?? 0; @@ -382,70 +393,137 @@ export default definePlugin({ }); }, - patchFakeNitroEmojisOrRemoveStickersLinks(content: Array, inline: boolean) { - if (content.length > 1 && !settings.store.transformCompoundSentence) return content; + trimContent(content: Array) { + const firstContent = content[0]; + if (typeof firstContent === "string") content[0] = firstContent.trimStart(); + if (content[0] === "") content.shift(); - const newContent: Array = []; + const lastIndex = content.length - 1; + const lastContent = content[lastIndex]; + if (typeof lastContent === "string") content[lastIndex] = lastContent.trimEnd(); + if (content[lastIndex] === "") content.pop(); + }, + + clearEmptyArrayItems(array: Array) { + return array.filter(item => item != null); + }, + + ensureChildrenIsArray(child: ReactElement) { + if (!Array.isArray(child.props.children)) child.props.children = [child.props.children]; + }, + + patchFakeNitroEmojisOrRemoveStickersLinks(content: Array, inline: boolean) { + // If content has more than one child or it's a single ReactElement like a header or list + if ((content.length > 1 || typeof content[0]?.type === "string") && !settings.store.transformCompoundSentence) return content; let nextIndex = content.length; - for (const element of content) { - if (element.props?.trusted == null) { - newContent.push(element); - continue; - } - + const transformLinkChild = (child: ReactElement) => { if (settings.store.transformEmojis) { - const fakeNitroMatch = element.props.href.match(fakeNitroEmojiRegex); + const fakeNitroMatch = child.props.href.match(fakeNitroEmojiRegex); if (fakeNitroMatch) { let url: URL | null = null; try { - url = new URL(element.props.href); + url = new URL(child.props.href); } catch { } const emojiName = EmojiStore.getCustomEmojiById(fakeNitroMatch[1])?.name ?? url?.searchParams.get("name") ?? "FakeNitroEmoji"; - newContent.push(Parser.defaultRules.customEmoji.react({ - jumboable: !inline && content.length === 1, + return Parser.defaultRules.customEmoji.react({ + jumboable: !inline && content.length === 1 && typeof content[0].type !== "string", animated: fakeNitroMatch[2] === "gif", emojiId: fakeNitroMatch[1], name: emojiName, fake: true - }, void 0, { key: String(nextIndex++) })); - - continue; + }, void 0, { key: String(nextIndex++) }); } } if (settings.store.transformStickers) { - if (fakeNitroStickerRegex.test(element.props.href)) continue; + if (fakeNitroStickerRegex.test(child.props.href)) return null; - const gifMatch = element.props.href.match(fakeNitroGifStickerRegex); + const gifMatch = child.props.href.match(fakeNitroGifStickerRegex); if (gifMatch) { // There is no way to differentiate a regular gif attachment from a fake nitro animated sticker, so we check if the StickerStore contains the id of the fake sticker - if (StickerStore.getStickerById(gifMatch[1])) continue; + if (StickerStore.getStickerById(gifMatch[1])) return null; } } - newContent.push(element); + return child; + }; + + const transformChild = (child: ReactElement) => { + if (child?.props?.trusted != null) return transformLinkChild(child); + if (child?.props?.children != null) { + if (!Array.isArray(child.props.children)) { + child.props.children = modifyChild(child.props.children); + return child; + } + + child.props.children = modifyChildren(child.props.children); + if (child.props.children.length === 0) return null; + return child; + } + + return child; + }; + + const modifyChild = (child: ReactElement) => { + const newChild = transformChild(child); + + if (newChild?.type === "ul" || newChild?.type === "ol") { + this.ensureChildrenIsArray(newChild); + if (newChild.props.children.length === 0) return null; + + let listHasAnItem = false; + for (const [index, child] of newChild.props.children.entries()) { + if (child == null) { + delete newChild.props.children[index]; + continue; + } + + this.ensureChildrenIsArray(child); + if (child.props.children.length > 0) listHasAnItem = true; + else delete newChild.props.children[index]; + } + + if (!listHasAnItem) return null; + + newChild.props.children = this.clearEmptyArrayItems(newChild.props.children); + } + + return newChild; + }; + + const modifyChildren = (children: Array) => { + for (const [index, child] of children.entries()) children[index] = modifyChild(child); + + children = this.clearEmptyArrayItems(children); + this.trimContent(children); + + return children; + }; + + try { + return modifyChildren(window._.cloneDeep(content)); + } catch (err) { + new Logger("FakeNitro").error(err); + return content; } - - const firstContent = newContent[0]; - if (typeof firstContent === "string") newContent[0] = firstContent.trimStart(); - - return newContent; }, patchFakeNitroStickers(stickers: Array, message: Message) { const itemsToMaybePush: Array = []; const contentItems = message.content.split(/\s/); - if (contentItems.length === 1 && !settings.store.transformCompoundSentence) itemsToMaybePush.push(contentItems[0]); - else itemsToMaybePush.push(...contentItems); + if (settings.store.transformCompoundSentence) itemsToMaybePush.push(...contentItems); + else if (contentItems.length === 1) itemsToMaybePush.push(contentItems[0]); itemsToMaybePush.push(...message.attachments.filter(attachment => attachment.content_type === "image/gif").map(attachment => attachment.url)); for (const item of itemsToMaybePush) { + if (!settings.store.transformCompoundSentence && !item.startsWith("http")) continue; + const imgMatch = item.match(fakeNitroStickerRegex); if (imgMatch) { let url: URL | null = null; @@ -482,10 +560,13 @@ export default definePlugin({ }, shouldIgnoreEmbed(embed: Message["embeds"][number], message: Message) { - if (message.content.split(/\s/).length > 1 && !settings.store.transformCompoundSentence) return false; + const contentItems = message.content.split(/\s/); + if (contentItems.length > 1 && !settings.store.transformCompoundSentence) return false; switch (embed.type) { case "image": { + if (!settings.store.transformCompoundSentence && !contentItems.includes(embed.url!) && !contentItems.includes(embed.image!.proxyURL)) return false; + if (settings.store.transformEmojis) { if (fakeNitroEmojiRegex.test(embed.url!)) return true; } @@ -544,7 +625,7 @@ export default definePlugin({ } }, - hasPermissionToUseExternalEmojis(channelId: string) { + hasPermissionToUseExternalEmojis(channelId: string): boolean { const channel = ChannelStore.getChannel(channelId); if (!channel || channel.isDM() || channel.isGroupDM() || channel.isMultiUserDM()) return true; @@ -625,8 +706,9 @@ export default definePlugin({ }, start() { - const settings = Settings.plugins.FakeNitro; - if (!settings.enableEmojiBypass && !settings.enableStickerBypass) { + const s = settings.store; + + if (!s.enableEmojiBypass && !s.enableStickerBypass) { return; } @@ -638,39 +720,37 @@ export default definePlugin({ const { guildId } = this; stickerBypass: { - if (!settings.enableStickerBypass) + if (!s.enableStickerBypass) break stickerBypass; const sticker = StickerStore.getStickerById(extra.stickers?.[0]!); if (!sticker) break stickerBypass; - if (sticker.available !== false && ((this.canUseStickers && this.hasPermissionToUseExternalStickers(channelId)) || (sticker as GuildSticker)?.guild_id === guildId)) + // Discord Stickers are now free yayyy!! :D + if ("pack_id" in sticker) break stickerBypass; - let link = this.getStickerLink(sticker.id); - if (sticker.format_type === 2) { + const canUseStickers = this.canUseStickers && this.hasPermissionToUseExternalStickers(channelId); + if (sticker.available !== false && (canUseStickers || sticker.guild_id === guildId)) + break stickerBypass; + + const link = this.getStickerLink(sticker.id); + if (sticker.format_type === StickerType.APNG) { this.sendAnimatedSticker(link, sticker.id, channelId); return { cancel: true }; } else { - if ("pack_id" in sticker) { - const packId = sticker.pack_id === "847199849233514549" - // Discord moved these stickers into a different pack at some point, but - // Distok still uses the old id - ? "749043879713701898" - : sticker.pack_id; - - link = `https://distok.top/stickers/${packId}/${sticker.id}.gif`; - } - extra.stickers!.length = 0; - messageObj.content += " " + link + `&name=${encodeURIComponent(sticker.name)}`; + messageObj.content += ` ${link}&name=${encodeURIComponent(sticker.name)}`; } } - if ((!this.canUseEmotes || !this.hasPermissionToUseExternalEmojis(channelId)) && settings.enableEmojiBypass) { + if (s.enableEmojiBypass) { + const canUseEmotes = this.canUseEmotes && this.hasPermissionToUseExternalEmojis(channelId); + for (const emoji of messageObj.validNonShortcutEmojis) { if (!emoji.require_colons) continue; + if (emoji.available !== false && canUseEmotes) continue; if (emoji.guildId === guildId && !emoji.animated) continue; const emojiString = `<${emoji.animated ? "a" : ""}:${emoji.originalName || emoji.name}:${emoji.id}>`; @@ -688,23 +768,25 @@ export default definePlugin({ }); this.preEdit = addPreEditListener((channelId, __, messageObj) => { - if (this.canUseEmotes && this.hasPermissionToUseExternalEmojis(channelId)) return; + if (!s.enableEmojiBypass) return; + + const canUseEmotes = this.canUseEmotes && this.hasPermissionToUseExternalEmojis(channelId); const { guildId } = this; - for (const [emojiStr, _, emojiId] of messageObj.content.matchAll(/(?/ig)) { + messageObj.content = messageObj.content.replace(/(?/ig, (emojiStr, emojiId, offset, origStr) => { const emoji = EmojiStore.getCustomEmojiById(emojiId); - if (emoji == null || (emoji.guildId === guildId && !emoji.animated)) continue; - if (!emoji.require_colons) continue; + if (emoji == null) return emojiStr; + if (!emoji.require_colons) return emojiStr; + if (emoji.available !== false && canUseEmotes) return emojiStr; + if (emoji.guildId === guildId && !emoji.animated) return emojiStr; const url = emoji.url.replace(/\?size=\d+/, "?" + new URLSearchParams({ size: Settings.plugins.FakeNitro.emojiSize, name: encodeURIComponent(emoji.name) })); - messageObj.content = messageObj.content.replace(emojiStr, (match, offset, origStr) => { - return `${getWordBoundary(origStr, offset - 1)}${url}${getWordBoundary(origStr, offset + match.length)}`; - }); - } + return `${getWordBoundary(origStr, offset - 1)}${url}${getWordBoundary(origStr, offset + emojiStr.length)}`; + }); }); }, diff --git a/src/plugins/favEmojiFirst.ts b/src/plugins/favEmojiFirst.ts new file mode 100644 index 0000000..fec0b04 --- /dev/null +++ b/src/plugins/favEmojiFirst.ts @@ -0,0 +1,83 @@ +/* + * Vencord, a modification for Discord's desktop app + * Copyright (c) 2023 Vendicated and contributors + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . +*/ + +import { Devs } from "@utils/constants"; +import definePlugin from "@utils/types"; +import { EmojiStore } from "@webpack/common"; +import { Emoji } from "@webpack/types"; + +interface EmojiAutocompleteState { + query?: { + type: string; + typeInfo: { + sentinel: string; + }; + results: { + emojis: Emoji[] & { sliceTo?: number; }; + }; + }; +} + +export default definePlugin({ + name: "FavoriteEmojiFirst", + authors: [Devs.Aria, Devs.Ven], + description: "Puts your favorite emoji first in the emoji autocomplete.", + patches: [ + { + find: ".activeCommandOption", + replacement: [ + { + // = someFunc(a.selectedIndex); ...trackEmojiSearch({ state: theState, isInPopoutExperimental: someBool }) + match: /=\i\(\i\.selectedIndex\);(?=.+?state:(\i),isInPopoutExperiment:\i)/, + // self.sortEmojis(theState) + replace: "$&$self.sortEmojis($1);" + }, + + // set maxCount to Infinity so our sortEmojis callback gets the entire list, not just the first 10 + // and remove Discord's emojiResult slice, storing the endIndex on the array for us to use later + { + // searchEmojis(...,maxCount: stuff) ... endEmojis = emojis.slice(0, maxCount - gifResults.length) + match: /,maxCount:(\i)(.+?)=(\i)\.slice\(0,(\1-\i\.length)\)/, + // ,maxCount:Infinity ... endEmojis = (emojis.sliceTo = n, emojis) + replace: ",maxCount:Infinity$2=($3.sliceTo=$4,$3)" + } + ] + } + ], + + sortEmojis({ query }: EmojiAutocompleteState) { + if ( + query?.type !== "EMOJIS_AND_STICKERS" + || query.typeInfo?.sentinel !== ":" + || !query.results?.emojis?.length + ) return; + + const emojiContext = EmojiStore.getDisambiguatedEmojiContext(); + + query.results.emojis = query.results.emojis.sort((a, b) => { + const aIsFavorite = emojiContext.isFavoriteEmojiWithoutFetchingLatest(a); + const bIsFavorite = emojiContext.isFavoriteEmojiWithoutFetchingLatest(b); + + if (aIsFavorite && !bIsFavorite) return -1; + + if (!aIsFavorite && bIsFavorite) return 1; + + return 0; + }).slice(0, query.results.emojis.sliceTo ?? 10); + } +}); diff --git a/src/plugins/imageZoom/index.tsx b/src/plugins/imageZoom/index.tsx index da6ac69..d4adcdc 100644 --- a/src/plugins/imageZoom/index.tsx +++ b/src/plugins/imageZoom/index.tsx @@ -130,6 +130,8 @@ export default definePlugin({ name: "ImageZoom", description: "Lets you zoom in to images and gifs. Use scroll wheel to zoom in and shift + scroll wheel to increase lens radius / size", authors: [Devs.Aria], + tags: ["ImageUtilities"], + patches: [ { find: '"renderLinkComponent","maxWidth"', diff --git a/src/plugins/invisibleChat/index.tsx b/src/plugins/invisibleChat/index.tsx index eb92d76..6f21628 100644 --- a/src/plugins/invisibleChat/index.tsx +++ b/src/plugins/invisibleChat/index.tsx @@ -22,7 +22,7 @@ import ErrorBoundary from "@components/ErrorBoundary"; import { Devs } from "@utils/constants"; import { getStegCloak } from "@utils/dependencies"; import definePlugin, { OptionType } from "@utils/types"; -import { Button, ButtonLooks, ButtonWrapperClasses, ChannelStore, FluxDispatcher, Tooltip } from "@webpack/common"; +import { Button, ButtonLooks, ButtonWrapperClasses, ChannelStore, FluxDispatcher, RestAPI, Tooltip } from "@webpack/common"; import { Message } from "discord-types/general"; import { buildDecModal } from "./components/DecryptionModal"; @@ -64,7 +64,13 @@ function Indicator() { } -function ChatBarIcon() { +function ChatBarIcon(chatBoxProps: { + type: { + analyticsName: string; + }; +}) { + if (chatBoxProps.type.analyticsName !== "normal") return null; + return ( {({ onMouseEnter, onMouseLeave }) => ( @@ -85,7 +91,7 @@ function ChatBarIcon() { onMouseLeave={onMouseLeave} innerClassName={ButtonWrapperClasses.button} onClick={() => buildEncModal()} - style={{ padding: "0 4px" }} + style={{ padding: "0 2px", scale: "0.9" }} >
>https://embed.sammcheese.net<< to provide embeds to decrypted links!", + description: "Encrypt your Messages in a non-suspicious way!", authors: [Devs.SammCheese], dependencies: ["MessagePopoverAPI"], patches: [ @@ -133,7 +139,7 @@ export default definePlugin({ find: ".activeCommandOption", replacement: { match: /(.)\.push.{1,30}disabled:(\i),.{1,20}\},"gift"\)\)/, - replace: "$&;try{$2||$1.push($self.chatBarIcon())}catch{}", + replace: "$&;try{$2||$1.push($self.chatBarIcon(arguments[0]))}catch{}", } }, ], @@ -172,25 +178,13 @@ export default definePlugin({ // Gets the Embed of a Link async getEmbed(url: URL): Promise { - const controller = new AbortController(); - const timeout = setTimeout(() => controller.abort(), 5000); - - const options: RequestInit = { - signal: controller.signal, - method: "POST", - headers: { - "Content-Type": "application/json", - }, - body: JSON.stringify({ - url, - }), - }; - - // AWS hosted url to discord embed object - const rawRes = await fetch(this.EMBED_API_URL, options); - clearTimeout(timeout); - - return await rawRes.json(); + const { body } = await RestAPI.post({ + url: "/unfurler/embed-urls", + body: { + urls: [url] + } + }); + return await body.embeds[0]; }, async buildEmbed(message: any, revealed: string): Promise { diff --git a/src/plugins/lastfm.tsx b/src/plugins/lastfm.tsx index 380d1ea..19620e0 100644 --- a/src/plugins/lastfm.tsx +++ b/src/plugins/lastfm.tsx @@ -72,7 +72,7 @@ enum ActivityFlag { INSTANCE = 1 << 0, } -const applicationId = "1043533871037284423"; +const applicationId = "1108588077900898414"; const placeholderId = "2a96cbd8b46e442fc41c2b86b821562f"; const logger = new Logger("LastFMRichPresence"); @@ -167,6 +167,7 @@ export default definePlugin({ settings, start() { + this.updatePresence(); this.updateInterval = setInterval(() => { this.updatePresence(); }, 16000); }, @@ -198,7 +199,7 @@ export default definePlugin({ const trackData = json.recenttracks?.track[0]; - if (!trackData || !trackData["@attr"]?.nowplaying) + if (!trackData?.["@attr"]?.nowplaying) return null; // why does the json api have xml structure diff --git a/src/plugins/messageClickActions.ts b/src/plugins/messageClickActions.ts index 03f1eb7..28c558e 100644 --- a/src/plugins/messageClickActions.ts +++ b/src/plugins/messageClickActions.ts @@ -17,10 +17,11 @@ */ import { addClickListener, removeClickListener } from "@api/MessageEvents"; +import { definePluginSettings, Settings } from "@api/Settings"; import { Devs } from "@utils/constants"; import definePlugin, { OptionType } from "@utils/types"; import { findByPropsLazy } from "@webpack"; -import { PermissionStore, UserStore } from "@webpack/common"; +import { FluxDispatcher, PermissionStore, UserStore } from "@webpack/common"; let isDeletePressed = false; const keydown = (e: KeyboardEvent) => e.key === "Backspace" && (isDeletePressed = true); @@ -28,24 +29,36 @@ const keyup = (e: KeyboardEvent) => e.key === "Backspace" && (isDeletePressed = const MANAGE_CHANNELS = 1n << 4n; +const settings = definePluginSettings({ + enableDeleteOnClick: { + type: OptionType.BOOLEAN, + description: "Enable delete on click", + default: true + }, + enableDoubleClickToEdit: { + type: OptionType.BOOLEAN, + description: "Enable double click to edit", + default: true + }, + enableDoubleClickToReply: { + type: OptionType.BOOLEAN, + description: "Enable double click to reply", + default: true + }, + requireModifier: { + type: OptionType.BOOLEAN, + description: "Only do double click actions when shift/ctrl is held", + default: false + } +}); + export default definePlugin({ name: "MessageClickActions", - description: "Hold Backspace and click to delete, double click to edit", + description: "Hold Backspace and click to delete, double click to edit/reply", authors: [Devs.Ven], dependencies: ["MessageEventsAPI"], - options: { - enableDeleteOnClick: { - type: OptionType.BOOLEAN, - description: "Enable delete on click", - default: true - }, - enableDoubleClickToEdit: { - type: OptionType.BOOLEAN, - description: "Enable double click to edit", - default: true - } - }, + settings, start() { const MessageActions = findByPropsLazy("deleteMessage", "startEditMessage"); @@ -54,15 +67,30 @@ export default definePlugin({ document.addEventListener("keydown", keydown); document.addEventListener("keyup", keyup); - this.onClick = addClickListener((msg, chan, event) => { + this.onClick = addClickListener((msg, channel, event) => { const isMe = msg.author.id === UserStore.getCurrentUser().id; if (!isDeletePressed) { - if (Vencord.Settings.plugins.MessageClickActions.enableDoubleClickToEdit && (isMe && event.detail >= 2 && !EditStore.isEditing(chan.id, msg.id))) { - MessageActions.startEditMessage(chan.id, msg.id, msg.content); + if (event.detail < 2) return; + if (settings.store.requireModifier && !event.ctrlKey && !event.shiftKey) return; + + if (isMe) { + if (!settings.store.enableDoubleClickToEdit || EditStore.isEditing(channel.id, msg.id)) return; + + MessageActions.startEditMessage(channel.id, msg.id, msg.content); event.preventDefault(); + } else { + if (!settings.store.enableDoubleClickToReply) return; + + FluxDispatcher.dispatch({ + type: "CREATE_PENDING_REPLY", + channel, + message: msg, + shouldMention: !Settings.plugins.NoReplyMention.enabled, + showMentionToggle: channel.guild_id !== null + }); } - } else if (Vencord.Settings.plugins.MessageClickActions.enableDeleteOnClick && (isMe || PermissionStore.can(MANAGE_CHANNELS, chan))) { - MessageActions.deleteMessage(chan.id, msg.id); + } else if (settings.store.enableDeleteOnClick && (isMe || PermissionStore.can(MANAGE_CHANNELS, channel))) { + MessageActions.deleteMessage(channel.id, msg.id); event.preventDefault(); } }); diff --git a/src/plugins/moreUserTags.ts b/src/plugins/moreUserTags.tsx similarity index 55% rename from src/plugins/moreUserTags.ts rename to src/plugins/moreUserTags.tsx index 90662b0..dbe8cc2 100644 --- a/src/plugins/moreUserTags.ts +++ b/src/plugins/moreUserTags.tsx @@ -17,11 +17,13 @@ */ import { definePluginSettings } from "@api/Settings"; +import { Flex } from "@components/Flex"; import { Devs } from "@utils/constants"; -import { proxyLazy } from "@utils/lazy.js"; +import { Margins } from "@utils/margins"; import definePlugin, { OptionType } from "@utils/types"; -import { find, findByPropsLazy } from "@webpack"; -import { ChannelStore, GuildStore } from "@webpack/common"; +import { findByPropsLazy, findLazy } from "@webpack"; +import { Card, ChannelStore, Forms, GuildStore, 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"; @@ -36,6 +38,21 @@ interface Tag { condition?(message: Message | null, user: User, channel: Channel): boolean; } +interface TagSetting { + text: string; + showInChat: boolean; + showInNotChat: boolean; +} +interface TagSettings { + WEBHOOK: TagSetting, + OWNER: TagSetting, + ADMINISTRATOR: TagSetting, + MODERATOR_STAFF: TagSetting, + MODERATOR: TagSetting, + VOICE_MODERATOR: TagSetting, + [k: string]: TagSetting; +} + const CLYDE_ID = "1081004946872352958"; // PermissionStore.computePermissions is not the same function and doesn't work here @@ -44,7 +61,7 @@ const PermissionUtil = findByPropsLazy("computePermissions", "canEveryoneRole") }; const Permissions = findByPropsLazy("SEND_MESSAGES", "VIEW_CREATOR_MONETIZATION_ANALYTICS") as Record; -const Tags = proxyLazy(() => find(m => m.Types?.[0] === "BOT").Types) as Record; +const Tag = findLazy(m => m.Types?.[0] === "BOT") as RC<{ type?: number, className?: string, useRemSizes?: boolean; }> & { Types: Record; }; const isWebhook = (message: Message, user: User) => !!message?.webhookId && user.isNonUserBot(); @@ -81,64 +98,119 @@ const tags: Tag[] = [ permissions: ["MOVE_MEMBERS", "MUTE_MEMBERS", "DEAFEN_MEMBERS"] } ]; +const defaultSettings = Object.fromEntries( + tags.map(({ name, displayName }) => [name, { text: displayName, showInChat: true, showInNotChat: true }]) +) as TagSettings; + +function SettingsComponent(props: { setValue(v: any): void; }) { + settings.store.tagSettings ??= defaultSettings; + + const [tagSettings, setTagSettings] = useState(settings.store.tagSettings as TagSettings); + const setValue = (v: TagSettings) => { + setTagSettings(v); + props.setValue(v); + }; + + return ( + + {tags.map(t => ( + + + + {({ onMouseEnter, onMouseLeave }) => ( +
+ {t.displayName} Tag +
+ )} + + + + { + tagSettings[t.name].text = v; + setValue(tagSettings); + }} + className={Margins.bottom16} + /> + + { + tagSettings[t.name].showInChat = v; + setValue(tagSettings); + }} + hideBorder + > + Show in messages + + + { + tagSettings[t.name].showInNotChat = v; + setValue(tagSettings); + }} + hideBorder + > + Show in member list and profiles + + + ))} + + ); +} const settings = definePluginSettings({ dontShowForBots: { - description: "Don't show tags (not including the webhook tag) for bots", + description: "Don't show extra tags for bots (excluding webhooks)", type: OptionType.BOOLEAN }, dontShowBotTag: { - description: "Don't show [BOT] text for bots with other tags (verified bots will still have checkmark)", + description: "Only show extra tags for bots / Hide [BOT] text", type: OptionType.BOOLEAN }, - ...Object.fromEntries(tags.map(({ name, displayName, description }) => [ - `visibility_${name}`, { - description: `Show ${displayName} tags (${description})`, - type: OptionType.SELECT, - options: [ - { - label: "Always", - value: "always", - default: true - }, { - label: "Only in chat", - value: "chat" - }, { - label: "Only in member list and profiles", - value: "not-chat" - }, { - label: "Never", - value: "never" - } - ] - } - ])) + tagSettings: { + type: OptionType.COMPONENT, + component: SettingsComponent, + description: "fill me", + } }); export default definePlugin({ name: "MoreUserTags", description: "Adds tags for webhooks and moderative roles (owner, admin, etc.)", - authors: [Devs.Cyn, Devs.TheSun, Devs.RyanCaoDev], + authors: [Devs.Cyn, Devs.TheSun, Devs.RyanCaoDev, Devs.LordElias], settings, patches: [ // add tags to the tag list { find: '.BOT=0]="BOT"', replacement: [ - // add tags to the exported tags list (the Tags variable here) + // add tags to the exported tags list (Tag.Types) { match: /(\i)\[.\.BOT=0\]="BOT";/, replace: "$&$1=$self.addTagVariants($1);" - }, + } + ] + }, + { + find: ".DISCORD_SYSTEM_MESSAGE_BOT_TAG_TOOLTIP;", + replacement: [ // make the tag show the right text { - match: /(switch\((\i)\){.+?)case (\i)\.BOT:default:(\i)=(\i\.\i\.Messages)\.BOT_TAG_BOT/, + match: /(switch\((\i)\){.+?)case (\i(?:\.\i)?)\.BOT:default:(\i)=(\i\.\i\.Messages)\.BOT_TAG_BOT/, replace: (_, origSwitch, variant, tags, displayedText, strings) => `${origSwitch}default:{${displayedText} = $self.getTagText(${tags}[${variant}], ${strings})}` }, // show OP tags correctly { - match: /(\i)=(\i)===\i\.ORIGINAL_POSTER/, + match: /(\i)=(\i)===\i(?:\.\i)?\.ORIGINAL_POSTER/, replace: "$1=$self.isOPTag($2)" }, // add HTML data attributes (for easier theming) @@ -169,15 +241,15 @@ return type!==null?$2.botTag,type" { find: ".hasAvatarForGuild(null==", replacement: { - match: /\.usernameSection,user/, - replace: ".usernameSection,moreTags_channelId:arguments[0].channelId,user" + match: /(?=usernameIcon:)/, + replace: "moreTags_channelId:arguments[0].channelId," } }, { find: 'copyMetaData:"User Tag"', replacement: { - match: /discriminatorClass:(.{1,100}),botClass:/, - replace: "discriminatorClass:$1,moreTags_channelId:arguments[0].moreTags_channelId,botClass:" + match: /(?=,botClass:)/, + replace: ",moreTags_channelId:arguments[0].moreTags_channelId" } }, // in profiles @@ -190,6 +262,37 @@ return type!==null?$2.botTag,type" }, ], + start() { + if (settings.store.tagSettings) return; + // @ts-ignore + if (!settings.store.visibility_WEBHOOK) settings.store.tagSettings = defaultSettings; + else { + const newSettings = { ...defaultSettings }; + Object.entries(Vencord.PlainSettings.plugins.MoreUserTags).forEach(([name, value]) => { + const [setting, tag] = name.split("_"); + if (setting === "visibility") { + switch (value) { + case "always": + // its the default + break; + case "chat": + newSettings[tag].showInNotChat = false; + break; + case "not-chat": + newSettings[tag].showInChat = false; + break; + case "never": + newSettings[tag].showInChat = false; + newSettings[tag].showInNotChat = false; + break; + } + } + settings.store.tagSettings = newSettings; + delete Vencord.Settings.plugins.MoreUserTags[name]; + }); + } + }, + getPermissions(user: User, channel: Channel): string[] { const guild = GuildStore.getGuild(channel?.guild_id); if (!guild) return []; @@ -202,35 +305,36 @@ return type!==null?$2.botTag,type" .filter(Boolean); }, - addTagVariants(val: any /* i cant think of a good name */) { + addTagVariants(tagConstant) { let i = 100; tags.forEach(({ name }) => { - val[name] = ++i; - val[i] = name; - val[`${name}-BOT`] = ++i; - val[i] = `${name}-BOT`; - val[`${name}-OP`] = ++i; - val[i] = `${name}-OP`; + tagConstant[name] = ++i; + tagConstant[i] = name; + tagConstant[`${name}-BOT`] = ++i; + tagConstant[i] = `${name}-BOT`; + tagConstant[`${name}-OP`] = ++i; + tagConstant[i] = `${name}-OP`; }); - return val; + return tagConstant; }, - isOPTag: (tag: number) => tag === Tags.ORIGINAL_POSTER || tags.some(t => tag === Tags[`${t.name}-OP`]), + isOPTag: (tag: number) => tag === Tag.Types.ORIGINAL_POSTER || tags.some(t => tag === Tag.Types[`${t.name}-OP`]), getTagText(passedTagName: string, strings: Record) { - if (!passedTagName) return "BOT"; + if (!passedTagName) return strings.BOT_TAG_BOT; const [tagName, variant] = passedTagName.split("-"); const tag = tags.find(({ name }) => tagName === name); - if (!tag) return "BOT"; + if (!tag) return strings.BOT_TAG_BOT; if (variant === "BOT" && tagName !== "WEBHOOK" && this.settings.store.dontShowForBots) return strings.BOT_TAG_BOT; + const tagText = settings.store.tagSettings?.[tag.name]?.text || tag.displayName; switch (variant) { case "OP": - return `${strings.BOT_TAG_FORUM_ORIGINAL_POSTER} β€’ ${tag.displayName}`; + return `${strings.BOT_TAG_FORUM_ORIGINAL_POSTER} β€’ ${tagText}`; case "BOT": - return `${strings.BOT_TAG_BOT} β€’ ${tag.displayName}`; + return `${strings.BOT_TAG_BOT} β€’ ${tagText}`; default: - return tag.displayName; + return tagText; } }, @@ -242,12 +346,12 @@ return type!==null?$2.botTag,type" channel?: Channel & { isForumPost(): boolean; }, channelId?: string; origType?: number; - location: string; + location: "chat" | "not-chat"; }): number | null { if (location === "chat" && user.id === "1") - return Tags.OFFICIAL; + return Tag.Types.OFFICIAL; if (user.id === CLYDE_ID) - return Tags.AI; + return Tag.Types.AI; let type = typeof origType === "number" ? origType : null; @@ -258,24 +362,19 @@ return type!==null?$2.botTag,type" const perms = this.getPermissions(user, channel); for (const tag of tags) { - switch (settings[`visibility_${tag.name}`]) { - case "always": - case location: - break; - default: - continue; - } + if (location === "chat" && !settings.tagSettings[tag.name].showInChat) continue; + if (location === "not-chat" && !settings.tagSettings[tag.name].showInNotChat) continue; if ( tag.permissions?.some(perm => perms.includes(perm)) || (tag.condition?.(message!, user, channel)) ) { if (channel.isForumPost() && channel.ownerId === user.id) - type = Tags[`${tag.name}-OP`]; + type = Tag.Types[`${tag.name}-OP`]; else if (user.bot && !isWebhook(message!, user) && !settings.dontShowBotTag) - type = Tags[`${tag.name}-BOT`]; + type = Tag.Types[`${tag.name}-BOT`]; else - type = Tags[tag.name]; + type = Tag.Types[tag.name]; break; } } diff --git a/src/plugins/noReplyMention.tsx b/src/plugins/noReplyMention.tsx index 3ec8aef..16b3a3e 100644 --- a/src/plugins/noReplyMention.tsx +++ b/src/plugins/noReplyMention.tsx @@ -22,12 +22,27 @@ import definePlugin, { OptionType } from "@utils/types"; import type { Message } from "discord-types/general"; const settings = definePluginSettings({ - exemptList: { + userList: { description: - "List of users to exempt from this plugin (separated by commas or spaces)", + "List of users to allow or exempt pings for (separated by commas or spaces)", type: OptionType.STRING, default: "1234567890123445,1234567890123445", }, + shouldPingListed: { + description: "Behaviour", + type: OptionType.SELECT, + options: [ + { + label: "Do not ping the listed users", + value: false, + }, + { + label: "Only ping the listed users", + value: true, + default: true, + }, + ], + }, inverseShiftReply: { description: "Invert Discord's shift replying behaviour (enable to make shift reply mention user)", type: OptionType.BOOLEAN, @@ -38,11 +53,12 @@ const settings = definePluginSettings({ export default definePlugin({ name: "NoReplyMention", description: "Disables reply pings by default", - authors: [Devs.DustyAngel47, Devs.axyie, Devs.pylix], + authors: [Devs.DustyAngel47, Devs.axyie, Devs.pylix, Devs.outfoxxed], settings, shouldMention(message: Message, isHoldingShift: boolean) { - const isExempt = settings.store.exemptList.includes(message.author.id); + const isListed = settings.store.userList.includes(message.author.id); + const isExempt = settings.store.shouldPingListed ? isListed : !isListed; return settings.store.inverseShiftReply ? isHoldingShift !== isExempt : !isHoldingShift && isExempt; }, diff --git a/src/plugins/partyMode.ts b/src/plugins/partyMode.ts new file mode 100644 index 0000000..bb822f5 --- /dev/null +++ b/src/plugins/partyMode.ts @@ -0,0 +1,105 @@ +/* + * 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 { definePluginSettings } from "@api/Settings"; +import { Devs } from "@utils/constants"; +import definePlugin, { OptionType } from "@utils/types"; +import { findStoreLazy } from "@webpack"; +import { GenericStore } from "@webpack/common"; + +const PoggerModeSettingsStore: GenericStore = findStoreLazy("PoggermodeSettingsStore"); + +const enum Intensity { + Normal, + Better, + ProjectX, +} + +const settings = definePluginSettings({ + superIntensePartyMode: { + description: "Party intensity", + type: OptionType.SELECT, + options: [ + { label: "Normal", value: Intensity.Normal, default: true }, + { label: "Better", value: Intensity.Better }, + { label: "Project X", value: Intensity.ProjectX }, + ], + restartNeeded: false, + onChange: setSettings + }, +}); + +export default definePlugin({ + name: "Party mode πŸŽ‰", + description: "Allows you to use party mode cause the party never ends ✨", + authors: [Devs.UwUDev], + settings, + + start() { + setPoggerState(true); + setSettings(settings.store.superIntensePartyMode); + }, + + stop() { + setPoggerState(false); + }, +}); + +function setPoggerState(state: boolean) { + Object.assign(PoggerModeSettingsStore.__getLocalVars().state, { + enabled: state, + settingsVisible: state + }); +} + +function setSettings(intensity: Intensity) { + const state = { + screenshakeEnabledLocations: { 0: true, 1: true, 2: true }, + shakeIntensity: 1, + confettiSize: 16, + confettiCount: 5, + combosRequiredCount: 1 + }; + + switch (intensity) { + case Intensity.Normal: { + Object.assign(state, { + screenshakeEnabledLocations: { 0: true, 1: false, 2: false }, + combosRequiredCount: 5 + }); + break; + } + case Intensity.Better: { + Object.assign(state, { + confettiSize: 12, + confettiCount: 8, + }); + break; + } + case Intensity.ProjectX: { + Object.assign(state, { + shakeIntensity: 20, + confettiSize: 25, + confettiCount: 15, + }); + break; + } + } + + Object.assign(PoggerModeSettingsStore.__getLocalVars().state, state); +} diff --git a/src/plugins/permissionsViewer/components/RolesAndUsersPermissions.tsx b/src/plugins/permissionsViewer/components/RolesAndUsersPermissions.tsx new file mode 100644 index 0000000..7a65a07 --- /dev/null +++ b/src/plugins/permissionsViewer/components/RolesAndUsersPermissions.tsx @@ -0,0 +1,225 @@ +/* + * 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 ErrorBoundary from "@components/ErrorBoundary"; +import { Flex } from "@components/Flex"; +import { InfoIcon, OwnerCrownIcon } from "@components/Icons"; +import { ModalCloseButton, ModalContent, ModalHeader, ModalProps, ModalRoot, ModalSize, openModal } from "@utils/modal"; +import { ContextMenu, FluxDispatcher, GuildMemberStore, Menu, PermissionsBits, Text, Tooltip, useEffect, UserStore, useState, useStateFromStores } from "@webpack/common"; +import type { Guild } from "discord-types/general"; + +import { cl, getPermissionDescription, getPermissionString } from "../utils"; +import { PermissionAllowedIcon, PermissionDefaultIcon, PermissionDeniedIcon } from "./icons"; + +export const enum PermissionType { + Role = 0, + User = 1, + Owner = 2 +} + +export interface RoleOrUserPermission { + type: PermissionType; + id?: string; + permissions?: bigint; + overwriteAllow?: bigint; + overwriteDeny?: bigint; +} + +function openRolesAndUsersPermissionsModal(permissions: Array, guild: Guild, header: string) { + return openModal(modalProps => ( + + )); +} + +function RolesAndUsersPermissionsComponent({ permissions, guild, modalProps, header }: { permissions: Array; guild: Guild; modalProps: ModalProps; header: string; }) { + permissions.sort((a, b) => a.type - b.type); + + useStateFromStores( + [GuildMemberStore], + () => GuildMemberStore.getMemberIds(guild.id), + null, + (old, current) => old.length === current.length + ); + + useEffect(() => { + const usersToRequest = permissions + .filter(p => p.type === PermissionType.User && !GuildMemberStore.isMember(guild.id, p.id!)) + .map(({ id }) => id); + + FluxDispatcher.dispatch({ + type: "GUILD_MEMBERS_REQUEST", + guildIds: [guild.id], + userIds: usersToRequest + }); + }, []); + + const [selectedItemIndex, selectItem] = useState(0); + const selectedItem = permissions[selectedItemIndex]; + + return ( + + + {header} permissions: + + + + + {!selectedItem && ( +
+ No permissions to display! +
+ )} + + {selectedItem && ( +
+
+ {permissions.map((permission, index) => { + const user = UserStore.getUser(permission.id ?? ""); + const role = guild.roles[permission.id ?? ""]; + + return ( + + ); + })} +
+
+ {Object.entries(PermissionsBits).map(([permissionName, bit]) => ( +
+
+ {(() => { + const { permissions, overwriteAllow, overwriteDeny } = selectedItem; + + if (permissions) + return (permissions & bit) === bit + ? PermissionAllowedIcon() + : PermissionDeniedIcon(); + + if (overwriteAllow && (overwriteAllow & bit) === bit) + return PermissionAllowedIcon(); + if (overwriteDeny && (overwriteDeny & bit) === bit) + return PermissionDeniedIcon(); + + return PermissionDefaultIcon(); + })()} +
+ {getPermissionString(permissionName)} + + + {props => } + +
+ ))} +
+
+ )} +
+
+ ); +} + +function RoleContextMenu({ guild, roleId, onClose }: { guild: Guild; roleId: string; onClose: () => void; }) { + return ( + + { + const role = guild.roles[roleId]; + if (!role) return; + + onClose(); + + FluxDispatcher.dispatch({ + type: "IMPERSONATE_UPDATE", + guildId: guild.id, + data: { + type: "ROLES", + roles: { + [roleId]: role + } + } + }); + }} + /> + + ); +} + +const RolesAndUsersPermissions = ErrorBoundary.wrap(RolesAndUsersPermissionsComponent); + +export default openRolesAndUsersPermissionsModal; diff --git a/src/plugins/permissionsViewer/components/UserPermissions.tsx b/src/plugins/permissionsViewer/components/UserPermissions.tsx new file mode 100644 index 0000000..ab9bfea --- /dev/null +++ b/src/plugins/permissionsViewer/components/UserPermissions.tsx @@ -0,0 +1,197 @@ +/* + * 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 ErrorBoundary from "@components/ErrorBoundary"; +import { proxyLazy } from "@utils/lazy"; +import { classes } from "@utils/misc"; +import { filters, findBulk } from "@webpack"; +import { i18n, PermissionsBits, Text, Tooltip, useMemo, UserStore, useState } from "@webpack/common"; +import type { Guild, GuildMember } from "discord-types/general"; + +import { PermissionsSortOrder, settings } from ".."; +import { cl, getPermissionString, getSortedRoles, sortUserRoles } from "../utils"; +import openRolesAndUsersPermissionsModal, { PermissionType, type RoleOrUserPermission } from "./RolesAndUsersPermissions"; + +interface UserPermission { + permission: string; + roleColor: string; + rolePosition: number; +} + +type UserPermissions = Array; + +const Classes = proxyLazy(() => { + const modules = findBulk( + filters.byProps("roles", "rolePill", "rolePillBorder"), + filters.byProps("roleCircle", "dotBorderBase", "dotBorderColor"), + filters.byProps("roleNameOverflow", "root", "roleName", "roleRemoveButton") + ); + + return Object.assign({}, ...modules); +}) as Record<"roles" | "rolePill" | "rolePillBorder" | "desaturateUserColors" | "flex" | "alignCenter" | "justifyCenter" | "svg" | "background" | "dot" | "dotBorderColor" | "roleCircle" | "dotBorderBase" | "flex" | "alignCenter" | "justifyCenter" | "wrap" | "root" | "role" | "roleRemoveButton" | "roleDot" | "roleFlowerStar" | "roleRemoveIcon" | "roleRemoveIconFocused" | "roleVerifiedIcon" | "roleName" | "roleNameOverflow" | "actionButton" | "overflowButton" | "addButton" | "addButtonIcon" | "overflowRolesPopout" | "overflowRolesPopoutArrowWrapper" | "overflowRolesPopoutArrow" | "popoutBottom" | "popoutTop" | "overflowRolesPopoutHeader" | "overflowRolesPopoutHeaderIcon" | "overflowRolesPopoutHeaderText" | "roleIcon", string>; + +function UserPermissionsComponent({ guild, guildMember }: { guild: Guild; guildMember: GuildMember; }) { + const stns = settings.use(["permissionsSortOrder"]); + const [viewPermissions, setViewPermissions] = useState(settings.store.defaultPermissionsDropdownState); + + const [rolePermissions, userPermissions] = useMemo(() => { + const userPermissions: UserPermissions = []; + + const userRoles = getSortedRoles(guild, guildMember); + + const rolePermissions: Array = userRoles.map(role => ({ + type: PermissionType.Role, + ...role + })); + + if (guild.ownerId === guildMember.userId) { + rolePermissions.push({ + type: PermissionType.Owner, + permissions: Object.values(PermissionsBits).reduce((prev, curr) => prev | curr, 0n) + }); + + const OWNER = i18n.Messages.GUILD_OWNER || "Server Owner"; + userPermissions.push({ + permission: OWNER, + roleColor: "var(--primary-300)", + rolePosition: Infinity + }); + } + + sortUserRoles(userRoles); + + for (const [permission, bit] of Object.entries(PermissionsBits)) { + for (const { permissions, colorString, position, name } of userRoles) { + if ((permissions & bit) === bit) { + userPermissions.push({ + permission: getPermissionString(permission), + roleColor: colorString || "var(--primary-300)", + rolePosition: position + }); + + break; + } + } + } + + userPermissions.sort((a, b) => b.rolePosition - a.rolePosition); + + return [rolePermissions, userPermissions]; + }, [stns.permissionsSortOrder]); + + const { root, role, roleRemoveButton, roleNameOverflow, roles, rolePill, rolePillBorder, roleCircle, roleName } = Classes; + + return ( +
+
+ Permissions + +
+ + {tooltipProps => ( + + )} + + + + {tooltipProps => ( + + )} + + + + {tooltipProps => ( + + )} + +
+
+ + {viewPermissions && userPermissions.length > 0 && ( +
+ {userPermissions.map(({ permission, roleColor }) => ( +
+
+ +
+
+ + {permission} + +
+
+ ))} +
+ )} +
+ ); +} + +export default ErrorBoundary.wrap(UserPermissionsComponent, { noop: true }); diff --git a/src/plugins/permissionsViewer/components/icons.tsx b/src/plugins/permissionsViewer/components/icons.tsx new file mode 100644 index 0000000..8b58a44 --- /dev/null +++ b/src/plugins/permissionsViewer/components/icons.tsx @@ -0,0 +1,58 @@ +/* + * Vencord, a modification for Discord's desktop app + * Copyright (c) 2023 Vendicated and contributors + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . +*/ + +export function PermissionDeniedIcon() { + return ( + + Denied + + + ); +} + +export function PermissionAllowedIcon() { + return ( + + Allowed + + + ); +} + +export function PermissionDefaultIcon() { + return ( + + + Not overwritten + + + + ); +} diff --git a/src/plugins/permissionsViewer/index.tsx b/src/plugins/permissionsViewer/index.tsx new file mode 100644 index 0000000..480efc1 --- /dev/null +++ b/src/plugins/permissionsViewer/index.tsx @@ -0,0 +1,189 @@ +/* + * 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 "./styles.css"; + +import { addContextMenuPatch, findGroupChildrenByChildId, NavContextMenuPatchCallback, removeContextMenuPatch } from "@api/ContextMenu"; +import { definePluginSettings } from "@api/Settings"; +import { Devs } from "@utils/constants"; +import definePlugin, { OptionType } from "@utils/types"; +import { ChannelStore, GuildMemberStore, GuildStore, Menu, PermissionsBits, UserStore } from "@webpack/common"; +import type { Guild, GuildMember } from "discord-types/general"; + +import openRolesAndUsersPermissionsModal, { PermissionType, RoleOrUserPermission } from "./components/RolesAndUsersPermissions"; +import UserPermissions from "./components/UserPermissions"; +import { getSortedRoles, sortPermissionOverwrites } from "./utils"; + +export const enum PermissionsSortOrder { + HighestRole, + LowestRole +} + +const enum MenuItemParentType { + User, + Channel, + Guild +} + +export const settings = definePluginSettings({ + permissionsSortOrder: { + description: "The sort method used for defining which role grants an user a certain permission", + type: OptionType.SELECT, + options: [ + { label: "Highest Role", value: PermissionsSortOrder.HighestRole, default: true }, + { label: "Lowest Role", value: PermissionsSortOrder.LowestRole } + ], + }, + defaultPermissionsDropdownState: { + description: "Whether the permissions dropdown on user popouts should be open by default", + type: OptionType.BOOLEAN, + default: false, + } +}); + +function MenuItem(guildId: string, id?: string, type?: MenuItemParentType) { + if (type === MenuItemParentType.User && !GuildMemberStore.isMember(guildId, id!)) return null; + + return ( + { + const guild = GuildStore.getGuild(guildId); + + let permissions: RoleOrUserPermission[]; + let header: string; + + switch (type) { + case MenuItemParentType.User: { + const member = GuildMemberStore.getMember(guildId, id!); + + permissions = getSortedRoles(guild, member) + .map(role => ({ + type: PermissionType.Role, + ...role + })); + + if (guild.ownerId === id) { + permissions.push({ + type: PermissionType.Owner, + permissions: Object.values(PermissionsBits).reduce((prev, curr) => prev | curr, 0n) + }); + } + + header = member.nick ?? UserStore.getUser(member.userId).username; + + break; + } + + case MenuItemParentType.Channel: { + const channel = ChannelStore.getChannel(id!); + + permissions = sortPermissionOverwrites(Object.values(channel.permissionOverwrites).map(({ id, allow, deny, type }) => ({ + type: type as PermissionType, + id, + overwriteAllow: allow, + overwriteDeny: deny + })), guildId); + + header = channel.name; + + break; + } + + default: { + permissions = Object.values(guild.roles).map(role => ({ + type: PermissionType.Role, + ...role + })); + + header = guild.name; + + break; + } + } + + openRolesAndUsersPermissionsModal(permissions, guild, header); + }} + /> + ); +} + +function makeContextMenuPatch(childId: string | string[], type?: MenuItemParentType): NavContextMenuPatchCallback { + return (children, props) => () => { + if (!props) return children; + + const group = findGroupChildrenByChildId(childId, children); + + const item = (() => { + switch (type) { + case MenuItemParentType.User: + return MenuItem(props.guildId, props.user.id, type); + case MenuItemParentType.Channel: + return MenuItem(props.guild.id, props.channel.id, type); + case MenuItemParentType.Guild: + return MenuItem(props.guild.id); + default: + return null; + } + })(); + + if (item == null) return; + + if (group) + group.push(item); + else if (childId === "roles" && props.guildId) + // "roles" may not be present due to the member not having any roles. In that case, add it above "Copy ID" + children.splice(-1, 0, {item}); + }; +} + +export default definePlugin({ + name: "PermissionsViewer", + description: "View the permissions a user or channel has, and the roles of a server", + authors: [Devs.Nuckyz, Devs.Ven], + settings, + + patches: [ + { + find: ".Messages.BOT_PROFILE_SLASH_COMMANDS", + replacement: { + match: /showBorder:.{0,60}}\),(?<=guild:(\i),guildMember:(\i),.+?)/, + replace: (m, guild, guildMember) => `${m}$self.UserPermissions(${guild},${guildMember}),` + } + } + ], + + UserPermissions: (guild: Guild, guildMember?: GuildMember) => !!guildMember && , + + userContextMenuPatch: makeContextMenuPatch("roles", MenuItemParentType.User), + channelContextMenuPatch: makeContextMenuPatch(["mute-channel", "unmute-channel"], MenuItemParentType.Channel), + guildContextMenuPatch: makeContextMenuPatch("privacy", MenuItemParentType.Guild), + + start() { + addContextMenuPatch("user-context", this.userContextMenuPatch); + addContextMenuPatch("channel-context", this.channelContextMenuPatch); + addContextMenuPatch("guild-context", this.guildContextMenuPatch); + }, + + stop() { + removeContextMenuPatch("user-context", this.userContextMenuPatch); + removeContextMenuPatch("channel-context", this.channelContextMenuPatch); + removeContextMenuPatch("guild-context", this.guildContextMenuPatch); + }, +}); diff --git a/src/plugins/permissionsViewer/styles.css b/src/plugins/permissionsViewer/styles.css new file mode 100644 index 0000000..1043491 --- /dev/null +++ b/src/plugins/permissionsViewer/styles.css @@ -0,0 +1,146 @@ +/* User Permissions Component */ + +.vc-permviewer-userperms-title-container { + display: flex; + justify-content: space-between; + align-items: center; + margin-top: 10px; + margin-bottom: 6px; +} + +.vc-permviewer-userperms-btns-container { + display: flex; + align-items: center; +} + +.vc-permviewer-userperms-sortorder-btn { + all: unset; + cursor: pointer; + display: flex; + align-items: center; + justify-content: center; + width: 24px; + height: 24px; +} + +.vc-permviewer-userperms-permdetails-btn { + all: unset; + cursor: pointer; + display: flex; + align-items: center; +} + +.vc-permviewer-userperms-toggleperms-btn { + all: unset; + cursor: pointer; + display: flex; + align-items: center; +} + +/* RolesAndUsersPermissions Component */ + +.vc-permviewer-perms-title { + flex-grow: 1; +} + +.vc-permviewer-perms-no-perms { + width: 100%; + height: 100%; + display: flex; + align-items: center; + justify-content: center; + text-align: center; +} + +.vc-permviewer-perms-container { + display: grid; + grid-template-columns: 1fr 2fr; + grid-template-areas: "list permissions"; + padding: 16px 0; +} + +.vc-permviewer-perms-list { + grid-area: list; + display: flex; + flex-direction: column; + border-right: 2px solid var(--background-modifier-active); +} + +.vc-permviewer-perms-list-item-btn { + all: unset; + cursor: pointer; +} + +.vc-permviewer-perms-list-item { + display: flex; + align-items: center; + padding: 8px 5px; + cursor: pointer; + width: 230px; +} + +.vc-permviewer-perms-list-item > div { + text-overflow: ellipsis; + white-space: nowrap; + overflow: hidden; +} + +.vc-permviewer-perms-list-item-active { + background-color: var(--background-modifier-selected); + border-radius: 5px; +} + +.vc-permviewer-perms-role-circle { + border-radius: 50%; + width: 12px; + height: 12px; + margin-left: 3px; + margin-right: 11px; + flex-shrink: 0; +} + +.vc-permviewer-perms-user-img { + border-radius: 50%; + width: 20px; + height: 20px; + margin-right: 6px; +} + +.vc-permviewer-perms-perms { + grid-area: permissions; + display: flex; + flex-direction: column; + margin-left: 5px; +} + +.vc-permviewer-perms-perms-item { + position: relative; + display: flex; + align-items: center; + padding: 10px; + border-bottom: 2px solid var(--background-modifier-active); +} + +.vc-permviewer-perms-perms-item:last-child { + border: 0; +} + +.vc-permviewer-perms-perms-item-icon { + border: 1px solid var(--background-modifier-selected); + width: 24px; + height: 24px; + margin-right: 5px; +} + +.vc-permviewer-perms-perms-item .vc-info-icon { + color: var(--interactive-muted); + cursor: pointer; + position: absolute; + right: 0; + scale: 0.9; + transition: color ease-in 0.1s; +} + +.vc-permviewer-perms-perms-item .vc-info-icon:hover { + color: var(--interactive-active); +} diff --git a/src/plugins/permissionsViewer/utils.ts b/src/plugins/permissionsViewer/utils.ts new file mode 100644 index 0000000..06f293b --- /dev/null +++ b/src/plugins/permissionsViewer/utils.ts @@ -0,0 +1,98 @@ +/* + * Vencord, a modification for Discord's desktop app + * Copyright (c) 2023 Vendicated and contributors + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . +*/ + +import { classNameFactory } from "@api/Styles"; +import { wordsToTitle } from "@utils/text"; +import { GuildStore, i18n, Parser } from "@webpack/common"; +import { Guild, GuildMember, Role } from "discord-types/general"; +import type { ReactNode } from "react"; + +import { PermissionsSortOrder, settings } from "."; +import { PermissionType } from "./components/RolesAndUsersPermissions"; + +export const cl = classNameFactory("vc-permviewer-"); + +function formatPermissionWithoutMatchingString(permission: string) { + return wordsToTitle(permission.toLowerCase().split("_")); +} + +// because discord is unable to be consistent with their names +const PermissionKeyMap = { + MANAGE_GUILD: "MANAGE_SERVER", + MANAGE_GUILD_EXPRESSIONS: "MANAGE_EXPRESSIONS", + CREATE_GUILD_EXPRESSIONS: "CREATE_EXPRESSIONS", + MODERATE_MEMBERS: "MODERATE_MEMBER", // HELLOOOO ?????? + STREAM: "VIDEO", + SEND_VOICE_MESSAGES: "ROLE_PERMISSIONS_SEND_VOICE_MESSAGE", +} as const; + +export function getPermissionString(permission: string) { + permission = PermissionKeyMap[permission] || permission; + + return i18n.Messages[permission] || + // shouldn't get here but just in case + formatPermissionWithoutMatchingString(permission); +} + +export function getPermissionDescription(permission: string): ReactNode { + // DISCORD PLEEEEEEEEAAAAASE IM BEGGING YOU :( + if (permission === "USE_APPLICATION_COMMANDS") + permission = "USE_APPLICATION_COMMANDS_GUILD"; + else if (permission === "SEND_VOICE_MESSAGES") + permission = "SEND_VOICE_MESSAGE_GUILD"; + else if (permission !== "STREAM") + permission = PermissionKeyMap[permission] || permission; + + const msg = i18n.Messages[`ROLE_PERMISSIONS_${permission}_DESCRIPTION`] as any; + if (msg?.hasMarkdown) + return Parser.parse(msg.message); + + if (typeof msg === "string") return msg; + + return ""; +} + +export function getSortedRoles({ roles, id }: Guild, member: GuildMember) { + return [...member.roles, id] + .map(id => roles[id]) + .sort((a, b) => b.position - a.position); +} + +export function sortUserRoles(roles: Role[]) { + switch (settings.store.permissionsSortOrder) { + case PermissionsSortOrder.HighestRole: + return roles.sort((a, b) => b.position - a.position); + case PermissionsSortOrder.LowestRole: + return roles.sort((a, b) => a.position - b.position); + default: + return roles; + } +} + +export function sortPermissionOverwrites(overwrites: T[], guildId: string) { + const guild = GuildStore.getGuild(guildId); + + return overwrites.sort((a, b) => { + if (a.type !== PermissionType.Role || b.type !== PermissionType.Role) return 0; + + const roleA = guild.roles[a.id]; + const roleB = guild.roles[b.id]; + + return roleB.position - roleA.position; + }); +} diff --git a/src/plugins/platformIndicators.tsx b/src/plugins/platformIndicators.tsx index 03165bf..6a7a8be 100644 --- a/src/plugins/platformIndicators.tsx +++ b/src/plugins/platformIndicators.tsx @@ -29,22 +29,16 @@ import { User } from "discord-types/general"; const SessionsStore = findStoreLazy("SessionsStore"); -function Icon(path: string, viewBox = "0 0 24 24") { - return ({ color, tooltip, wantMargin }: { color: string; tooltip: string; wantMargin: boolean; }) => ( +function Icon(path: string, opts?: { viewBox?: string; width?: number; height?: number; }) { + return ({ color, tooltip }: { color: string; tooltip: string; }) => ( {(tooltipProps: any) => ( @@ -56,23 +50,23 @@ function Icon(path: string, viewBox = "0 0 24 24") { const Icons = { desktop: Icon("M4 2.5c-1.103 0-2 .897-2 2v11c0 1.104.897 2 2 2h7v2H7v2h10v-2h-4v-2h7c1.103 0 2-.896 2-2v-11c0-1.103-.897-2-2-2H4Zm16 2v9H4v-9h16Z"), web: Icon("M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2Zm-1 17.93c-3.95-.49-7-3.85-7-7.93 0-.62.08-1.21.21-1.79L9 15v1c0 1.1.9 2 2 2v1.93Zm6.9-2.54c-.26-.81-1-1.39-1.9-1.39h-1v-3c0-.55-.45-1-1-1H8v-2h2c.55 0 1-.45 1-1V7h2c1.1 0 2-.9 2-2v-.41c2.93 1.19 5 4.06 5 7.41 0 2.08-.8 3.97-2.1 5.39Z"), - mobile: Icon("M15.5 1h-8A2.5 2.5 0 0 0 5 3.5v17A2.5 2.5 0 0 0 7.5 23h8a2.5 2.5 0 0 0 2.5-2.5v-17A2.5 2.5 0 0 0 15.5 1zm-4 21c-.83 0-1.5-.67-1.5-1.5s.67-1.5 1.5-1.5 1.5.67 1.5 1.5-.67 1.5-1.5 1.5zm4.5-4H7V4h9v14z"), - console: Icon("M14.8 2.7 9 3.1V47h3.3c1.7 0 6.2.3 10 .7l6.7.6V2l-4.2.2c-2.4.1-6.9.3-10 .5zm1.8 6.4c1 1.7-1.3 3.6-2.7 2.2C12.7 10.1 13.5 8 15 8c.5 0 1.2.5 1.6 1.1zM16 33c0 6-.4 10-1 10s-1-4-1-10 .4-10 1-10 1 4 1 10zm15-8v23.3l3.8-.7c2-.3 4.7-.6 6-.6H43V3h-2.2c-1.3 0-4-.3-6-.6L31 1.7V25z", "0 0 50 50"), + mobile: Icon("M 187 0 L 813 0 C 916.277 0 1000 83.723 1000 187 L 1000 1313 C 1000 1416.277 916.277 1500 813 1500 L 187 1500 C 83.723 1500 0 1416.277 0 1313 L 0 187 C 0 83.723 83.723 0 187 0 Z M 125 1000 L 875 1000 L 875 250 L 125 250 Z M 500 1125 C 430.964 1125 375 1180.964 375 1250 C 375 1319.036 430.964 1375 500 1375 C 569.036 1375 625 1319.036 625 1250 C 625 1180.964 569.036 1125 500 1125 Z", { viewBox: "0 0 1000 1500", height: 17, width: 17 }), + console: Icon("M14.8 2.7 9 3.1V47h3.3c1.7 0 6.2.3 10 .7l6.7.6V2l-4.2.2c-2.4.1-6.9.3-10 .5zm1.8 6.4c1 1.7-1.3 3.6-2.7 2.2C12.7 10.1 13.5 8 15 8c.5 0 1.2.5 1.6 1.1zM16 33c0 6-.4 10-1 10s-1-4-1-10 .4-10 1-10 1 4 1 10zm15-8v23.3l3.8-.7c2-.3 4.7-.6 6-.6H43V3h-2.2c-1.3 0-4-.3-6-.6L31 1.7V25z", { viewBox: "0 0 50 50" }), }; type Platform = keyof typeof Icons; const getStatusColor = findByCodeLazy(".TWITCH", ".STREAMING", ".INVISIBLE"); -const PlatformIcon = ({ platform, status, wantMargin }: { platform: Platform, status: string; wantMargin: boolean; }) => { +const PlatformIcon = ({ platform, status }: { platform: Platform, status: string; }) => { const tooltip = platform[0].toUpperCase() + platform.slice(1); const Icon = Icons[platform] ?? Icons.desktop; - return ; + return ; }; const getStatus = (id: string): Record => PresenceStore.getState()?.clientStatuses?.[id]; -const PlatformIndicator = ({ user, wantMargin = true }: { user: User; wantMargin?: boolean; }) => { +const PlatformIndicator = ({ user, wantMargin = true, wantTopMargin = false }: { user: User; wantMargin?: boolean; wantTopMargin?: boolean; }) => { if (!user || user.bot) return null; if (user.id === UserStore.getCurrentUser().id) { @@ -105,14 +99,27 @@ const PlatformIndicator = ({ user, wantMargin = true }: { user: User; wantMargin key={platform} platform={platform as Platform} status={status} - wantMargin={wantMargin} /> )); if (!icons.length) return null; return ( - + {icons} ); @@ -144,7 +151,7 @@ const indicatorLocations = { description: "Inside messages", onEnable: () => addDecoration("platform-indicator", props => - + ), onDisable: () => removeDecoration("platform-indicator") @@ -154,7 +161,7 @@ const indicatorLocations = { export default definePlugin({ name: "PlatformIndicators", description: "Adds platform indicators (Desktop, Mobile, Web...) to users", - authors: [Devs.kemo, Devs.TheSun, Devs.Nuckyz], + authors: [Devs.kemo, Devs.TheSun, Devs.Nuckyz, Devs.Ven], dependencies: ["MessageDecorationsAPI", "MemberListDecoratorsAPI"], start() { diff --git a/src/plugins/pronoundb/components/PronounsChatComponent.tsx b/src/plugins/pronoundb/components/PronounsChatComponent.tsx index e302676..3e51544 100644 --- a/src/plugins/pronoundb/components/PronounsChatComponent.tsx +++ b/src/plugins/pronoundb/components/PronounsChatComponent.tsx @@ -26,10 +26,12 @@ import { settings } from "../settings"; const styles: Record = findByPropsLazy("timestampInline"); +const AUTO_MODERATION_ACTION = 24; + function shouldShow(message: Message): boolean { if (!settings.store.showInMessages) return false; - if (message.author.bot || message.author.system) + if (message.author.bot || message.author.system || message.type === AUTO_MODERATION_ACTION) return false; if (!settings.store.showSelf && message.author.id === UserStore.getCurrentUser().id) return false; diff --git a/src/plugins/reverseImageSearch.tsx b/src/plugins/reverseImageSearch.tsx index fd98d0f..811e7ff 100644 --- a/src/plugins/reverseImageSearch.tsx +++ b/src/plugins/reverseImageSearch.tsx @@ -17,6 +17,8 @@ */ import { addContextMenuPatch, findGroupChildrenByChildId, NavContextMenuPatchCallback, removeContextMenuPatch } from "@api/ContextMenu"; +import { Flex } from "@components/Flex"; +import { OpenExternalIcon } from "@components/Icons"; import { Devs } from "@utils/constants"; import definePlugin from "@utils/types"; import { Menu } from "@webpack/common"; @@ -28,7 +30,7 @@ const Engines = { IQDB: "https://iqdb.org/?url=", TinEye: "https://www.tineye.com/search?url=", ImgOps: "https://imgops.com/start?url=" -}; +} as const; function search(src: string, engine: string) { open(engine + encodeURIComponent(src), "_blank"); @@ -50,13 +52,28 @@ const imageContextMenuPatch: NavContextMenuPatchCallback = (children, props) => key="search-image" id="search-image" > - {Object.keys(Engines).map(engine => { + {Object.keys(Engines).map((engine, i) => { const key = "search-image-" + engine; return ( + = 3 // Do not round Google, Yandex & SauceNAO + ? "50%" + : void 0 + }} + aria-hidden="true" + height={16} + width={16} + src={new URL("/favicon.ico", Engines[engine]).toString().replace("lens.", "")} + /> + {engine} + + } action={() => search(src, Engines[engine])} /> ); @@ -64,7 +81,12 @@ const imageContextMenuPatch: NavContextMenuPatchCallback = (children, props) => + + All + + } action={() => Object.values(Engines).forEach(e => search(src, e))} /> @@ -76,6 +98,8 @@ export default definePlugin({ name: "ReverseImageSearch", description: "Adds ImageSearch to image context menus", authors: [Devs.Ven, Devs.Nuckyz], + tags: ["ImageUtilities"], + patches: [ { find: ".Messages.MESSAGE_ACTIONS_MENU_LABEL", diff --git a/src/plugins/reviewDB/Utils/Utils.tsx b/src/plugins/reviewDB/Utils/Utils.tsx index d09c8d4..42426b2 100644 --- a/src/plugins/reviewDB/Utils/Utils.tsx +++ b/src/plugins/reviewDB/Utils/Utils.tsx @@ -44,20 +44,19 @@ export function authorize(callback?: any) { {...props} scopes={["identify"]} responseType="code" - redirectUri="https://manti.vendicated.dev/URauth" + redirectUri="https://manti.vendicated.dev/api/reviewdb/auth" permissions={0n} clientId="915703782174752809" cancelCompletesFlow={false} callback={async (u: string) => { try { const url = new URL(u); - url.searchParams.append("returnType", "json"); url.searchParams.append("clientMod", "vencord"); const res = await fetch(url, { headers: new Headers({ Accept: "application/json" }) }); - const { token, status } = await res.json(); - if (status === 0) { + const { token, success } = await res.json(); + if (success) { Settings.plugins.ReviewDB.token = token; showToast("Successfully logged in!"); callback?.(); @@ -65,7 +64,7 @@ export function authorize(callback?: any) { showToast("An Error occurred while logging in."); } } catch (e) { - new Logger("ReviewDB").error("Failed to authorise", e); + new Logger("ReviewDB").error("Failed to authorize", e); } }} /> @@ -86,5 +85,5 @@ export function showToast(text: string) { export const sleep = (ms: number) => new Promise(r => setTimeout(r, ms)); export function canDeleteReview(review: Review, userId: string) { - if (review.sender.discordID === userId || Settings.plugins.ReviewDB.userType === UserType.Admin) return true; + if (review.sender.discordID === userId || Settings.plugins.ReviewDB.user?.type === UserType.Admin) return true; } diff --git a/src/plugins/reviewDB/components/ReviewComponent.tsx b/src/plugins/reviewDB/components/ReviewComponent.tsx index 04973d7..ac09b4c 100644 --- a/src/plugins/reviewDB/components/ReviewComponent.tsx +++ b/src/plugins/reviewDB/components/ReviewComponent.tsx @@ -34,19 +34,17 @@ export default LazyComponent(() => { const [ { cozyMessage, buttons, message, groupStart }, { container, isHeader }, - { avatar, clickable, username, messageContent, wrapper, cozy, timestampInline, timestamp }, - { contents }, + { avatar, clickable, username, messageContent, wrapper, cozy }, buttonClasses, - { defaultColor } ] = findBulk( p("cozyMessage"), p("container", "isHeader"), p("avatar", "zalgo"), - p("contents"), p("button", "wrapper", "selected"), - p("defaultColor") ); + const dateFormat = new Intl.DateTimeFormat(); + return function ReviewComponent({ review, refetch }: { review: Review; refetch(): void; }) { function openModal() { openUserProfileModal(review.sender.discordID); @@ -89,7 +87,7 @@ export default LazyComponent(() => { } }> -
+
{ { !Settings.plugins.ReviewDB.hideTimestamps && ( - - ) + + {dateFormat.format(review.timestamp * 1000)} + ) }

{review.comment}

diff --git a/src/plugins/reviewDB/components/ReviewsView.tsx b/src/plugins/reviewDB/components/ReviewsView.tsx index f4bd248..ff46cca 100644 --- a/src/plugins/reviewDB/components/ReviewsView.tsx +++ b/src/plugins/reviewDB/components/ReviewsView.tsx @@ -19,7 +19,7 @@ import { Settings } from "@api/Settings"; import { classes } from "@utils/misc"; import { useAwaiter } from "@utils/react"; -import { findLazy } from "@webpack"; +import { findByPropsLazy } from "@webpack"; import { Forms, React, Text, UserStore } from "@webpack/common"; import type { KeyboardEvent } from "react"; @@ -27,7 +27,7 @@ import { addReview, getReviews } from "../Utils/ReviewDBAPI"; import { authorize, showToast } from "../Utils/Utils"; import ReviewComponent from "./ReviewComponent"; -const Classes = findLazy(m => typeof m.textarea === "string"); +const Classes = findByPropsLazy("inputDefault", "editable"); export default function ReviewsView({ userId }: { userId: string; }) { const { token } = Settings.plugins.ReviewDB; @@ -65,7 +65,7 @@ export default function ReviewsView({ userId }: { userId: string; }) { tag="h2" variant="eyebrow" style={{ - marginBottom: "12px", + marginBottom: "8px", color: "var(--header-primary)" }} > @@ -79,13 +79,17 @@ export default function ReviewsView({ userId }: { userId: string; }) { /> )} {reviews?.length === 0 && ( - + Looks like nobody reviewed this user yet. You could be the first! )}