mirror of
https://github.com/Vendicated/Vencord.git
synced 2025-01-09 17:36:23 +00:00
Merge branch 'dev' into bannersEverywhere
This commit is contained in:
commit
9494c07562
180 changed files with 3252 additions and 1753 deletions
3
.github/ISSUE_TEMPLATE/blank.yml
vendored
3
.github/ISSUE_TEMPLATE/blank.yml
vendored
|
@ -12,7 +12,8 @@ body:
|
|||
DO NOT USE THIS FORM, unless
|
||||
- you are a vencord contributor
|
||||
- you were given explicit permission to use this form by a moderator in our support server
|
||||
- you are filing a security related report
|
||||
|
||||
DO NOT USE THIS FORM FOR SECURITY RELATED ISSUES. [CREATE A SECURITY ADVISORY INSTEAD.](https://github.com/Vendicated/Vencord/security/advisories/new)
|
||||
|
||||
- type: textarea
|
||||
id: content
|
||||
|
|
2
.github/workflows/build.yml
vendored
2
.github/workflows/build.yml
vendored
|
@ -32,7 +32,7 @@ jobs:
|
|||
run: pnpm install --frozen-lockfile
|
||||
|
||||
- name: Build web
|
||||
run: pnpm buildWeb --standalone
|
||||
run: pnpm buildWebStandalone
|
||||
|
||||
- name: Build
|
||||
run: pnpm build --standalone
|
||||
|
|
2
.github/workflows/publish.yml
vendored
2
.github/workflows/publish.yml
vendored
|
@ -32,7 +32,7 @@ jobs:
|
|||
run: pnpm install --frozen-lockfile
|
||||
|
||||
- name: Build web
|
||||
run: pnpm buildWeb --standalone
|
||||
run: pnpm buildWebStandalone
|
||||
|
||||
- name: Publish extension
|
||||
run: |
|
||||
|
|
4
.github/workflows/reportBrokenPlugins.yml
vendored
4
.github/workflows/reportBrokenPlugins.yml
vendored
|
@ -37,8 +37,8 @@ jobs:
|
|||
with:
|
||||
chrome-version: stable
|
||||
|
||||
- name: Build web
|
||||
run: pnpm buildWeb --standalone --dev
|
||||
- name: Build Vencord Reporter Version
|
||||
run: pnpm buildReporter
|
||||
|
||||
- name: Create Report
|
||||
timeout-minutes: 10
|
||||
|
|
2
.vscode/settings.json
vendored
2
.vscode/settings.json
vendored
|
@ -14,6 +14,8 @@
|
|||
"typescript.preferences.quoteStyle": "double",
|
||||
"javascript.preferences.quoteStyle": "double",
|
||||
|
||||
"eslint.experimental.useFlatConfig": false,
|
||||
|
||||
"gitlens.remotes": [
|
||||
{
|
||||
"domain": "codeberg.org",
|
||||
|
|
|
@ -5,7 +5,7 @@
|
|||
The cutest Discord client mod
|
||||
|
||||
| ![image](https://github.com/Vendicated/Vencord/assets/45497981/706722b1-32de-4d99-bee9-93993b504334) |
|
||||
|:--:|
|
||||
| :--------------------------------------------------------------------------------------------------: |
|
||||
| A screenshot of vencord showcasing the [vencord-theme](https://github.com/synqat/vencord-theme) |
|
||||
|
||||
## Features
|
||||
|
@ -33,7 +33,7 @@ https://discord.gg/D9uwnFnqmd
|
|||
## Sponsors
|
||||
|
||||
| **Thanks a lot to all Vencord [sponsors](https://github.com/sponsors/Vendicated)!!** |
|
||||
|:--:|
|
||||
| :------------------------------------------------------------------------------------------: |
|
||||
| [![](https://meow.vendicated.dev/sponsors.png)](https://github.com/sponsors/Vendicated) |
|
||||
| *generated using [github-sponsor-graph](https://github.com/Vendicated/github-sponsor-graph)* |
|
||||
|
||||
|
|
|
@ -2,23 +2,22 @@ if (typeof browser === "undefined") {
|
|||
var browser = chrome;
|
||||
}
|
||||
|
||||
const script = document.createElement("script");
|
||||
script.src = browser.runtime.getURL("dist/Vencord.js");
|
||||
script.id = "vencord-script";
|
||||
Object.assign(script.dataset, {
|
||||
extensionBaseUrl: browser.runtime.getURL(""),
|
||||
version: browser.runtime.getManifest().version
|
||||
});
|
||||
|
||||
const style = document.createElement("link");
|
||||
style.type = "text/css";
|
||||
style.rel = "stylesheet";
|
||||
style.href = browser.runtime.getURL("dist/Vencord.css");
|
||||
|
||||
document.documentElement.append(script);
|
||||
|
||||
document.addEventListener(
|
||||
"DOMContentLoaded",
|
||||
() => document.documentElement.append(style),
|
||||
() => {
|
||||
document.documentElement.append(style);
|
||||
window.postMessage({
|
||||
type: "vencord:meta",
|
||||
meta: {
|
||||
EXTENSION_VERSION: browser.runtime.getManifest().version,
|
||||
EXTENSION_BASE_URL: browser.runtime.getURL(""),
|
||||
}
|
||||
});
|
||||
},
|
||||
{ once: true }
|
||||
);
|
||||
|
|
|
@ -22,7 +22,15 @@
|
|||
"run_at": "document_start",
|
||||
"matches": ["*://*.discord.com/*"],
|
||||
"js": ["content.js"],
|
||||
"all_frames": true
|
||||
"all_frames": true,
|
||||
"world": "ISOLATED"
|
||||
},
|
||||
{
|
||||
"run_at": "document_start",
|
||||
"matches": ["*://*.discord.com/*"],
|
||||
"js": ["dist/Vencord.js"],
|
||||
"all_frames": true,
|
||||
"world": "MAIN"
|
||||
}
|
||||
],
|
||||
|
||||
|
|
|
@ -22,7 +22,15 @@
|
|||
"run_at": "document_start",
|
||||
"matches": ["*://*.discord.com/*"],
|
||||
"js": ["content.js"],
|
||||
"all_frames": true
|
||||
"all_frames": true,
|
||||
"world": "ISOLATED"
|
||||
},
|
||||
{
|
||||
"run_at": "document_start",
|
||||
"matches": ["*://*.discord.com/*"],
|
||||
"js": ["dist/Vencord.js"],
|
||||
"all_frames": true,
|
||||
"world": "MAIN"
|
||||
}
|
||||
],
|
||||
|
||||
|
|
10
package.json
10
package.json
|
@ -1,7 +1,7 @@
|
|||
{
|
||||
"name": "vencord",
|
||||
"private": "true",
|
||||
"version": "1.8.6",
|
||||
"version": "1.9.1",
|
||||
"description": "The cutest Discord client mod",
|
||||
"homepage": "https://github.com/Vendicated/Vencord#readme",
|
||||
"bugs": {
|
||||
|
@ -20,7 +20,11 @@
|
|||
"build": "node --require=./scripts/suppressExperimentalWarnings.js scripts/build/build.mjs",
|
||||
"buildStandalone": "pnpm build --standalone",
|
||||
"buildWeb": "node --require=./scripts/suppressExperimentalWarnings.js scripts/build/buildWeb.mjs",
|
||||
"buildWebStandalone": "pnpm buildWeb --standalone",
|
||||
"buildReporter": "pnpm buildWebStandalone --reporter --skip-extension",
|
||||
"buildReporterDesktop": "pnpm build --reporter",
|
||||
"watch": "pnpm build --watch",
|
||||
"watchWeb": "pnpm buildWeb --watch",
|
||||
"generatePluginJson": "tsx scripts/generatePluginList.ts",
|
||||
"generateTypes": "tspc --emitDeclarationOnly --declaration --outDir packages/vencord-types",
|
||||
"inject": "node scripts/runInstaller.mjs",
|
||||
|
@ -39,7 +43,7 @@
|
|||
"eslint-plugin-simple-header": "^1.0.2",
|
||||
"fflate": "^0.7.4",
|
||||
"gifenc": "github:mattdesl/gifenc#64842fca317b112a8590f8fef2bf3825da8f6fe3",
|
||||
"monaco-editor": "^0.43.0",
|
||||
"monaco-editor": "^0.50.0",
|
||||
"nanoid": "^4.0.2",
|
||||
"virtual-merge": "^1.0.1"
|
||||
},
|
||||
|
@ -103,6 +107,6 @@
|
|||
},
|
||||
"engines": {
|
||||
"node": ">=18",
|
||||
"pnpm": ">=8"
|
||||
"pnpm": ">=9"
|
||||
}
|
||||
}
|
||||
|
|
|
@ -35,8 +35,8 @@ importers:
|
|||
specifier: github:mattdesl/gifenc#64842fca317b112a8590f8fef2bf3825da8f6fe3
|
||||
version: https://codeload.github.com/mattdesl/gifenc/tar.gz/64842fca317b112a8590f8fef2bf3825da8f6fe3
|
||||
monaco-editor:
|
||||
specifier: ^0.43.0
|
||||
version: 0.43.0
|
||||
specifier: ^0.50.0
|
||||
version: 0.50.0
|
||||
nanoid:
|
||||
specifier: ^4.0.2
|
||||
version: 4.0.2
|
||||
|
@ -1531,6 +1531,10 @@ packages:
|
|||
is-core-module@2.13.1:
|
||||
resolution: {integrity: sha512-hHrIjvZsftOsvKSn2TRYl63zvxsgE0K+0mYMoH6gD4omR5IWB2KynivBQczo3+wF1cCkjzvptnI9Q0sPU66ilw==}
|
||||
|
||||
is-core-module@2.14.0:
|
||||
resolution: {integrity: sha512-a5dFJih5ZLYlRtDc0dZWP7RiKr6xIKzmn/oAYCDvdLThadVgyJwlaoQPmRtMSpz+rk0OGAgIu+TcM9HUF0fk1A==}
|
||||
engines: {node: '>= 0.4'}
|
||||
|
||||
is-data-descriptor@0.1.4:
|
||||
resolution: {integrity: sha512-+w9D5ulSoBNlmw9OHn3U2v51SyoCd0he+bB3xMl62oijhrspxowjU+AIcDY0N3iEJbUEkB15IlMASQsxYigvXg==}
|
||||
engines: {node: '>=0.10.0'}
|
||||
|
@ -1791,8 +1795,8 @@ packages:
|
|||
moment@2.29.4:
|
||||
resolution: {integrity: sha512-5LC9SOxjSc2HF6vO2CyuTDNivEdoz2IvyJJGj6X8DJ0eFyfszE0QiEd+iXmBvUP3WHxSjFH/vIsA0EN00cgr8w==}
|
||||
|
||||
monaco-editor@0.43.0:
|
||||
resolution: {integrity: sha512-cnoqwQi/9fml2Szamv1XbSJieGJ1Dc8tENVMD26Kcfl7xGQWp7OBKMjlwKVGYFJ3/AXJjSOGvcqK7Ry/j9BM1Q==}
|
||||
monaco-editor@0.50.0:
|
||||
resolution: {integrity: sha512-8CclLCmrRRh+sul7C08BmPBP3P8wVWfBHomsTcndxg5NRCEPfu/mc2AGU8k37ajjDVXcXFc12ORAMUkmk+lkFA==}
|
||||
|
||||
ms@2.0.0:
|
||||
resolution: {integrity: sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A==}
|
||||
|
@ -3463,7 +3467,7 @@ snapshots:
|
|||
eslint-import-resolver-node@0.3.9:
|
||||
dependencies:
|
||||
debug: 3.2.7
|
||||
is-core-module: 2.13.1
|
||||
is-core-module: 2.14.0
|
||||
resolve: 1.22.8
|
||||
transitivePeerDependencies:
|
||||
- supports-color
|
||||
|
@ -3490,7 +3494,7 @@ snapshots:
|
|||
eslint-import-resolver-node: 0.3.9
|
||||
eslint-module-utils: 2.8.1(@typescript-eslint/parser@5.59.1(eslint@8.46.0(patch_hash=xm46kqcmdgzlmm4aifkfpxaho4))(typescript@5.4.5))(eslint-import-resolver-node@0.3.9)(eslint@8.46.0(patch_hash=xm46kqcmdgzlmm4aifkfpxaho4))
|
||||
hasown: 2.0.2
|
||||
is-core-module: 2.13.1
|
||||
is-core-module: 2.14.0
|
||||
is-glob: 4.0.3
|
||||
minimatch: 3.1.2
|
||||
object.fromentries: 2.0.8
|
||||
|
@ -3934,6 +3938,10 @@ snapshots:
|
|||
dependencies:
|
||||
hasown: 2.0.2
|
||||
|
||||
is-core-module@2.14.0:
|
||||
dependencies:
|
||||
hasown: 2.0.2
|
||||
|
||||
is-data-descriptor@0.1.4:
|
||||
dependencies:
|
||||
kind-of: 3.2.2
|
||||
|
@ -4169,7 +4177,7 @@ snapshots:
|
|||
|
||||
moment@2.29.4: {}
|
||||
|
||||
monaco-editor@0.43.0: {}
|
||||
monaco-editor@0.50.0: {}
|
||||
|
||||
ms@2.0.0: {}
|
||||
|
||||
|
|
|
@ -21,19 +21,21 @@ import esbuild from "esbuild";
|
|||
import { readdir } from "fs/promises";
|
||||
import { join } from "path";
|
||||
|
||||
import { BUILD_TIMESTAMP, commonOpts, existsAsync, globPlugins, isDev, isStandalone, updaterDisabled, VERSION, watch } from "./common.mjs";
|
||||
import { BUILD_TIMESTAMP, commonOpts, exists, globPlugins, IS_DEV, IS_REPORTER, IS_STANDALONE, IS_UPDATER_DISABLED, resolvePluginName, VERSION, watch } from "./common.mjs";
|
||||
|
||||
const defines = {
|
||||
IS_STANDALONE: isStandalone,
|
||||
IS_DEV: JSON.stringify(isDev),
|
||||
IS_UPDATER_DISABLED: updaterDisabled,
|
||||
IS_STANDALONE,
|
||||
IS_DEV,
|
||||
IS_REPORTER,
|
||||
IS_UPDATER_DISABLED,
|
||||
IS_WEB: false,
|
||||
IS_EXTENSION: false,
|
||||
VERSION: JSON.stringify(VERSION),
|
||||
BUILD_TIMESTAMP,
|
||||
BUILD_TIMESTAMP
|
||||
};
|
||||
if (defines.IS_STANDALONE === "false")
|
||||
// If this is a local build (not standalone), optimise
|
||||
|
||||
if (defines.IS_STANDALONE === false)
|
||||
// If this is a local build (not standalone), optimize
|
||||
// for the specific platform we're on
|
||||
defines["process.platform"] = JSON.stringify(process.platform);
|
||||
|
||||
|
@ -46,7 +48,7 @@ const nodeCommonOpts = {
|
|||
platform: "node",
|
||||
target: ["esnext"],
|
||||
external: ["electron", "original-fs", "~pluginNatives", ...commonOpts.external],
|
||||
define: defines,
|
||||
define: defines
|
||||
};
|
||||
|
||||
const sourceMapFooter = s => watch ? "" : `//# sourceMappingURL=vencord://${s}.js.map`;
|
||||
|
@ -73,23 +75,21 @@ const globNativesPlugin = {
|
|||
let i = 0;
|
||||
for (const dir of pluginDirs) {
|
||||
const dirPath = join("src", dir);
|
||||
if (!await existsAsync(dirPath)) continue;
|
||||
const plugins = await readdir(dirPath);
|
||||
for (const p of plugins) {
|
||||
const nativePath = join(dirPath, p, "native.ts");
|
||||
const indexNativePath = join(dirPath, p, "native/index.ts");
|
||||
if (!await exists(dirPath)) continue;
|
||||
const plugins = await readdir(dirPath, { withFileTypes: true });
|
||||
for (const file of plugins) {
|
||||
const fileName = file.name;
|
||||
const nativePath = join(dirPath, fileName, "native.ts");
|
||||
const indexNativePath = join(dirPath, fileName, "native/index.ts");
|
||||
|
||||
if (!(await existsAsync(nativePath)) && !(await existsAsync(indexNativePath)))
|
||||
if (!(await exists(nativePath)) && !(await exists(indexNativePath)))
|
||||
continue;
|
||||
|
||||
const nameParts = p.split(".");
|
||||
const namePartsWithoutTarget = nameParts.length === 1 ? nameParts : nameParts.slice(0, -1);
|
||||
// pluginName.thing.desktop -> PluginName.thing
|
||||
const cleanPluginName = p[0].toUpperCase() + namePartsWithoutTarget.join(".").slice(1);
|
||||
const pluginName = await resolvePluginName(dirPath, file);
|
||||
|
||||
const mod = `p${i}`;
|
||||
code += `import * as ${mod} from "./${dir}/${p}/native";\n`;
|
||||
natives += `${JSON.stringify(cleanPluginName)}:${mod},\n`;
|
||||
code += `import * as ${mod} from "./${dir}/${fileName}/native";\n`;
|
||||
natives += `${JSON.stringify(pluginName)}:${mod},\n`;
|
||||
i++;
|
||||
}
|
||||
}
|
||||
|
|
|
@ -23,7 +23,7 @@ import { appendFile, mkdir, readdir, readFile, rm, writeFile } from "fs/promises
|
|||
import { join } from "path";
|
||||
import Zip from "zip-local";
|
||||
|
||||
import { BUILD_TIMESTAMP, commonOpts, globPlugins, isDev, VERSION } from "./common.mjs";
|
||||
import { BUILD_TIMESTAMP, commonOpts, globPlugins, IS_DEV, IS_REPORTER, VERSION } from "./common.mjs";
|
||||
|
||||
/**
|
||||
* @type {esbuild.BuildOptions}
|
||||
|
@ -33,22 +33,23 @@ const commonOptions = {
|
|||
entryPoints: ["browser/Vencord.ts"],
|
||||
globalName: "Vencord",
|
||||
format: "iife",
|
||||
external: ["plugins", "git-hash", "/assets/*"],
|
||||
external: ["~plugins", "~git-hash", "/assets/*"],
|
||||
plugins: [
|
||||
globPlugins("web"),
|
||||
...commonOpts.plugins,
|
||||
],
|
||||
target: ["esnext"],
|
||||
define: {
|
||||
IS_WEB: "true",
|
||||
IS_EXTENSION: "false",
|
||||
IS_STANDALONE: "true",
|
||||
IS_DEV: JSON.stringify(isDev),
|
||||
IS_DISCORD_DESKTOP: "false",
|
||||
IS_VESKTOP: "false",
|
||||
IS_UPDATER_DISABLED: "true",
|
||||
IS_WEB: true,
|
||||
IS_EXTENSION: false,
|
||||
IS_STANDALONE: true,
|
||||
IS_DEV,
|
||||
IS_REPORTER,
|
||||
IS_DISCORD_DESKTOP: false,
|
||||
IS_VESKTOP: false,
|
||||
IS_UPDATER_DISABLED: true,
|
||||
VERSION: JSON.stringify(VERSION),
|
||||
BUILD_TIMESTAMP,
|
||||
BUILD_TIMESTAMP
|
||||
}
|
||||
};
|
||||
|
||||
|
@ -87,16 +88,16 @@ await Promise.all(
|
|||
esbuild.build({
|
||||
...commonOptions,
|
||||
outfile: "dist/browser.js",
|
||||
footer: { js: "//# sourceURL=VencordWeb" },
|
||||
footer: { js: "//# sourceURL=VencordWeb" }
|
||||
}),
|
||||
esbuild.build({
|
||||
...commonOptions,
|
||||
outfile: "dist/extension.js",
|
||||
define: {
|
||||
...commonOptions?.define,
|
||||
IS_EXTENSION: "true",
|
||||
IS_EXTENSION: true,
|
||||
},
|
||||
footer: { js: "//# sourceURL=VencordWeb" },
|
||||
footer: { js: "//# sourceURL=VencordWeb" }
|
||||
}),
|
||||
esbuild.build({
|
||||
...commonOptions,
|
||||
|
@ -112,7 +113,7 @@ await Promise.all(
|
|||
footer: {
|
||||
// UserScripts get wrapped in an iife, so define Vencord prop on window that returns our local
|
||||
js: "Object.defineProperty(unsafeWindow,'Vencord',{get:()=>Vencord});"
|
||||
},
|
||||
}
|
||||
})
|
||||
]
|
||||
);
|
||||
|
@ -165,7 +166,7 @@ async function buildExtension(target, files) {
|
|||
f.startsWith("manifest") ? "manifest.json" : f,
|
||||
content
|
||||
];
|
||||
}))),
|
||||
})))
|
||||
};
|
||||
|
||||
await rm(target, { recursive: true, force: true });
|
||||
|
@ -192,14 +193,19 @@ const appendCssRuntime = readFile("dist/Vencord.user.css", "utf-8").then(content
|
|||
return appendFile("dist/Vencord.user.js", cssRuntime);
|
||||
});
|
||||
|
||||
await Promise.all([
|
||||
if (!process.argv.includes("--skip-extension")) {
|
||||
await Promise.all([
|
||||
appendCssRuntime,
|
||||
buildExtension("chromium-unpacked", ["modifyResponseHeaders.json", "content.js", "manifest.json", "icon.png"]),
|
||||
buildExtension("firefox-unpacked", ["background.js", "content.js", "manifestv2.json", "icon.png"]),
|
||||
]);
|
||||
]);
|
||||
|
||||
Zip.sync.zip("dist/chromium-unpacked").compress().save("dist/extension-chrome.zip");
|
||||
console.info("Packed Chromium Extension written to dist/extension-chrome.zip");
|
||||
Zip.sync.zip("dist/chromium-unpacked").compress().save("dist/extension-chrome.zip");
|
||||
console.info("Packed Chromium Extension written to dist/extension-chrome.zip");
|
||||
|
||||
Zip.sync.zip("dist/firefox-unpacked").compress().save("dist/extension-firefox.zip");
|
||||
console.info("Packed Firefox Extension written to dist/extension-firefox.zip");
|
||||
Zip.sync.zip("dist/firefox-unpacked").compress().save("dist/extension-firefox.zip");
|
||||
console.info("Packed Firefox Extension written to dist/extension-firefox.zip");
|
||||
|
||||
} else {
|
||||
await appendCssRuntime;
|
||||
}
|
||||
|
|
|
@ -35,24 +35,52 @@ const PackageJSON = JSON.parse(readFileSync("package.json"));
|
|||
export const VERSION = PackageJSON.version;
|
||||
// https://reproducible-builds.org/docs/source-date-epoch/
|
||||
export const BUILD_TIMESTAMP = Number(process.env.SOURCE_DATE_EPOCH) || Date.now();
|
||||
|
||||
export const watch = process.argv.includes("--watch");
|
||||
export const isDev = watch || process.argv.includes("--dev");
|
||||
export const isStandalone = JSON.stringify(process.argv.includes("--standalone"));
|
||||
export const updaterDisabled = JSON.stringify(process.argv.includes("--disable-updater"));
|
||||
export const IS_DEV = watch || process.argv.includes("--dev");
|
||||
export const IS_REPORTER = process.argv.includes("--reporter");
|
||||
export const IS_STANDALONE = process.argv.includes("--standalone");
|
||||
|
||||
export const IS_UPDATER_DISABLED = process.argv.includes("--disable-updater");
|
||||
export const gitHash = process.env.VENCORD_HASH || execSync("git rev-parse --short HEAD", { encoding: "utf-8" }).trim();
|
||||
|
||||
export const banner = {
|
||||
js: `
|
||||
// Vencord ${gitHash}
|
||||
// Standalone: ${isStandalone}
|
||||
// Platform: ${isStandalone === "false" ? process.platform : "Universal"}
|
||||
// Updater disabled: ${updaterDisabled}
|
||||
// Standalone: ${IS_STANDALONE}
|
||||
// Platform: ${IS_STANDALONE === false ? process.platform : "Universal"}
|
||||
// Updater Disabled: ${IS_UPDATER_DISABLED}
|
||||
`.trim()
|
||||
};
|
||||
|
||||
const isWeb = process.argv.slice(0, 2).some(f => f.endsWith("buildWeb.mjs"));
|
||||
const PluginDefinitionNameMatcher = /definePlugin\(\{\s*(["'])?name\1:\s*(["'`])(.+?)\2/;
|
||||
/**
|
||||
* @param {string} base
|
||||
* @param {import("fs").Dirent} dirent
|
||||
*/
|
||||
export async function resolvePluginName(base, dirent) {
|
||||
const fullPath = join(base, dirent.name);
|
||||
const content = dirent.isFile()
|
||||
? await readFile(fullPath, "utf-8")
|
||||
: await (async () => {
|
||||
for (const file of ["index.ts", "index.tsx"]) {
|
||||
try {
|
||||
return await readFile(join(fullPath, file), "utf-8");
|
||||
} catch {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
throw new Error(`Invalid plugin ${fullPath}: could not resolve entry point`);
|
||||
})();
|
||||
|
||||
export function existsAsync(path) {
|
||||
return access(path, FsConstants.F_OK)
|
||||
return PluginDefinitionNameMatcher.exec(content)?.[3]
|
||||
?? (() => {
|
||||
throw new Error(`Invalid plugin ${fullPath}: must contain definePlugin call with simple string name property as first property`);
|
||||
})();
|
||||
}
|
||||
|
||||
export async function exists(path) {
|
||||
return await access(path, FsConstants.F_OK)
|
||||
.then(() => true)
|
||||
.catch(() => false);
|
||||
}
|
||||
|
@ -66,7 +94,7 @@ export const makeAllPackagesExternalPlugin = {
|
|||
setup(build) {
|
||||
const filter = /^[^./]|^\.[^./]|^\.\.[^/]/; // Must not start with "/" or "./" or "../"
|
||||
build.onResolve({ filter }, args => ({ path: args.path, external: true }));
|
||||
},
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
|
@ -86,31 +114,48 @@ export const globPlugins = kind => ({
|
|||
build.onLoad({ filter, namespace: "import-plugins" }, async () => {
|
||||
const pluginDirs = ["plugins/_api", "plugins/_core", "plugins", "userplugins"];
|
||||
let code = "";
|
||||
let plugins = "\n";
|
||||
let pluginsCode = "\n";
|
||||
let metaCode = "\n";
|
||||
let excludedCode = "\n";
|
||||
let i = 0;
|
||||
for (const dir of pluginDirs) {
|
||||
if (!await existsAsync(`./src/${dir}`)) continue;
|
||||
const files = await readdir(`./src/${dir}`);
|
||||
for (const file of files) {
|
||||
if (file.startsWith("_") || file.startsWith(".")) continue;
|
||||
if (file === "index.ts") continue;
|
||||
const userPlugin = dir === "userplugins";
|
||||
|
||||
const target = getPluginTarget(file);
|
||||
if (target) {
|
||||
if (target === "dev" && !watch) continue;
|
||||
if (target === "web" && kind === "discordDesktop") continue;
|
||||
if (target === "desktop" && kind === "web") continue;
|
||||
if (target === "discordDesktop" && kind !== "discordDesktop") continue;
|
||||
if (target === "vencordDesktop" && kind !== "vencordDesktop") continue;
|
||||
const fullDir = `./src/${dir}`;
|
||||
if (!await exists(fullDir)) continue;
|
||||
const files = await readdir(fullDir, { withFileTypes: true });
|
||||
for (const file of files) {
|
||||
const fileName = file.name;
|
||||
if (fileName.startsWith("_") || fileName.startsWith(".")) continue;
|
||||
if (fileName === "index.ts") continue;
|
||||
|
||||
const target = getPluginTarget(fileName);
|
||||
|
||||
if (target && !IS_REPORTER) {
|
||||
const excluded =
|
||||
(target === "dev" && !IS_DEV) ||
|
||||
(target === "web" && kind === "discordDesktop") ||
|
||||
(target === "desktop" && kind === "web") ||
|
||||
(target === "discordDesktop" && kind !== "discordDesktop") ||
|
||||
(target === "vencordDesktop" && kind !== "vencordDesktop");
|
||||
|
||||
if (excluded) {
|
||||
const name = await resolvePluginName(fullDir, file);
|
||||
excludedCode += `${JSON.stringify(name)}:${JSON.stringify(target)},\n`;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
const folderName = `src/${dir}/${fileName}`.replace(/^src\/plugins\//, "");
|
||||
|
||||
const mod = `p${i}`;
|
||||
code += `import ${mod} from "./${dir}/${file.replace(/\.tsx?$/, "")}";\n`;
|
||||
plugins += `[${mod}.name]:${mod},\n`;
|
||||
code += `import ${mod} from "./${dir}/${fileName.replace(/\.tsx?$/, "")}";\n`;
|
||||
pluginsCode += `[${mod}.name]:${mod},\n`;
|
||||
metaCode += `[${mod}.name]:${JSON.stringify({ folderName, userPlugin })},\n`; // TODO: add excluded plugins to display in the UI?
|
||||
i++;
|
||||
}
|
||||
}
|
||||
code += `export default {${plugins}};`;
|
||||
code += `export default {${pluginsCode}};export const PluginMeta={${metaCode}};export const ExcludedPlugins={${excludedCode}};`;
|
||||
return {
|
||||
contents: code,
|
||||
resolveDir: "./src"
|
||||
|
@ -178,7 +223,7 @@ export const fileUrlPlugin = {
|
|||
build.onLoad({ filter, namespace: "file-uri" }, async ({ pluginData: { path, uri } }) => {
|
||||
const { searchParams } = new URL(uri);
|
||||
const base64 = searchParams.has("base64");
|
||||
const minify = isStandalone === "true" && searchParams.has("minify");
|
||||
const minify = IS_STANDALONE === true && searchParams.has("minify");
|
||||
const noTrim = searchParams.get("trim") === "false";
|
||||
|
||||
const encoding = base64 ? "base64" : "utf-8";
|
||||
|
|
|
@ -39,7 +39,7 @@ interface PluginData {
|
|||
hasCommands: boolean;
|
||||
required: boolean;
|
||||
enabledByDefault: boolean;
|
||||
target: "discordDesktop" | "vencordDesktop" | "web" | "dev";
|
||||
target: "discordDesktop" | "vencordDesktop" | "desktop" | "web" | "dev";
|
||||
filePath: string;
|
||||
}
|
||||
|
||||
|
|
|
@ -16,6 +16,8 @@
|
|||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
/* eslint-disable no-fallthrough */
|
||||
|
||||
// eslint-disable-next-line spaced-comment
|
||||
/// <reference types="../src/globals" />
|
||||
// eslint-disable-next-line spaced-comment
|
||||
|
@ -40,10 +42,12 @@ const browser = await pup.launch({
|
|||
|
||||
const page = await browser.newPage();
|
||||
await page.setUserAgent("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.0.0 Safari/537.36");
|
||||
await page.setBypassCSP(true);
|
||||
|
||||
function maybeGetError(handle: JSHandle) {
|
||||
return (handle as JSHandle<Error>)?.getProperty("message")
|
||||
.then(m => m.jsonValue());
|
||||
async function maybeGetError(handle: JSHandle): Promise<string | undefined> {
|
||||
return await (handle as JSHandle<Error>)?.getProperty("message")
|
||||
.then(m => m?.jsonValue())
|
||||
.catch(() => undefined);
|
||||
}
|
||||
|
||||
const report = {
|
||||
|
@ -59,6 +63,7 @@ const report = {
|
|||
error: string;
|
||||
}[],
|
||||
otherErrors: [] as string[],
|
||||
ignoredErrors: [] as string[],
|
||||
badWebpackFinds: [] as string[]
|
||||
};
|
||||
|
||||
|
@ -71,9 +76,11 @@ const IGNORED_DISCORD_ERRORS = [
|
|||
"Attempting to set fast connect zstd when unsupported"
|
||||
] as Array<string | RegExp>;
|
||||
|
||||
function toCodeBlock(s: string) {
|
||||
function toCodeBlock(s: string, indentation = 0, isDiscord = false) {
|
||||
s = s.replace(/```/g, "`\u200B`\u200B`");
|
||||
return "```" + s + " ```";
|
||||
|
||||
const indentationStr = Array(!isDiscord ? indentation : 0).fill(" ").join("");
|
||||
return `\`\`\`\n${s.split("\n").map(s => indentationStr + s).join("\n")}\n${indentationStr}\`\`\``;
|
||||
}
|
||||
|
||||
async function printReport() {
|
||||
|
@ -87,44 +94,35 @@ async function printReport() {
|
|||
report.badPatches.forEach(p => {
|
||||
console.log(`- ${p.plugin} (${p.type})`);
|
||||
console.log(` - ID: \`${p.id}\``);
|
||||
console.log(` - Match: ${toCodeBlock(p.match)}`);
|
||||
if (p.error) console.log(` - Error: ${toCodeBlock(p.error)}`);
|
||||
console.log(` - Match: ${toCodeBlock(p.match, " - Match: ".length)}`);
|
||||
if (p.error) console.log(` - Error: ${toCodeBlock(p.error, " - Error: ".length)}`);
|
||||
});
|
||||
|
||||
console.log();
|
||||
|
||||
console.log("## Bad Webpack Finds");
|
||||
report.badWebpackFinds.forEach(p => console.log("- " + p));
|
||||
report.badWebpackFinds.forEach(p => console.log("- " + toCodeBlock(p, "- ".length)));
|
||||
|
||||
console.log();
|
||||
|
||||
console.log("## Bad Starts");
|
||||
report.badStarts.forEach(p => {
|
||||
console.log(`- ${p.plugin}`);
|
||||
console.log(` - Error: ${toCodeBlock(p.error)}`);
|
||||
console.log(` - Error: ${toCodeBlock(p.error, " - Error: ".length)}`);
|
||||
});
|
||||
|
||||
console.log();
|
||||
|
||||
const ignoredErrors = [] as string[];
|
||||
report.otherErrors = report.otherErrors.filter(e => {
|
||||
if (IGNORED_DISCORD_ERRORS.some(regex => e.match(regex))) {
|
||||
ignoredErrors.push(e);
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
});
|
||||
|
||||
console.log("## Discord Errors");
|
||||
report.otherErrors.forEach(e => {
|
||||
console.log(`- ${toCodeBlock(e)}`);
|
||||
console.log(`- ${toCodeBlock(e, "- ".length)}`);
|
||||
});
|
||||
|
||||
console.log();
|
||||
|
||||
console.log("## Ignored Discord Errors");
|
||||
ignoredErrors.forEach(e => {
|
||||
console.log(`- ${toCodeBlock(e)}`);
|
||||
report.ignoredErrors.forEach(e => {
|
||||
console.log(`- ${toCodeBlock(e, "- ".length)}`);
|
||||
});
|
||||
|
||||
console.log();
|
||||
|
@ -146,16 +144,16 @@ async function printReport() {
|
|||
const lines = [
|
||||
`**__${p.plugin} (${p.type}):__**`,
|
||||
`ID: \`${p.id}\``,
|
||||
`Match: ${toCodeBlock(p.match)}`
|
||||
`Match: ${toCodeBlock(p.match, "Match: ".length, true)}`
|
||||
];
|
||||
if (p.error) lines.push(`Error: ${toCodeBlock(p.error)}`);
|
||||
if (p.error) lines.push(`Error: ${toCodeBlock(p.error, "Error: ".length, true)}`);
|
||||
return lines.join("\n");
|
||||
}).join("\n\n") || "None",
|
||||
color: report.badPatches.length ? 0xff0000 : 0x00ff00
|
||||
},
|
||||
{
|
||||
title: "Bad Webpack Finds",
|
||||
description: report.badWebpackFinds.map(toCodeBlock).join("\n") || "None",
|
||||
description: report.badWebpackFinds.map(f => toCodeBlock(f, 0, true)).join("\n") || "None",
|
||||
color: report.badWebpackFinds.length ? 0xff0000 : 0x00ff00
|
||||
},
|
||||
{
|
||||
|
@ -163,7 +161,7 @@ async function printReport() {
|
|||
description: report.badStarts.map(p => {
|
||||
const lines = [
|
||||
`**__${p.plugin}:__**`,
|
||||
toCodeBlock(p.error)
|
||||
toCodeBlock(p.error, 0, true)
|
||||
];
|
||||
return lines.join("\n");
|
||||
}
|
||||
|
@ -172,7 +170,7 @@ async function printReport() {
|
|||
},
|
||||
{
|
||||
title: "Discord Errors",
|
||||
description: report.otherErrors.length ? toCodeBlock(report.otherErrors.join("\n")) : "None",
|
||||
description: report.otherErrors.length ? toCodeBlock(report.otherErrors.join("\n"), 0, true) : "None",
|
||||
color: report.otherErrors.length ? 0xff0000 : 0x00ff00
|
||||
}
|
||||
]
|
||||
|
@ -188,61 +186,6 @@ page.on("console", async e => {
|
|||
const level = e.type();
|
||||
const rawArgs = e.args();
|
||||
|
||||
const firstArg = await rawArgs[0]?.jsonValue();
|
||||
if (firstArg === "[PUPPETEER_TEST_DONE_SIGNAL]") {
|
||||
await browser.close();
|
||||
await printReport();
|
||||
process.exit();
|
||||
}
|
||||
|
||||
const isVencord = firstArg === "[Vencord]";
|
||||
const isDebug = firstArg === "[PUP_DEBUG]";
|
||||
const isWebpackFindFail = firstArg === "[PUP_WEBPACK_FIND_FAIL]";
|
||||
|
||||
if (isWebpackFindFail) {
|
||||
process.exitCode = 1;
|
||||
report.badWebpackFinds.push(await rawArgs[1].jsonValue() as string);
|
||||
}
|
||||
|
||||
if (isVencord) {
|
||||
const args = await Promise.all(e.args().map(a => a.jsonValue()));
|
||||
|
||||
const [, tag, message] = args as Array<string>;
|
||||
const cause = await maybeGetError(e.args()[3]);
|
||||
|
||||
switch (tag) {
|
||||
case "WebpackInterceptor:":
|
||||
const patchFailMatch = message.match(/Patch by (.+?) (had no effect|errored|found no module) \(Module id is (.+?)\): (.+)/)!;
|
||||
if (!patchFailMatch) break;
|
||||
|
||||
process.exitCode = 1;
|
||||
|
||||
const [, plugin, type, id, regex] = patchFailMatch;
|
||||
report.badPatches.push({
|
||||
plugin,
|
||||
type,
|
||||
id,
|
||||
match: regex.replace(/\[A-Za-z_\$\]\[\\w\$\]\*/g, "\\i"),
|
||||
error: cause
|
||||
});
|
||||
|
||||
break;
|
||||
case "PluginManager:":
|
||||
const failedToStartMatch = message.match(/Failed to start (.+)/);
|
||||
if (!failedToStartMatch) break;
|
||||
|
||||
process.exitCode = 1;
|
||||
|
||||
const [, name] = failedToStartMatch;
|
||||
report.badStarts.push({
|
||||
plugin: name,
|
||||
error: cause
|
||||
});
|
||||
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
async function getText() {
|
||||
try {
|
||||
return await Promise.all(
|
||||
|
@ -255,174 +198,107 @@ page.on("console", async e => {
|
|||
}
|
||||
}
|
||||
|
||||
if (isDebug) {
|
||||
const text = await getText();
|
||||
const firstArg = await rawArgs[0]?.jsonValue();
|
||||
|
||||
console.error(text);
|
||||
if (text.includes("A fatal error occurred:")) {
|
||||
const isVencord = firstArg === "[Vencord]";
|
||||
const isDebug = firstArg === "[PUP_DEBUG]";
|
||||
|
||||
outer:
|
||||
if (isVencord) {
|
||||
try {
|
||||
var args = await Promise.all(e.args().map(a => a.jsonValue()));
|
||||
} catch {
|
||||
break outer;
|
||||
}
|
||||
|
||||
const [, tag, message, otherMessage] = args as Array<string>;
|
||||
|
||||
switch (tag) {
|
||||
case "WebpackInterceptor:":
|
||||
const patchFailMatch = message.match(/Patch by (.+?) (had no effect|errored|found no module) \(Module id is (.+?)\): (.+)/)!;
|
||||
if (!patchFailMatch) break;
|
||||
|
||||
console.error(await getText());
|
||||
process.exitCode = 1;
|
||||
|
||||
const [, plugin, type, id, regex] = patchFailMatch;
|
||||
report.badPatches.push({
|
||||
plugin,
|
||||
type,
|
||||
id,
|
||||
match: regex.replace(/\[A-Za-z_\$\]\[\\w\$\]\*/g, "\\i"),
|
||||
error: await maybeGetError(e.args()[3])
|
||||
});
|
||||
|
||||
break;
|
||||
case "PluginManager:":
|
||||
const failedToStartMatch = message.match(/Failed to start (.+)/);
|
||||
if (!failedToStartMatch) break;
|
||||
|
||||
console.error(await getText());
|
||||
process.exitCode = 1;
|
||||
|
||||
const [, name] = failedToStartMatch;
|
||||
report.badStarts.push({
|
||||
plugin: name,
|
||||
error: await maybeGetError(e.args()[3]) ?? "Unknown error"
|
||||
});
|
||||
|
||||
break;
|
||||
case "LazyChunkLoader:":
|
||||
console.error(await getText());
|
||||
|
||||
switch (message) {
|
||||
case "A fatal error occurred:":
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
break;
|
||||
case "Reporter:":
|
||||
console.error(await getText());
|
||||
|
||||
switch (message) {
|
||||
case "A fatal error occurred:":
|
||||
process.exit(1);
|
||||
case "Webpack Find Fail:":
|
||||
process.exitCode = 1;
|
||||
report.badWebpackFinds.push(otherMessage);
|
||||
break;
|
||||
case "Finished test":
|
||||
await browser.close();
|
||||
await printReport();
|
||||
process.exit();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (isDebug) {
|
||||
console.error(await getText());
|
||||
} else if (level === "error") {
|
||||
const text = await getText();
|
||||
|
||||
if (text.length && !text.startsWith("Failed to load resource: the server responded with a status of") && !text.includes("Webpack")) {
|
||||
if (IGNORED_DISCORD_ERRORS.some(regex => text.match(regex))) {
|
||||
report.ignoredErrors.push(text);
|
||||
} else {
|
||||
console.error("[Unexpected Error]", text);
|
||||
report.otherErrors.push(text);
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
page.on("error", e => console.error("[Error]", e));
|
||||
page.on("pageerror", e => console.error("[Page Error]", e));
|
||||
|
||||
await page.setBypassCSP(true);
|
||||
|
||||
async function runtime(token: string) {
|
||||
console.log("[PUP_DEBUG]", "Starting test...");
|
||||
|
||||
try {
|
||||
// Spoof languages to not be suspicious
|
||||
Object.defineProperty(navigator, "languages", {
|
||||
get: function () {
|
||||
return ["en-US", "en"];
|
||||
},
|
||||
});
|
||||
|
||||
// Monkey patch Logger to not log with custom css
|
||||
// @ts-ignore
|
||||
const originalLog = Vencord.Util.Logger.prototype._log;
|
||||
// @ts-ignore
|
||||
Vencord.Util.Logger.prototype._log = function (level, levelColor, args) {
|
||||
if (level === "warn" || level === "error")
|
||||
return console[level]("[Vencord]", this.name + ":", ...args);
|
||||
|
||||
return originalLog.call(this, level, levelColor, args);
|
||||
};
|
||||
|
||||
// Force enable all plugins and patches
|
||||
Vencord.Plugins.patches.length = 0;
|
||||
Object.values(Vencord.Plugins.plugins).forEach(p => {
|
||||
// Needs native server to run
|
||||
if (p.name === "WebRichPresence (arRPC)") return;
|
||||
|
||||
Vencord.Settings.plugins[p.name].enabled = true;
|
||||
p.patches?.forEach(patch => {
|
||||
patch.plugin = p.name;
|
||||
delete patch.predicate;
|
||||
delete patch.group;
|
||||
|
||||
Vencord.Util.canonicalizeFind(patch);
|
||||
if (!Array.isArray(patch.replacement)) {
|
||||
patch.replacement = [patch.replacement];
|
||||
}
|
||||
|
||||
patch.replacement.forEach(r => {
|
||||
delete r.predicate;
|
||||
});
|
||||
|
||||
Vencord.Plugins.patches.push(patch);
|
||||
});
|
||||
});
|
||||
|
||||
let wreq: typeof Vencord.Webpack.wreq;
|
||||
|
||||
const { canonicalizeMatch, Logger } = Vencord.Util;
|
||||
|
||||
const validChunks = new Set<string>();
|
||||
const invalidChunks = new Set<string>();
|
||||
const deferredRequires = new Set<string>();
|
||||
|
||||
let chunksSearchingResolve: (value: void | PromiseLike<void>) => void;
|
||||
const chunksSearchingDone = new Promise<void>(r => chunksSearchingResolve = r);
|
||||
|
||||
// True if resolved, false otherwise
|
||||
const chunksSearchPromises = [] as Array<() => boolean>;
|
||||
|
||||
const LazyChunkRegex = canonicalizeMatch(/(?:Promise\.all\(\[(\i\.\i\("[^)]+?"\)[^\]]+?)\]\)|(\i\.\i\("[^)]+?"\)))\.then\(\i\.bind\(\i,"([^)]+?)"\)\)/g);
|
||||
|
||||
async function searchAndLoadLazyChunks(factoryCode: string) {
|
||||
const lazyChunks = factoryCode.matchAll(LazyChunkRegex);
|
||||
const validChunkGroups = new Set<[chunkIds: string[], entryPoint: string]>();
|
||||
|
||||
// Workaround for a chunk that depends on the ChannelMessage component but may be be force loaded before
|
||||
// the chunk containing the component
|
||||
const shouldForceDefer = factoryCode.includes(".Messages.GUILD_FEED_UNFEATURE_BUTTON_TEXT");
|
||||
|
||||
await Promise.all(Array.from(lazyChunks).map(async ([, rawChunkIdsArray, rawChunkIdsSingle, entryPoint]) => {
|
||||
const rawChunkIds = rawChunkIdsArray ?? rawChunkIdsSingle;
|
||||
const chunkIds = rawChunkIds ? Array.from(rawChunkIds.matchAll(Vencord.Webpack.ChunkIdsRegex)).map(m => m[1]) : [];
|
||||
|
||||
if (chunkIds.length === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
let invalidChunkGroup = false;
|
||||
|
||||
for (const id of chunkIds) {
|
||||
if (wreq.u(id) == null || wreq.u(id) === "undefined.js") continue;
|
||||
|
||||
const isWasm = await fetch(wreq.p + wreq.u(id))
|
||||
.then(r => r.text())
|
||||
.then(t => t.includes(".module.wasm") || !t.includes("(this.webpackChunkdiscord_app=this.webpackChunkdiscord_app||[]).push"));
|
||||
|
||||
if (isWasm) {
|
||||
invalidChunks.add(id);
|
||||
invalidChunkGroup = true;
|
||||
continue;
|
||||
}
|
||||
|
||||
validChunks.add(id);
|
||||
}
|
||||
|
||||
if (!invalidChunkGroup) {
|
||||
validChunkGroups.add([chunkIds, entryPoint]);
|
||||
}
|
||||
}));
|
||||
|
||||
// Loads all found valid chunk groups
|
||||
await Promise.all(
|
||||
Array.from(validChunkGroups)
|
||||
.map(([chunkIds]) =>
|
||||
Promise.all(chunkIds.map(id => wreq.e(id as any).catch(() => { })))
|
||||
)
|
||||
);
|
||||
|
||||
// Requires the entry points for all valid chunk groups
|
||||
for (const [, entryPoint] of validChunkGroups) {
|
||||
try {
|
||||
if (shouldForceDefer) {
|
||||
deferredRequires.add(entryPoint);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (wreq.m[entryPoint]) wreq(entryPoint as any);
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
}
|
||||
}
|
||||
|
||||
// setImmediate to only check if all chunks were loaded after this function resolves
|
||||
// We check if all chunks were loaded every time a factory is loaded
|
||||
// If we are still looking for chunks in the other factories, the array will have that factory's chunk search promise not resolved
|
||||
// But, if all chunk search promises are resolved, this means we found every lazy chunk loaded by Discord code and manually loaded them
|
||||
setTimeout(() => {
|
||||
let allResolved = true;
|
||||
|
||||
for (let i = 0; i < chunksSearchPromises.length; i++) {
|
||||
const isResolved = chunksSearchPromises[i]();
|
||||
|
||||
if (isResolved) {
|
||||
// Remove finished promises to avoid having to iterate through a huge array everytime
|
||||
chunksSearchPromises.splice(i--, 1);
|
||||
page.on("error", e => console.error("[Error]", e.message));
|
||||
page.on("pageerror", e => {
|
||||
if (!e.message.startsWith("Object") && !e.message.includes("Cannot find module")) {
|
||||
console.error("[Page Error]", e.message);
|
||||
report.otherErrors.push(e.message);
|
||||
} else {
|
||||
allResolved = false;
|
||||
}
|
||||
}
|
||||
|
||||
if (allResolved) chunksSearchingResolve();
|
||||
}, 0);
|
||||
report.ignoredErrors.push(e.message);
|
||||
}
|
||||
});
|
||||
|
||||
async function reporterRuntime(token: string) {
|
||||
Vencord.Webpack.waitFor(
|
||||
"loginToken",
|
||||
m => {
|
||||
|
@ -430,124 +306,13 @@ async function runtime(token: string) {
|
|||
m.loginToken(token);
|
||||
}
|
||||
);
|
||||
|
||||
Vencord.Webpack.beforeInitListeners.add(async webpackRequire => {
|
||||
console.log("[PUP_DEBUG]", "Loading all chunks...");
|
||||
|
||||
wreq = webpackRequire;
|
||||
|
||||
Vencord.Webpack.factoryListeners.add(factory => {
|
||||
let isResolved = false;
|
||||
searchAndLoadLazyChunks(factory.toString()).then(() => isResolved = true);
|
||||
|
||||
chunksSearchPromises.push(() => isResolved);
|
||||
});
|
||||
|
||||
// setImmediate to only search the initial factories after Discord initialized the app
|
||||
// our beforeInitListeners are called before Discord initializes the app
|
||||
setTimeout(() => {
|
||||
for (const factoryId in wreq.m) {
|
||||
let isResolved = false;
|
||||
searchAndLoadLazyChunks(wreq.m[factoryId].toString()).then(() => isResolved = true);
|
||||
|
||||
chunksSearchPromises.push(() => isResolved);
|
||||
}
|
||||
}, 0);
|
||||
});
|
||||
|
||||
await chunksSearchingDone;
|
||||
|
||||
// Require deferred entry points
|
||||
for (const deferredRequire of deferredRequires) {
|
||||
wreq!(deferredRequire as any);
|
||||
}
|
||||
|
||||
// All chunks Discord has mapped to asset files, even if they are not used anymore
|
||||
const allChunks = [] as string[];
|
||||
|
||||
// Matches "id" or id:
|
||||
for (const currentMatch of wreq!.u.toString().matchAll(/(?:"(\d+?)")|(?:(\d+?):)/g)) {
|
||||
const id = currentMatch[1] ?? currentMatch[2];
|
||||
if (id == null) continue;
|
||||
|
||||
allChunks.push(id);
|
||||
}
|
||||
|
||||
if (allChunks.length === 0) throw new Error("Failed to get all chunks");
|
||||
|
||||
// Chunks that are not loaded (not used) by Discord code anymore
|
||||
const chunksLeft = allChunks.filter(id => {
|
||||
return !(validChunks.has(id) || invalidChunks.has(id));
|
||||
});
|
||||
|
||||
await Promise.all(chunksLeft.map(async id => {
|
||||
const isWasm = await fetch(wreq.p + wreq.u(id))
|
||||
.then(r => r.text())
|
||||
.then(t => t.includes(".module.wasm") || !t.includes("(this.webpackChunkdiscord_app=this.webpackChunkdiscord_app||[]).push"));
|
||||
|
||||
// Loads and requires a chunk
|
||||
if (!isWasm) {
|
||||
await wreq.e(id as any);
|
||||
if (wreq.m[id]) wreq(id as any);
|
||||
}
|
||||
}));
|
||||
|
||||
console.log("[PUP_DEBUG]", "Finished loading all chunks!");
|
||||
|
||||
for (const patch of Vencord.Plugins.patches) {
|
||||
if (!patch.all) {
|
||||
new Logger("WebpackInterceptor").warn(`Patch by ${patch.plugin} found no module (Module id is -): ${patch.find}`);
|
||||
}
|
||||
}
|
||||
|
||||
for (const [searchType, args] of Vencord.Webpack.lazyWebpackSearchHistory) {
|
||||
let method = searchType;
|
||||
|
||||
if (searchType === "findComponent") method = "find";
|
||||
if (searchType === "findExportedComponent") method = "findByProps";
|
||||
if (searchType === "waitFor" || searchType === "waitForComponent") {
|
||||
if (typeof args[0] === "string") method = "findByProps";
|
||||
else method = "find";
|
||||
}
|
||||
if (searchType === "waitForStore") method = "findStore";
|
||||
|
||||
try {
|
||||
let result: any;
|
||||
|
||||
if (method === "proxyLazyWebpack" || method === "LazyComponentWebpack") {
|
||||
const [factory] = args;
|
||||
result = factory();
|
||||
} else if (method === "extractAndLoadChunks") {
|
||||
const [code, matcher] = args;
|
||||
|
||||
const module = Vencord.Webpack.findModuleFactory(...code);
|
||||
if (module) result = module.toString().match(canonicalizeMatch(matcher));
|
||||
} else {
|
||||
// @ts-ignore
|
||||
result = Vencord.Webpack[method](...args);
|
||||
}
|
||||
|
||||
if (result == null || ("$$vencordInternal" in result && result.$$vencordInternal() == null)) throw "a rock at ben shapiro";
|
||||
} catch (e) {
|
||||
let logMessage = searchType;
|
||||
if (method === "find" || method === "proxyLazyWebpack" || method === "LazyComponentWebpack") logMessage += `(${args[0].toString().slice(0, 147)}...)`;
|
||||
else if (method === "extractAndLoadChunks") logMessage += `([${args[0].map(arg => `"${arg}"`).join(", ")}], ${args[1].toString()})`;
|
||||
else logMessage += `(${args.map(arg => `"${arg}"`).join(", ")})`;
|
||||
|
||||
console.log("[PUP_WEBPACK_FIND_FAIL]", logMessage);
|
||||
}
|
||||
}
|
||||
|
||||
setTimeout(() => console.log("[PUPPETEER_TEST_DONE_SIGNAL]"), 1000);
|
||||
} catch (e) {
|
||||
console.log("[PUP_DEBUG]", "A fatal error occurred:", e);
|
||||
}
|
||||
}
|
||||
|
||||
await page.evaluateOnNewDocument(`
|
||||
${readFileSync("./dist/browser.js", "utf-8")}
|
||||
|
||||
;(${runtime.toString()})(${JSON.stringify(process.env.DISCORD_TOKEN)});
|
||||
if (location.host.endsWith("discord.com")) {
|
||||
${readFileSync("./dist/browser.js", "utf-8")};
|
||||
(${reporterRuntime.toString()})(${JSON.stringify(process.env.DISCORD_TOKEN)});
|
||||
}
|
||||
`);
|
||||
|
||||
await page.goto(CANARY ? "https://canary.discord.com/login" : "https://discord.com/login");
|
||||
|
|
|
@ -42,6 +42,10 @@ import { checkForUpdates, update, UpdateLogger } from "./utils/updater";
|
|||
import { onceReady } from "./webpack";
|
||||
import { SettingsRouter } from "./webpack/common";
|
||||
|
||||
if (IS_REPORTER) {
|
||||
require("./debug/runReporter");
|
||||
}
|
||||
|
||||
async function syncSettings() {
|
||||
// pre-check for local shared settings
|
||||
if (
|
||||
|
|
|
@ -17,7 +17,6 @@
|
|||
*/
|
||||
|
||||
import ErrorBoundary from "@components/ErrorBoundary";
|
||||
import { User } from "discord-types/general";
|
||||
import { ComponentType, HTMLProps } from "react";
|
||||
|
||||
import Plugins from "~plugins";
|
||||
|
@ -79,14 +78,14 @@ export function _getBadges(args: BadgeUserArgs) {
|
|||
: badges.push({ ...badge, ...args });
|
||||
}
|
||||
}
|
||||
const donorBadges = (Plugins.BadgeAPI as unknown as typeof import("../plugins/_api/badges").default).getDonorBadges(args.user.id);
|
||||
const donorBadges = (Plugins.BadgeAPI as unknown as typeof import("../plugins/_api/badges").default).getDonorBadges(args.userId);
|
||||
if (donorBadges) badges.unshift(...donorBadges);
|
||||
|
||||
return badges;
|
||||
}
|
||||
|
||||
export interface BadgeUserArgs {
|
||||
user: User;
|
||||
userId: string;
|
||||
guildId: string;
|
||||
}
|
||||
|
||||
|
|
|
@ -17,14 +17,14 @@
|
|||
*/
|
||||
|
||||
import { mergeDefaults } from "@utils/mergeDefaults";
|
||||
import { findByPropsLazy } from "@webpack";
|
||||
import { findByCodeLazy } from "@webpack";
|
||||
import { MessageActions, SnowflakeUtils } from "@webpack/common";
|
||||
import { Message } from "discord-types/general";
|
||||
import type { PartialDeep } from "type-fest";
|
||||
|
||||
import { Argument } from "./types";
|
||||
|
||||
const MessageCreator = findByPropsLazy("createBotMessage");
|
||||
const createBotMessage = findByCodeLazy('username:"Clyde"');
|
||||
|
||||
export function generateId() {
|
||||
return `-${SnowflakeUtils.fromTimestamp(Date.now())}`;
|
||||
|
@ -37,7 +37,7 @@ export function generateId() {
|
|||
* @returns {Message}
|
||||
*/
|
||||
export function sendBotMessage(channelId: string, message: PartialDeep<Message>): Message {
|
||||
const botMessage = MessageCreator.createBotMessage({ channelId, content: "", embeds: [] });
|
||||
const botMessage = createBotMessage({ channelId, content: "", embeds: [] });
|
||||
|
||||
MessageActions.receiveMessage(channelId, mergeDefaults(message, botMessage));
|
||||
|
||||
|
|
|
@ -49,7 +49,7 @@ let defaultGetStoreFunc: UseStore | undefined;
|
|||
|
||||
function defaultGetStore() {
|
||||
if (!defaultGetStoreFunc) {
|
||||
defaultGetStoreFunc = createStore("VencordData", "VencordStore");
|
||||
defaultGetStoreFunc = createStore(!IS_REPORTER ? "VencordData" : "VencordDataReporter", "VencordStore");
|
||||
}
|
||||
return defaultGetStoreFunc;
|
||||
}
|
||||
|
|
29
src/api/MessageUpdater.ts
Normal file
29
src/api/MessageUpdater.ts
Normal file
|
@ -0,0 +1,29 @@
|
|||
/*
|
||||
* Vencord, a Discord client mod
|
||||
* Copyright (c) 2024 Vendicated and contributors
|
||||
* SPDX-License-Identifier: GPL-3.0-or-later
|
||||
*/
|
||||
|
||||
import { MessageCache, MessageStore } from "@webpack/common";
|
||||
import { FluxStore } from "@webpack/types";
|
||||
import { Message } from "discord-types/general";
|
||||
|
||||
/**
|
||||
* Update and re-render a message
|
||||
* @param channelId The channel id of the message
|
||||
* @param messageId The message id
|
||||
* @param fields The fields of the message to change. Leave empty if you just want to re-render
|
||||
*/
|
||||
export function updateMessage(channelId: string, messageId: string, fields?: Partial<Message & Record<string, any>>) {
|
||||
const channelMessageCache = MessageCache.getOrCreate(channelId);
|
||||
if (!channelMessageCache.has(messageId)) return;
|
||||
|
||||
// To cause a message to re-render, we basically need to create a new instance of the message and obtain a new reference
|
||||
// If we have fields to modify we can use the merge method of the class, otherwise we just create a new instance with the old fields
|
||||
const newChannelMessageCache = channelMessageCache.update(messageId, (oldMessage: any) => {
|
||||
return fields ? oldMessage.merge(fields) : new oldMessage.constructor(oldMessage);
|
||||
});
|
||||
|
||||
MessageCache.commit(newChannelMessageCache);
|
||||
(MessageStore as unknown as FluxStore).emitChange();
|
||||
}
|
|
@ -113,7 +113,7 @@ export default ErrorBoundary.wrap(function NotificationComponent({
|
|||
{timeout !== 0 && !permanent && (
|
||||
<div
|
||||
className="vc-notification-progressbar"
|
||||
style={{ width: `${(1 - timeoutProgress) * 100}%`, backgroundColor: color || "var(--brand-experiment)" }}
|
||||
style={{ width: `${(1 - timeoutProgress) * 100}%`, backgroundColor: color || "var(--brand-500)" }}
|
||||
/>
|
||||
)}
|
||||
</button>
|
||||
|
|
|
@ -106,7 +106,7 @@ const DefaultSettings: Settings = {
|
|||
}
|
||||
};
|
||||
|
||||
const settings = VencordNative.settings.get();
|
||||
const settings = !IS_REPORTER ? VencordNative.settings.get() : {} as Settings;
|
||||
mergeDefaults(settings, DefaultSettings);
|
||||
|
||||
const saveSettingsOnFrequentAction = debounce(async () => {
|
||||
|
@ -129,7 +129,7 @@ export const SettingsStore = new SettingsStoreClass(settings, {
|
|||
|
||||
if (path === "plugins" && key in plugins)
|
||||
return target[key] = {
|
||||
enabled: plugins[key].required ?? plugins[key].enabledByDefault ?? false
|
||||
enabled: IS_REPORTER ?? plugins[key].required ?? plugins[key].enabledByDefault ?? false
|
||||
};
|
||||
|
||||
// Since the property is not set, check if this is a plugin's setting and if so, try to resolve
|
||||
|
@ -156,12 +156,14 @@ export const SettingsStore = new SettingsStoreClass(settings, {
|
|||
}
|
||||
});
|
||||
|
||||
SettingsStore.addGlobalChangeListener((_, path) => {
|
||||
if (!IS_REPORTER) {
|
||||
SettingsStore.addGlobalChangeListener((_, path) => {
|
||||
SettingsStore.plain.cloud.settingsSyncVersion = Date.now();
|
||||
localStorage.Vencord_settingsDirty = true;
|
||||
saveSettingsOnFrequentAction();
|
||||
VencordNative.settings.set(SettingsStore.plain, path);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Same as {@link Settings} but unproxied. You should treat this as readonly,
|
||||
|
|
81
src/api/UserSettings.ts
Normal file
81
src/api/UserSettings.ts
Normal file
|
@ -0,0 +1,81 @@
|
|||
/*
|
||||
* Vencord, a modification for Discord's desktop app
|
||||
* Copyright (c) 2023 Vendicated and contributors
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
import { proxyLazy } from "@utils/lazy";
|
||||
import { Logger } from "@utils/Logger";
|
||||
import { findModuleId, proxyLazyWebpack, wreq } from "@webpack";
|
||||
|
||||
interface UserSettingDefinition<T> {
|
||||
/**
|
||||
* Get the setting value
|
||||
*/
|
||||
getSetting(): T;
|
||||
/**
|
||||
* Update the setting value
|
||||
* @param value The new value
|
||||
*/
|
||||
updateSetting(value: T): Promise<void>;
|
||||
/**
|
||||
* Update the setting value
|
||||
* @param value A callback that accepts the old value as the first argument, and returns the new value
|
||||
*/
|
||||
updateSetting(value: (old: T) => T): Promise<void>;
|
||||
/**
|
||||
* Stateful React hook for this setting value
|
||||
*/
|
||||
useSetting(): T;
|
||||
userSettingsAPIGroup: string;
|
||||
userSettingsAPIName: string;
|
||||
}
|
||||
|
||||
export const UserSettings: Record<PropertyKey, UserSettingDefinition<any>> | undefined = proxyLazyWebpack(() => {
|
||||
const modId = findModuleId('"textAndImages","renderSpoilers"');
|
||||
if (modId == null) return new Logger("UserSettingsAPI ").error("Didn't find settings module.");
|
||||
|
||||
return wreq(modId as any);
|
||||
});
|
||||
|
||||
/**
|
||||
* Get the setting with the given setting group and name.
|
||||
*
|
||||
* @param group The setting group
|
||||
* @param name The name of the setting
|
||||
*/
|
||||
export function getUserSetting<T = any>(group: string, name: string): UserSettingDefinition<T> | undefined {
|
||||
if (!Vencord.Plugins.isPluginEnabled("UserSettingsAPI")) throw new Error("Cannot use UserSettingsAPI without setting as dependency.");
|
||||
|
||||
for (const key in UserSettings) {
|
||||
const userSetting = UserSettings[key];
|
||||
|
||||
if (userSetting.userSettingsAPIGroup === group && userSetting.userSettingsAPIName === name) {
|
||||
return userSetting;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* {@link getUserSettingDefinition}, lazy.
|
||||
*
|
||||
* Get the setting with the given setting group and name.
|
||||
*
|
||||
* @param group The setting group
|
||||
* @param name The name of the setting
|
||||
*/
|
||||
export function getUserSettingLazy<T = any>(group: string, name: string) {
|
||||
return proxyLazy(() => getUserSetting<T>(group, name));
|
||||
}
|
|
@ -26,11 +26,13 @@ import * as $MessageAccessories from "./MessageAccessories";
|
|||
import * as $MessageDecorations from "./MessageDecorations";
|
||||
import * as $MessageEventsAPI from "./MessageEvents";
|
||||
import * as $MessagePopover from "./MessagePopover";
|
||||
import * as $MessageUpdater from "./MessageUpdater";
|
||||
import * as $Notices from "./Notices";
|
||||
import * as $Notifications from "./Notifications";
|
||||
import * as $ServerList from "./ServerList";
|
||||
import * as $Settings from "./Settings";
|
||||
import * as $Styles from "./Styles";
|
||||
import * as $UserSettings from "./UserSettings";
|
||||
|
||||
/**
|
||||
* An API allowing you to listen to Message Clicks or run your own logic
|
||||
|
@ -110,3 +112,13 @@ export const ContextMenu = $ContextMenu;
|
|||
* An API allowing you to add buttons to the chat input
|
||||
*/
|
||||
export const ChatButtons = $ChatButtons;
|
||||
|
||||
/**
|
||||
* An API allowing you to update and re-render messages
|
||||
*/
|
||||
export const MessageUpdater = $MessageUpdater;
|
||||
|
||||
/**
|
||||
* An API allowing you to get an user setting
|
||||
*/
|
||||
export const UserSettings = $UserSettings;
|
||||
|
|
|
@ -11,20 +11,16 @@ import { classNameFactory } from "@api/Styles";
|
|||
import ErrorBoundary from "@components/ErrorBoundary";
|
||||
import { Link } from "@components/Link";
|
||||
import { DevsById } from "@utils/constants";
|
||||
import { fetchUserProfile, getTheme, Theme } from "@utils/discord";
|
||||
import { pluralise } from "@utils/misc";
|
||||
import { fetchUserProfile } from "@utils/discord";
|
||||
import { classes, pluralise } from "@utils/misc";
|
||||
import { ModalContent, ModalRoot, openModal } from "@utils/modal";
|
||||
import { Forms, MaskedLink, showToast, Tooltip, useEffect, useMemo, UserProfileStore, useStateFromStores } from "@webpack/common";
|
||||
import { Forms, showToast, useEffect, useMemo, UserProfileStore, useStateFromStores } from "@webpack/common";
|
||||
import { User } from "discord-types/general";
|
||||
|
||||
import Plugins from "~plugins";
|
||||
|
||||
import { PluginCard } from ".";
|
||||
|
||||
const WebsiteIconDark = "/assets/e1e96d89e192de1997f73730db26e94f.svg";
|
||||
const WebsiteIconLight = "/assets/730f58bcfd5a57a5e22460c445a0c6cf.svg";
|
||||
const GithubIconLight = "/assets/3ff98ad75ac94fa883af5ed62d17c459.svg";
|
||||
const GithubIconDark = "/assets/6a853b4c87fce386cbfef4a2efbacb09.svg";
|
||||
import { GithubButton, WebsiteButton } from "./LinkIconButton";
|
||||
|
||||
const cl = classNameFactory("vc-author-modal-");
|
||||
|
||||
|
@ -40,16 +36,6 @@ export function openContributorModal(user: User) {
|
|||
);
|
||||
}
|
||||
|
||||
function GithubIcon() {
|
||||
const src = getTheme() === Theme.Light ? GithubIconLight : GithubIconDark;
|
||||
return <img src={src} alt="GitHub" />;
|
||||
}
|
||||
|
||||
function WebsiteIcon() {
|
||||
const src = getTheme() === Theme.Light ? WebsiteIconLight : WebsiteIconDark;
|
||||
return <img src={src} alt="Website" />;
|
||||
}
|
||||
|
||||
function ContributorModal({ user }: { user: User; }) {
|
||||
useSettings();
|
||||
|
||||
|
@ -86,24 +72,18 @@ function ContributorModal({ user }: { user: User; }) {
|
|||
/>
|
||||
<Forms.FormTitle tag="h2" className={cl("name")}>{user.username}</Forms.FormTitle>
|
||||
|
||||
<div className={cl("links")}>
|
||||
<div className={classes("vc-settings-modal-links", cl("links"))}>
|
||||
{website && (
|
||||
<Tooltip text={website}>
|
||||
{props => (
|
||||
<MaskedLink {...props} href={"https://" + website}>
|
||||
<WebsiteIcon />
|
||||
</MaskedLink>
|
||||
)}
|
||||
</Tooltip>
|
||||
<WebsiteButton
|
||||
text={website}
|
||||
href={`https://${website}`}
|
||||
/>
|
||||
)}
|
||||
{githubName && (
|
||||
<Tooltip text={githubName}>
|
||||
{props => (
|
||||
<MaskedLink {...props} href={`https://github.com/${githubName}`}>
|
||||
<GithubIcon />
|
||||
</MaskedLink>
|
||||
)}
|
||||
</Tooltip>
|
||||
<GithubButton
|
||||
text={githubName}
|
||||
href={`https://github.com/${githubName}`}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
|
12
src/components/PluginSettings/LinkIconButton.css
Normal file
12
src/components/PluginSettings/LinkIconButton.css
Normal file
|
@ -0,0 +1,12 @@
|
|||
.vc-settings-modal-link-icon {
|
||||
height: 32px;
|
||||
width: 32px;
|
||||
border-radius: 50%;
|
||||
border: 4px solid var(--background-tertiary);
|
||||
box-sizing: border-box
|
||||
}
|
||||
|
||||
.vc-settings-modal-links {
|
||||
display: flex;
|
||||
gap: 0.2em;
|
||||
}
|
45
src/components/PluginSettings/LinkIconButton.tsx
Normal file
45
src/components/PluginSettings/LinkIconButton.tsx
Normal file
|
@ -0,0 +1,45 @@
|
|||
/*
|
||||
* Vencord, a Discord client mod
|
||||
* Copyright (c) 2024 Vendicated and contributors
|
||||
* SPDX-License-Identifier: GPL-3.0-or-later
|
||||
*/
|
||||
|
||||
import "./LinkIconButton.css";
|
||||
|
||||
import { getTheme, Theme } from "@utils/discord";
|
||||
import { MaskedLink, Tooltip } from "@webpack/common";
|
||||
|
||||
const WebsiteIconDark = "/assets/e1e96d89e192de1997f73730db26e94f.svg";
|
||||
const WebsiteIconLight = "/assets/730f58bcfd5a57a5e22460c445a0c6cf.svg";
|
||||
const GithubIconLight = "/assets/3ff98ad75ac94fa883af5ed62d17c459.svg";
|
||||
const GithubIconDark = "/assets/6a853b4c87fce386cbfef4a2efbacb09.svg";
|
||||
|
||||
export function GithubIcon() {
|
||||
const src = getTheme() === Theme.Light ? GithubIconLight : GithubIconDark;
|
||||
return <img src={src} aria-hidden className={"vc-settings-modal-link-icon"} />;
|
||||
}
|
||||
|
||||
export function WebsiteIcon() {
|
||||
const src = getTheme() === Theme.Light ? WebsiteIconLight : WebsiteIconDark;
|
||||
return <img src={src} aria-hidden className={"vc-settings-modal-link-icon"} />;
|
||||
}
|
||||
|
||||
interface Props {
|
||||
text: string;
|
||||
href: string;
|
||||
}
|
||||
|
||||
function LinkIcon({ text, href, Icon }: Props & { Icon: React.ComponentType; }) {
|
||||
return (
|
||||
<Tooltip text={text}>
|
||||
{props => (
|
||||
<MaskedLink {...props} href={href}>
|
||||
<Icon />
|
||||
</MaskedLink>
|
||||
)}
|
||||
</Tooltip>
|
||||
);
|
||||
}
|
||||
|
||||
export const WebsiteButton = (props: Props) => <LinkIcon {...props} Icon={WebsiteIcon} />;
|
||||
export const GithubButton = (props: Props) => <LinkIcon {...props} Icon={GithubIcon} />;
|
7
src/components/PluginSettings/PluginModal.css
Normal file
7
src/components/PluginSettings/PluginModal.css
Normal file
|
@ -0,0 +1,7 @@
|
|||
.vc-plugin-modal-info {
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.vc-plugin-modal-description {
|
||||
flex-grow: 1;
|
||||
}
|
|
@ -16,10 +16,14 @@
|
|||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
import "./PluginModal.css";
|
||||
|
||||
import { generateId } from "@api/Commands";
|
||||
import { useSettings } from "@api/Settings";
|
||||
import { classNameFactory } from "@api/Styles";
|
||||
import ErrorBoundary from "@components/ErrorBoundary";
|
||||
import { Flex } from "@components/Flex";
|
||||
import { gitRemote } from "@shared/vencordUserAgent";
|
||||
import { proxyLazy } from "@utils/lazy";
|
||||
import { Margins } from "@utils/margins";
|
||||
import { classes, isObjectEmpty } from "@utils/misc";
|
||||
|
@ -30,6 +34,8 @@ import { Button, Clickable, FluxDispatcher, Forms, React, Text, Tooltip, UserSto
|
|||
import { User } from "discord-types/general";
|
||||
import { Constructor } from "type-fest";
|
||||
|
||||
import { PluginMeta } from "~plugins";
|
||||
|
||||
import {
|
||||
ISettingElementProps,
|
||||
SettingBooleanComponent,
|
||||
|
@ -40,6 +46,9 @@ import {
|
|||
SettingTextComponent
|
||||
} from "./components";
|
||||
import { openContributorModal } from "./ContributorModal";
|
||||
import { GithubButton, WebsiteButton } from "./LinkIconButton";
|
||||
|
||||
const cl = classNameFactory("vc-plugin-modal-");
|
||||
|
||||
const UserSummaryItem = findComponentByCodeLazy("defaultRenderUser", "showDefaultAvatarsForNullUsers");
|
||||
const AvatarStyles = findByPropsLazy("moreUsers", "emptyUser", "avatarContainer", "clickableAvatar");
|
||||
|
@ -180,16 +189,54 @@ export default function PluginModal({ plugin, onRestartNeeded, onClose, transiti
|
|||
);
|
||||
}
|
||||
|
||||
/*
|
||||
function switchToPopout() {
|
||||
onClose();
|
||||
|
||||
const PopoutKey = `DISCORD_VENCORD_PLUGIN_SETTINGS_MODAL_${plugin.name}`;
|
||||
PopoutActions.open(
|
||||
PopoutKey,
|
||||
() => <PluginModal
|
||||
transitionState={transitionState}
|
||||
plugin={plugin}
|
||||
onRestartNeeded={onRestartNeeded}
|
||||
onClose={() => PopoutActions.close(PopoutKey)}
|
||||
/>
|
||||
);
|
||||
}
|
||||
*/
|
||||
|
||||
const pluginMeta = PluginMeta[plugin.name];
|
||||
|
||||
return (
|
||||
<ModalRoot transitionState={transitionState} size={ModalSize.MEDIUM} className="vc-text-selectable">
|
||||
<ModalHeader separator={false}>
|
||||
<Text variant="heading-lg/semibold" style={{ flexGrow: 1 }}>{plugin.name}</Text>
|
||||
|
||||
{/*
|
||||
<Button look={Button.Looks.BLANK} onClick={switchToPopout}>
|
||||
<OpenExternalIcon aria-label="Open in Popout" />
|
||||
</Button>
|
||||
*/}
|
||||
<ModalCloseButton onClick={onClose} />
|
||||
</ModalHeader>
|
||||
<ModalContent>
|
||||
<Forms.FormSection>
|
||||
<Forms.FormTitle tag="h3">About {plugin.name}</Forms.FormTitle>
|
||||
<Forms.FormText>{plugin.description}</Forms.FormText>
|
||||
<Flex className={cl("info")}>
|
||||
<Forms.FormText className={cl("description")}>{plugin.description}</Forms.FormText>
|
||||
{!pluginMeta.userPlugin && (
|
||||
<div className="vc-settings-modal-links">
|
||||
<WebsiteButton
|
||||
text="View more info"
|
||||
href={`https://vencord.dev/plugins/${plugin.name}`}
|
||||
/>
|
||||
<GithubButton
|
||||
text="View source code"
|
||||
href={`https://github.com/${gitRemote}/tree/main/src/plugins/${pluginMeta.folderName}`}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</Flex>
|
||||
<Forms.FormTitle tag="h3" style={{ marginTop: 8, marginBottom: 0 }}>Authors</Forms.FormTitle>
|
||||
<div style={{ width: "fit-content", marginBottom: 8 }}>
|
||||
<UserSummaryItem
|
||||
|
|
|
@ -42,16 +42,6 @@
|
|||
|
||||
.vc-author-modal-links {
|
||||
margin-left: auto;
|
||||
display: flex;
|
||||
gap: 0.2em;
|
||||
}
|
||||
|
||||
.vc-author-modal-links img {
|
||||
height: 32px;
|
||||
width: 32px;
|
||||
border-radius: 50%;
|
||||
border: 4px solid var(--background-tertiary);
|
||||
box-sizing: border-box
|
||||
}
|
||||
|
||||
.vc-author-modal-plugins {
|
||||
|
|
|
@ -35,9 +35,9 @@ import { openModalLazy } from "@utils/modal";
|
|||
import { useAwaiter } from "@utils/react";
|
||||
import { Plugin } from "@utils/types";
|
||||
import { findByPropsLazy } from "@webpack";
|
||||
import { Alerts, Button, Card, Forms, lodash, Parser, React, Select, Text, TextInput, Toasts, Tooltip } from "@webpack/common";
|
||||
import { Alerts, Button, Card, Forms, lodash, Parser, React, Select, Text, TextInput, Toasts, Tooltip, useMemo } from "@webpack/common";
|
||||
|
||||
import Plugins from "~plugins";
|
||||
import Plugins, { ExcludedPlugins } from "~plugins";
|
||||
|
||||
// Avoid circular dependency
|
||||
const { startDependenciesRecursive, startPlugin, stopPlugin } = proxyLazy(() => require("../../plugins"));
|
||||
|
@ -69,7 +69,7 @@ function ReloadRequiredCard({ required }: { required: boolean; }) {
|
|||
<Forms.FormText className={cl("dep-text")}>
|
||||
Restart now to apply new plugins and their settings
|
||||
</Forms.FormText>
|
||||
<Button color={Button.Colors.YELLOW} onClick={() => location.reload()}>
|
||||
<Button onClick={() => location.reload()}>
|
||||
Restart
|
||||
</Button>
|
||||
</>
|
||||
|
@ -177,6 +177,37 @@ const enum SearchStatus {
|
|||
NEW
|
||||
}
|
||||
|
||||
function ExcludedPluginsList({ search }: { search: string; }) {
|
||||
const matchingExcludedPlugins = Object.entries(ExcludedPlugins)
|
||||
.filter(([name]) => name.toLowerCase().includes(search));
|
||||
|
||||
const ExcludedReasons: Record<"web" | "discordDesktop" | "vencordDesktop" | "desktop" | "dev", string> = {
|
||||
desktop: "Discord Desktop app or Vesktop",
|
||||
discordDesktop: "Discord Desktop app",
|
||||
vencordDesktop: "Vesktop app",
|
||||
web: "Vesktop app and the Web version of Discord",
|
||||
dev: "Developer version of Vencord"
|
||||
};
|
||||
|
||||
return (
|
||||
<Text variant="text-md/normal" className={Margins.top16}>
|
||||
{matchingExcludedPlugins.length
|
||||
? <>
|
||||
<Forms.FormText>Are you looking for:</Forms.FormText>
|
||||
<ul>
|
||||
{matchingExcludedPlugins.map(([name, reason]) => (
|
||||
<li key={name}>
|
||||
<b>{name}</b>: Only available on the {ExcludedReasons[reason]}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</>
|
||||
: "No plugins meet the search criteria."
|
||||
}
|
||||
</Text>
|
||||
);
|
||||
}
|
||||
|
||||
export default function PluginSettings() {
|
||||
const settings = useSettings();
|
||||
const changes = React.useMemo(() => new ChangeList<string>(), []);
|
||||
|
@ -215,26 +246,27 @@ export default function PluginSettings() {
|
|||
return o;
|
||||
}, []);
|
||||
|
||||
const sortedPlugins = React.useMemo(() => Object.values(Plugins)
|
||||
const sortedPlugins = useMemo(() => Object.values(Plugins)
|
||||
.sort((a, b) => a.name.localeCompare(b.name)), []);
|
||||
|
||||
const [searchValue, setSearchValue] = React.useState({ value: "", status: SearchStatus.ALL });
|
||||
|
||||
const search = searchValue.value.toLowerCase();
|
||||
const onSearch = (query: string) => setSearchValue(prev => ({ ...prev, value: query }));
|
||||
const onStatusChange = (status: SearchStatus) => setSearchValue(prev => ({ ...prev, status }));
|
||||
|
||||
const pluginFilter = (plugin: typeof Plugins[keyof typeof Plugins]) => {
|
||||
const enabled = settings.plugins[plugin.name]?.enabled;
|
||||
if (enabled && searchValue.status === SearchStatus.DISABLED) return false;
|
||||
if (!enabled && searchValue.status === SearchStatus.ENABLED) return false;
|
||||
if (searchValue.status === SearchStatus.NEW && !newPlugins?.includes(plugin.name)) return false;
|
||||
if (!searchValue.value.length) return true;
|
||||
const { status } = searchValue;
|
||||
const enabled = Vencord.Plugins.isPluginEnabled(plugin.name);
|
||||
if (enabled && status === SearchStatus.DISABLED) return false;
|
||||
if (!enabled && status === SearchStatus.ENABLED) return false;
|
||||
if (status === SearchStatus.NEW && !newPlugins?.includes(plugin.name)) return false;
|
||||
if (!search.length) return true;
|
||||
|
||||
const v = searchValue.value.toLowerCase();
|
||||
return (
|
||||
plugin.name.toLowerCase().includes(v) ||
|
||||
plugin.description.toLowerCase().includes(v) ||
|
||||
plugin.tags?.some(t => t.toLowerCase().includes(v))
|
||||
plugin.name.toLowerCase().includes(search) ||
|
||||
plugin.description.toLowerCase().includes(search) ||
|
||||
plugin.tags?.some(t => t.toLowerCase().includes(search))
|
||||
);
|
||||
};
|
||||
|
||||
|
@ -255,14 +287,12 @@ export default function PluginSettings() {
|
|||
return lodash.isEqual(newPlugins, sortedPluginNames) ? [] : newPlugins;
|
||||
}));
|
||||
|
||||
type P = JSX.Element | JSX.Element[];
|
||||
let plugins: P, requiredPlugins: P;
|
||||
if (sortedPlugins?.length) {
|
||||
plugins = [];
|
||||
requiredPlugins = [];
|
||||
const plugins = [] as JSX.Element[];
|
||||
const requiredPlugins = [] as JSX.Element[];
|
||||
|
||||
const showApi = searchValue.value.includes("API");
|
||||
for (const p of sortedPlugins) {
|
||||
if (!p.options && p.name.endsWith("API") && searchValue.value !== "API")
|
||||
if (p.hidden || (!p.options && p.name.endsWith("API") && !showApi))
|
||||
continue;
|
||||
|
||||
if (!pluginFilter(p)) continue;
|
||||
|
@ -283,6 +313,7 @@ export default function PluginSettings() {
|
|||
onRestartNeeded={name => changes.handleChange(name)}
|
||||
disabled={true}
|
||||
plugin={p}
|
||||
key={p.name}
|
||||
/>
|
||||
)}
|
||||
</Tooltip>
|
||||
|
@ -298,10 +329,6 @@ export default function PluginSettings() {
|
|||
/>
|
||||
);
|
||||
}
|
||||
|
||||
}
|
||||
} else {
|
||||
plugins = requiredPlugins = <Text variant="text-md/normal">No plugins meet search criteria.</Text>;
|
||||
}
|
||||
|
||||
return (
|
||||
|
@ -332,9 +359,18 @@ export default function PluginSettings() {
|
|||
|
||||
<Forms.FormTitle className={Margins.top20}>Plugins</Forms.FormTitle>
|
||||
|
||||
{plugins.length || requiredPlugins.length
|
||||
? (
|
||||
<div className={cl("grid")}>
|
||||
{plugins}
|
||||
{plugins.length
|
||||
? plugins
|
||||
: <Text variant="text-md/normal">No plugins meet the search criteria.</Text>
|
||||
}
|
||||
</div>
|
||||
)
|
||||
: <ExcludedPluginsList search={search} />
|
||||
}
|
||||
|
||||
|
||||
<Forms.FormDivider className={Margins.top20} />
|
||||
|
||||
|
@ -342,7 +378,10 @@ export default function PluginSettings() {
|
|||
Required Plugins
|
||||
</Forms.FormTitle>
|
||||
<div className={cl("grid")}>
|
||||
{requiredPlugins}
|
||||
{requiredPlugins.length
|
||||
? requiredPlugins
|
||||
: <Text variant="text-md/normal">No plugins meet the search criteria.</Text>
|
||||
}
|
||||
</div>
|
||||
</SettingsTab >
|
||||
);
|
||||
|
|
|
@ -78,6 +78,7 @@
|
|||
|
||||
.vc-plugins-restart-card button {
|
||||
margin-top: 0.5em;
|
||||
background: var(--info-warning-foreground) !important;
|
||||
}
|
||||
|
||||
.vc-plugins-info-button svg:not(:hover, :focus) {
|
||||
|
|
|
@ -18,14 +18,14 @@
|
|||
|
||||
import { Logger } from "@utils/Logger";
|
||||
|
||||
if (IS_DEV) {
|
||||
if (IS_DEV || IS_REPORTER) {
|
||||
var traces = {} as Record<string, [number, any[]]>;
|
||||
var logger = new Logger("Tracer", "#FFD166");
|
||||
}
|
||||
|
||||
const noop = function () { };
|
||||
|
||||
export const beginTrace = !IS_DEV ? noop :
|
||||
export const beginTrace = !(IS_DEV || IS_REPORTER) ? noop :
|
||||
function beginTrace(name: string, ...args: any[]) {
|
||||
if (name in traces)
|
||||
throw new Error(`Trace ${name} already exists!`);
|
||||
|
@ -33,7 +33,7 @@ export const beginTrace = !IS_DEV ? noop :
|
|||
traces[name] = [performance.now(), args];
|
||||
};
|
||||
|
||||
export const finishTrace = !IS_DEV ? noop : function finishTrace(name: string) {
|
||||
export const finishTrace = !(IS_DEV || IS_REPORTER) ? noop : function finishTrace(name: string) {
|
||||
const end = performance.now();
|
||||
|
||||
const [start, args] = traces[name];
|
||||
|
@ -48,7 +48,7 @@ type TraceNameMapper<F extends Func> = (...args: Parameters<F>) => string;
|
|||
const noopTracer =
|
||||
<F extends Func>(name: string, f: F, mapper?: TraceNameMapper<F>) => f;
|
||||
|
||||
export const traceFunction = !IS_DEV
|
||||
export const traceFunction = !(IS_DEV || IS_REPORTER)
|
||||
? noopTracer
|
||||
: function traceFunction<F extends Func>(name: string, f: F, mapper?: TraceNameMapper<F>): F {
|
||||
return function (this: any, ...args: Parameters<F>) {
|
||||
|
|
169
src/debug/loadLazyChunks.ts
Normal file
169
src/debug/loadLazyChunks.ts
Normal file
|
@ -0,0 +1,169 @@
|
|||
/*
|
||||
* Vencord, a Discord client mod
|
||||
* Copyright (c) 2024 Vendicated and contributors
|
||||
* SPDX-License-Identifier: GPL-3.0-or-later
|
||||
*/
|
||||
|
||||
import { Logger } from "@utils/Logger";
|
||||
import { canonicalizeMatch } from "@utils/patches";
|
||||
import * as Webpack from "@webpack";
|
||||
import { wreq } from "@webpack";
|
||||
|
||||
const LazyChunkLoaderLogger = new Logger("LazyChunkLoader");
|
||||
|
||||
export async function loadLazyChunks() {
|
||||
try {
|
||||
LazyChunkLoaderLogger.log("Loading all chunks...");
|
||||
|
||||
const validChunks = new Set<string>();
|
||||
const invalidChunks = new Set<string>();
|
||||
const deferredRequires = new Set<string>();
|
||||
|
||||
let chunksSearchingResolve: (value: void | PromiseLike<void>) => void;
|
||||
const chunksSearchingDone = new Promise<void>(r => chunksSearchingResolve = r);
|
||||
|
||||
// True if resolved, false otherwise
|
||||
const chunksSearchPromises = [] as Array<() => boolean>;
|
||||
|
||||
const LazyChunkRegex = canonicalizeMatch(/(?:(?:Promise\.all\(\[)?(\i\.e\("?[^)]+?"?\)[^\]]*?)(?:\]\))?)\.then\(\i\.bind\(\i,"?([^)]+?)"?\)\)/g);
|
||||
|
||||
async function searchAndLoadLazyChunks(factoryCode: string) {
|
||||
const lazyChunks = factoryCode.matchAll(LazyChunkRegex);
|
||||
const validChunkGroups = new Set<[chunkIds: string[], entryPoint: string]>();
|
||||
|
||||
// Workaround for a chunk that depends on the ChannelMessage component but may be be force loaded before
|
||||
// the chunk containing the component
|
||||
const shouldForceDefer = factoryCode.includes(".Messages.GUILD_FEED_UNFEATURE_BUTTON_TEXT");
|
||||
|
||||
await Promise.all(Array.from(lazyChunks).map(async ([, rawChunkIds, entryPoint]) => {
|
||||
const chunkIds = rawChunkIds ? Array.from(rawChunkIds.matchAll(Webpack.ChunkIdsRegex)).map(m => m[1]) : [];
|
||||
|
||||
if (chunkIds.length === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
let invalidChunkGroup = false;
|
||||
|
||||
for (const id of chunkIds) {
|
||||
if (wreq.u(id) == null || wreq.u(id) === "undefined.js") continue;
|
||||
|
||||
const isWorkerAsset = await fetch(wreq.p + wreq.u(id))
|
||||
.then(r => r.text())
|
||||
.then(t => t.includes("importScripts("));
|
||||
|
||||
if (isWorkerAsset) {
|
||||
invalidChunks.add(id);
|
||||
invalidChunkGroup = true;
|
||||
continue;
|
||||
}
|
||||
|
||||
validChunks.add(id);
|
||||
}
|
||||
|
||||
if (!invalidChunkGroup) {
|
||||
validChunkGroups.add([chunkIds, entryPoint]);
|
||||
}
|
||||
}));
|
||||
|
||||
// Loads all found valid chunk groups
|
||||
await Promise.all(
|
||||
Array.from(validChunkGroups)
|
||||
.map(([chunkIds]) =>
|
||||
Promise.all(chunkIds.map(id => wreq.e(id as any).catch(() => { })))
|
||||
)
|
||||
);
|
||||
|
||||
// Requires the entry points for all valid chunk groups
|
||||
for (const [, entryPoint] of validChunkGroups) {
|
||||
try {
|
||||
if (shouldForceDefer) {
|
||||
deferredRequires.add(entryPoint);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (wreq.m[entryPoint]) wreq(entryPoint as any);
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
}
|
||||
}
|
||||
|
||||
// setImmediate to only check if all chunks were loaded after this function resolves
|
||||
// We check if all chunks were loaded every time a factory is loaded
|
||||
// If we are still looking for chunks in the other factories, the array will have that factory's chunk search promise not resolved
|
||||
// But, if all chunk search promises are resolved, this means we found every lazy chunk loaded by Discord code and manually loaded them
|
||||
setTimeout(() => {
|
||||
let allResolved = true;
|
||||
|
||||
for (let i = 0; i < chunksSearchPromises.length; i++) {
|
||||
const isResolved = chunksSearchPromises[i]();
|
||||
|
||||
if (isResolved) {
|
||||
// Remove finished promises to avoid having to iterate through a huge array everytime
|
||||
chunksSearchPromises.splice(i--, 1);
|
||||
} else {
|
||||
allResolved = false;
|
||||
}
|
||||
}
|
||||
|
||||
if (allResolved) chunksSearchingResolve();
|
||||
}, 0);
|
||||
}
|
||||
|
||||
Webpack.factoryListeners.add(factory => {
|
||||
let isResolved = false;
|
||||
searchAndLoadLazyChunks(factory.toString()).then(() => isResolved = true);
|
||||
|
||||
chunksSearchPromises.push(() => isResolved);
|
||||
});
|
||||
|
||||
for (const factoryId in wreq.m) {
|
||||
let isResolved = false;
|
||||
searchAndLoadLazyChunks(wreq.m[factoryId].toString()).then(() => isResolved = true);
|
||||
|
||||
chunksSearchPromises.push(() => isResolved);
|
||||
}
|
||||
|
||||
await chunksSearchingDone;
|
||||
|
||||
// Require deferred entry points
|
||||
for (const deferredRequire of deferredRequires) {
|
||||
wreq!(deferredRequire as any);
|
||||
}
|
||||
|
||||
// All chunks Discord has mapped to asset files, even if they are not used anymore
|
||||
const allChunks = [] as string[];
|
||||
|
||||
// Matches "id" or id:
|
||||
for (const currentMatch of wreq!.u.toString().matchAll(/(?:"(\d+?)")|(?:(\d+?):)/g)) {
|
||||
const id = currentMatch[1] ?? currentMatch[2];
|
||||
if (id == null) continue;
|
||||
|
||||
allChunks.push(id);
|
||||
}
|
||||
|
||||
if (allChunks.length === 0) throw new Error("Failed to get all chunks");
|
||||
|
||||
// Chunks that are not loaded (not used) by Discord code anymore
|
||||
const chunksLeft = allChunks.filter(id => {
|
||||
return !(validChunks.has(id) || invalidChunks.has(id));
|
||||
});
|
||||
|
||||
await Promise.all(chunksLeft.map(async id => {
|
||||
const isWorkerAsset = await fetch(wreq.p + wreq.u(id))
|
||||
.then(r => r.text())
|
||||
.then(t => t.includes("importScripts("));
|
||||
|
||||
// Loads and requires a chunk
|
||||
if (!isWorkerAsset) {
|
||||
await wreq.e(id as any);
|
||||
// Technically, the id of the chunk does not match the entry point
|
||||
// But, still try it because we have no way to get the actual entry point
|
||||
if (wreq.m[id]) wreq(id as any);
|
||||
}
|
||||
}));
|
||||
|
||||
LazyChunkLoaderLogger.log("Finished loading all chunks!");
|
||||
} catch (e) {
|
||||
LazyChunkLoaderLogger.log("A fatal error occurred:", e);
|
||||
}
|
||||
}
|
84
src/debug/runReporter.ts
Normal file
84
src/debug/runReporter.ts
Normal file
|
@ -0,0 +1,84 @@
|
|||
/*
|
||||
* Vencord, a Discord client mod
|
||||
* Copyright (c) 2024 Vendicated and contributors
|
||||
* SPDX-License-Identifier: GPL-3.0-or-later
|
||||
*/
|
||||
|
||||
import { Logger } from "@utils/Logger";
|
||||
import * as Webpack from "@webpack";
|
||||
import { patches } from "plugins";
|
||||
|
||||
import { loadLazyChunks } from "./loadLazyChunks";
|
||||
|
||||
const ReporterLogger = new Logger("Reporter");
|
||||
|
||||
async function runReporter() {
|
||||
try {
|
||||
ReporterLogger.log("Starting test...");
|
||||
|
||||
let loadLazyChunksResolve: (value: void | PromiseLike<void>) => void;
|
||||
const loadLazyChunksDone = new Promise<void>(r => loadLazyChunksResolve = r);
|
||||
|
||||
Webpack.beforeInitListeners.add(() => loadLazyChunks().then((loadLazyChunksResolve)));
|
||||
await loadLazyChunksDone;
|
||||
|
||||
for (const patch of patches) {
|
||||
if (!patch.all) {
|
||||
new Logger("WebpackInterceptor").warn(`Patch by ${patch.plugin} found no module (Module id is -): ${patch.find}`);
|
||||
}
|
||||
}
|
||||
|
||||
for (const [searchType, args] of Webpack.lazyWebpackSearchHistory) {
|
||||
let method = searchType;
|
||||
|
||||
if (searchType === "findComponent") method = "find";
|
||||
if (searchType === "findExportedComponent") method = "findByProps";
|
||||
if (searchType === "waitFor" || searchType === "waitForComponent") {
|
||||
if (typeof args[0] === "string") method = "findByProps";
|
||||
else method = "find";
|
||||
}
|
||||
if (searchType === "waitForStore") method = "findStore";
|
||||
|
||||
let result: any;
|
||||
try {
|
||||
if (method === "proxyLazyWebpack" || method === "LazyComponentWebpack") {
|
||||
const [factory] = args;
|
||||
result = factory();
|
||||
} else if (method === "extractAndLoadChunks") {
|
||||
const [code, matcher] = args;
|
||||
|
||||
result = await Webpack.extractAndLoadChunks(code, matcher);
|
||||
if (result === false) result = null;
|
||||
} else if (method === "mapMangledModule") {
|
||||
const [code, mapper] = args;
|
||||
|
||||
result = Webpack.mapMangledModule(code, mapper);
|
||||
if (Object.keys(result).length !== Object.keys(mapper).length) throw new Error("Webpack Find Fail");
|
||||
} else {
|
||||
// @ts-ignore
|
||||
result = Webpack[method](...args);
|
||||
}
|
||||
|
||||
if (result == null || (result.$$vencordInternal != null && result.$$vencordInternal() == null)) throw new Error("Webpack Find Fail");
|
||||
} catch (e) {
|
||||
let logMessage = searchType;
|
||||
if (method === "find" || method === "proxyLazyWebpack" || method === "LazyComponentWebpack") logMessage += `(${args[0].toString().slice(0, 147)}...)`;
|
||||
else if (method === "extractAndLoadChunks") logMessage += `([${args[0].map(arg => `"${arg}"`).join(", ")}], ${args[1].toString()})`;
|
||||
else if (method === "mapMangledModule") {
|
||||
const failedMappings = Object.keys(args[1]).filter(key => result?.[key] == null);
|
||||
|
||||
logMessage += `("${args[0]}", {\n${failedMappings.map(mapping => `\t${mapping}: ${args[1][mapping].toString().slice(0, 147)}...`).join(",\n")}\n})`;
|
||||
}
|
||||
else logMessage += `(${args.map(arg => `"${arg}"`).join(", ")})`;
|
||||
|
||||
ReporterLogger.log("Webpack Find Fail:", logMessage);
|
||||
}
|
||||
}
|
||||
|
||||
ReporterLogger.log("Finished test");
|
||||
} catch (e) {
|
||||
ReporterLogger.log("A fatal error occurred:", e);
|
||||
}
|
||||
}
|
||||
|
||||
runReporter();
|
3
src/globals.d.ts
vendored
3
src/globals.d.ts
vendored
|
@ -34,9 +34,10 @@ declare global {
|
|||
*/
|
||||
export var IS_WEB: boolean;
|
||||
export var IS_EXTENSION: boolean;
|
||||
export var IS_DEV: boolean;
|
||||
export var IS_STANDALONE: boolean;
|
||||
export var IS_UPDATER_DISABLED: boolean;
|
||||
export var IS_DEV: boolean;
|
||||
export var IS_REPORTER: boolean;
|
||||
export var IS_DISCORD_DESKTOP: boolean;
|
||||
export var IS_VESKTOP: boolean;
|
||||
export var VERSION: string;
|
||||
|
|
|
@ -5,8 +5,8 @@
|
|||
<title>Vencord QuickCSS Editor</title>
|
||||
<link
|
||||
rel="stylesheet"
|
||||
href="https://cdnjs.cloudflare.com/ajax/libs/monaco-editor/0.40.0/min/vs/editor/editor.main.min.css"
|
||||
integrity="sha512-MOoQ02h80hklccfLrXFYkCzG+WVjORflOp9Zp8dltiaRP+35LYnO4LKOklR64oMGfGgJDLO8WJpkM1o5gZXYZQ=="
|
||||
href="https://cdn.jsdelivr.net/npm/monaco-editor@0.50.0/min/vs/editor/editor.main.css"
|
||||
integrity="sha256-tiJPQ2O04z/pZ/AwdyIghrOMzewf+PIvEl1YKbQvsZk="
|
||||
crossorigin="anonymous"
|
||||
referrerpolicy="no-referrer"
|
||||
/>
|
||||
|
@ -29,8 +29,8 @@
|
|||
<body>
|
||||
<div id="container"></div>
|
||||
<script
|
||||
src="https://cdnjs.cloudflare.com/ajax/libs/monaco-editor/0.40.0/min/vs/loader.min.js"
|
||||
integrity="sha512-QzMpXeCPciAHP4wbYlV2PYgrQcaEkDQUjzkPU4xnjyVSD9T36/udamxtNBqb4qK4/bMQMPZ8ayrBe9hrGdBFjQ=="
|
||||
src="https://cdn.jsdelivr.net/npm/monaco-editor@0.50.0/min/vs/loader.js"
|
||||
integrity="sha256-KcU48TGr84r7unF7J5IgBo95aeVrEbrGe04S7TcFUjs="
|
||||
crossorigin="anonymous"
|
||||
referrerpolicy="no-referrer"
|
||||
></script>
|
||||
|
@ -38,7 +38,7 @@
|
|||
<script>
|
||||
require.config({
|
||||
paths: {
|
||||
vs: "https://cdnjs.cloudflare.com/ajax/libs/monaco-editor/0.40.0/min/vs",
|
||||
vs: "https://cdn.jsdelivr.net/npm/monaco-editor@0.50.0/min/vs",
|
||||
},
|
||||
});
|
||||
|
||||
|
|
|
@ -131,17 +131,28 @@ if (!IS_VANILLA) {
|
|||
|
||||
process.env.DATA_DIR = join(app.getPath("userData"), "..", "Vencord");
|
||||
|
||||
// Monkey patch commandLine to disable WidgetLayering: Fix DevTools context menus https://github.com/electron/electron/issues/38790
|
||||
// Monkey patch commandLine to:
|
||||
// - disable WidgetLayering: Fix DevTools context menus https://github.com/electron/electron/issues/38790
|
||||
// - disable UseEcoQoSForBackgroundProcess: Work around Discord unloading when in background
|
||||
const originalAppend = app.commandLine.appendSwitch;
|
||||
app.commandLine.appendSwitch = function (...args) {
|
||||
if (args[0] === "disable-features" && !args[1]?.includes("WidgetLayering")) {
|
||||
args[1] += ",WidgetLayering";
|
||||
if (args[0] === "disable-features") {
|
||||
const disabledFeatures = new Set((args[1] ?? "").split(","));
|
||||
disabledFeatures.add("WidgetLayering");
|
||||
disabledFeatures.add("UseEcoQoSForBackgroundProcess");
|
||||
args[1] += [...disabledFeatures].join(",");
|
||||
}
|
||||
return originalAppend.apply(this, args);
|
||||
};
|
||||
|
||||
// disable renderer backgrounding to prevent the app from unloading when in the background
|
||||
// https://github.com/electron/electron/issues/2822
|
||||
// https://github.com/GoogleChrome/chrome-launcher/blob/5a27dd574d47a75fec0fb50f7b774ebf8a9791ba/docs/chrome-flags-for-tools.md#task-throttling
|
||||
// Work around discord unloading when in background
|
||||
// Discord also recently started adding these flags but only on windows for some reason dunno why, it happens on Linux too
|
||||
app.commandLine.appendSwitch("disable-renderer-backgrounding");
|
||||
app.commandLine.appendSwitch("disable-background-timer-throttling");
|
||||
app.commandLine.appendSwitch("disable-backgrounding-occluded-windows");
|
||||
} else {
|
||||
console.log("[Vencord] Running in vanilla mode. Not loading Vencord");
|
||||
}
|
||||
|
|
|
@ -17,4 +17,4 @@
|
|||
*/
|
||||
|
||||
if (!IS_UPDATER_DISABLED)
|
||||
import(IS_STANDALONE ? "./http" : "./git");
|
||||
require(IS_STANDALONE ? "./http" : "./git");
|
||||
|
|
5
src/modules.d.ts
vendored
5
src/modules.d.ts
vendored
|
@ -22,6 +22,11 @@
|
|||
declare module "~plugins" {
|
||||
const plugins: Record<string, import("./utils/types").Plugin>;
|
||||
export default plugins;
|
||||
export const PluginMeta: Record<string, {
|
||||
folderName: string;
|
||||
userPlugin: boolean;
|
||||
}>;
|
||||
export const ExcludedPlugins: Record<string, "web" | "discordDesktop" | "vencordDesktop" | "desktop" | "dev">;
|
||||
}
|
||||
|
||||
declare module "~pluginNatives" {
|
||||
|
|
|
@ -18,18 +18,20 @@
|
|||
|
||||
import "./fixBadgeOverflow.css";
|
||||
|
||||
import { BadgePosition, BadgeUserArgs, ProfileBadge } from "@api/Badges";
|
||||
import { _getBadges, BadgePosition, BadgeUserArgs, ProfileBadge } from "@api/Badges";
|
||||
import DonateButton from "@components/DonateButton";
|
||||
import ErrorBoundary from "@components/ErrorBoundary";
|
||||
import { Flex } from "@components/Flex";
|
||||
import { Heart } from "@components/Heart";
|
||||
import { openContributorModal } from "@components/PluginSettings/ContributorModal";
|
||||
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";
|
||||
import { Forms, Toasts, UserStore } from "@webpack/common";
|
||||
import { User } from "discord-types/general";
|
||||
|
||||
const CONTRIBUTOR_BADGE = "https://vencord.dev/assets/favicon.png";
|
||||
|
||||
|
@ -37,8 +39,8 @@ const ContributorBadge: ProfileBadge = {
|
|||
description: "Vencord Contributor",
|
||||
image: CONTRIBUTOR_BADGE,
|
||||
position: BadgePosition.START,
|
||||
shouldShow: ({ user }) => isPluginDev(user.id),
|
||||
onClick: (_, { user }) => openContributorModal(user)
|
||||
shouldShow: ({ userId }) => isPluginDev(userId),
|
||||
onClick: (_, { userId }) => openContributorModal(UserStore.getUser(userId))
|
||||
};
|
||||
|
||||
let DonorBadges = {} as Record<string, Array<Record<"tooltip" | "badge", string>>>;
|
||||
|
@ -66,7 +68,7 @@ export default definePlugin({
|
|||
replacement: [
|
||||
{
|
||||
match: /&&(\i)\.push\(\{id:"premium".+?\}\);/,
|
||||
replace: "$&$1.unshift(...Vencord.Api.Badges._getBadges(arguments[0]));",
|
||||
replace: "$&$1.unshift(...$self.getBadges(arguments[0]));",
|
||||
},
|
||||
{
|
||||
// alt: "", aria-hidden: false, src: originalSrc
|
||||
|
@ -82,7 +84,36 @@ export default definePlugin({
|
|||
// conditionally override their onClick with badge.onClick if it exists
|
||||
{
|
||||
match: /href:(\i)\.link/,
|
||||
replace: "...($1.onClick && { onClick: vcE => $1.onClick(vcE, arguments[0]) }),$&"
|
||||
replace: "...($1.onClick && { onClick: vcE => $1.onClick(vcE, $1) }),$&"
|
||||
}
|
||||
]
|
||||
},
|
||||
|
||||
/* new profiles */
|
||||
{
|
||||
find: ".PANEL]:14",
|
||||
replacement: {
|
||||
match: /(?<=(\i)=\(0,\i\.\i\)\(\i\);)return 0===\i.length\?/,
|
||||
replace: "$1.unshift(...$self.getBadges(arguments[0].displayProfile));$&"
|
||||
}
|
||||
},
|
||||
{
|
||||
find: ".description,delay:",
|
||||
replacement: [
|
||||
{
|
||||
// alt: "", aria-hidden: false, src: originalSrc
|
||||
match: /alt:" ","aria-hidden":!0,src:(?=.{0,20}(\i)\.icon)/,
|
||||
// ...badge.props, ..., src: badge.image ?? ...
|
||||
replace: "...$1.props,$& $1.image??"
|
||||
},
|
||||
{
|
||||
match: /(?<=text:(\i)\.description,.{0,50})children:/,
|
||||
replace: "children:$1.component ? $self.renderBadgeComponent({ ...$1 }) :"
|
||||
},
|
||||
// conditionally override their onClick with badge.onClick if it exists
|
||||
{
|
||||
match: /href:(\i)\.link/,
|
||||
replace: "...($1.onClick && { onClick: vcE => $1.onClick(vcE, $1) }),$&"
|
||||
}
|
||||
]
|
||||
}
|
||||
|
@ -104,6 +135,17 @@ export default definePlugin({
|
|||
await loadBadges();
|
||||
},
|
||||
|
||||
getBadges(props: { userId: string; user?: User; guildId: string; }) {
|
||||
try {
|
||||
props.userId ??= props.user?.id!;
|
||||
|
||||
return _getBadges(props);
|
||||
} catch (e) {
|
||||
new Logger("BadgeAPI#hasBadges").error(e);
|
||||
return [];
|
||||
}
|
||||
},
|
||||
|
||||
renderBadgeComponent: ErrorBoundary.wrap((badge: ProfileBadge & BadgeUserArgs) => {
|
||||
const Component = badge.component!;
|
||||
return <Component {...badge} />;
|
||||
|
|
|
@ -15,8 +15,8 @@ export default definePlugin({
|
|||
patches: [{
|
||||
find: '"sticker")',
|
||||
replacement: {
|
||||
match: /!\i\.isMobile(?=.+?(\i)\.push\(.{0,50}"gift")/,
|
||||
replace: "$& &&(Vencord.Api.ChatButtons._injectButtons($1,arguments[0]),true)"
|
||||
match: /return\(!\i\.\i&&(?=\(\i\.isDM.+?(\i)\.push\(.{0,50}"gift")/,
|
||||
replace: "$&(Vencord.Api.ChatButtons._injectButtons($1,arguments[0]),true)&&"
|
||||
}
|
||||
}]
|
||||
});
|
||||
|
|
|
@ -35,7 +35,7 @@ export default definePlugin({
|
|||
}
|
||||
},
|
||||
{
|
||||
find: ".handleSendMessage",
|
||||
find: ".handleSendMessage,onResize",
|
||||
replacement: {
|
||||
// props.chatInputType...then((function(isMessageValid)... var parsedMessage = b.c.parse(channel,... var replyOptions = f.g.getSendMessageOptionsForReply(pendingReply);
|
||||
// Lookbehind: validateMessage)({openWarningPopout:..., type: i.props.chatInputType, content: t, stickers: r, ...}).then((function(isMessageValid)
|
||||
|
|
37
src/plugins/_api/messageUpdater.ts
Normal file
37
src/plugins/_api/messageUpdater.ts
Normal file
|
@ -0,0 +1,37 @@
|
|||
/*
|
||||
* 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 <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
import { Devs } from "@utils/constants";
|
||||
import definePlugin from "@utils/types";
|
||||
|
||||
export default definePlugin({
|
||||
name: "MessageUpdaterAPI",
|
||||
description: "API for updating and re-rendering messages.",
|
||||
authors: [Devs.Nuckyz],
|
||||
|
||||
patches: [
|
||||
{
|
||||
// Message accessories have a custom logic to decide if they should render again, so we need to make it not ignore changed message reference
|
||||
find: "}renderEmbeds(",
|
||||
replacement: {
|
||||
match: /(?<=this.props,\i,\[)"message",/,
|
||||
replace: ""
|
||||
}
|
||||
}
|
||||
]
|
||||
});
|
50
src/plugins/_api/userSettings.ts
Normal file
50
src/plugins/_api/userSettings.ts
Normal file
|
@ -0,0 +1,50 @@
|
|||
/*
|
||||
* 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 <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
import { Devs } from "@utils/constants";
|
||||
import definePlugin from "@utils/types";
|
||||
|
||||
export default definePlugin({
|
||||
name: "UserSettingsAPI",
|
||||
description: "Patches Discord's UserSettings to expose their group and name.",
|
||||
authors: [Devs.Nuckyz],
|
||||
|
||||
patches: [
|
||||
{
|
||||
find: ",updateSetting:",
|
||||
replacement: [
|
||||
// Main setting definition
|
||||
{
|
||||
match: /(?<=INFREQUENT_USER_ACTION.{0,20},)useSetting:/,
|
||||
replace: "userSettingsAPIGroup:arguments[0],userSettingsAPIName:arguments[1],$&"
|
||||
},
|
||||
// Selective wrapper
|
||||
{
|
||||
match: /updateSetting:.{0,100}SELECTIVELY_SYNCED_USER_SETTINGS_UPDATE/,
|
||||
replace: "userSettingsAPIGroup:arguments[0].userSettingsAPIGroup,userSettingsAPIName:arguments[0].userSettingsAPIName,$&"
|
||||
},
|
||||
// Override wrapper
|
||||
{
|
||||
match: /updateSetting:.{0,60}USER_SETTINGS_OVERRIDE_CLEAR/,
|
||||
replace: "userSettingsAPIGroup:arguments[0].userSettingsAPIGroup,userSettingsAPIName:arguments[0].userSettingsAPIName,$&"
|
||||
}
|
||||
|
||||
]
|
||||
}
|
||||
]
|
||||
});
|
|
@ -56,45 +56,24 @@ export default definePlugin({
|
|||
}
|
||||
]
|
||||
},
|
||||
// Discord Stable
|
||||
// FIXME: remove once change merged to stable
|
||||
{
|
||||
find: "Messages.ACTIVITY_SETTINGS",
|
||||
replacement: {
|
||||
get match() {
|
||||
switch (Settings.plugins.Settings.settingsLocation) {
|
||||
case "top": return /\{section:(\i\.\i)\.HEADER,\s*label:(\i)\.\i\.Messages\.USER_SETTINGS/;
|
||||
case "aboveNitro": return /\{section:(\i\.\i)\.HEADER,\s*label:(\i)\.\i\.Messages\.BILLING_SETTINGS/;
|
||||
case "belowNitro": return /\{section:(\i\.\i)\.HEADER,\s*label:(\i)\.\i\.Messages\.APP_SETTINGS/;
|
||||
case "belowActivity": return /(?<=\{section:(\i\.\i)\.DIVIDER},)\{section:"changelog"/;
|
||||
case "bottom": return /\{section:(\i\.\i)\.CUSTOM,\s*element:.+?}/;
|
||||
case "aboveActivity":
|
||||
default:
|
||||
return /\{section:(\i\.\i)\.HEADER,\s*label:(\i)\.\i\.Messages\.ACTIVITY_SETTINGS/;
|
||||
}
|
||||
},
|
||||
replace: "...$self.makeSettingsCategories($1),$&"
|
||||
}
|
||||
},
|
||||
replacement: [
|
||||
{
|
||||
find: "Messages.ACTIVITY_SETTINGS",
|
||||
replacement: {
|
||||
match: /(?<=section:(.{0,50})\.DIVIDER\}\))([,;])(?=.{0,200}(\i)\.push.{0,100}label:(\i)\.header)/,
|
||||
replace: (_, sectionTypes, commaOrSemi, elements, element) => `${commaOrSemi} $self.addSettings(${elements}, ${element}, ${sectionTypes}) ${commaOrSemi}`
|
||||
}
|
||||
},
|
||||
{
|
||||
find: "useDefaultUserSettingsSections:function",
|
||||
replacement: {
|
||||
match: /(?<=useDefaultUserSettingsSections:function\(\){return )(\i)\}/,
|
||||
replace: "$self.wrapSettingsHook($1)}"
|
||||
match: /({(?=.+?function (\i).{0,120}(\i)=\i\.useMemo.{0,30}return \i\.useMemo\(\(\)=>\i\(\3).+?function\(\){return )\2(?=})/,
|
||||
replace: (_, rest, settingsHook) => `${rest}$self.wrapSettingsHook(${settingsHook})`
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
find: "Messages.USER_SETTINGS_ACTIONS_MENU_LABEL",
|
||||
replacement: {
|
||||
match: /(?<=function\((\i),\i\)\{)(?=let \i=Object.values\(\i.UserSettingsSections\).*?(\i)\.default\.open\()/,
|
||||
replace: "$2.default.open($1);return;"
|
||||
match: /(?<=function\((\i),\i\)\{)(?=let \i=Object.values\(\i.\i\).*?(\i\.\i)\.open\()/,
|
||||
replace: "$2.open($1);return;"
|
||||
}
|
||||
}
|
||||
],
|
||||
|
|
|
@ -16,24 +16,33 @@
|
|||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
import { addAccessory } from "@api/MessageAccessories";
|
||||
import { getUserSettingLazy } from "@api/UserSettings";
|
||||
import ErrorBoundary from "@components/ErrorBoundary";
|
||||
import { Flex } from "@components/Flex";
|
||||
import { Link } from "@components/Link";
|
||||
import { openUpdaterModal } from "@components/VencordSettings/UpdaterTab";
|
||||
import { Devs, SUPPORT_CHANNEL_ID } from "@utils/constants";
|
||||
import { sendMessage } from "@utils/discord";
|
||||
import { Logger } from "@utils/Logger";
|
||||
import { Margins } from "@utils/margins";
|
||||
import { isPluginDev } from "@utils/misc";
|
||||
import { isPluginDev, tryOrElse } from "@utils/misc";
|
||||
import { relaunch } from "@utils/native";
|
||||
import { onlyOnce } from "@utils/onlyOnce";
|
||||
import { makeCodeblock } from "@utils/text";
|
||||
import definePlugin from "@utils/types";
|
||||
import { isOutdated, update } from "@utils/updater";
|
||||
import { Alerts, Card, ChannelStore, Forms, GuildMemberStore, NavigationRouter, Parser, RelationshipStore, UserStore } from "@webpack/common";
|
||||
import { checkForUpdates, isOutdated, update } from "@utils/updater";
|
||||
import { Alerts, Button, Card, ChannelStore, Forms, GuildMemberStore, Parser, RelationshipStore, showToast, Toasts, UserStore } from "@webpack/common";
|
||||
|
||||
import gitHash from "~git-hash";
|
||||
import plugins from "~plugins";
|
||||
import plugins, { PluginMeta } from "~plugins";
|
||||
|
||||
import settings from "./settings";
|
||||
|
||||
const VENCORD_GUILD_ID = "1015060230222131221";
|
||||
const VENBOT_USER_ID = "1017176847865352332";
|
||||
const KNOWN_ISSUES_CHANNEL_ID = "1222936386626129920";
|
||||
const CodeBlockRe = /```js\n(.+?)```/s;
|
||||
|
||||
const AllowedChannelIds = [
|
||||
SUPPORT_CHANNEL_ID,
|
||||
|
@ -47,26 +56,21 @@ const TrustedRolesIds = [
|
|||
"1042507929485586532", // donor
|
||||
];
|
||||
|
||||
export default definePlugin({
|
||||
name: "SupportHelper",
|
||||
required: true,
|
||||
description: "Helps us provide support to you",
|
||||
authors: [Devs.Ven],
|
||||
dependencies: ["CommandsAPI"],
|
||||
const AsyncFunction = async function () { }.constructor;
|
||||
|
||||
patches: [{
|
||||
find: ".BEGINNING_DM.format",
|
||||
replacement: {
|
||||
match: /BEGINNING_DM\.format\(\{.+?\}\),(?=.{0,100}userId:(\i\.getRecipientId\(\)))/,
|
||||
replace: "$& $self.ContributorDmWarningCard({ userId: $1 }),"
|
||||
const ShowCurrentGame = getUserSettingLazy<boolean>("status", "showCurrentGame")!;
|
||||
|
||||
async function forceUpdate() {
|
||||
const outdated = await checkForUpdates();
|
||||
if (outdated) {
|
||||
await update();
|
||||
relaunch();
|
||||
}
|
||||
}],
|
||||
|
||||
commands: [{
|
||||
name: "vencord-debug",
|
||||
description: "Send Vencord Debug info",
|
||||
predicate: ctx => AllowedChannelIds.includes(ctx.channel.id),
|
||||
async execute() {
|
||||
return outdated;
|
||||
}
|
||||
|
||||
async function generateDebugInfoMessage() {
|
||||
const { RELEASE_CHANNEL } = window.GLOBAL_ENV;
|
||||
|
||||
const client = (() => {
|
||||
|
@ -79,10 +83,6 @@ export default definePlugin({
|
|||
return `${name} (${navigator.userAgent})`;
|
||||
})();
|
||||
|
||||
const isApiPlugin = (plugin: string) => plugin.endsWith("API") || plugins[plugin].required;
|
||||
|
||||
const enabledPlugins = Object.keys(plugins).filter(p => Vencord.Plugins.isPluginEnabled(p) && !isApiPlugin(p));
|
||||
|
||||
const info = {
|
||||
Vencord:
|
||||
`v${VERSION} • [${gitHash}](<https://github.com/Vendicated/Vencord/commit/${gitHash}>)` +
|
||||
|
@ -92,22 +92,76 @@ export default definePlugin({
|
|||
};
|
||||
|
||||
if (IS_DISCORD_DESKTOP) {
|
||||
info["Last Crash Reason"] = (await DiscordNative.processUtils.getLastCrash())?.rendererCrashReason ?? "N/A";
|
||||
info["Last Crash Reason"] = (await tryOrElse(() => DiscordNative.processUtils.getLastCrash(), undefined))?.rendererCrashReason ?? "N/A";
|
||||
}
|
||||
|
||||
const debugInfo = `
|
||||
>>> ${Object.entries(info).map(([k, v]) => `**${k}**: ${v}`).join("\n")}
|
||||
|
||||
Enabled Plugins (${enabledPlugins.length}):
|
||||
${makeCodeblock(enabledPlugins.join(", "))}
|
||||
`;
|
||||
|
||||
return {
|
||||
content: debugInfo.trim().replaceAll("```\n", "```")
|
||||
const commonIssues = {
|
||||
"NoRPC enabled": Vencord.Plugins.isPluginEnabled("NoRPC"),
|
||||
"Activity Sharing disabled": tryOrElse(() => !ShowCurrentGame.getSetting(), false),
|
||||
"Vencord DevBuild": !IS_STANDALONE,
|
||||
"Has UserPlugins": Object.values(PluginMeta).some(m => m.userPlugin),
|
||||
"More than two weeks out of date": BUILD_TIMESTAMP < Date.now() - 12096e5,
|
||||
};
|
||||
|
||||
let content = `>>> ${Object.entries(info).map(([k, v]) => `**${k}**: ${v}`).join("\n")}`;
|
||||
content += "\n" + Object.entries(commonIssues)
|
||||
.filter(([, v]) => v).map(([k]) => `⚠️ ${k}`)
|
||||
.join("\n");
|
||||
|
||||
return content.trim();
|
||||
}
|
||||
|
||||
function generatePluginList() {
|
||||
const isApiPlugin = (plugin: string) => plugin.endsWith("API") || plugins[plugin].required;
|
||||
|
||||
const enabledPlugins = Object.keys(plugins)
|
||||
.filter(p => Vencord.Plugins.isPluginEnabled(p) && !isApiPlugin(p));
|
||||
|
||||
const enabledStockPlugins = enabledPlugins.filter(p => !PluginMeta[p].userPlugin);
|
||||
const enabledUserPlugins = enabledPlugins.filter(p => PluginMeta[p].userPlugin);
|
||||
|
||||
|
||||
let content = `**Enabled Plugins (${enabledStockPlugins.length}):**\n${makeCodeblock(enabledStockPlugins.join(", "))}`;
|
||||
|
||||
if (enabledUserPlugins.length) {
|
||||
content += `**Enabled UserPlugins (${enabledUserPlugins.length}):**\n${makeCodeblock(enabledUserPlugins.join(", "))}`;
|
||||
}
|
||||
|
||||
return content;
|
||||
}
|
||||
|
||||
const checkForUpdatesOnce = onlyOnce(checkForUpdates);
|
||||
|
||||
export default definePlugin({
|
||||
name: "SupportHelper",
|
||||
required: true,
|
||||
description: "Helps us provide support to you",
|
||||
authors: [Devs.Ven],
|
||||
dependencies: ["CommandsAPI", "UserSettingsAPI", "MessageAccessoriesAPI"],
|
||||
|
||||
patches: [{
|
||||
find: ".BEGINNING_DM.format",
|
||||
replacement: {
|
||||
match: /BEGINNING_DM\.format\(\{.+?\}\),(?=.{0,100}userId:(\i\.getRecipientId\(\)))/,
|
||||
replace: "$& $self.ContributorDmWarningCard({ userId: $1 }),"
|
||||
}
|
||||
}],
|
||||
|
||||
commands: [
|
||||
{
|
||||
name: "vencord-debug",
|
||||
description: "Send Vencord debug info",
|
||||
predicate: ctx => isPluginDev(UserStore.getCurrentUser()?.id) || AllowedChannelIds.includes(ctx.channel.id),
|
||||
execute: async () => ({ content: await generateDebugInfoMessage() })
|
||||
},
|
||||
{
|
||||
name: "vencord-plugins",
|
||||
description: "Send Vencord plugin list",
|
||||
predicate: ctx => isPluginDev(UserStore.getCurrentUser()?.id) || AllowedChannelIds.includes(ctx.channel.id),
|
||||
execute: () => ({ content: generatePluginList() })
|
||||
}
|
||||
],
|
||||
|
||||
flux: {
|
||||
async CHANNEL_SELECT({ channelId }) {
|
||||
if (channelId !== SUPPORT_CHANNEL_ID) return;
|
||||
|
@ -115,6 +169,9 @@ ${makeCodeblock(enabledPlugins.join(", "))}
|
|||
const selfId = UserStore.getCurrentUser()?.id;
|
||||
if (!selfId || isPluginDev(selfId)) return;
|
||||
|
||||
if (!IS_UPDATER_DISABLED) {
|
||||
await checkForUpdatesOnce().catch(() => { });
|
||||
|
||||
if (isOutdated) {
|
||||
return Alerts.show({
|
||||
title: "Hold on!",
|
||||
|
@ -127,13 +184,11 @@ ${makeCodeblock(enabledPlugins.join(", "))}
|
|||
onCancel: () => openUpdaterModal!(),
|
||||
cancelText: "View Updates",
|
||||
confirmText: "Update & Restart Now",
|
||||
async onConfirm() {
|
||||
await update();
|
||||
relaunch();
|
||||
},
|
||||
onConfirm: forceUpdate,
|
||||
secondaryConfirmText: "I know what I'm doing or I can't update"
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// @ts-ignore outdated type
|
||||
const roles = GuildMemberStore.getSelfMember(VENCORD_GUILD_ID)?.roles;
|
||||
|
@ -148,8 +203,7 @@ ${makeCodeblock(enabledPlugins.join(", "))}
|
|||
Please either switch to an <Link href="https://vencord.dev/download">officially supported version of Vencord</Link>, or
|
||||
contact your package maintainer for support instead.
|
||||
</Forms.FormText>
|
||||
</div>,
|
||||
onCloseCallback: () => setTimeout(() => NavigationRouter.back(), 50)
|
||||
</div>
|
||||
});
|
||||
}
|
||||
|
||||
|
@ -163,8 +217,7 @@ ${makeCodeblock(enabledPlugins.join(", "))}
|
|||
Please either switch to an <Link href="https://vencord.dev/download">officially supported version of Vencord</Link>, or
|
||||
contact your package maintainer for support instead.
|
||||
</Forms.FormText>
|
||||
</div>,
|
||||
onCloseCallback: () => setTimeout(() => NavigationRouter.back(), 50)
|
||||
</div>
|
||||
});
|
||||
}
|
||||
}
|
||||
|
@ -172,7 +225,7 @@ ${makeCodeblock(enabledPlugins.join(", "))}
|
|||
|
||||
ContributorDmWarningCard: ErrorBoundary.wrap(({ userId }) => {
|
||||
if (!isPluginDev(userId)) return null;
|
||||
if (RelationshipStore.isFriend(userId)) return null;
|
||||
if (RelationshipStore.isFriend(userId) || isPluginDev(UserStore.getCurrentUser()?.id)) return null;
|
||||
|
||||
return (
|
||||
<Card className={`vc-plugins-restart-card ${Margins.top8}`}>
|
||||
|
@ -182,5 +235,86 @@ ${makeCodeblock(enabledPlugins.join(", "))}
|
|||
{!ChannelStore.getChannel(SUPPORT_CHANNEL_ID) && " (Click the link to join)"}
|
||||
</Card>
|
||||
);
|
||||
}, { noop: true })
|
||||
}, { noop: true }),
|
||||
|
||||
start() {
|
||||
addAccessory("vencord-debug", props => {
|
||||
const buttons = [] as JSX.Element[];
|
||||
|
||||
const shouldAddUpdateButton =
|
||||
!IS_UPDATER_DISABLED
|
||||
&& (
|
||||
(props.channel.id === KNOWN_ISSUES_CHANNEL_ID) ||
|
||||
(props.channel.id === SUPPORT_CHANNEL_ID && props.message.author.id === VENBOT_USER_ID)
|
||||
)
|
||||
&& props.message.content?.includes("update");
|
||||
|
||||
if (shouldAddUpdateButton) {
|
||||
buttons.push(
|
||||
<Button
|
||||
key="vc-update"
|
||||
color={Button.Colors.GREEN}
|
||||
onClick={async () => {
|
||||
try {
|
||||
if (await forceUpdate())
|
||||
showToast("Success! Restarting...", Toasts.Type.SUCCESS);
|
||||
else
|
||||
showToast("Already up to date!", Toasts.Type.MESSAGE);
|
||||
} catch (e) {
|
||||
new Logger(this.name).error("Error while updating:", e);
|
||||
showToast("Failed to update :(", Toasts.Type.FAILURE);
|
||||
}
|
||||
}}
|
||||
>
|
||||
Update Now
|
||||
</Button>
|
||||
);
|
||||
}
|
||||
|
||||
if (props.channel.id === SUPPORT_CHANNEL_ID) {
|
||||
if (props.message.content.includes("/vencord-debug") || props.message.content.includes("/vencord-plugins")) {
|
||||
buttons.push(
|
||||
<Button
|
||||
key="vc-dbg"
|
||||
onClick={async () => sendMessage(props.channel.id, { content: await generateDebugInfoMessage() })}
|
||||
>
|
||||
Run /vencord-debug
|
||||
</Button>,
|
||||
<Button
|
||||
key="vc-plg-list"
|
||||
onClick={async () => sendMessage(props.channel.id, { content: generatePluginList() })}
|
||||
>
|
||||
Run /vencord-plugins
|
||||
</Button>
|
||||
);
|
||||
}
|
||||
|
||||
if (props.message.author.id === VENBOT_USER_ID) {
|
||||
const match = CodeBlockRe.exec(props.message.content || props.message.embeds[0]?.rawDescription || "");
|
||||
if (match) {
|
||||
buttons.push(
|
||||
<Button
|
||||
key="vc-run-snippet"
|
||||
onClick={async () => {
|
||||
try {
|
||||
await AsyncFunction(match[1])();
|
||||
showToast("Success!", Toasts.Type.SUCCESS);
|
||||
} catch (e) {
|
||||
new Logger(this.name).error("Error while running snippet:", e);
|
||||
showToast("Failed to run snippet :(", Toasts.Type.FAILURE);
|
||||
}
|
||||
}}
|
||||
>
|
||||
Run Snippet
|
||||
</Button>
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return buttons.length
|
||||
? <Flex>{buttons}</Flex>
|
||||
: null;
|
||||
});
|
||||
},
|
||||
});
|
||||
|
|
|
@ -49,7 +49,7 @@ export default definePlugin({
|
|||
predicate: () => settings.store.domain
|
||||
},
|
||||
{
|
||||
find: "isSuspiciousDownload:",
|
||||
find: "bitbucket.org",
|
||||
replacement: {
|
||||
match: /function \i\(\i\){(?=.{0,60}\.parse\(\i\))/,
|
||||
replace: "$&return null;"
|
||||
|
|
9
src/plugins/appleMusic.desktop/README.md
Normal file
9
src/plugins/appleMusic.desktop/README.md
Normal file
|
@ -0,0 +1,9 @@
|
|||
# AppleMusicRichPresence
|
||||
|
||||
This plugin enables Discord rich presence for your Apple Music! (This only works on macOS with the Music app.)
|
||||
|
||||
![Screenshot of the activity in Discord](https://github.com/Vendicated/Vencord/assets/70191398/1f811090-ab5f-4060-a9ee-d0ac44a1d3c0)
|
||||
|
||||
## Configuration
|
||||
|
||||
For the customizable activity format strings, you can use several special strings to include track data in activities! `{name}` is replaced with the track name; `{artist}` is replaced with the artist(s)' name(s); and `{album}` is replaced with the album name.
|
262
src/plugins/appleMusic.desktop/index.tsx
Normal file
262
src/plugins/appleMusic.desktop/index.tsx
Normal file
|
@ -0,0 +1,262 @@
|
|||
/*
|
||||
* Vencord, a Discord client mod
|
||||
* Copyright (c) 2024 Vendicated and contributors
|
||||
* SPDX-License-Identifier: GPL-3.0-or-later
|
||||
*/
|
||||
|
||||
import { definePluginSettings } from "@api/Settings";
|
||||
import { Devs } from "@utils/constants";
|
||||
import definePlugin, { OptionType, PluginNative, ReporterTestable } from "@utils/types";
|
||||
import { ApplicationAssetUtils, FluxDispatcher, Forms } from "@webpack/common";
|
||||
|
||||
const Native = VencordNative.pluginHelpers.AppleMusicRichPresence as PluginNative<typeof import("./native")>;
|
||||
|
||||
interface ActivityAssets {
|
||||
large_image?: string;
|
||||
large_text?: string;
|
||||
small_image?: string;
|
||||
small_text?: string;
|
||||
}
|
||||
|
||||
interface ActivityButton {
|
||||
label: string;
|
||||
url: string;
|
||||
}
|
||||
|
||||
interface Activity {
|
||||
state: string;
|
||||
details?: string;
|
||||
timestamps?: {
|
||||
start?: number;
|
||||
end?: number;
|
||||
};
|
||||
assets?: ActivityAssets;
|
||||
buttons?: Array<string>;
|
||||
name: string;
|
||||
application_id: string;
|
||||
metadata?: {
|
||||
button_urls?: Array<string>;
|
||||
};
|
||||
type: number;
|
||||
flags: number;
|
||||
}
|
||||
|
||||
const enum ActivityType {
|
||||
PLAYING = 0,
|
||||
LISTENING = 2,
|
||||
}
|
||||
|
||||
const enum ActivityFlag {
|
||||
INSTANCE = 1 << 0,
|
||||
}
|
||||
|
||||
export interface TrackData {
|
||||
name: string;
|
||||
album: string;
|
||||
artist: string;
|
||||
|
||||
appleMusicLink?: string;
|
||||
songLink?: string;
|
||||
|
||||
albumArtwork?: string;
|
||||
artistArtwork?: string;
|
||||
|
||||
playerPosition: number;
|
||||
duration: number;
|
||||
}
|
||||
|
||||
const enum AssetImageType {
|
||||
Album = "Album",
|
||||
Artist = "Artist",
|
||||
Disabled = "Disabled"
|
||||
}
|
||||
|
||||
const applicationId = "1239490006054207550";
|
||||
|
||||
function setActivity(activity: Activity | null) {
|
||||
FluxDispatcher.dispatch({
|
||||
type: "LOCAL_ACTIVITY_UPDATE",
|
||||
activity,
|
||||
socketId: "AppleMusic",
|
||||
});
|
||||
}
|
||||
|
||||
const settings = definePluginSettings({
|
||||
activityType: {
|
||||
type: OptionType.SELECT,
|
||||
description: "Which type of activity",
|
||||
options: [
|
||||
{ label: "Playing", value: ActivityType.PLAYING, default: true },
|
||||
{ label: "Listening", value: ActivityType.LISTENING }
|
||||
],
|
||||
},
|
||||
refreshInterval: {
|
||||
type: OptionType.SLIDER,
|
||||
description: "The interval between activity refreshes (seconds)",
|
||||
markers: [1, 2, 2.5, 3, 5, 10, 15],
|
||||
default: 5,
|
||||
restartNeeded: true,
|
||||
},
|
||||
enableTimestamps: {
|
||||
type: OptionType.BOOLEAN,
|
||||
description: "Whether or not to enable timestamps",
|
||||
default: true,
|
||||
},
|
||||
enableButtons: {
|
||||
type: OptionType.BOOLEAN,
|
||||
description: "Whether or not to enable buttons",
|
||||
default: true,
|
||||
},
|
||||
nameString: {
|
||||
type: OptionType.STRING,
|
||||
description: "Activity name format string",
|
||||
default: "Apple Music"
|
||||
},
|
||||
detailsString: {
|
||||
type: OptionType.STRING,
|
||||
description: "Activity details format string",
|
||||
default: "{name}"
|
||||
},
|
||||
stateString: {
|
||||
type: OptionType.STRING,
|
||||
description: "Activity state format string",
|
||||
default: "{artist}"
|
||||
},
|
||||
largeImageType: {
|
||||
type: OptionType.SELECT,
|
||||
description: "Activity assets large image type",
|
||||
options: [
|
||||
{ label: "Album artwork", value: AssetImageType.Album, default: true },
|
||||
{ label: "Artist artwork", value: AssetImageType.Artist },
|
||||
{ label: "Disabled", value: AssetImageType.Disabled }
|
||||
],
|
||||
},
|
||||
largeTextString: {
|
||||
type: OptionType.STRING,
|
||||
description: "Activity assets large text format string",
|
||||
default: "{album}"
|
||||
},
|
||||
smallImageType: {
|
||||
type: OptionType.SELECT,
|
||||
description: "Activity assets small image type",
|
||||
options: [
|
||||
{ label: "Album artwork", value: AssetImageType.Album },
|
||||
{ label: "Artist artwork", value: AssetImageType.Artist, default: true },
|
||||
{ label: "Disabled", value: AssetImageType.Disabled }
|
||||
],
|
||||
},
|
||||
smallTextString: {
|
||||
type: OptionType.STRING,
|
||||
description: "Activity assets small text format string",
|
||||
default: "{artist}"
|
||||
},
|
||||
});
|
||||
|
||||
function customFormat(formatStr: string, data: TrackData) {
|
||||
return formatStr
|
||||
.replaceAll("{name}", data.name)
|
||||
.replaceAll("{album}", data.album)
|
||||
.replaceAll("{artist}", data.artist);
|
||||
}
|
||||
|
||||
function getImageAsset(type: AssetImageType, data: TrackData) {
|
||||
const source = type === AssetImageType.Album
|
||||
? data.albumArtwork
|
||||
: data.artistArtwork;
|
||||
|
||||
if (!source) return undefined;
|
||||
|
||||
return ApplicationAssetUtils.fetchAssetIds(applicationId, [source]).then(ids => ids[0]);
|
||||
}
|
||||
|
||||
export default definePlugin({
|
||||
name: "AppleMusicRichPresence",
|
||||
description: "Discord rich presence for your Apple Music!",
|
||||
authors: [Devs.RyanCaoDev],
|
||||
hidden: !navigator.platform.startsWith("Mac"),
|
||||
reporterTestable: ReporterTestable.None,
|
||||
|
||||
settingsAboutComponent() {
|
||||
return <>
|
||||
<Forms.FormText>
|
||||
For the customizable activity format strings, you can use several special strings to include track data in activities!{" "}
|
||||
<code>{"{name}"}</code> is replaced with the track name; <code>{"{artist}"}</code> is replaced with the artist(s)' name(s); and <code>{"{album}"}</code> is replaced with the album name.
|
||||
</Forms.FormText>
|
||||
</>;
|
||||
},
|
||||
|
||||
settings,
|
||||
|
||||
start() {
|
||||
this.updatePresence();
|
||||
this.updateInterval = setInterval(() => { this.updatePresence(); }, settings.store.refreshInterval * 1000);
|
||||
},
|
||||
|
||||
stop() {
|
||||
clearInterval(this.updateInterval);
|
||||
FluxDispatcher.dispatch({ type: "LOCAL_ACTIVITY_UPDATE", activity: null });
|
||||
},
|
||||
|
||||
updatePresence() {
|
||||
this.getActivity().then(activity => { setActivity(activity); });
|
||||
},
|
||||
|
||||
async getActivity(): Promise<Activity | null> {
|
||||
const trackData = await Native.fetchTrackData();
|
||||
if (!trackData) return null;
|
||||
|
||||
const [largeImageAsset, smallImageAsset] = await Promise.all([
|
||||
getImageAsset(settings.store.largeImageType, trackData),
|
||||
getImageAsset(settings.store.smallImageType, trackData)
|
||||
]);
|
||||
|
||||
const assets: ActivityAssets = {};
|
||||
|
||||
if (settings.store.largeImageType !== AssetImageType.Disabled) {
|
||||
assets.large_image = largeImageAsset;
|
||||
assets.large_text = customFormat(settings.store.largeTextString, trackData);
|
||||
}
|
||||
|
||||
if (settings.store.smallImageType !== AssetImageType.Disabled) {
|
||||
assets.small_image = smallImageAsset;
|
||||
assets.small_text = customFormat(settings.store.smallTextString, trackData);
|
||||
}
|
||||
|
||||
const buttons: ActivityButton[] = [];
|
||||
|
||||
if (settings.store.enableButtons) {
|
||||
if (trackData.appleMusicLink)
|
||||
buttons.push({
|
||||
label: "Listen on Apple Music",
|
||||
url: trackData.appleMusicLink,
|
||||
});
|
||||
|
||||
if (trackData.songLink)
|
||||
buttons.push({
|
||||
label: "View on SongLink",
|
||||
url: trackData.songLink,
|
||||
});
|
||||
}
|
||||
|
||||
return {
|
||||
application_id: applicationId,
|
||||
|
||||
name: customFormat(settings.store.nameString, trackData),
|
||||
details: customFormat(settings.store.detailsString, trackData),
|
||||
state: customFormat(settings.store.stateString, trackData),
|
||||
|
||||
timestamps: (settings.store.enableTimestamps ? {
|
||||
start: Date.now() - (trackData.playerPosition * 1000),
|
||||
end: Date.now() - (trackData.playerPosition * 1000) + (trackData.duration * 1000),
|
||||
} : undefined),
|
||||
|
||||
assets,
|
||||
|
||||
buttons: buttons.length ? buttons.map(v => v.label) : undefined,
|
||||
metadata: { button_urls: buttons.map(v => v.url) || undefined, },
|
||||
|
||||
type: settings.store.activityType,
|
||||
flags: ActivityFlag.INSTANCE,
|
||||
};
|
||||
}
|
||||
});
|
120
src/plugins/appleMusic.desktop/native.ts
Normal file
120
src/plugins/appleMusic.desktop/native.ts
Normal file
|
@ -0,0 +1,120 @@
|
|||
/*
|
||||
* Vencord, a Discord client mod
|
||||
* Copyright (c) 2024 Vendicated and contributors
|
||||
* SPDX-License-Identifier: GPL-3.0-or-later
|
||||
*/
|
||||
|
||||
import { execFile } from "child_process";
|
||||
import { promisify } from "util";
|
||||
|
||||
import type { TrackData } from ".";
|
||||
|
||||
const exec = promisify(execFile);
|
||||
|
||||
// function exec(file: string, args: string[] = []) {
|
||||
// return new Promise<{ code: number | null, stdout: string | null, stderr: string | null; }>((resolve, reject) => {
|
||||
// const process = spawn(file, args, { stdio: [null, "pipe", "pipe"] });
|
||||
|
||||
// let stdout: string | null = null;
|
||||
// process.stdout.on("data", (chunk: string) => { stdout ??= ""; stdout += chunk; });
|
||||
// let stderr: string | null = null;
|
||||
// process.stderr.on("data", (chunk: string) => { stdout ??= ""; stderr += chunk; });
|
||||
|
||||
// process.on("exit", code => { resolve({ code, stdout, stderr }); });
|
||||
// process.on("error", err => reject(err));
|
||||
// });
|
||||
// }
|
||||
|
||||
async function applescript(cmds: string[]) {
|
||||
const { stdout } = await exec("osascript", cmds.map(c => ["-e", c]).flat());
|
||||
return stdout;
|
||||
}
|
||||
|
||||
function makeSearchUrl(type: string, query: string) {
|
||||
const url = new URL("https://tools.applemediaservices.com/api/apple-media/music/US/search.json");
|
||||
url.searchParams.set("types", type);
|
||||
url.searchParams.set("limit", "1");
|
||||
url.searchParams.set("term", query);
|
||||
return url;
|
||||
}
|
||||
|
||||
const requestOptions: RequestInit = {
|
||||
headers: { "user-agent": "Mozilla/5.0 (Windows NT 10.0; rv:125.0) Gecko/20100101 Firefox/125.0" },
|
||||
};
|
||||
|
||||
interface RemoteData {
|
||||
appleMusicLink?: string,
|
||||
songLink?: string,
|
||||
albumArtwork?: string,
|
||||
artistArtwork?: string;
|
||||
}
|
||||
|
||||
let cachedRemoteData: { id: string, data: RemoteData; } | { id: string, failures: number; } | null = null;
|
||||
|
||||
async function fetchRemoteData({ id, name, artist, album }: { id: string, name: string, artist: string, album: string; }) {
|
||||
if (id === cachedRemoteData?.id) {
|
||||
if ("data" in cachedRemoteData) return cachedRemoteData.data;
|
||||
if ("failures" in cachedRemoteData && cachedRemoteData.failures >= 5) return null;
|
||||
}
|
||||
|
||||
try {
|
||||
const [songData, artistData] = await Promise.all([
|
||||
fetch(makeSearchUrl("songs", artist + " " + album + " " + name), requestOptions).then(r => r.json()),
|
||||
fetch(makeSearchUrl("artists", artist.split(/ *[,&] */)[0]), requestOptions).then(r => r.json())
|
||||
]);
|
||||
|
||||
const appleMusicLink = songData?.songs?.data[0]?.attributes.url;
|
||||
const songLink = songData?.songs?.data[0]?.id ? `https://song.link/i/${songData?.songs?.data[0]?.id}` : undefined;
|
||||
|
||||
const albumArtwork = songData?.songs?.data[0]?.attributes.artwork.url.replace("{w}", "512").replace("{h}", "512");
|
||||
const artistArtwork = artistData?.artists?.data[0]?.attributes.artwork.url.replace("{w}", "512").replace("{h}", "512");
|
||||
|
||||
cachedRemoteData = {
|
||||
id,
|
||||
data: { appleMusicLink, songLink, albumArtwork, artistArtwork }
|
||||
};
|
||||
return cachedRemoteData.data;
|
||||
} catch (e) {
|
||||
console.error("[AppleMusicRichPresence] Failed to fetch remote data:", e);
|
||||
cachedRemoteData = {
|
||||
id,
|
||||
failures: (id === cachedRemoteData?.id && "failures" in cachedRemoteData ? cachedRemoteData.failures : 0) + 1
|
||||
};
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export async function fetchTrackData(): Promise<TrackData | null> {
|
||||
try {
|
||||
await exec("pgrep", ["^Music$"]);
|
||||
} catch (error) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const playerState = await applescript(['tell application "Music"', "get player state", "end tell"])
|
||||
.then(out => out.trim());
|
||||
if (playerState !== "playing") return null;
|
||||
|
||||
const playerPosition = await applescript(['tell application "Music"', "get player position", "end tell"])
|
||||
.then(text => Number.parseFloat(text.trim()));
|
||||
|
||||
const stdout = await applescript([
|
||||
'set output to ""',
|
||||
'tell application "Music"',
|
||||
"set t_id to database id of current track",
|
||||
"set t_name to name of current track",
|
||||
"set t_album to album of current track",
|
||||
"set t_artist to artist of current track",
|
||||
"set t_duration to duration of current track",
|
||||
'set output to "" & t_id & "\\n" & t_name & "\\n" & t_album & "\\n" & t_artist & "\\n" & t_duration',
|
||||
"end tell",
|
||||
"return output"
|
||||
]);
|
||||
|
||||
const [id, name, album, artist, durationStr] = stdout.split("\n").filter(k => !!k);
|
||||
const duration = Number.parseFloat(durationStr);
|
||||
|
||||
const remoteData = await fetchRemoteData({ id, name, artist, album });
|
||||
|
||||
return { name, album, artist, playerPosition, duration, ...remoteData };
|
||||
}
|
|
@ -19,11 +19,11 @@
|
|||
import { popNotice, showNotice } from "@api/Notices";
|
||||
import { Link } from "@components/Link";
|
||||
import { Devs } from "@utils/constants";
|
||||
import definePlugin from "@utils/types";
|
||||
import { findByPropsLazy } from "@webpack";
|
||||
import definePlugin, { ReporterTestable } from "@utils/types";
|
||||
import { findByCodeLazy } from "@webpack";
|
||||
import { ApplicationAssetUtils, FluxDispatcher, Forms, Toasts } from "@webpack/common";
|
||||
|
||||
const RpcUtils = findByPropsLazy("fetchApplicationsRPC", "getRemoteIconURL");
|
||||
const fetchApplicationsRPC = findByCodeLazy("APPLICATION_RPC(", "Client ID");
|
||||
|
||||
async function lookupAsset(applicationId: string, key: string): Promise<string> {
|
||||
return (await ApplicationAssetUtils.fetchAssetIds(applicationId, [key]))[0];
|
||||
|
@ -32,7 +32,7 @@ async function lookupAsset(applicationId: string, key: string): Promise<string>
|
|||
const apps: any = {};
|
||||
async function lookupApp(applicationId: string): Promise<string> {
|
||||
const socket: any = {};
|
||||
await RpcUtils.fetchApplicationsRPC(socket, applicationId);
|
||||
await fetchApplicationsRPC(socket, applicationId);
|
||||
return socket.application;
|
||||
}
|
||||
|
||||
|
@ -41,6 +41,7 @@ export default definePlugin({
|
|||
name: "WebRichPresence (arRPC)",
|
||||
description: "Client plugin for arRPC to enable RPC on Discord Web (experimental)",
|
||||
authors: [Devs.Ducko],
|
||||
reporterTestable: ReporterTestable.None,
|
||||
|
||||
settingsAboutComponent: () => (
|
||||
<>
|
||||
|
|
|
@ -27,7 +27,7 @@ export default definePlugin({
|
|||
{
|
||||
find: "BAN_CONFIRM_TITLE.",
|
||||
replacement: {
|
||||
match: /src:\i\("\d+"\)/g,
|
||||
match: /src:\i\("?\d+"?\)/g,
|
||||
replace: "src: Vencord.Settings.plugins.BANger.source"
|
||||
}
|
||||
}
|
||||
|
|
|
@ -19,7 +19,7 @@
|
|||
import { definePluginSettings } from "@api/Settings";
|
||||
import { Devs } from "@utils/constants";
|
||||
import definePlugin, { OptionType } from "@utils/types";
|
||||
import { findByPropsLazy, findStoreLazy } from "@webpack";
|
||||
import { findByPropsLazy, findLazy, findStoreLazy } from "@webpack";
|
||||
import { FluxDispatcher, i18n, useMemo } from "@webpack/common";
|
||||
|
||||
import FolderSideBar from "./FolderSideBar";
|
||||
|
@ -30,7 +30,7 @@ enum FolderIconDisplay {
|
|||
MoreThanOneFolderExpanded
|
||||
}
|
||||
|
||||
const { GuildsTree } = findByPropsLazy("GuildsTree");
|
||||
const GuildsTree = findLazy(m => m.prototype?.moveNextTo);
|
||||
const SortedGuildStore = findStoreLazy("SortedGuildStore");
|
||||
export const ExpandedGuildFolderStore = findStoreLazy("ExpandedGuildFolderStore");
|
||||
const FolderUtils = findByPropsLazy("move", "toggleGuildFolderExpand");
|
||||
|
@ -117,7 +117,7 @@ export default definePlugin({
|
|||
},
|
||||
// If we are rendering the Better Folders sidebar, we filter out guilds that are not in folders and unexpanded folders
|
||||
{
|
||||
match: /\[(\i)\]=(\(0,\i\.useStateFromStoresArray\).{0,40}getGuildsTree\(\).+?}\))(?=,)/,
|
||||
match: /\[(\i)\]=(\(0,\i\.\i\).{0,40}getGuildsTree\(\).+?}\))(?=,)/,
|
||||
replace: (_, originalTreeVar, rest) => `[betterFoldersOriginalTree]=${rest},${originalTreeVar}=$self.getGuildTree(!!arguments[0].isBetterFolders,betterFoldersOriginalTree,arguments[0].betterFoldersExpandedIds)`
|
||||
},
|
||||
// If we are rendering the Better Folders sidebar, we filter out everything but the servers and folders from the GuildsBar Guild List children
|
||||
|
@ -139,13 +139,13 @@ export default definePlugin({
|
|||
},
|
||||
{
|
||||
// This is the parent folder component
|
||||
find: ".MAX_GUILD_FOLDER_NAME_LENGTH,",
|
||||
find: ".toggleGuildFolderExpand(",
|
||||
predicate: () => settings.store.sidebar && settings.store.showFolderIcon !== FolderIconDisplay.Always,
|
||||
replacement: [
|
||||
{
|
||||
// Modify the expanded state to instead return the list of expanded folders
|
||||
match: /(useStateFromStores\).{0,20}=>)(\i\.\i)\.isFolderExpanded\(\i\)/,
|
||||
replace: (_, rest, ExpandedGuildFolderStore) => `${rest}${ExpandedGuildFolderStore}.getExpandedFolders()`,
|
||||
match: /(\],\(\)=>)(\i\.\i)\.isFolderExpanded\(\i\)\)/,
|
||||
replace: (_, rest, ExpandedGuildFolderStore) => `${rest}${ExpandedGuildFolderStore}.getExpandedFolders())`,
|
||||
},
|
||||
{
|
||||
// Modify the expanded prop to use the boolean if the above patch fails, or check if the folder is expanded from the list if it succeeds
|
||||
|
@ -196,7 +196,7 @@ export default definePlugin({
|
|||
]
|
||||
},
|
||||
{
|
||||
find: "APPLICATION_LIBRARY,render",
|
||||
find: "APPLICATION_LIBRARY,render:",
|
||||
predicate: () => settings.store.sidebar,
|
||||
replacement: {
|
||||
// Render the Better Folders sidebar
|
||||
|
|
|
@ -36,7 +36,7 @@ export default definePlugin({
|
|||
{
|
||||
find: ".Messages.GIF,",
|
||||
replacement: {
|
||||
match: /alt:(\i)=(\i\.default\.Messages\.GIF)(?=,[^}]*\}=(\i))/,
|
||||
match: /alt:(\i)=(\i\.\i\.Messages\.GIF)(?=,[^}]*\}=(\i))/,
|
||||
replace:
|
||||
// rename prop so we can always use default value
|
||||
"alt_$$:$1=$self.altify($3)||$2",
|
||||
|
|
|
@ -13,7 +13,7 @@ export default definePlugin({
|
|||
authors: [Devs.Samwich],
|
||||
patches: [
|
||||
{
|
||||
find: ".GIFPickerResultTypes.SEARCH",
|
||||
find: '"state",{resultType:',
|
||||
replacement: [{
|
||||
match: /(?<="state",{resultType:)null/,
|
||||
replace: '"Favorites"'
|
||||
|
|
|
@ -5,15 +5,18 @@
|
|||
*/
|
||||
|
||||
import { definePluginSettings } from "@api/Settings";
|
||||
import { getUserSettingLazy } from "@api/UserSettings";
|
||||
import { ImageIcon } from "@components/Icons";
|
||||
import { Devs } from "@utils/constants";
|
||||
import { getCurrentGuild, openImageModal } from "@utils/discord";
|
||||
import definePlugin, { OptionType } from "@utils/types";
|
||||
import { findByPropsLazy } from "@webpack";
|
||||
import { Clipboard, GuildStore, Menu, PermissionStore, TextAndImagesSettingsStores } from "@webpack/common";
|
||||
import { Clipboard, GuildStore, Menu, PermissionStore } from "@webpack/common";
|
||||
|
||||
const GuildSettingsActions = findByPropsLazy("open", "selectRole", "updateGuild");
|
||||
|
||||
const DeveloperMode = getUserSettingLazy("appearance", "developerMode")!;
|
||||
|
||||
function PencilIcon() {
|
||||
return (
|
||||
<svg
|
||||
|
@ -62,12 +65,13 @@ export default definePlugin({
|
|||
name: "BetterRoleContext",
|
||||
description: "Adds options to copy role color / edit role / view role icon when right clicking roles in the user profile",
|
||||
authors: [Devs.Ven, Devs.goodbee],
|
||||
dependencies: ["UserSettingsAPI"],
|
||||
|
||||
settings,
|
||||
|
||||
start() {
|
||||
// DeveloperMode needs to be enabled for the context menu to be shown
|
||||
TextAndImagesSettingsStores.DeveloperMode.updateSetting(true);
|
||||
DeveloperMode.updateSetting(true);
|
||||
},
|
||||
|
||||
contextMenus: {
|
||||
|
|
|
@ -48,6 +48,7 @@ export default definePlugin({
|
|||
|
||||
{
|
||||
find: ".ADD_ROLE_A11Y_LABEL",
|
||||
all: true,
|
||||
predicate: () => Settings.plugins.BetterRoleDot.copyRoleColorInProfilePopout && !Settings.plugins.BetterRoleDot.bothStyles,
|
||||
noWarn: true,
|
||||
replacement: {
|
||||
|
@ -57,6 +58,7 @@ export default definePlugin({
|
|||
},
|
||||
{
|
||||
find: ".roleVerifiedIcon",
|
||||
all: true,
|
||||
predicate: () => Settings.plugins.BetterRoleDot.copyRoleColorInProfilePopout && !Settings.plugins.BetterRoleDot.bothStyles,
|
||||
noWarn: true,
|
||||
replacement: {
|
||||
|
|
|
@ -77,15 +77,6 @@ export default definePlugin({
|
|||
replace: "$& $self.renderIcon({ ...arguments[0], DeviceIcon: $1 }), false &&"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
// Add the ability to change BlobMask's lower badge height
|
||||
// (it allows changing width so we can mirror that logic)
|
||||
find: "this.getBadgePositionInterpolation(",
|
||||
replacement: {
|
||||
match: /(\i\.animated\.rect,{id:\i,x:48-\(\i\+8\)\+4,y:)28(,width:\i\+8,height:)24,/,
|
||||
replace: (_, leftPart, rightPart) => `${leftPart} 48 - ((this.props.lowerBadgeHeight ?? 16) + 8) + 4 ${rightPart} (this.props.lowerBadgeHeight ?? 16) + 8,`
|
||||
}
|
||||
}
|
||||
],
|
||||
|
||||
|
@ -153,14 +144,16 @@ export default definePlugin({
|
|||
<PlatformIcon width={14} height={14} />
|
||||
</div>
|
||||
}
|
||||
lowerBadgeWidth={20}
|
||||
lowerBadgeHeight={20}
|
||||
lowerBadgeSize={{
|
||||
width: 20,
|
||||
height: 20
|
||||
}}
|
||||
>
|
||||
<div
|
||||
className={SessionIconClasses.sessionIcon}
|
||||
style={{ backgroundColor: GetOsColor(session.client_info.os) }}
|
||||
>
|
||||
<DeviceIcon width={28} height={28} />
|
||||
<DeviceIcon width={28} height={28} color="currentColor" />
|
||||
</div>
|
||||
</BlobMask>
|
||||
);
|
||||
|
|
|
@ -83,19 +83,19 @@ export default definePlugin({
|
|||
find: "this.renderArtisanalHack()",
|
||||
replacement: [
|
||||
{ // Fade in on layer
|
||||
match: /(?<=\((\i),"contextType",\i\.AccessibilityPreferencesContext\);)/,
|
||||
match: /(?<=\((\i),"contextType",\i\.\i\);)/,
|
||||
replace: "$1=$self.Layer;",
|
||||
predicate: () => settings.store.disableFade
|
||||
},
|
||||
{ // Lazy-load contents
|
||||
match: /createPromise:\(\)=>([^:}]*?),webpackId:"\d+",name:(?!="CollectiblesShop")"[^"]+"/g,
|
||||
match: /createPromise:\(\)=>([^:}]*?),webpackId:"?\d+"?,name:(?!="CollectiblesShop")"[^"]+"/g,
|
||||
replace: "$&,_:$1",
|
||||
predicate: () => settings.store.eagerLoad
|
||||
}
|
||||
]
|
||||
},
|
||||
{ // For some reason standardSidebarView also has a small fade-in
|
||||
find: "DefaultCustomContentScroller:function()",
|
||||
find: 'minimal:"contentColumnMinimal"',
|
||||
replacement: [
|
||||
{
|
||||
match: /\(0,\i\.useTransition\)\((\i)/,
|
||||
|
@ -111,7 +111,7 @@ export default definePlugin({
|
|||
{ // Load menu TOC eagerly
|
||||
find: "Messages.USER_SETTINGS_WITH_BUILD_OVERRIDE.format",
|
||||
replacement: {
|
||||
match: /(\i)\(this,"handleOpenSettingsContextMenu",.{0,100}?openContextMenuLazy.{0,100}?(await Promise\.all[^};]*?\)\)).*?,(?=\1\(this)/,
|
||||
match: /(\i)\(this,"handleOpenSettingsContextMenu",.{0,100}?null!=\i&&.{0,100}?(await Promise\.all[^};]*?\)\)).*?,(?=\1\(this)/,
|
||||
replace: "$&(async ()=>$2)(),"
|
||||
},
|
||||
predicate: () => settings.store.eagerLoad
|
||||
|
@ -119,8 +119,8 @@ export default definePlugin({
|
|||
{ // Settings cog context menu
|
||||
find: "Messages.USER_SETTINGS_ACTIONS_MENU_LABEL",
|
||||
replacement: {
|
||||
match: /\(0,\i.useDefaultUserSettingsSections\)\(\)(?=\.filter\(\i=>\{let\{section:\i\}=)/,
|
||||
replace: "$self.wrapMenu($&)"
|
||||
match: /(EXPERIMENTS:.+?)(\(0,\i.\i\)\(\))(?=\.filter\(\i=>\{let\{section:\i\}=)/,
|
||||
replace: "$1$self.wrapMenu($2)"
|
||||
}
|
||||
}
|
||||
],
|
||||
|
|
|
@ -11,7 +11,7 @@ import { Devs } from "@utils/constants";
|
|||
import { Margins } from "@utils/margins";
|
||||
import { classes } from "@utils/misc";
|
||||
import definePlugin, { OptionType, StartAt } from "@utils/types";
|
||||
import { findByPropsLazy, findComponentByCodeLazy, findStoreLazy } from "@webpack";
|
||||
import { findByCodeLazy, findComponentByCodeLazy, findStoreLazy } from "@webpack";
|
||||
import { Button, Forms, useStateFromStores } from "@webpack/common";
|
||||
|
||||
const ColorPicker = findComponentByCodeLazy(".Messages.USER_SETTINGS_PROFILE_COLOR_SELECT_COLOR", ".BACKGROUND_PRIMARY)");
|
||||
|
@ -30,7 +30,7 @@ function onPickColor(color: number) {
|
|||
updateColorVars(hexColor);
|
||||
}
|
||||
|
||||
const { saveClientTheme } = findByPropsLazy("saveClientTheme");
|
||||
const saveClientTheme = findByCodeLazy('type:"UNSYNCED_USER_SETTINGS_UPDATE",settings:{useSystemTheme:"system"===');
|
||||
|
||||
function setTheme(theme: string) {
|
||||
saveClientTheme({ theme });
|
||||
|
|
|
@ -17,24 +17,34 @@
|
|||
*/
|
||||
|
||||
import { Devs } from "@utils/constants";
|
||||
import { getCurrentChannel, getCurrentGuild } from "@utils/discord";
|
||||
import { SYM_LAZY_CACHED, SYM_LAZY_GET } from "@utils/lazy";
|
||||
import { relaunch } from "@utils/native";
|
||||
import { canonicalizeMatch, canonicalizeReplace, canonicalizeReplacement } from "@utils/patches";
|
||||
import definePlugin, { StartAt } from "@utils/types";
|
||||
import definePlugin, { PluginNative, StartAt } from "@utils/types";
|
||||
import * as Webpack from "@webpack";
|
||||
import { extract, filters, findAll, findModuleId, search } from "@webpack";
|
||||
import * as Common from "@webpack/common";
|
||||
import { loadLazyChunks } from "debug/loadLazyChunks";
|
||||
import type { ComponentType } from "react";
|
||||
|
||||
const WEB_ONLY = (f: string) => () => {
|
||||
const DESKTOP_ONLY = (f: string) => () => {
|
||||
throw new Error(`'${f}' is Discord Desktop only.`);
|
||||
};
|
||||
|
||||
export default definePlugin({
|
||||
name: "ConsoleShortcuts",
|
||||
description: "Adds shorter Aliases for many things on the window. Run `shortcutList` for a list.",
|
||||
authors: [Devs.Ven],
|
||||
const define: typeof Object.defineProperty =
|
||||
(obj, prop, desc) => {
|
||||
if (Object.hasOwn(desc, "value"))
|
||||
desc.writable = true;
|
||||
|
||||
getShortcuts(): Record<PropertyKey, any> {
|
||||
return Object.defineProperty(obj, prop, {
|
||||
configurable: true,
|
||||
enumerable: true,
|
||||
...desc
|
||||
});
|
||||
};
|
||||
|
||||
function makeShortcuts() {
|
||||
function newFindWrapper(filterFactory: (...props: any[]) => Webpack.FilterFn) {
|
||||
const cache = new Map<string, unknown>();
|
||||
|
||||
|
@ -73,6 +83,7 @@ export default definePlugin({
|
|||
wpsearch: search,
|
||||
wpex: extract,
|
||||
wpexs: (code: string) => extract(findModuleId(code)!),
|
||||
loadLazyChunks: IS_DEV ? loadLazyChunks : () => { throw new Error("loadLazyChunks is dev only."); },
|
||||
find,
|
||||
findAll: findAll,
|
||||
findByProps,
|
||||
|
@ -87,14 +98,17 @@ export default definePlugin({
|
|||
plugins: { getter: () => Vencord.Plugins.plugins },
|
||||
Settings: { getter: () => Vencord.Settings },
|
||||
Api: { getter: () => Vencord.Api },
|
||||
Util: { getter: () => Vencord.Util },
|
||||
reload: () => location.reload(),
|
||||
restart: IS_WEB ? WEB_ONLY("restart") : relaunch,
|
||||
restart: IS_WEB ? DESKTOP_ONLY("restart") : relaunch,
|
||||
canonicalizeMatch,
|
||||
canonicalizeReplace,
|
||||
canonicalizeReplacement,
|
||||
fakeRender: (component: ComponentType, props: any) => {
|
||||
const prevWin = fakeRenderWin?.deref();
|
||||
const win = prevWin?.closed === false ? prevWin : window.open("about:blank", "Fake Render", "popup,width=500,height=500")!;
|
||||
const win = prevWin?.closed === false
|
||||
? prevWin
|
||||
: window.open("about:blank", "Fake Render", "popup,width=500,height=500")!;
|
||||
fakeRenderWin = new WeakRef(win);
|
||||
win.focus();
|
||||
|
||||
|
@ -117,38 +131,94 @@ export default definePlugin({
|
|||
}
|
||||
|
||||
Common.ReactDOM.render(Common.React.createElement(component, props), doc.body.appendChild(document.createElement("div")));
|
||||
},
|
||||
|
||||
preEnable: (plugin: string) => (Vencord.Settings.plugins[plugin] ??= { enabled: true }).enabled = true,
|
||||
|
||||
channel: { getter: () => getCurrentChannel(), preload: false },
|
||||
channelId: { getter: () => Common.SelectedChannelStore.getChannelId(), preload: false },
|
||||
guild: { getter: () => getCurrentGuild(), preload: false },
|
||||
guildId: { getter: () => Common.SelectedGuildStore.getGuildId(), preload: false },
|
||||
me: { getter: () => Common.UserStore.getCurrentUser(), preload: false },
|
||||
meId: { getter: () => Common.UserStore.getCurrentUser().id, preload: false },
|
||||
messages: { getter: () => Common.MessageStore.getMessages(Common.SelectedChannelStore.getChannelId()), preload: false },
|
||||
|
||||
Stores: {
|
||||
getter: () => Object.fromEntries(
|
||||
Common.Flux.Store.getAll()
|
||||
.map(store => [store.getName(), store] as const)
|
||||
.filter(([name]) => name.length > 1)
|
||||
)
|
||||
}
|
||||
};
|
||||
},
|
||||
}
|
||||
|
||||
function loadAndCacheShortcut(key: string, val: any, forceLoad: boolean) {
|
||||
const currentVal = val.getter();
|
||||
if (!currentVal || val.preload === false) return currentVal;
|
||||
|
||||
const value = currentVal[SYM_LAZY_GET]
|
||||
? forceLoad ? currentVal[SYM_LAZY_GET]() : currentVal[SYM_LAZY_CACHED]
|
||||
: currentVal;
|
||||
|
||||
if (value) define(window.shortcutList, key, { value });
|
||||
|
||||
return value;
|
||||
}
|
||||
|
||||
export default definePlugin({
|
||||
name: "ConsoleShortcuts",
|
||||
description: "Adds shorter Aliases for many things on the window. Run `shortcutList` for a list.",
|
||||
authors: [Devs.Ven],
|
||||
|
||||
startAt: StartAt.Init,
|
||||
start() {
|
||||
const shortcuts = this.getShortcuts();
|
||||
const shortcuts = makeShortcuts();
|
||||
window.shortcutList = {};
|
||||
|
||||
for (const [key, val] of Object.entries(shortcuts)) {
|
||||
if (val.getter != null) {
|
||||
Object.defineProperty(window.shortcutList, key, {
|
||||
get: val.getter,
|
||||
configurable: true,
|
||||
enumerable: true
|
||||
if ("getter" in val) {
|
||||
define(window.shortcutList, key, {
|
||||
get: () => loadAndCacheShortcut(key, val, true)
|
||||
});
|
||||
|
||||
Object.defineProperty(window, key, {
|
||||
get: () => window.shortcutList[key],
|
||||
configurable: true,
|
||||
enumerable: true
|
||||
define(window, key, {
|
||||
get: () => window.shortcutList[key]
|
||||
});
|
||||
} else {
|
||||
window.shortcutList[key] = val;
|
||||
window[key] = val;
|
||||
}
|
||||
}
|
||||
|
||||
// unproxy loaded modules
|
||||
Webpack.onceReady.then(() => {
|
||||
setTimeout(() => this.eagerLoad(false), 1000);
|
||||
|
||||
if (!IS_WEB) {
|
||||
const Native = VencordNative.pluginHelpers.ConsoleShortcuts as PluginNative<typeof import("./native")>;
|
||||
Native.initDevtoolsOpenEagerLoad();
|
||||
}
|
||||
});
|
||||
},
|
||||
|
||||
async eagerLoad(forceLoad: boolean) {
|
||||
await Webpack.onceReady;
|
||||
|
||||
const shortcuts = makeShortcuts();
|
||||
|
||||
for (const [key, val] of Object.entries(shortcuts)) {
|
||||
if (!Object.hasOwn(val, "getter") || (val as any).preload === false) continue;
|
||||
|
||||
try {
|
||||
loadAndCacheShortcut(key, val, forceLoad);
|
||||
} catch { } // swallow not found errors in DEV
|
||||
}
|
||||
},
|
||||
|
||||
stop() {
|
||||
delete window.shortcutList;
|
||||
for (const key in this.getShortcuts()) {
|
||||
for (const key in makeShortcuts()) {
|
||||
delete window[key];
|
||||
}
|
||||
}
|
||||
|
|
16
src/plugins/consoleShortcuts/native.ts
Normal file
16
src/plugins/consoleShortcuts/native.ts
Normal file
|
@ -0,0 +1,16 @@
|
|||
/*
|
||||
* Vencord, a Discord client mod
|
||||
* Copyright (c) 2024 Vendicated and contributors
|
||||
* SPDX-License-Identifier: GPL-3.0-or-later
|
||||
*/
|
||||
|
||||
import { IpcMainInvokeEvent } from "electron";
|
||||
|
||||
export function initDevtoolsOpenEagerLoad(e: IpcMainInvokeEvent) {
|
||||
const handleDevtoolsOpened = () => e.sender.executeJavaScript("Vencord.Plugins.plugins.ConsoleShortcuts.eagerLoad(true)");
|
||||
|
||||
if (e.sender.isDevToolsOpened())
|
||||
handleDevtoolsOpened();
|
||||
else
|
||||
e.sender.once("devtools-opened", () => handleDevtoolsOpened());
|
||||
}
|
5
src/plugins/copyEmojiMarkdown/README.md
Normal file
5
src/plugins/copyEmojiMarkdown/README.md
Normal file
|
@ -0,0 +1,5 @@
|
|||
# CopyEmojiMarkdown
|
||||
|
||||
Allows you to copy emojis as formatted string. Custom emojis will be copied as `<:trolley:1024751352028602449>`, default emojis as `🛒`
|
||||
|
||||
![](https://github.com/Vendicated/Vencord/assets/45497981/417f345a-7031-4fe7-8e42-e238870cd547)
|
75
src/plugins/copyEmojiMarkdown/index.tsx
Normal file
75
src/plugins/copyEmojiMarkdown/index.tsx
Normal file
|
@ -0,0 +1,75 @@
|
|||
/*
|
||||
* Vencord, a Discord client mod
|
||||
* Copyright (c) 2024 Vendicated and contributors
|
||||
* SPDX-License-Identifier: GPL-3.0-or-later
|
||||
*/
|
||||
|
||||
import { definePluginSettings } from "@api/Settings";
|
||||
import { Devs } from "@utils/constants";
|
||||
import { copyWithToast } from "@utils/misc";
|
||||
import definePlugin, { OptionType } from "@utils/types";
|
||||
import { findByPropsLazy } from "@webpack";
|
||||
import { Menu } from "@webpack/common";
|
||||
|
||||
const { convertNameToSurrogate } = findByPropsLazy("convertNameToSurrogate");
|
||||
|
||||
interface Emoji {
|
||||
type: string;
|
||||
id: string;
|
||||
name: string;
|
||||
}
|
||||
|
||||
interface Target {
|
||||
dataset: Emoji;
|
||||
firstChild: HTMLImageElement;
|
||||
}
|
||||
|
||||
function getEmojiMarkdown(target: Target, copyUnicode: boolean): string {
|
||||
const { id: emojiId, name: emojiName } = target.dataset;
|
||||
|
||||
if (!emojiId) {
|
||||
return copyUnicode
|
||||
? convertNameToSurrogate(emojiName)
|
||||
: `:${emojiName}:`;
|
||||
}
|
||||
|
||||
const extension = target?.firstChild.src.match(
|
||||
/https:\/\/cdn\.discordapp\.com\/emojis\/\d+\.(\w+)/
|
||||
)?.[1];
|
||||
|
||||
return `<${extension === "gif" ? "a" : ""}:${emojiName.replace(/~\d+$/, "")}:${emojiId}>`;
|
||||
}
|
||||
|
||||
const settings = definePluginSettings({
|
||||
copyUnicode: {
|
||||
type: OptionType.BOOLEAN,
|
||||
description: "Copy the raw unicode character instead of :name: for default emojis (👽)",
|
||||
default: true,
|
||||
},
|
||||
});
|
||||
|
||||
export default definePlugin({
|
||||
name: "CopyEmojiMarkdown",
|
||||
description: "Allows you to copy emojis as formatted string (<:blobcatcozy:1026533070955872337>)",
|
||||
authors: [Devs.HappyEnderman, Devs.Vishnya],
|
||||
settings,
|
||||
|
||||
contextMenus: {
|
||||
"expression-picker"(children, { target }: { target: Target }) {
|
||||
if (target.dataset.type !== "emoji") return;
|
||||
|
||||
children.push(
|
||||
<Menu.MenuItem
|
||||
id="vc-copy-emoji-markdown"
|
||||
label="Copy Emoji Markdown"
|
||||
action={() => {
|
||||
copyWithToast(
|
||||
getEmojiMarkdown(target, settings.store.copyUnicode),
|
||||
"Success! Copied emoji markdown."
|
||||
);
|
||||
}}
|
||||
/>
|
||||
);
|
||||
},
|
||||
},
|
||||
});
|
|
@ -24,20 +24,19 @@ import { closeAllModals } from "@utils/modal";
|
|||
import definePlugin, { OptionType } from "@utils/types";
|
||||
import { maybePromptToUpdate } from "@utils/updater";
|
||||
import { filters, findBulk, proxyLazyWebpack } from "@webpack";
|
||||
import { DraftType, FluxDispatcher, NavigationRouter, SelectedChannelStore } from "@webpack/common";
|
||||
import { DraftType, ExpressionPickerStore, FluxDispatcher, NavigationRouter, SelectedChannelStore } from "@webpack/common";
|
||||
|
||||
const CrashHandlerLogger = new Logger("CrashHandler");
|
||||
|
||||
const { ModalStack, DraftManager, closeExpressionPicker } = proxyLazyWebpack(() => {
|
||||
const [ModalStack, DraftManager, ExpressionManager] = findBulk(
|
||||
const { ModalStack, DraftManager } = proxyLazyWebpack(() => {
|
||||
const [ModalStack, DraftManager] = findBulk(
|
||||
filters.byProps("pushLazy", "popAll"),
|
||||
filters.byProps("clearDraft", "saveDraft"),
|
||||
filters.byProps("closeExpressionPicker", "openExpressionPicker"),);
|
||||
);
|
||||
|
||||
return {
|
||||
ModalStack,
|
||||
DraftManager,
|
||||
closeExpressionPicker: ExpressionManager?.closeExpressionPicker,
|
||||
DraftManager
|
||||
};
|
||||
});
|
||||
|
||||
|
@ -144,7 +143,7 @@ export default definePlugin({
|
|||
CrashHandlerLogger.debug("Failed to clear drafts.", err);
|
||||
}
|
||||
try {
|
||||
closeExpressionPicker();
|
||||
ExpressionPickerStore.closeExpressionPicker();
|
||||
}
|
||||
catch (err) {
|
||||
CrashHandlerLogger.debug("Failed to close expression picker.", err);
|
||||
|
|
|
@ -40,9 +40,9 @@ export default definePlugin({
|
|||
}),
|
||||
patches: [
|
||||
{
|
||||
find: "KeyboardKeys.ENTER&&(!",
|
||||
find: ".ENTER&&(!",
|
||||
replacement: {
|
||||
match: /(?<=(\i)\.which===\i\.KeyboardKeys.ENTER&&).{0,100}(\(0,\i\.hasOpenPlainTextCodeBlock\)\(\i\)).{0,100}(?=&&\(\i\.preventDefault)/,
|
||||
match: /(?<=(\i)\.which===\i\.\i.ENTER&&).{0,100}(\(0,\i\.\i\)\(\i\)).{0,100}(?=&&\(\i\.preventDefault)/,
|
||||
replace: "$self.shouldSubmit($1, $2)"
|
||||
}
|
||||
}
|
||||
|
|
|
@ -17,6 +17,7 @@
|
|||
*/
|
||||
|
||||
import { definePluginSettings, Settings } from "@api/Settings";
|
||||
import { getUserSettingLazy } from "@api/UserSettings";
|
||||
import { ErrorCard } from "@components/ErrorCard";
|
||||
import { Link } from "@components/Link";
|
||||
import { Devs } from "@utils/constants";
|
||||
|
@ -26,12 +27,14 @@ import { classes } from "@utils/misc";
|
|||
import { useAwaiter } from "@utils/react";
|
||||
import definePlugin, { OptionType } from "@utils/types";
|
||||
import { findByCodeLazy, findByPropsLazy, findComponentByCodeLazy } from "@webpack";
|
||||
import { ApplicationAssetUtils, Button, FluxDispatcher, Forms, GuildStore, React, SelectedChannelStore, SelectedGuildStore, StatusSettingsStores, UserStore } from "@webpack/common";
|
||||
import { ApplicationAssetUtils, Button, FluxDispatcher, Forms, GuildStore, React, SelectedChannelStore, SelectedGuildStore, UserStore } from "@webpack/common";
|
||||
|
||||
const useProfileThemeStyle = findByCodeLazy("profileThemeStyle:", "--profile-gradient-primary-color");
|
||||
const ActivityComponent = findComponentByCodeLazy("onOpenGameProfile");
|
||||
const ActivityClassName = findByPropsLazy("activity", "buttonColor");
|
||||
|
||||
const ShowCurrentGame = getUserSettingLazy<boolean>("status", "showCurrentGame")!;
|
||||
|
||||
async function getApplicationAsset(key: string): Promise<string> {
|
||||
if (/https?:\/\/(cdn|media)\.discordapp\.(com|net)\/attachments\//.test(key)) return "mp:" + key.replace(/https?:\/\/(cdn|media)\.discordapp\.(com|net)\//, "");
|
||||
return (await ApplicationAssetUtils.fetchAssetIds(settings.store.appID!, [key]))[0];
|
||||
|
@ -178,7 +181,7 @@ const settings = definePluginSettings({
|
|||
},
|
||||
startTime: {
|
||||
type: OptionType.NUMBER,
|
||||
description: "Start timestamp in milisecond (only for custom timestamp mode)",
|
||||
description: "Start timestamp in milliseconds (only for custom timestamp mode)",
|
||||
onChange: onChange,
|
||||
disabled: isTimestampDisabled,
|
||||
isValid: (value: number) => {
|
||||
|
@ -188,7 +191,7 @@ const settings = definePluginSettings({
|
|||
},
|
||||
endTime: {
|
||||
type: OptionType.NUMBER,
|
||||
description: "End timestamp in milisecond (only for custom timestamp mode)",
|
||||
description: "End timestamp in milliseconds (only for custom timestamp mode)",
|
||||
onChange: onChange,
|
||||
disabled: isTimestampDisabled,
|
||||
isValid: (value: number) => {
|
||||
|
@ -390,13 +393,14 @@ export default definePlugin({
|
|||
name: "CustomRPC",
|
||||
description: "Allows you to set a custom rich presence.",
|
||||
authors: [Devs.captain, Devs.AutumnVN, Devs.nin0dev],
|
||||
dependencies: ["UserSettingsAPI"],
|
||||
start: setRpc,
|
||||
stop: () => setRpc(true),
|
||||
settings,
|
||||
|
||||
settingsAboutComponent: () => {
|
||||
const activity = useAwaiter(createActivity);
|
||||
const gameActivityEnabled = StatusSettingsStores.ShowCurrentGame.useSetting();
|
||||
const gameActivityEnabled = ShowCurrentGame.useSetting();
|
||||
const { profileThemeStyle } = useProfileThemeStyle({});
|
||||
|
||||
return (
|
||||
|
@ -412,7 +416,7 @@ export default definePlugin({
|
|||
<Button
|
||||
color={Button.Colors.TRANSPARENT}
|
||||
className={Margins.top8}
|
||||
onClick={() => StatusSettingsStores.ShowCurrentGame.updateSetting(true)}
|
||||
onClick={() => ShowCurrentGame.updateSetting(true)}
|
||||
>
|
||||
Enable
|
||||
</Button>
|
||||
|
|
|
@ -33,26 +33,23 @@ export default definePlugin({
|
|||
authors: [Devs.newwares],
|
||||
settings,
|
||||
patches: [
|
||||
{
|
||||
find: "IDLE_DURATION:function(){return",
|
||||
replacement: {
|
||||
match: /(IDLE_DURATION:function\(\){return )\i/,
|
||||
replace: "$1$self.getIdleTimeout()"
|
||||
}
|
||||
},
|
||||
{
|
||||
find: 'type:"IDLE",idle:',
|
||||
replacement: [
|
||||
{
|
||||
match: /Math\.min\((\i\.AfkTimeout\.getSetting\(\)\*\i\.default\.Millis\.SECOND),\i\.IDLE_DURATION\)/,
|
||||
match: /(?<=Date\.now\(\)-\i>)\i\.\i/,
|
||||
replace: "$self.getIdleTimeout()"
|
||||
},
|
||||
{
|
||||
match: /Math\.min\((\i\.\i\.getSetting\(\)\*\i\.\i\.\i\.SECOND),\i\.\i\)/,
|
||||
replace: "$1" // Decouple idle from afk (phone notifications will remain at user setting or 10 min maximum)
|
||||
},
|
||||
{
|
||||
match: /\i\.default\.dispatch\({type:"IDLE",idle:!1}\)/,
|
||||
match: /\i\.\i\.dispatch\({type:"IDLE",idle:!1}\)/,
|
||||
replace: "$self.handleOnline()"
|
||||
},
|
||||
{
|
||||
match: /(setInterval\(\i,\.25\*)\i\.IDLE_DURATION/,
|
||||
match: /(setInterval\(\i,\.25\*)\i\.\i/,
|
||||
replace: "$1$self.getIntervalDelay()" // For web installs
|
||||
}
|
||||
]
|
||||
|
|
|
@ -69,7 +69,7 @@ async function embedDidMount(this: Component<Props>) {
|
|||
|
||||
if (hasTitle && replaceElements !== ReplaceElements.ReplaceThumbnailsOnly) {
|
||||
embed.dearrow.oldTitle = embed.rawTitle;
|
||||
embed.rawTitle = titles[0].title.replace(/ >(\S)/g, " $1");
|
||||
embed.rawTitle = titles[0].title.replace(/(^|\s)>(\S)/g, "$1$2");
|
||||
}
|
||||
|
||||
if (hasThumb && replaceElements !== ReplaceElements.ReplaceTitlesOnly) {
|
||||
|
@ -182,8 +182,8 @@ export default definePlugin({
|
|||
|
||||
// add dearrow button
|
||||
{
|
||||
match: /children:\[(?=null!=\i\?\i\.renderSuppressButton)/,
|
||||
replace: "children:[$self.renderButton(this),",
|
||||
match: /children:\[(?=null!=\i\?(\i)\.renderSuppressButton)/,
|
||||
replace: "children:[$self.renderButton($1),",
|
||||
predicate: () => !settings.store.hideButton
|
||||
}
|
||||
]
|
||||
|
|
|
@ -9,7 +9,6 @@ import "./ui/styles.css";
|
|||
import ErrorBoundary from "@components/ErrorBoundary";
|
||||
import { Devs } from "@utils/constants";
|
||||
import definePlugin from "@utils/types";
|
||||
import { findByPropsLazy } from "@webpack";
|
||||
import { UserStore } from "@webpack/common";
|
||||
|
||||
import { CDN_URL, RAW_SKU_ID, SKU_ID } from "./lib/constants";
|
||||
|
@ -20,7 +19,6 @@ import { settings } from "./settings";
|
|||
import { setDecorationGridDecoration, setDecorationGridItem } from "./ui/components";
|
||||
import DecorSection from "./ui/components/DecorSection";
|
||||
|
||||
const { isAnimatedAvatarDecoration } = findByPropsLazy("isAnimatedAvatarDecoration");
|
||||
export interface AvatarDecoration {
|
||||
asset: string;
|
||||
skuId: string;
|
||||
|
@ -61,7 +59,7 @@ export default definePlugin({
|
|||
},
|
||||
// Remove NEW label from decor avatar decorations
|
||||
{
|
||||
match: /(?<=\.Section\.PREMIUM_PURCHASE&&\i)(?<=avatarDecoration:(\i).+?)/,
|
||||
match: /(?<=\.\i\.PREMIUM_PURCHASE&&\i)(?<=avatarDecoration:(\i).+?)/,
|
||||
replace: "||$1.skuId===$self.SKU_ID"
|
||||
}
|
||||
]
|
||||
|
@ -93,7 +91,7 @@ export default definePlugin({
|
|||
replacement: [
|
||||
// Use Decor avatar decoration hook
|
||||
{
|
||||
match: /(?<=getAvatarDecorationURL\)\({avatarDecoration:)(\i).avatarDecoration(?=,)/,
|
||||
match: /(?<=\i\)\({avatarDecoration:)(\i).avatarDecoration(?=,)/,
|
||||
replace: "$self.useUserDecorAvatarDecoration($1)??$&"
|
||||
}
|
||||
]
|
||||
|
@ -133,7 +131,7 @@ export default definePlugin({
|
|||
if (avatarDecoration?.skuId === SKU_ID) {
|
||||
const parts = avatarDecoration.asset.split("_");
|
||||
// Remove a_ prefix if it's animated and animation is disabled
|
||||
if (isAnimatedAvatarDecoration(avatarDecoration.asset) && !canAnimate) parts.shift();
|
||||
if (avatarDecoration.asset.startsWith("a_") && !canAnimate) parts.shift();
|
||||
return `${CDN_URL}/${parts.join("_")}.png`;
|
||||
} else if (avatarDecoration?.skuId === RAW_SKU_ID) {
|
||||
return avatarDecoration.asset;
|
||||
|
|
|
@ -10,5 +10,5 @@ import { extractAndLoadChunksLazy, findByPropsLazy } from "@webpack";
|
|||
export const cl = classNameFactory("vc-decor-");
|
||||
export const DecorationModalStyles = findByPropsLazy("modalFooterShopButton");
|
||||
|
||||
export const requireAvatarDecorationModal = extractAndLoadChunksLazy(["openAvatarDecorationModal:"]);
|
||||
export const requireAvatarDecorationModal = extractAndLoadChunksLazy([".COLLECTIBLES_SHOP_FULLSCREEN&&"]);
|
||||
export const requireCreateStickerModal = extractAndLoadChunksLazy(["stickerInspected]:"]);
|
||||
|
|
|
@ -9,7 +9,7 @@ import { Link } from "@components/Link";
|
|||
import { openInviteModal } from "@utils/discord";
|
||||
import { Margins } from "@utils/margins";
|
||||
import { closeAllModals, ModalCloseButton, ModalContent, ModalFooter, ModalHeader, ModalProps, ModalRoot, ModalSize, openModal } from "@utils/modal";
|
||||
import { findByPropsLazy, findComponentByCodeLazy } from "@webpack";
|
||||
import { filters, findComponentByCodeLazy, mapMangledModuleLazy } from "@webpack";
|
||||
import { Button, FluxDispatcher, Forms, GuildStore, NavigationRouter, Text, TextInput, useEffect, useMemo, UserStore, useState } from "@webpack/common";
|
||||
|
||||
import { GUILD_ID, INVITE_KEY, RAW_SKU_ID } from "../../lib/constants";
|
||||
|
@ -19,7 +19,10 @@ import { AvatarDecorationModalPreview } from "../components";
|
|||
|
||||
const FileUpload = findComponentByCodeLazy("fileUploadInput,");
|
||||
|
||||
const { default: HelpMessage, HelpMessageTypes } = findByPropsLazy("HelpMessageTypes");
|
||||
const { HelpMessage, HelpMessageTypes } = mapMangledModuleLazy('POSITIVE=3]="POSITIVE', {
|
||||
HelpMessageTypes: filters.byProps("POSITIVE", "WARNING"),
|
||||
HelpMessage: filters.byCode(".iconDiv")
|
||||
});
|
||||
|
||||
function useObjectURL(object: Blob | MediaSource | null) {
|
||||
const [url, setUrl] = useState<string | null>(null);
|
||||
|
|
|
@ -21,7 +21,7 @@ import { definePluginSettings } from "@api/Settings";
|
|||
import { Devs } from "@utils/constants";
|
||||
import { Logger } from "@utils/Logger";
|
||||
import { canonicalizeMatch, canonicalizeReplace } from "@utils/patches";
|
||||
import definePlugin, { OptionType } from "@utils/types";
|
||||
import definePlugin, { OptionType, ReporterTestable } from "@utils/types";
|
||||
import { filters, findAll, search } from "@webpack";
|
||||
|
||||
const PORT = 8485;
|
||||
|
@ -243,6 +243,7 @@ export default definePlugin({
|
|||
name: "DevCompanion",
|
||||
description: "Dev Companion Plugin",
|
||||
authors: [Devs.Ven],
|
||||
reporterTestable: ReporterTestable.None,
|
||||
settings,
|
||||
|
||||
toolboxActions: {
|
||||
|
|
|
@ -29,7 +29,7 @@ export default definePlugin({
|
|||
{
|
||||
find: ".Messages.BOT_CALL_IDLE_DISCONNECT",
|
||||
replacement: {
|
||||
match: /,?(?=\i\(this,"idleTimeout",new \i\.Timeout\))/,
|
||||
match: /,?(?=\i\(this,"idleTimeout",new \i\.\i\))/,
|
||||
replace: ";return;"
|
||||
}
|
||||
},
|
||||
|
|
35
src/plugins/dontRoundMyTimestamps/index.ts
Normal file
35
src/plugins/dontRoundMyTimestamps/index.ts
Normal file
|
@ -0,0 +1,35 @@
|
|||
/*
|
||||
* 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 <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
import { Devs } from "@utils/constants";
|
||||
import definePlugin from "@utils/types";
|
||||
import { moment } from "@webpack/common";
|
||||
|
||||
export default definePlugin({
|
||||
name: "DontRoundMyTimestamps",
|
||||
authors: [Devs.Lexi],
|
||||
description: "Always rounds relative timestamps down, so 7.6y becomes 7y instead of 8y",
|
||||
|
||||
start() {
|
||||
moment.relativeTimeRounding(Math.floor);
|
||||
},
|
||||
|
||||
stop() {
|
||||
moment.relativeTimeRounding(Math.round);
|
||||
}
|
||||
});
|
|
@ -23,12 +23,12 @@ import { Logger } from "@utils/Logger";
|
|||
import { Margins } from "@utils/margins";
|
||||
import { ModalContent, ModalHeader, ModalRoot, openModalLazy } from "@utils/modal";
|
||||
import definePlugin from "@utils/types";
|
||||
import { findByPropsLazy, findStoreLazy } from "@webpack";
|
||||
import { findByCodeLazy, findStoreLazy } from "@webpack";
|
||||
import { Constants, EmojiStore, FluxDispatcher, Forms, GuildStore, Menu, PermissionsBits, PermissionStore, React, RestAPI, Toasts, Tooltip, UserStore } from "@webpack/common";
|
||||
import { Promisable } from "type-fest";
|
||||
|
||||
const StickersStore = findStoreLazy("StickersStore");
|
||||
const EmojiManager = findByPropsLazy("fetchEmoji", "uploadEmoji", "deleteEmoji");
|
||||
const uploadEmoji = findByCodeLazy(".GUILD_EMOJIS(", "EMOJI_UPLOAD_START");
|
||||
|
||||
interface Sticker {
|
||||
t: "Sticker";
|
||||
|
@ -106,7 +106,7 @@ async function cloneEmoji(guildId: string, emoji: Emoji) {
|
|||
reader.readAsDataURL(data);
|
||||
});
|
||||
|
||||
return EmojiManager.uploadEmoji({
|
||||
return uploadEmoji({
|
||||
guildId,
|
||||
name: emoji.name.split("~")[0],
|
||||
image: dataUrl
|
||||
|
|
3
src/plugins/experiments/hideBugReport.css
Normal file
3
src/plugins/experiments/hideBugReport.css
Normal file
|
@ -0,0 +1,3 @@
|
|||
#staff-help-popout-staff-help-bug-reporter {
|
||||
display: none;
|
||||
}
|
|
@ -17,22 +17,23 @@
|
|||
*/
|
||||
|
||||
import { definePluginSettings } from "@api/Settings";
|
||||
import { disableStyle, enableStyle } from "@api/Styles";
|
||||
import ErrorBoundary from "@components/ErrorBoundary";
|
||||
import { ErrorCard } from "@components/ErrorCard";
|
||||
import { Devs } from "@utils/constants";
|
||||
import { Logger } from "@utils/Logger";
|
||||
import { Margins } from "@utils/margins";
|
||||
import definePlugin, { OptionType } from "@utils/types";
|
||||
import { findByPropsLazy } from "@webpack";
|
||||
import { Forms, React, UserStore } from "@webpack/common";
|
||||
import { User } from "discord-types/general";
|
||||
import { Forms, React } from "@webpack/common";
|
||||
|
||||
const KbdStyles = findByPropsLazy("key", "removeBuildOverride");
|
||||
import hideBugReport from "./hideBugReport.css?managed";
|
||||
|
||||
const KbdStyles = findByPropsLazy("key", "combo");
|
||||
|
||||
const settings = definePluginSettings({
|
||||
enableIsStaff: {
|
||||
description: "Enable isStaff",
|
||||
toolbarDevMenu: {
|
||||
type: OptionType.BOOLEAN,
|
||||
description: "Change the Help (?) toolbar button (top right in chat) to Discord's developer menu",
|
||||
default: false,
|
||||
restartNeeded: true
|
||||
}
|
||||
|
@ -40,7 +41,7 @@ const settings = definePluginSettings({
|
|||
|
||||
export default definePlugin({
|
||||
name: "Experiments",
|
||||
description: "Enable Access to Experiments in Discord!",
|
||||
description: "Enable Access to Experiments & other dev-only features in Discord!",
|
||||
authors: [
|
||||
Devs.Megu,
|
||||
Devs.Ven,
|
||||
|
@ -48,6 +49,7 @@ export default definePlugin({
|
|||
Devs.BanTheNons,
|
||||
Devs.Nuckyz
|
||||
],
|
||||
|
||||
settings,
|
||||
|
||||
patches: [
|
||||
|
@ -65,37 +67,35 @@ export default definePlugin({
|
|||
replace: "$1=!0;"
|
||||
}
|
||||
},
|
||||
{
|
||||
find: '"isStaff",',
|
||||
predicate: () => settings.store.enableIsStaff,
|
||||
replacement: [
|
||||
{
|
||||
match: /(?<=>)(\i)\.hasFlag\((\i\.\i)\.STAFF\)(?=})/,
|
||||
replace: (_, user, flags) => `$self.isStaff(${user},${flags})`
|
||||
},
|
||||
{
|
||||
match: /hasFreePremium\(\){return this.isStaff\(\)\s*?\|\|/,
|
||||
replace: "hasFreePremium(){return ",
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
find: 'H1,title:"Experiments"',
|
||||
replacement: {
|
||||
match: 'title:"Experiments",children:[',
|
||||
replace: "$&$self.WarningCard(),"
|
||||
}
|
||||
},
|
||||
// change top right chat toolbar button from the help one to the dev one
|
||||
{
|
||||
find: "toolbar:function",
|
||||
replacement: {
|
||||
match: /\i\.isStaff\(\)/,
|
||||
replace: "true"
|
||||
},
|
||||
predicate: () => settings.store.toolbarDevMenu
|
||||
},
|
||||
|
||||
// makes the Favourites Server experiment allow favouriting DMs and threads
|
||||
{
|
||||
find: "useCanFavoriteChannel",
|
||||
replacement: {
|
||||
match: /!\(\i\.isDM\(\)\|\|\i\.isThread\(\)\)/,
|
||||
replace: "true",
|
||||
}
|
||||
}
|
||||
],
|
||||
|
||||
isStaff(user: User, flags: any) {
|
||||
try {
|
||||
return UserStore.getCurrentUser()?.id === user.id || user.hasFlag(flags.STAFF);
|
||||
} catch (err) {
|
||||
new Logger("Experiments").error(err);
|
||||
return user.hasFlag(flags.STAFF);
|
||||
}
|
||||
},
|
||||
start: () => enableStyle(hideBugReport),
|
||||
stop: () => disableStyle(hideBugReport),
|
||||
|
||||
settingsAboutComponent: () => {
|
||||
const isMacOS = navigator.platform.includes("Mac");
|
||||
|
@ -105,14 +105,12 @@ export default definePlugin({
|
|||
<React.Fragment>
|
||||
<Forms.FormTitle tag="h3">More Information</Forms.FormTitle>
|
||||
<Forms.FormText variant="text-md/normal">
|
||||
You can enable client DevTools{" "}
|
||||
You can open Discord's DevTools via {" "}
|
||||
<div className={KbdStyles.combo} style={{ display: "inline-flex" }}>
|
||||
<kbd className={KbdStyles.key}>{modKey}</kbd> +{" "}
|
||||
<kbd className={KbdStyles.key}>{altKey}</kbd> +{" "}
|
||||
<kbd className={KbdStyles.key}>O</kbd>{" "}
|
||||
after enabling <code>isStaff</code> below
|
||||
</Forms.FormText>
|
||||
<Forms.FormText>
|
||||
and then toggling <code>Enable DevTools</code> in the <code>Developer Options</code> tab in settings.
|
||||
</div>
|
||||
</Forms.FormText>
|
||||
</React.Fragment>
|
||||
);
|
||||
|
@ -128,6 +126,12 @@ export default definePlugin({
|
|||
|
||||
<Forms.FormText className={Margins.top8}>
|
||||
Only use experiments if you know what you're doing. Vencord is not responsible for any damage caused by enabling experiments.
|
||||
|
||||
If you don't know what an experiment does, ignore it. Do not ask us what experiments do either, we probably don't know.
|
||||
</Forms.FormText>
|
||||
|
||||
<Forms.FormText className={Margins.top8}>
|
||||
No, you cannot use server-side features like checking the "Send to Client" box.
|
||||
</Forms.FormText>
|
||||
</ErrorCard>
|
||||
), { noop: true })
|
||||
|
|
|
@ -23,7 +23,7 @@ import { ApngBlendOp, ApngDisposeOp, importApngJs } from "@utils/dependencies";
|
|||
import { getCurrentGuild } from "@utils/discord";
|
||||
import { Logger } from "@utils/Logger";
|
||||
import definePlugin, { OptionType } from "@utils/types";
|
||||
import { findByPropsLazy, findStoreLazy, proxyLazyWebpack } from "@webpack";
|
||||
import { findByCodeLazy, findByPropsLazy, findStoreLazy, proxyLazyWebpack } from "@webpack";
|
||||
import { Alerts, ChannelStore, DraftType, EmojiStore, FluxDispatcher, Forms, IconUtils, lodash, Parser, PermissionsBits, PermissionStore, UploadHandler, UserSettingsActionCreators, UserStore } from "@webpack/common";
|
||||
import type { Emoji } from "@webpack/types";
|
||||
import type { Message } from "discord-types/general";
|
||||
|
@ -37,8 +37,8 @@ const StickerStore = findStoreLazy("StickersStore") as {
|
|||
};
|
||||
|
||||
const UserSettingsProtoStore = findStoreLazy("UserSettingsProtoStore");
|
||||
const ProtoUtils = findByPropsLazy("BINARY_READ_OPTIONS");
|
||||
const RoleSubscriptionEmojiUtils = findByPropsLazy("isUnusableRoleSubscriptionEmoji");
|
||||
|
||||
const BINARY_READ_OPTIONS = findByPropsLazy("readerFactory");
|
||||
|
||||
function searchProtoClassField(localName: string, protoClass: any) {
|
||||
const field = protoClass?.fields?.find((field: any) => field.localName === localName);
|
||||
|
@ -52,6 +52,7 @@ const PreloadedUserSettingsActionCreators = proxyLazyWebpack(() => UserSettingsA
|
|||
const AppearanceSettingsActionCreators = proxyLazyWebpack(() => searchProtoClassField("appearance", PreloadedUserSettingsActionCreators.ProtoClass));
|
||||
const ClientThemeSettingsActionsCreators = proxyLazyWebpack(() => searchProtoClassField("clientThemeSettings", AppearanceSettingsActionCreators));
|
||||
|
||||
const isUnusableRoleSubscriptionEmoji = findByCodeLazy(".getUserIsAdmin(");
|
||||
|
||||
const enum EmojiIntentions {
|
||||
REACTION,
|
||||
|
@ -236,11 +237,10 @@ export default definePlugin({
|
|||
},
|
||||
// Allows the usage of subscription-locked emojis
|
||||
{
|
||||
find: "isUnusableRoleSubscriptionEmoji:function",
|
||||
find: ".getUserIsAdmin(",
|
||||
replacement: {
|
||||
match: /isUnusableRoleSubscriptionEmoji:function/,
|
||||
// Replace the original export with a func that always returns false and alias the original
|
||||
replace: "isUnusableRoleSubscriptionEmoji:()=>()=>false,isUnusableRoleSubscriptionEmojiOriginal:function"
|
||||
match: /(function \i\(\i,\i)\){(.{0,250}.getUserIsAdmin\(.+?return!1})/,
|
||||
replace: (_, rest1, rest2) => `${rest1},fakeNitroOriginal){if(!fakeNitroOriginal)return false;${rest2}`
|
||||
}
|
||||
},
|
||||
// Allow stickers to be sent everywhere
|
||||
|
@ -333,12 +333,12 @@ export default definePlugin({
|
|||
]
|
||||
},
|
||||
{
|
||||
find: "renderEmbeds(",
|
||||
find: "}renderEmbeds(",
|
||||
replacement: [
|
||||
{
|
||||
// Call our function to decide whether the embed should be ignored or not
|
||||
predicate: () => settings.store.transformEmojis || settings.store.transformStickers,
|
||||
match: /(renderEmbeds\((\i)\){)(.+?embeds\.map\((\i)=>{)/,
|
||||
match: /(renderEmbeds\((\i)\){)(.+?embeds\.map\(\((\i),\i\)?=>{)/,
|
||||
replace: (_, rest1, message, rest2, embed) => `${rest1}const fakeNitroMessage=${message};${rest2}if($self.shouldIgnoreEmbed(${embed},fakeNitroMessage))return null;`
|
||||
},
|
||||
{
|
||||
|
@ -361,7 +361,7 @@ export default definePlugin({
|
|||
replacement: [
|
||||
{
|
||||
// Export the renderable sticker to be used in the fake nitro sticker notice
|
||||
match: /let{renderableSticker:(\i).{0,250}isGuildSticker.+?channel:\i,/,
|
||||
match: /let{renderableSticker:(\i).{0,270}sticker:\i,channel:\i,/,
|
||||
replace: (m, renderableSticker) => `${m}fakeNitroRenderableSticker:${renderableSticker},`
|
||||
},
|
||||
{
|
||||
|
@ -399,7 +399,7 @@ export default definePlugin({
|
|||
},
|
||||
// Separate patch for allowing using custom app icons
|
||||
{
|
||||
find: ".FreemiumAppIconIds.DEFAULT&&(",
|
||||
find: /\.getCurrentDesktopIcon.{0,25}\.isPremium/,
|
||||
replacement: {
|
||||
match: /\i\.\i\.isPremium\(\i\.\i\.getCurrentUser\(\)\)/,
|
||||
replace: "true"
|
||||
|
@ -472,12 +472,12 @@ export default definePlugin({
|
|||
const premiumType = UserStore?.getCurrentUser()?.premiumType ?? 0;
|
||||
if (premiumType === 2 || backgroundGradientPresetId == null) return original();
|
||||
|
||||
if (!PreloadedUserSettingsActionCreators || !AppearanceSettingsActionCreators || !ClientThemeSettingsActionsCreators || !ProtoUtils) return;
|
||||
if (!PreloadedUserSettingsActionCreators || !AppearanceSettingsActionCreators || !ClientThemeSettingsActionsCreators || !BINARY_READ_OPTIONS) return;
|
||||
|
||||
const currentAppearanceSettings = PreloadedUserSettingsActionCreators.getCurrentValue().appearance;
|
||||
|
||||
const newAppearanceProto = currentAppearanceSettings != null
|
||||
? AppearanceSettingsActionCreators.fromBinary(AppearanceSettingsActionCreators.toBinary(currentAppearanceSettings), ProtoUtils.BINARY_READ_OPTIONS)
|
||||
? AppearanceSettingsActionCreators.fromBinary(AppearanceSettingsActionCreators.toBinary(currentAppearanceSettings), BINARY_READ_OPTIONS)
|
||||
: AppearanceSettingsActionCreators.create();
|
||||
|
||||
newAppearanceProto.theme = theme;
|
||||
|
@ -816,8 +816,7 @@ export default definePlugin({
|
|||
if (e.type === 0) return true;
|
||||
if (e.available === false) return false;
|
||||
|
||||
const isUnusableRoleSubEmoji = RoleSubscriptionEmojiUtils.isUnusableRoleSubscriptionEmojiOriginal ?? RoleSubscriptionEmojiUtils.isUnusableRoleSubscriptionEmoji;
|
||||
if (isUnusableRoleSubEmoji(e, this.guildId)) return false;
|
||||
if (isUnusableRoleSubscriptionEmoji(e, this.guildId, true)) return false;
|
||||
|
||||
if (this.canUseEmotes)
|
||||
return e.guildId === this.guildId || hasExternalEmojiPerms(channelId);
|
||||
|
|
|
@ -111,7 +111,7 @@ interface ProfileModalProps {
|
|||
const ColorPicker = findComponentByCodeLazy<ColorPickerProps>(".Messages.USER_SETTINGS_PROFILE_COLOR_SELECT_COLOR", ".BACKGROUND_PRIMARY)");
|
||||
const ProfileModal = findComponentByCodeLazy<ProfileModalProps>('"ProfileCustomizationPreview"');
|
||||
|
||||
const requireColorPicker = extractAndLoadChunksLazy(["USER_SETTINGS_PROFILE_COLOR_DEFAULT_BUTTON.format"], /createPromise:\(\)=>\i\.\i\("(.+?)"\).then\(\i\.bind\(\i,"(.+?)"\)\)/);
|
||||
const requireColorPicker = extractAndLoadChunksLazy(["USER_SETTINGS_PROFILE_COLOR_DEFAULT_BUTTON.format"], /createPromise:\(\)=>\i\.\i\("?(.+?)"?\).then\(\i\.bind\(\i,"?(.+?)"?\)\)/);
|
||||
|
||||
export default definePlugin({
|
||||
name: "FakeProfileThemes",
|
||||
|
|
|
@ -50,7 +50,7 @@ export default definePlugin({
|
|||
},
|
||||
|
||||
{
|
||||
find: "MAX_AUTOCOMPLETE_RESULTS+",
|
||||
find: "numLockedEmojiResults:",
|
||||
replacement: [
|
||||
// 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
|
||||
|
|
|
@ -25,7 +25,7 @@ export default definePlugin({
|
|||
authors: [Devs.Grzesiek11],
|
||||
patches: [
|
||||
{
|
||||
find: ".default.Messages.DELETED_ROLE_PLACEHOLDER",
|
||||
find: String.raw`/^${"```"}(?:([a-z0-9_+\-.#]+?)\n)?\n*([^\n][^]*?)\n*${"```"}`,
|
||||
replacement: {
|
||||
match: String.raw`/^${"```"}(?:([a-z0-9_+\-.#]+?)\n)?\n*([^\n][^]*?)\n*${"```"}`,
|
||||
replace: "$&\\n?",
|
||||
|
|
|
@ -27,7 +27,7 @@ export default definePlugin({
|
|||
authors: [Devs.D3SOX, Devs.Nickyux],
|
||||
patches: [
|
||||
{
|
||||
find: "AVATAR_DECORATION_PADDING:",
|
||||
find: ".PREMIUM_GUILD_SUBSCRIPTION_TOOLTIP",
|
||||
replacement: {
|
||||
match: /,isOwner:(\i),/,
|
||||
replace: ",_isOwner:$1=$self.isGuildOwner(e),"
|
||||
|
|
|
@ -16,14 +16,12 @@
|
|||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
import { ApplicationCommandInputType, ApplicationCommandOptionType, findOption, sendBotMessage } from "@api/Commands";
|
||||
import { ApplicationCommandInputType, sendBotMessage } from "@api/Commands";
|
||||
import { Devs } from "@utils/constants";
|
||||
import definePlugin from "@utils/types";
|
||||
import { findByPropsLazy } from "@webpack";
|
||||
import { Constants, RestAPI, UserStore } from "@webpack/common";
|
||||
|
||||
const FriendInvites = findByPropsLazy("createFriendInvite");
|
||||
const { uuid4 } = findByPropsLazy("uuid4");
|
||||
|
||||
export default definePlugin({
|
||||
name: "FriendInvites",
|
||||
|
@ -35,47 +33,9 @@ export default definePlugin({
|
|||
name: "create friend invite",
|
||||
description: "Generates a friend invite link.",
|
||||
inputType: ApplicationCommandInputType.BOT,
|
||||
options: [{
|
||||
name: "Uses",
|
||||
description: "How many uses?",
|
||||
choices: [
|
||||
{ label: "1", name: "1", value: "1" },
|
||||
{ label: "5", name: "5", value: "5" }
|
||||
],
|
||||
required: false,
|
||||
type: ApplicationCommandOptionType.INTEGER
|
||||
}],
|
||||
|
||||
execute: async (args, ctx) => {
|
||||
const uses = findOption<number>(args, "Uses", 5);
|
||||
|
||||
if (uses === 1 && !UserStore.getCurrentUser().phone)
|
||||
return sendBotMessage(ctx.channel.id, {
|
||||
content: "You need to have a phone number connected to your account to create a friend invite with 1 use!"
|
||||
});
|
||||
|
||||
let invite: any;
|
||||
if (uses === 1) {
|
||||
const random = uuid4();
|
||||
const { body: { invite_suggestions } } = await RestAPI.post({
|
||||
url: Constants.Endpoints.FRIEND_FINDER,
|
||||
body: {
|
||||
modified_contacts: {
|
||||
[random]: [1, "", ""]
|
||||
},
|
||||
phone_contact_methods_count: 1
|
||||
}
|
||||
});
|
||||
invite = await FriendInvites.createFriendInvite({
|
||||
code: invite_suggestions[0][3],
|
||||
recipient_phone_number_or_email: random,
|
||||
contact_visibility: 1,
|
||||
filter_visibilities: [],
|
||||
filtered_invite_suggestions_index: 1
|
||||
});
|
||||
} else {
|
||||
invite = await FriendInvites.createFriendInvite();
|
||||
}
|
||||
const invite = await FriendInvites.createFriendInvite();
|
||||
|
||||
sendBotMessage(ctx.channel.id, {
|
||||
content: `
|
||||
|
|
|
@ -4,21 +4,23 @@
|
|||
* SPDX-License-Identifier: GPL-3.0-or-later
|
||||
*/
|
||||
|
||||
import { classNameFactory } from "@api/Styles";
|
||||
import ErrorBoundary from "@components/ErrorBoundary";
|
||||
import { Devs } from "@utils/constants";
|
||||
import { getCurrentChannel } from "@utils/discord";
|
||||
import { Logger } from "@utils/Logger";
|
||||
import { classes } from "@utils/misc";
|
||||
import definePlugin from "@utils/types";
|
||||
import { findByPropsLazy } from "@webpack";
|
||||
import { findByCodeLazy, findByPropsLazy } from "@webpack";
|
||||
import { Heading, React, RelationshipStore, Text } from "@webpack/common";
|
||||
|
||||
const container = findByPropsLazy("memberSinceWrapper");
|
||||
const { getCreatedAtDate } = findByPropsLazy("getCreatedAtDate");
|
||||
const clydeMoreInfo = findByPropsLazy("clydeMoreInfo");
|
||||
const getCreatedAtDate = findByCodeLazy('month:"short",day:"numeric"');
|
||||
const locale = findByPropsLazy("getLocale");
|
||||
const lastSection = findByPropsLazy("lastSection");
|
||||
|
||||
const cl = classNameFactory("vc-friendssince-");
|
||||
|
||||
export default definePlugin({
|
||||
name: "FriendsSince",
|
||||
description: "Shows when you became friends with someone in the user popout",
|
||||
|
@ -26,17 +28,17 @@ export default definePlugin({
|
|||
patches: [
|
||||
// User popup
|
||||
{
|
||||
find: ".AnalyticsSections.USER_PROFILE}",
|
||||
find: ".USER_PROFILE}};return",
|
||||
replacement: {
|
||||
match: /\i.default,\{userId:(\i.id).{0,30}}\)/,
|
||||
match: /,{userId:(\i.id).{0,30}}\)/,
|
||||
replace: "$&,$self.friendsSince({ userId: $1 })"
|
||||
}
|
||||
},
|
||||
// User DMs "User Profile" popup in the right
|
||||
{
|
||||
find: ".UserPopoutUpsellSource.PROFILE_PANEL,",
|
||||
find: ".PROFILE_PANEL,",
|
||||
replacement: {
|
||||
match: /\i.default,\{userId:(\i)}\)/,
|
||||
match: /,{userId:([^,]+?)}\)/,
|
||||
replace: "$&,$self.friendsSince({ userId: $1 })"
|
||||
}
|
||||
},
|
||||
|
@ -69,7 +71,7 @@ export default definePlugin({
|
|||
|
||||
return (
|
||||
<div className={lastSection.section}>
|
||||
<Heading variant="eyebrow" className={clydeMoreInfo.title}>
|
||||
<Heading variant="eyebrow" className={cl("title")}>
|
||||
Friends Since
|
||||
</Heading>
|
||||
|
||||
|
@ -86,7 +88,7 @@ export default definePlugin({
|
|||
<path d="M3 5v-.75C3 3.56 3.56 3 4.25 3s1.24.56 1.33 1.25C6.12 8.65 9.46 12 13 12h1a8 8 0 0 1 8 8 2 2 0 0 1-2 2 .21.21 0 0 1-.2-.15 7.65 7.65 0 0 0-1.32-2.3c-.15-.2-.42-.06-.39.17l.25 2c.02.15-.1.28-.25.28H9a2 2 0 0 1-2-2v-2.22c0-1.57-.67-3.05-1.53-4.37A15.85 15.85 0 0 1 3 5Z" />
|
||||
</svg>
|
||||
)}
|
||||
<Text variant="text-sm/normal" className={classes(clydeMoreInfo.body, textClassName)}>
|
||||
<Text variant="text-sm/normal" className={classes(cl("body"), textClassName)}>
|
||||
{getCreatedAtDate(friendsSince, locale.getLocale())}
|
||||
</Text>
|
||||
</div>
|
||||
|
|
12
src/plugins/friendsSince/styles.css
Normal file
12
src/plugins/friendsSince/styles.css
Normal file
|
@ -0,0 +1,12 @@
|
|||
/* copy pasted from discord */
|
||||
|
||||
.vc-friendssince-title {
|
||||
display: flex;
|
||||
font-weight: 700;
|
||||
margin-bottom: 6px
|
||||
}
|
||||
|
||||
.vc-friendssince-body {
|
||||
font-size: 14px;
|
||||
line-height: 18px
|
||||
}
|
|
@ -18,16 +18,18 @@
|
|||
|
||||
import { definePluginSettings } from "@api/Settings";
|
||||
import { disableStyle, enableStyle } from "@api/Styles";
|
||||
import { getUserSettingLazy } from "@api/UserSettings";
|
||||
import ErrorBoundary from "@components/ErrorBoundary";
|
||||
import { Devs } from "@utils/constants";
|
||||
import definePlugin, { OptionType } from "@utils/types";
|
||||
import { findComponentByCodeLazy } from "@webpack";
|
||||
import { StatusSettingsStores } from "@webpack/common";
|
||||
|
||||
import style from "./style.css?managed";
|
||||
|
||||
const Button = findComponentByCodeLazy("Button.Sizes.NONE,disabled:");
|
||||
|
||||
const ShowCurrentGame = getUserSettingLazy<boolean>("status", "showCurrentGame")!;
|
||||
|
||||
function makeIcon(showCurrentGame?: boolean) {
|
||||
const { oldIcon } = settings.use(["oldIcon"]);
|
||||
|
||||
|
@ -60,7 +62,7 @@ function makeIcon(showCurrentGame?: boolean) {
|
|||
}
|
||||
|
||||
function GameActivityToggleButton() {
|
||||
const showCurrentGame = StatusSettingsStores.ShowCurrentGame.useSetting();
|
||||
const showCurrentGame = ShowCurrentGame.useSetting();
|
||||
|
||||
return (
|
||||
<Button
|
||||
|
@ -68,7 +70,7 @@ function GameActivityToggleButton() {
|
|||
icon={makeIcon(showCurrentGame)}
|
||||
role="switch"
|
||||
aria-checked={!showCurrentGame}
|
||||
onClick={() => StatusSettingsStores.ShowCurrentGame.updateSetting(old => !old)}
|
||||
onClick={() => ShowCurrentGame.updateSetting(old => !old)}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
@ -85,6 +87,7 @@ export default definePlugin({
|
|||
name: "GameActivityToggle",
|
||||
description: "Adds a button next to the mic and deafen button to toggle game activity.",
|
||||
authors: [Devs.Nuckyz, Devs.RuukuLada],
|
||||
dependencies: ["UserSettingsAPI"],
|
||||
settings,
|
||||
|
||||
patches: [
|
||||
|
|
|
@ -1,3 +1,3 @@
|
|||
[class*="withTagAsButton"] {
|
||||
min-width: 88px !important;
|
||||
[class*="panels"] [class*="avatarWrapper"] {
|
||||
min-width: 88px;
|
||||
}
|
||||
|
|
|
@ -19,9 +19,7 @@
|
|||
import { Devs } from "@utils/constants";
|
||||
import { insertTextIntoChatInputBox } from "@utils/discord";
|
||||
import definePlugin from "@utils/types";
|
||||
import { findByPropsLazy } from "@webpack";
|
||||
|
||||
const { closeExpressionPicker } = findByPropsLazy("closeExpressionPicker");
|
||||
import { ExpressionPickerStore } from "@webpack/common";
|
||||
|
||||
export default definePlugin({
|
||||
name: "GifPaste",
|
||||
|
@ -39,7 +37,7 @@ export default definePlugin({
|
|||
handleSelect(gif?: { url: string; }) {
|
||||
if (gif) {
|
||||
insertTextIntoChatInputBox(gif.url + " ");
|
||||
closeExpressionPicker();
|
||||
ExpressionPickerStore.closeExpressionPicker();
|
||||
}
|
||||
}
|
||||
});
|
||||
|
|
|
@ -19,7 +19,7 @@
|
|||
import { definePluginSettings } from "@api/Settings";
|
||||
import { Devs } from "@utils/constants";
|
||||
import definePlugin, { OptionType } from "@utils/types";
|
||||
import { findByPropsLazy } from "@webpack";
|
||||
import { findLazy } from "@webpack";
|
||||
import { ContextMenuApi, FluxDispatcher, Menu, MessageActions } from "@webpack/common";
|
||||
import { Channel, Message } from "discord-types/general";
|
||||
|
||||
|
@ -49,7 +49,7 @@ const settings = definePluginSettings({
|
|||
unholyMultiGreetEnabled?: boolean;
|
||||
}>();
|
||||
|
||||
const { WELCOME_STICKERS } = findByPropsLazy("WELCOME_STICKERS");
|
||||
const WELCOME_STICKERS = findLazy(m => Array.isArray(m) && m[0]?.name === "Wave");
|
||||
|
||||
function greet(channel: Channel, message: Message, stickers: string[]) {
|
||||
const options = MessageActions.getSendMessageOptionsForReply({
|
||||
|
|
|
@ -6,13 +6,14 @@
|
|||
|
||||
import * as DataStore from "@api/DataStore";
|
||||
import { definePluginSettings, Settings } from "@api/Settings";
|
||||
import { getUserSettingLazy } from "@api/UserSettings";
|
||||
import ErrorBoundary from "@components/ErrorBoundary";
|
||||
import { Flex } from "@components/Flex";
|
||||
import { Devs } from "@utils/constants";
|
||||
import { Margins } from "@utils/margins";
|
||||
import definePlugin, { OptionType } from "@utils/types";
|
||||
import { findStoreLazy } from "@webpack";
|
||||
import { Button, Forms, showToast, StatusSettingsStores, TextInput, Toasts, Tooltip, useEffect, useState } from "webpack/common";
|
||||
import { Button, Forms, showToast, TextInput, Toasts, Tooltip, useEffect, useState } from "webpack/common";
|
||||
|
||||
const enum ActivitiesTypes {
|
||||
Game,
|
||||
|
@ -27,6 +28,8 @@ interface IgnoredActivity {
|
|||
|
||||
const RunningGameStore = findStoreLazy("RunningGameStore");
|
||||
|
||||
const ShowCurrentGame = getUserSettingLazy("status", "showCurrentGame")!;
|
||||
|
||||
function ToggleIcon(activity: IgnoredActivity, tooltipText: string, path: string, fill: string) {
|
||||
return (
|
||||
<Tooltip text={tooltipText}>
|
||||
|
@ -68,7 +71,7 @@ function handleActivityToggle(e: React.MouseEvent<HTMLButtonElement, MouseEvent>
|
|||
else settings.store.ignoredActivities = getIgnoredActivities().filter((_, index) => index !== ignoredActivityIndex);
|
||||
|
||||
// Trigger activities recalculation
|
||||
StatusSettingsStores.ShowCurrentGame.updateSetting(old => old);
|
||||
ShowCurrentGame.updateSetting(old => old);
|
||||
}
|
||||
|
||||
function ImportCustomRPCComponent() {
|
||||
|
@ -205,6 +208,7 @@ export default definePlugin({
|
|||
name: "IgnoreActivities",
|
||||
authors: [Devs.Nuckyz],
|
||||
description: "Ignore activities from showing up on your status ONLY. You can configure which ones are specifically ignored from the Registered Games and Activities tabs, or use the general settings below.",
|
||||
dependencies: ["UserSettingsAPI"],
|
||||
|
||||
settings,
|
||||
|
||||
|
|
|
@ -16,7 +16,8 @@ export default definePlugin({
|
|||
{
|
||||
find: "unknownUserMentionPlaceholder:",
|
||||
replacement: {
|
||||
match: /\(0,\i\.isEmbedInline\)\(\i\)/,
|
||||
// SimpleEmbedTypes.has(embed.type) && isEmbedInline(embed)
|
||||
match: /\i\.has\(\i\.type\)&&\(0,\i\.\i\)\(\i\)/,
|
||||
replace: "false",
|
||||
}
|
||||
}
|
||||
|
|
|
@ -67,15 +67,18 @@ export const Magnifier = ErrorBoundary.wrap<MagnifierProps>(({ instance, size: i
|
|||
}
|
||||
};
|
||||
const syncVideos = () => {
|
||||
currentVideoElementRef.current!.currentTime = originalVideoElementRef.current!.currentTime;
|
||||
if (currentVideoElementRef.current && originalVideoElementRef.current)
|
||||
currentVideoElementRef.current.currentTime = originalVideoElementRef.current.currentTime;
|
||||
};
|
||||
|
||||
const updateMousePosition = (e: MouseEvent) => {
|
||||
if (!element.current) return;
|
||||
|
||||
if (instance.state.mouseOver && instance.state.mouseDown) {
|
||||
const offset = size.current / 2;
|
||||
const pos = { x: e.pageX, y: e.pageY };
|
||||
const x = -((pos.x - element.current!.getBoundingClientRect().left) * zoom.current - offset);
|
||||
const y = -((pos.y - element.current!.getBoundingClientRect().top) * zoom.current - offset);
|
||||
const x = -((pos.x - element.current.getBoundingClientRect().left) * zoom.current - offset);
|
||||
const y = -((pos.y - element.current.getBoundingClientRect().top) * zoom.current - offset);
|
||||
setLensPosition({ x: e.x - offset, y: e.y - offset });
|
||||
setImagePosition({ x, y });
|
||||
setOpacity(1);
|
||||
|
@ -184,6 +187,7 @@ export const Magnifier = ErrorBoundary.wrap<MagnifierProps>(({ instance, size: i
|
|||
src={originalVideoElementRef.current?.src ?? instance.props.src}
|
||||
autoPlay
|
||||
loop
|
||||
muted
|
||||
/>
|
||||
) : (
|
||||
<img
|
||||
|
|
|
@ -19,17 +19,11 @@
|
|||
import { definePluginSettings } from "@api/Settings";
|
||||
import { Devs } from "@utils/constants";
|
||||
import definePlugin, { OptionType } from "@utils/types";
|
||||
import { findByPropsLazy, findStoreLazy } from "@webpack";
|
||||
import { ChannelStore, FluxDispatcher, GuildStore, RelationshipStore, SnowflakeUtils, UserStore } from "@webpack/common";
|
||||
import { findStoreLazy } from "@webpack";
|
||||
import { ChannelStore, Constants, FluxDispatcher, GuildStore, RelationshipStore, SnowflakeUtils, UserStore } from "@webpack/common";
|
||||
import { Settings } from "Vencord";
|
||||
|
||||
const UserAffinitiesStore = findStoreLazy("UserAffinitiesStore");
|
||||
const { FriendsSections } = findByPropsLazy("FriendsSections");
|
||||
|
||||
interface UserAffinity {
|
||||
user_id: string;
|
||||
affinity: number;
|
||||
}
|
||||
|
||||
export default definePlugin({
|
||||
name: "ImplicitRelationships",
|
||||
|
@ -70,7 +64,7 @@ export default definePlugin({
|
|||
},
|
||||
// Piggyback relationship fetch
|
||||
{
|
||||
find: ".fetchRelationships()",
|
||||
find: '"FriendsStore',
|
||||
replacement: {
|
||||
match: /(\i\.\i)\.fetchRelationships\(\)/,
|
||||
// This relationship fetch is actually completely useless, but whatevs
|
||||
|
@ -182,6 +176,6 @@ export default definePlugin({
|
|||
},
|
||||
|
||||
start() {
|
||||
FriendsSections.IMPLICIT = "IMPLICIT";
|
||||
Constants.FriendsSections.IMPLICIT = "IMPLICIT";
|
||||
}
|
||||
});
|
||||
|
|
|
@ -21,7 +21,7 @@ import { addContextMenuPatch, removeContextMenuPatch } from "@api/ContextMenu";
|
|||
import { Settings } from "@api/Settings";
|
||||
import { Logger } from "@utils/Logger";
|
||||
import { canonicalizeFind } from "@utils/patches";
|
||||
import { Patch, Plugin, StartAt } from "@utils/types";
|
||||
import { Patch, Plugin, ReporterTestable, StartAt } from "@utils/types";
|
||||
import { FluxDispatcher } from "@webpack/common";
|
||||
import { FluxEvents } from "@webpack/types";
|
||||
|
||||
|
@ -39,6 +39,7 @@ export const patches = [] as Patch[];
|
|||
let enabledPluginsSubscribedFlux = false;
|
||||
const subscribedFluxEventsPlugins = new Set<string>();
|
||||
|
||||
const pluginsValues = Object.values(Plugins);
|
||||
const settings = Settings.plugins;
|
||||
|
||||
export function isPluginEnabled(p: string) {
|
||||
|
@ -49,25 +50,56 @@ export function isPluginEnabled(p: string) {
|
|||
) ?? false;
|
||||
}
|
||||
|
||||
const pluginsValues = Object.values(Plugins);
|
||||
export function addPatch(newPatch: Omit<Patch, "plugin">, pluginName: string) {
|
||||
const patch = newPatch as Patch;
|
||||
patch.plugin = pluginName;
|
||||
|
||||
// First roundtrip to mark and force enable dependencies (only for enabled plugins)
|
||||
if (IS_REPORTER) {
|
||||
delete patch.predicate;
|
||||
delete patch.group;
|
||||
}
|
||||
|
||||
canonicalizeFind(patch);
|
||||
if (!Array.isArray(patch.replacement)) {
|
||||
patch.replacement = [patch.replacement];
|
||||
}
|
||||
|
||||
if (IS_REPORTER) {
|
||||
patch.replacement.forEach(r => {
|
||||
delete r.predicate;
|
||||
});
|
||||
}
|
||||
|
||||
patches.push(patch);
|
||||
}
|
||||
|
||||
function isReporterTestable(p: Plugin, part: ReporterTestable) {
|
||||
return p.reporterTestable == null
|
||||
? true
|
||||
: (p.reporterTestable & part) === part;
|
||||
}
|
||||
|
||||
// First round-trip to mark and force enable dependencies
|
||||
//
|
||||
// FIXME: might need to revisit this if there's ever nested (dependencies of dependencies) dependencies since this only
|
||||
// goes for the top level and their children, but for now this works okay with the current API plugins
|
||||
for (const p of pluginsValues) if (settings[p.name]?.enabled) {
|
||||
for (const p of pluginsValues) if (isPluginEnabled(p.name)) {
|
||||
p.dependencies?.forEach(d => {
|
||||
const dep = Plugins[d];
|
||||
if (dep) {
|
||||
|
||||
if (!dep) {
|
||||
const error = new Error(`Plugin ${p.name} has unresolved dependency ${d}`);
|
||||
|
||||
if (IS_DEV) {
|
||||
throw error;
|
||||
}
|
||||
|
||||
logger.warn(error);
|
||||
return;
|
||||
}
|
||||
|
||||
settings[d].enabled = true;
|
||||
dep.isDependency = true;
|
||||
}
|
||||
else {
|
||||
const error = new Error(`Plugin ${p.name} has unresolved dependency ${d}`);
|
||||
if (IS_DEV)
|
||||
throw error;
|
||||
logger.warn(error);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
|
@ -82,23 +114,18 @@ for (const p of pluginsValues) {
|
|||
}
|
||||
|
||||
if (p.patches && isPluginEnabled(p.name)) {
|
||||
if (!IS_REPORTER || isReporterTestable(p, ReporterTestable.Patches)) {
|
||||
for (const patch of p.patches) {
|
||||
patch.plugin = p.name;
|
||||
|
||||
canonicalizeFind(patch);
|
||||
if (!Array.isArray(patch.replacement)) {
|
||||
patch.replacement = [patch.replacement];
|
||||
addPatch(patch, p.name);
|
||||
}
|
||||
|
||||
patches.push(patch);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export const startAllPlugins = traceFunction("startAllPlugins", function startAllPlugins(target: StartAt) {
|
||||
logger.info(`Starting plugins (stage ${target})`);
|
||||
for (const name in Plugins)
|
||||
if (isPluginEnabled(name)) {
|
||||
for (const name in Plugins) {
|
||||
if (isPluginEnabled(name) && (!IS_REPORTER || isReporterTestable(Plugins[name], ReporterTestable.Start))) {
|
||||
const p = Plugins[name];
|
||||
|
||||
const startAt = p.startAt ?? StartAt.WebpackReady;
|
||||
|
@ -106,35 +133,54 @@ export const startAllPlugins = traceFunction("startAllPlugins", function startAl
|
|||
|
||||
startPlugin(Plugins[name]);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
export function startDependenciesRecursive(p: Plugin) {
|
||||
let restartNeeded = false;
|
||||
const failures: string[] = [];
|
||||
p.dependencies?.forEach(dep => {
|
||||
if (!Settings.plugins[dep].enabled) {
|
||||
startDependenciesRecursive(Plugins[dep]);
|
||||
|
||||
p.dependencies?.forEach(d => {
|
||||
if (!settings[d].enabled) {
|
||||
const dep = Plugins[d];
|
||||
startDependenciesRecursive(dep);
|
||||
|
||||
// If the plugin has patches, don't start the plugin, just enable it.
|
||||
Settings.plugins[dep].enabled = true;
|
||||
if (Plugins[dep].patches) {
|
||||
logger.warn(`Enabling dependency ${dep} requires restart.`);
|
||||
settings[d].enabled = true;
|
||||
dep.isDependency = true;
|
||||
|
||||
if (dep.patches) {
|
||||
logger.warn(`Enabling dependency ${d} requires restart.`);
|
||||
restartNeeded = true;
|
||||
return;
|
||||
}
|
||||
const result = startPlugin(Plugins[dep]);
|
||||
if (!result) failures.push(dep);
|
||||
|
||||
const result = startPlugin(dep);
|
||||
if (!result) failures.push(d);
|
||||
}
|
||||
});
|
||||
|
||||
return { restartNeeded, failures };
|
||||
}
|
||||
|
||||
export function subscribePluginFluxEvents(p: Plugin, fluxDispatcher: typeof FluxDispatcher) {
|
||||
if (p.flux && !subscribedFluxEventsPlugins.has(p.name)) {
|
||||
if (p.flux && !subscribedFluxEventsPlugins.has(p.name) && (!IS_REPORTER || isReporterTestable(p, ReporterTestable.FluxEvents))) {
|
||||
subscribedFluxEventsPlugins.add(p.name);
|
||||
|
||||
logger.debug("Subscribing to flux events of plugin", p.name);
|
||||
for (const [event, handler] of Object.entries(p.flux)) {
|
||||
fluxDispatcher.subscribe(event as FluxEvents, handler);
|
||||
const wrappedHandler = p.flux[event] = function () {
|
||||
try {
|
||||
const res = handler.apply(p, arguments as any);
|
||||
return res instanceof Promise
|
||||
? res.catch(e => logger.error(`${p.name}: Error while handling ${event}\n`, e))
|
||||
: res;
|
||||
} catch (e) {
|
||||
logger.error(`${p.name}: Error while handling ${event}\n`, e);
|
||||
}
|
||||
};
|
||||
|
||||
fluxDispatcher.subscribe(event as FluxEvents, wrappedHandler);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -160,7 +206,7 @@ export function subscribeAllPluginsFluxEvents(fluxDispatcher: typeof FluxDispatc
|
|||
}
|
||||
|
||||
export const startPlugin = traceFunction("startPlugin", function startPlugin(p: Plugin) {
|
||||
const { name, commands, flux, contextMenus } = p;
|
||||
const { name, commands, contextMenus } = p;
|
||||
|
||||
if (p.start) {
|
||||
logger.info("Starting plugin", name);
|
||||
|
@ -206,7 +252,7 @@ export const startPlugin = traceFunction("startPlugin", function startPlugin(p:
|
|||
}, p => `startPlugin ${p.name}`);
|
||||
|
||||
export const stopPlugin = traceFunction("stopPlugin", function stopPlugin(p: Plugin) {
|
||||
const { name, commands, flux, contextMenus } = p;
|
||||
const { name, commands, contextMenus } = p;
|
||||
|
||||
if (p.stop) {
|
||||
logger.info("Stopping plugin", name);
|
||||
|
|
|
@ -18,12 +18,13 @@
|
|||
|
||||
import { addChatBarButton, ChatBarButton } from "@api/ChatButtons";
|
||||
import { addButton, removeButton } from "@api/MessagePopover";
|
||||
import { updateMessage } from "@api/MessageUpdater";
|
||||
import { definePluginSettings } from "@api/Settings";
|
||||
import ErrorBoundary from "@components/ErrorBoundary";
|
||||
import { Devs } from "@utils/constants";
|
||||
import { getStegCloak } from "@utils/dependencies";
|
||||
import definePlugin, { OptionType } from "@utils/types";
|
||||
import { ChannelStore, Constants, FluxDispatcher, RestAPI, Tooltip } from "@webpack/common";
|
||||
import definePlugin, { OptionType, ReporterTestable } from "@utils/types";
|
||||
import { ChannelStore, Constants, RestAPI, Tooltip } from "@webpack/common";
|
||||
import { Message } from "discord-types/general";
|
||||
|
||||
import { buildDecModal } from "./components/DecryptionModal";
|
||||
|
@ -103,7 +104,10 @@ export default definePlugin({
|
|||
name: "InvisibleChat",
|
||||
description: "Encrypt your Messages in a non-suspicious way!",
|
||||
authors: [Devs.SammCheese],
|
||||
dependencies: ["MessagePopoverAPI", "ChatInputButtonAPI"],
|
||||
dependencies: ["MessagePopoverAPI", "ChatInputButtonAPI", "MessageUpdaterAPI"],
|
||||
reporterTestable: ReporterTestable.Patches,
|
||||
settings,
|
||||
|
||||
patches: [
|
||||
{
|
||||
// Indicator
|
||||
|
@ -120,7 +124,6 @@ export default definePlugin({
|
|||
URL_REGEX: new RegExp(
|
||||
/(http(s)?:\/\/.)?(www\.)?[-a-zA-Z0-9@:%._+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9@:%_+.~#?&//=]*)/,
|
||||
),
|
||||
settings,
|
||||
async start() {
|
||||
addButton("InvisibleChat", message => {
|
||||
return this.INV_REGEX.test(message?.content)
|
||||
|
@ -180,14 +183,7 @@ export default definePlugin({
|
|||
message.embeds.push(embed);
|
||||
}
|
||||
|
||||
this.updateMessage(message);
|
||||
},
|
||||
|
||||
updateMessage: (message: any) => {
|
||||
FluxDispatcher.dispatch({
|
||||
type: "MESSAGE_UPDATE",
|
||||
message,
|
||||
});
|
||||
updateMessage(message.channel_id, message.id, { embeds: message.embeds });
|
||||
},
|
||||
|
||||
popOverIcon: () => <PopOverIcon />,
|
||||
|
|
5
src/plugins/maskedLinkPaste/README.md
Normal file
5
src/plugins/maskedLinkPaste/README.md
Normal file
|
@ -0,0 +1,5 @@
|
|||
# MaskedLinkPaste
|
||||
|
||||
Pasting a link while you have text selected will paste your link as a masked link at that location
|
||||
|
||||
![](https://github.com/Vendicated/Vencord/assets/78964224/1d3be2c6-7957-44c9-92ec-551069d46c02)
|
38
src/plugins/maskedLinkPaste/index.ts
Normal file
38
src/plugins/maskedLinkPaste/index.ts
Normal file
|
@ -0,0 +1,38 @@
|
|||
/*
|
||||
* Vencord, a Discord client mod
|
||||
* Copyright (c) 2023 Vendicated and contributors
|
||||
* SPDX-License-Identifier: GPL-3.0-or-later
|
||||
*/
|
||||
|
||||
import { Devs } from "@utils/constants.js";
|
||||
import definePlugin from "@utils/types";
|
||||
import { findByPropsLazy } from "@webpack";
|
||||
|
||||
const linkRegex = /https?:\/\/(www\.)?[-a-zA-Z0-9@:%._+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_+.~#?&//=]*)/;
|
||||
|
||||
const SlateTransforms = findByPropsLazy("insertText", "selectCommandOption");
|
||||
|
||||
export default definePlugin({
|
||||
name: "MaskedLinkPaste",
|
||||
authors: [Devs.TheSun],
|
||||
description: "Pasting a link while having text selected will paste a hyperlink",
|
||||
patches: [
|
||||
{
|
||||
find: ".selection,preventEmojiSurrogates:",
|
||||
replacement: {
|
||||
match: /(?<=\i.delete.{0,50})(\i)\.insertText\((\i)\)/,
|
||||
replace: "$self.handlePaste($1, $2, () => $&)"
|
||||
}
|
||||
}
|
||||
],
|
||||
|
||||
handlePaste(editor, content: string, originalBehavior: () => void) {
|
||||
if (content && linkRegex.test(content) && editor.operations?.[0]?.type === "remove_text") {
|
||||
SlateTransforms.insertText(
|
||||
editor,
|
||||
`[${editor.operations[0].text}](${content})`
|
||||
);
|
||||
}
|
||||
else originalBehavior();
|
||||
}
|
||||
});
|
Some files were not shown because too many files have changed in this diff Show more
Loading…
Reference in a new issue