Merge branch 'BetterDiscord:main' into liveupdate-checkbox

This commit is contained in:
Fede 2022-12-19 20:35:37 +01:00 committed by GitHub
commit d51c223a6f
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
27 changed files with 462 additions and 1270 deletions

63
.github/workflows/ci.yml vendored Normal file
View File

@ -0,0 +1,63 @@
name: BetterDiscord CI
on:
push:
branches: [ "main" ]
pull_request:
branches: [ "main" ]
jobs:
build:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v3
- name: Install Node.js
uses: actions/setup-node@v3
with:
node-version: 16
- uses: pnpm/action-setup@v2
name: Install pnpm
id: pnpm-install
with:
version: 7
run_install: false
- name: Get pnpm store directory
id: pnpm-cache
shell: bash
run: |
echo "STORE_PATH=$(pnpm store path)" >> $GITHUB_OUTPUT
- uses: actions/cache@v3
name: Setup pnpm cache
with:
path: ${{ steps.pnpm-cache.outputs.STORE_PATH }}
key: ${{ runner.os }}-pnpm-store-${{ hashFiles('**/pnpm-lock.yaml') }}
restore-keys: |
${{ runner.os }}-pnpm-store-
- name: Install dependencies
run: pnpm install --frozen-lockfile
# - name: Lint
# run: pnpm lint
# - name: Run tests
# run: pnpm test
- name: Build asar
run: pnpm dist
- uses: actions/upload-artifact@v3
name: Upload artifact
# if: ${{ github.ref == 'refs/heads/main' }} # Only create artifacts when pushed to main
with:
name: betterdiscord.asar
path: dist/betterdiscord.asar
retention-days: 30
if-no-files-found: error

View File

@ -2,6 +2,48 @@
This changelog starts with the restructured 1.0.0 release that happened after context isolation changes. The changelogs here should more-or-less mirror the ones that get shown in the client but probably with less formatting and pizzazz.
## 1.8.4
### Added
### Removed
### Changed
### Fixed
- Fixed more bugs with context menu api
## 1.8.3
### Added
- Checking for old installs and deleting them
### Removed
- All references to Emotes, this will become a separate plugin
### Changed
- Moved to the more permissive Apache 2.0 license
- Now check for discord.asar for electron17+
- Handle setting module exports internally rather than maintaining getter references
### Fixed
- Fixed `inject` for electron17+
- Updater checking `>` which does not work for open versions
- Fixed a startup bug with the context menu api
## 1.8.2
### Added
### Removed
### Changed
### Fixed
- Fixed modals not working
- Fixed downloading binary files
- Fixed public server invites
## 1.8.1
### Added

View File

@ -46,7 +46,7 @@ Preload is the preload script for Discord's main `BrowserWindow` object. This se
#### Renderer Application
This is the main payload of BetterDiscord. This is what gets executed in the renderer context by the [injector](#injector). This portion is where most of the user interaction and development will be. This module is responsible for loading plugins and themes, as well as handling settings, emotes and more. The renderer and its code live in the `renderer` folder.
This is the main payload of BetterDiscord. This is what gets executed in the renderer context by the [injector](#injector). This portion is where most of the user interaction and development will be. This module is responsible for loading plugins and themes, as well as handling settings, and more. The renderer and its code live in the `renderer` folder.
## How Can I Contribute?

View File

@ -1,7 +1,15 @@
import fs from "fs";
import path from "path";
import {app} from "electron";
import Module from "module";
import path from "path";
import fs from "fs";
// Detect old install and delete it
const appPath = app.getAppPath(); // Should point to app or app.asar
const oldInstall = path.resolve(appPath, "..", "app");
if (fs.existsSync(oldInstall)) {
fs.rmdirSync(oldInstall, {recursive: true});
app.quit();
app.relaunch();
}
import ipc from "./modules/ipc";
import BrowserWindow from "./modules/browserwindow";
@ -19,32 +27,30 @@ if (!process.argv.includes("--vanilla")) {
// Remove CSP immediately on linux since they install to discord_desktop_core still
if (process.platform == "win32" || process.platform == "darwin") app.once("ready", CSP.remove);
else CSP.remove();
try {
CSP.remove();
}
catch (_) {
// Remove when everyone is moved to core
}
}
// Enable DevTools on Stable.
let fakeAppSettings;
Object.defineProperty(global, "appSettings", {
get() {
return fakeAppSettings;
},
set(value) {
if (!value.hasOwnProperty("settings")) value.settings = {};
value.settings.DANGEROUS_ENABLE_DEVTOOLS_ONLY_ENABLE_IF_YOU_KNOW_WHAT_YOURE_DOING = true;
fakeAppSettings = value;
},
});
// Use Discord's info to run the app
if (process.platform == "win32" || process.platform == "darwin") {
const appAsar = path.join(app.getAppPath(), "..", "app.asar");
const discordAsar = path.join(app.getAppPath(), "..", "discord.asar");
const basePath = fs.existsSync(discordAsar) ? discordAsar : appAsar;
const pkg = __non_webpack_require__(path.join(basePath, "package.json"));
app.setAppPath(basePath);
app.name = pkg.name;
Module._load(path.join(basePath, pkg.main), null, true);
try {
let fakeAppSettings;
Object.defineProperty(global, "appSettings", {
get() {
return fakeAppSettings;
},
set(value) {
if (!value.hasOwnProperty("settings")) value.settings = {};
value.settings.DANGEROUS_ENABLE_DEVTOOLS_ONLY_ENABLE_IF_YOU_KNOW_WHAT_YOURE_DOING = true;
fakeAppSettings = value;
},
});
}
catch (_) {
// Remove when everyone is moved to core
}
// Needs to run this after Discord but before ready()

View File

@ -46,16 +46,6 @@ export default class BetterDiscord {
if (!fs.existsSync(path.join(dataPath, "themes"))) fs.mkdirSync(path.join(dataPath, "themes"));
}
static async ensureWebpackModules(browserWindow) {
await browserWindow.webContents.executeJavaScript(`new Promise(resolve => {
const check = function() {
if (window.webpackJsonp && window.webpackJsonp.flat().flat().length >= 7000) return resolve();
setTimeout(check, 100);
};
check();
});`);
}
static async injectRenderer(browserWindow) {
const location = path.join(__dirname, "renderer.js");
if (!fs.existsSync(location)) return; // TODO: cut a fatal log

View File

@ -128,17 +128,23 @@ const registerPreload = (event, path) => {
export default class IPCMain {
static registerEvents() {
ipc.on(IPCEvents.GET_PATH, getPath);
ipc.on(IPCEvents.RELAUNCH, relaunch);
ipc.on(IPCEvents.OPEN_DEVTOOLS, openDevTools);
ipc.on(IPCEvents.CLOSE_DEVTOOLS, closeDevTools);
ipc.on(IPCEvents.TOGGLE_DEVTOOLS, toggleDevTools);
ipc.on(IPCEvents.INSPECT_ELEMENT, inspectElement);
ipc.on(IPCEvents.MINIMUM_SIZE, setMinimumSize);
ipc.on(IPCEvents.DEVTOOLS_WARNING, stopDevtoolsWarning);
ipc.on(IPCEvents.REGISTER_PRELOAD, registerPreload);
ipc.handle(IPCEvents.RUN_SCRIPT, runScript);
ipc.handle(IPCEvents.OPEN_DIALOG, openDialog);
ipc.handle(IPCEvents.OPEN_WINDOW, createBrowserWindow);
try {
ipc.on(IPCEvents.GET_PATH, getPath);
ipc.on(IPCEvents.RELAUNCH, relaunch);
ipc.on(IPCEvents.OPEN_DEVTOOLS, openDevTools);
ipc.on(IPCEvents.CLOSE_DEVTOOLS, closeDevTools);
ipc.on(IPCEvents.TOGGLE_DEVTOOLS, toggleDevTools);
ipc.on(IPCEvents.INSPECT_ELEMENT, inspectElement);
ipc.on(IPCEvents.MINIMUM_SIZE, setMinimumSize);
ipc.on(IPCEvents.DEVTOOLS_WARNING, stopDevtoolsWarning);
ipc.on(IPCEvents.REGISTER_PRELOAD, registerPreload);
ipc.handle(IPCEvents.RUN_SCRIPT, runScript);
ipc.handle(IPCEvents.OPEN_DIALOG, openDialog);
ipc.handle(IPCEvents.OPEN_WINDOW, createBrowserWindow);
}
catch (err) {
// eslint-disable-next-line no-console
console.error(err);
}
}
}

View File

@ -1,6 +1,6 @@
{
"name": "betterdiscord",
"version": "1.8.2",
"version": "1.8.4",
"description": "Enhances Discord by adding functionality and themes.",
"main": "src/index.js",
"scripts": {
@ -9,7 +9,6 @@
"build-injector": "pnpm --filter injector build",
"build-renderer": "pnpm --filter renderer build",
"build-preload": "pnpm --filter preload build",
"pack-emotes": "node scripts/emotes.js",
"inject": "node scripts/inject.js",
"lint": "eslint --ext .js common/ && pnpm --filter injector lint && pnpm --filter preload lint && pnpm --filter renderer lint-js",
"test": "mocha --require @babel/register --recursive \"./tests/renderer/*.js\"",

View File

@ -41,7 +41,8 @@ export default function () {
if (!Reflect.has(exports, key) || target[key]) continue;
Object.defineProperty(target, key, {
get: exports[key],
get: () => exports[key](),
set: v => {exports[key] = () => v;},
enumerable: true,
configurable: true
});

View File

@ -1,27 +0,0 @@
import {React} from "modules";
import DownArrow from "../../ui/icons/downarrow";
export default class Category extends React.Component {
constructor(props) {
super(props);
this.state = {
expanded: true
};
}
render() {
return <div className="bd-emote-category">
<div className={`bd-emote-header ${this.state.expanded ? "expanded" : "collapsed"}`}>
<div className="bd-emote-header-inner" onClick={() => this.setState({expanded: !this.state.expanded})}>
<div className="bd-emote-header-icon">
{this.props.icon ? this.props.icon : null}
</div>
<div className="bd-emote-header-label">{this.props.label}</div>
<div className={`bd-emote-collapse-icon ${this.state.expanded ? "expanded" : "collapsed"}`}>
<DownArrow/>
</div>
</div>
</div>
{this.state.expanded && this.props.children}
</div>;
}
}

View File

@ -1,95 +0,0 @@
import Builtin from "../../structs/builtin";
import {Utilities, WebpackModules, React} from "modules";
import EmoteModule from "./emotes";
import EmoteMenuCard from "../../ui/emotemenucard";
import EmoteIcon from "../../ui/emoteicon";
import Category from "./category";
import Favorite from "../../ui/icons/favorite";
import Twitch from "../../ui/icons/twitch";
const EmojiPicker = WebpackModules.find(m => m.type && m.type.displayName == "ExpressionPicker");
const {useExpressionPickerStore} = WebpackModules.getByProps("useExpressionPickerStore") ?? {};
export default new class EmoteMenu extends Builtin {
get name() {return "EmoteMenu";}
get collection() {return "emotes";}
get category() {return "general";}
get id() {return "emoteMenu";}
get hideEmojisID() {return "hideEmojiMenu";}
get hideEmojis() {return this.get(this.hideEmojisID);}
enabled() {
this.after(EmojiPicker, "type", (_, __, returnValue) => {
const originalChildren = returnValue?.props?.children?.props?.children;
if (!originalChildren || originalChildren.__patched) return;
const activePicker = useExpressionPickerStore((state) => state.activeView);
returnValue.props.children.props.children = (props) => {
const childrenReturn = Reflect.apply(originalChildren, null, [props]);
// Attach a try {} catch {} because this might crash the user.
try {
const head = Utilities.findInTree(childrenReturn, (e) => e?.role === "tablist", {walkable: ["props", "children", "return", "stateNode"]})?.children;
const body = Utilities.findInTree(childrenReturn, (e) => e?.[0]?.type === "nav", {walkable: ["props", "children", "return", "stateNode"]});
if (!head || !body) return childrenReturn;
const isActive = activePicker == "bd-emotes";
const TabItem = head[0]?.type ?? (() => null);
if (!isActive && activePicker == "emoji" && this.hideEmojis) {
useExpressionPickerStore.setState({activeView: "bd-emotes"});
}
if (this.hideEmojis) {
const emojiTabIndex = head.findIndex((e) => e?.props?.id == "emoji-picker-tab");
if (emojiTabIndex > -1) head.splice(emojiTabIndex, 1);
}
head.push(
React.createElement(TabItem, {
"aria-controls": "bd-emotes",
"id": "bd-emotes",
"aria-selected": isActive,
"isActive": isActive,
"viewType": "bd-emotes"
}, "Twitch")
);
if (isActive) {
body.push(
React.createElement(EmoteMenuCard, {
type: "twitch",
}, [
React.createElement(Category, {
label: "Favorites",
icon: React.createElement(Favorite, {}),
}, Object.entries(EmoteModule.favorites).map(([emote, url]) => {
return React.createElement(EmoteIcon, {emote, url});
})),
React.createElement(Category, {
label: "Twitch Emotes",
icon: React.createElement(Twitch, {})
}, Object.keys(EmoteModule.getCategory("TwitchGlobal")).map((emote) => {
const url = EmoteModule.getUrl("TwitchGlobal", emote);
return React.createElement(EmoteIcon, {emote, url});
}))
])
);
}
}
catch (error) {
this.error("Error in EmojiPicker patch:\n", error);
}
return childrenReturn;
};
returnValue.props.children.props.children.__patched = true;
});
}
disabled() {
this.unpatchAll();
}
};

View File

@ -1,260 +0,0 @@
import Builtin from "../../structs/builtin";
import {EmoteConfig, Config} from "data";
import {WebpackModules, DataStore, DiscordModules, Events, Settings, Strings} from "modules";
import BDEmote from "../../ui/emote";
import Modals from "../../ui/modals";
import Toasts from "../../ui/toasts";
import FormattableString from "../../structs/string";
const request = require("request");
const path = require("path");
const fs = require("fs");
const EmoteURLs = {
TwitchGlobal: new FormattableString(`https://static-cdn.jtvnw.net/emoticons/v1/{{id}}/1.0`),
TwitchSubscriber: new FormattableString(`https://static-cdn.jtvnw.net/emoticons/v1/{{id}}/1.0`),
FrankerFaceZ: new FormattableString(`https://cdn.frankerfacez.com/emoticon/{{id}}/1`),
BTTV: new FormattableString(`https://cdn.betterttv.net/emote/{{id}}/1x`),
};
const Emotes = {
TwitchGlobal: {},
TwitchSubscriber: {},
BTTV: {},
FrankerFaceZ: {}
};
const escape = (s) => {
return s.replace(/[-/\\^$*+?.()|[\]{}]/g, "\\$&");
};
const blocklist = [];
const overrides = ["twitch", "subscriber", "bttv", "ffz"];
const modifiers = ["flip", "spin", "pulse", "spin2", "spin3", "1spin", "2spin", "3spin", "tr", "bl", "br", "shake", "shake2", "shake3", "flap"];
export default new class EmoteModule extends Builtin {
get name() {return "Emotes";}
get collection() {return "settings";}
get category() {return "general";}
get id() {return "emotes";}
get categories() {return Object.keys(Emotes).filter(k => this.isCategoryEnabled(k));}
get shouldDownload() {return Settings.get("emotes", this.category, "download");}
get asarPath() {return path.join(DataStore.baseFolder, "emotes.asar");}
isCategoryEnabled(id) {return super.get("emotes", "categories", id.toLowerCase());}
get(id) {return super.get("emotes", "general", id);}
get MessageComponent() {return WebpackModules.find(m => m.default && m.default.toString().search("childrenRepliedMessage") > -1);}
get Emotes() {return Emotes;}
get TwitchGlobal() {return Emotes.TwitchGlobal;}
get TwitchSubscriber() {return Emotes.TwitchSubscriber;}
get BTTV() {return Emotes.BTTV;}
get FrankerFaceZ() {return Emotes.FrankerFaceZ;}
get blocklist() {return blocklist;}
get favorites() {return this.favoriteEmotes;}
getUrl(category, name) {return EmoteURLs[category].format({id: Emotes[category][name]});}
getCategory(category) {return Emotes[category];}
getRemoteFile(category) {return `https://cdn.staticaly.com/gh/BetterDiscord/BetterDiscord/${Config.hash}/assets/emotes/${category.toLowerCase()}.json`;}
initialize() {
super.initialize();
const storedFavorites = DataStore.getBDData("favoriteEmotes");
this.favoriteEmotes = storedFavorites || {};
this.addFavorite = this.addFavorite.bind(this);
this.removeFavorite = this.removeFavorite.bind(this);
this.onCategoryToggle = this.onCategoryToggle.bind(this);
this.resetEmotes = this.resetEmotes.bind(this);
}
async enabled() {
Settings.registerCollection("emotes", "Emotes", EmoteConfig, {title: Strings.Emotes.clearEmotes, onClick: this.resetEmotes.bind(this)});
// await this.getBlocklist();
await this.loadEmoteData();
Events.on("emotes-favorite-added", this.addFavorite);
Events.on("emotes-favorite-removed", this.removeFavorite);
Events.on("setting-updated", this.onCategoryToggle);
this.patchMessageContent();
}
disabled() {
Events.off("setting-updated", this.onCategoryToggle);
Events.off("emotes-favorite-added", this.addFavorite);
Events.off("emotes-favorite-removed", this.removeFavorite);
Settings.removeCollection("emotes");
this.emptyEmotes();
if (!this.cancelEmoteRender) return;
this.cancelEmoteRender();
delete this.cancelEmoteRender;
}
onCategoryToggle(collection, cat, category, enabled) {
if (collection != "emotes" || cat != "categories") return;
if (enabled) return this.loadEmoteData(category);
return this.unloadEmoteData(category);
}
addFavorite(name, url) {
if (!this.favoriteEmotes.hasOwnProperty(name)) this.favoriteEmotes[name] = url;
this.saveFavorites();
}
removeFavorite(name) {
if (!this.favoriteEmotes.hasOwnProperty(name)) return;
delete this.favoriteEmotes[name];
this.saveFavorites();
}
isFavorite(name) {
return this.favoriteEmotes.hasOwnProperty(name);
}
saveFavorites() {
DataStore.setBDData("favoriteEmotes", this.favoriteEmotes);
}
emptyEmotes() {
for (const cat in Emotes) Object.assign(Emotes, {[cat]: {}});
}
patchMessageContent() {
if (this.cancelEmoteRender) return;
this.cancelEmoteRender = this.before(this.MessageComponent, "default", (thisObj, args) => {
const nodes = args[0].childrenMessageContent.props.content;
if (!nodes || !nodes.length) return;
for (let n = 0; n < nodes.length; n++) {
const node = nodes[n];
if (typeof(node) !== "string") continue;
const words = node.split(/([^\s]+)([\s]|$)/g);
for (let c = 0, clen = this.categories.length; c < clen; c++) {
for (let w = 0, wlen = words.length; w < wlen; w++) {
const emote = words[w];
const emoteSplit = emote.split(":");
const emoteName = emoteSplit[0];
let emoteModifier = emoteSplit[1] ? emoteSplit[1] : "";
let emoteOverride = emoteModifier.slice(0);
if (emoteName.length < 4 || blocklist.includes(emoteName)) continue;
if (!modifiers.includes(emoteModifier) || !Settings.get("emotes", "general", "modifiers")) emoteModifier = "";
if (!overrides.includes(emoteOverride)) emoteOverride = "";
else emoteModifier = emoteOverride;
let current = this.categories[c];
if (emoteOverride === "twitch") {
if (Emotes.TwitchGlobal[emoteName]) current = "TwitchGlobal";
else if (Emotes.TwitchSubscriber[emoteName]) current = "TwitchSubscriber";
}
else if (emoteOverride === "subscriber") {
if (Emotes.TwitchSubscriber[emoteName]) current = "TwitchSubscriber";
}
else if (emoteOverride === "bttv") {
if (Emotes.BTTV[emoteName]) current = "BTTV";
}
else if (emoteOverride === "ffz") {
if (Emotes.FrankerFaceZ[emoteName]) current = "FrankerFaceZ";
}
if (!Emotes[current][emoteName]) continue;
const results = nodes[n].match(new RegExp(`([\\s]|^)${escape(emoteModifier ? emoteName + ":" + emoteModifier : emoteName)}([\\s]|$)`));
if (!results) continue;
const pre = nodes[n].substring(0, results.index + results[1].length);
const post = nodes[n].substring(results.index + results[0].length - results[2].length);
nodes[n] = pre;
const emoteComponent = DiscordModules.React.createElement(BDEmote, {name: emoteName, url: EmoteURLs[current].format({id: Emotes[current][emoteName]}), modifier: emoteModifier, isFavorite: this.isFavorite(emoteName)});
nodes.splice(n + 1, 0, post);
nodes.splice(n + 1, 0, emoteComponent);
}
}
}
const onlyEmotes = nodes.every(r => {
if (typeof(r) == "string" && r.replace(/\s*/, "") == "") return true;
else if (r.type && r.type.name == "BDEmote") return true;
else if (r.props && r.props.children && r.props.children.props && r.props.children.props.emojiName) return true;
return false;
});
if (!onlyEmotes) return;
for (const node of nodes) {
if (typeof(node) != "object") continue;
if (node.type.name == "BDEmote") node.props.jumboable = true;
else if (node.props && node.props.children && node.props.children.props && node.props.children.props.emojiName) node.props.children.props.jumboable = true;
}
});
}
async loadEmoteData(categories) {
if (!categories) categories = this.categories;
if (!Array.isArray(categories)) categories = [categories];
const all = Object.keys(Emotes);
categories = categories.map(k => all.find(c => c.toLowerCase() == k.toLowerCase()));
Toasts.show(Strings.Emotes.loading, {type: "info"});
this.emotesLoaded = false;
const localOutdated = Config.release.tag_name > DataStore.getBDData("emoteVersion");
if (!fs.existsSync(this.asarPath) || (localOutdated && this.shouldDownload)) await this.downloadEmotes();
try {
for (const category of categories) {
this.log(category);
const EmoteData = __non_webpack_require__(path.join(this.asarPath, category.toLowerCase()));
Object.assign(Emotes[category], EmoteData);
delete __non_webpack_require__.cache[path.join(this.asarPath, category.toLowerCase())];
await new Promise(r => setTimeout(r, 1000));
}
const EmoteData = __non_webpack_require__(path.join(this.asarPath, "blocklist"));
blocklist.push(...EmoteData);
delete __non_webpack_require__.cache[path.join(this.asarPath, "blocklist")];
}
catch (err) {
this.log("Failed to load emotes.");
}
this.emotesLoaded = true;
Events.dispatch("emotes-loaded");
Toasts.show(Strings.Emotes.loaded, {type: "success"});
}
unloadEmoteData(categories) {
if (!categories) categories = this.categories;
if (!Array.isArray(categories)) categories = [categories];
const all = Object.keys(Emotes);
categories = categories.map(k => all.find(c => c.toLowerCase() == k.toLowerCase()));
for (const category of categories) {
delete Emotes[category];
Emotes[category] = {};
}
}
async downloadEmotes() {
try {
const asar = Config.release.assets.find(a => a.name === "emotes.asar");
this.log(`Downloading emotes from: ${asar.url}`);
const buff = await new Promise((resolve, reject) =>
request(asar.url, {encoding: null, headers: {"User-Agent": "BetterDiscord Emotes", "Accept": "application/octet-stream"}}, (err, resp, body) => {
if (err || resp.statusCode != 200) return reject(err || `${resp.statusCode} ${resp.statusMessage}`);
return resolve(body);
}));
this.log("Successfully downloaded emotes.asar");
const asarPath = this.asarPath;
const originalFs = require("original-fs");
originalFs.writeFileSync(asarPath, buff);
this.log(`Saved emotes.asar to ${asarPath}`);
DataStore.setBDData("emoteVersion", Config.release.tag_name);
}
catch (err) {
this.stacktrace("Failed to download emotes.", err);
Modals.showConfirmationModal(Strings.Emotes.downloadFailed, Strings.Emotes.failureMessage, {cancelText: null});
}
}
resetEmotes() {
this.unloadEmoteData();
DataStore.setBDData("emoteVersion", "0");
this.loadEmoteData();
}
};

View File

@ -1,16 +1,12 @@
// fixed, improved, added, progress
export default {
description: "Just some smaller fixes while we work on some big things in the background.",
description: "More features are coming soon!",
changes: [
{
title: "Bug Fixes",
type: "fixed",
items: [
"Fixed _even more_ issues with the built-in updater.",
"Fixed not being able to click support server links in plugin/theme pages.",
"Fixed some issues with not being able to join public servers.",
"Fixed plugin settings not being able to be displayed.",
"Fixed changelog modal not being able to be displayed."
"Fixed crashing on right click.",
]
}
]

View File

@ -1,4 +1,3 @@
export {default as Config} from "./config";
export {default as EmoteConfig} from "./emotesettings";
export {default as SettingsConfig} from "./settings";
export {default as Changelog} from "./changelog";

View File

@ -1,27 +0,0 @@
export default [
{
type: "category",
id: "general",
name: "General",
collapsible: true,
settings: [
{type: "switch", id: "download", value: true},
{type: "switch", id: "emoteMenu", value: true},
{type: "switch", id: "hideEmojiMenu", value: false, enableWith: "emoteMenu"},
{type: "switch", id: "modifiers", value: true},
{type: "switch", id: "animateOnHover", value: false}
]
},
{
type: "category",
id: "categories",
name: "Categories",
collapsible: true,
settings: [
{type: "switch", id: "twitchglobal", value: true},
{type: "switch", id: "twitchsubscriber", value: false},
{type: "switch", id: "frankerfacez", value: true},
{type: "switch", id: "bttv", value: true}
]
}
];

View File

@ -4,7 +4,6 @@ export default [
id: "general",
collapsible: true,
settings: [
{type: "switch", id: "emotes", value: true, disabled: true},
{type: "switch", id: "publicServers", value: true},
{type: "switch", id: "voiceDisconnect", value: false},
{type: "switch", id: "showToasts", value: true},

View File

@ -3,6 +3,8 @@ import Patcher from "../patcher";
import Logger from "common/logger";
import {React} from "../modules";
let startupComplete = false;
const MenuComponents = (() => {
const out = {};
const componentMap = {
@ -14,14 +16,25 @@ const MenuComponents = (() => {
customitem: "Item"
};
let ContextMenuIndex = null;
const ContextMenuModule = WebpackModules.getModule((m, _, id) => Object.values(m).some(v => v?.FLEXIBLE) && (ContextMenuIndex = id), {searchExports: false});
const rawMatches = WebpackModules.require.m[ContextMenuIndex].toString().matchAll(/if\(\w+\.type===\w+\.(\w+)\).+?type:"(.+?)"/g);
out.Menu = Object.values(ContextMenuModule).find(v => v.toString().includes(".isUsingKeyboardNavigation"));
try {
let contextMenuId = Object.keys(WebpackModules.require.m).find(e => WebpackModules.require.m[e]?.toString().includes("menuitemcheckbox"));
const ContextMenuModule = WebpackModules.getModule((m, t, id) => id === contextMenuId);
const rawMatches = WebpackModules.require.m[contextMenuId].toString().matchAll(/if\(\w+\.type===\w+\.(\w+)\).+?type:"(.+?)"/g);
for (const [, identifier, type] of rawMatches) {
out[componentMap[type]] = ContextMenuModule[identifier];
out.Menu = Object.values(ContextMenuModule).find(v => v.toString().includes(".isUsingKeyboardNavigation"));
for (const [, identifier, type] of rawMatches) {
out[componentMap[type]] = ContextMenuModule[identifier];
}
startupComplete = Object.values(componentMap).every(k => out[k]) && !!out.Menu;
} catch (error) {
startupComplete = false;
Logger.stacktrace("ContextMenu~Components", "Fatal startup error:", error);
Object.assign(out, Object.fromEntries(
Object.values(componentMap).map(k => [k, () => null])
));
}
return out;
@ -30,15 +43,27 @@ const MenuComponents = (() => {
const ContextMenuActions = (() => {
const out = {};
const ActionsModule = WebpackModules.getModule(m => Object.values(m).some(v => typeof v === "function" && v.toString().includes("CONTEXT_MENU_CLOSE")), {searchExports: false});
try {
const ActionsModule = WebpackModules.getModule(m => Object.values(m).some(v => typeof v === "function" && v.toString().includes("CONTEXT_MENU_CLOSE")), {searchExports: false});
for (const key of Object.keys(ActionsModule)) {
if (ActionsModule[key].toString().includes("CONTEXT_MENU_CLOSE")) {
out.closeContextMenu = ActionsModule[key];
}
else if (ActionsModule[key].toString().includes("renderLazy")) {
out.openContextMenu = ActionsModule[key];
for (const key of Object.keys(ActionsModule)) {
if (ActionsModule[key].toString().includes("CONTEXT_MENU_CLOSE")) {
out.closeContextMenu = ActionsModule[key];
}
else if (ActionsModule[key].toString().includes("renderLazy")) {
out.openContextMenu = ActionsModule[key];
}
}
startupComplete = typeof(out.closeContextMenu) === "function" && typeof(out.openContextMenu) === "function";
} catch (error) {
startupComplete = false;
Logger.stacktrace("ContextMenu~Components", "Fatal startup error:", error);
Object.assign(out, {
closeContextMenu: () => {},
openContextMenu: () => {}
});
}
return out;
@ -50,6 +75,8 @@ class MenuPatcher {
static subPatches = new WeakMap();
static initialize() {
if (!startupComplete) return Logger.warn("ContextMenu~Patcher", "Startup wasn't successfully, aborting initialization.");
const {module, key} = (() => {
const foundModule = WebpackModules.getModule(m => Object.values(m).some(v => typeof v === "function" && v.toString().includes("CONTEXT_MENU_CLOSE")), {searchExports: false});
const foundKey = Object.keys(foundModule).find(k => foundModule[k].length === 3);
@ -320,6 +347,11 @@ class ContextMenu {
Object.assign(ContextMenu.prototype, MenuComponents);
Object.freeze(ContextMenu);
Object.freeze(ContextMenu.prototype);
MenuPatcher.initialize();
try {
MenuPatcher.initialize();
} catch (error) {
Logger.error("ContextMenu~Patcher", "Fatal error:", error);
}
export default ContextMenu;

View File

@ -9,7 +9,6 @@ import Modals from "../../ui/modals";
import Settings from "../settingsmanager";
import Logger from "common/logger";
import Patcher from "../patcher";
import Emotes from "../../builtins/emotes/emotes";
import ipc from "../ipc";
/**
@ -40,18 +39,7 @@ const settings = Settings.collections;
* @deprecated
* @memberof BdApi
*/
const emotes = new Proxy(Emotes.Emotes, {
get(obj, category) {
if (category === "blocklist") return Emotes.blocklist;
const group = Emotes.Emotes[category];
if (!group) return undefined;
return new Proxy(group, {
get(cat, emote) {return group[emote];},
set() {Logger.warn("BdApi.emotes", "Addon policy for plugins #5 https://github.com/BetterDiscord/BetterDiscord/wiki/Addon-Policies#plugins");}
});
},
set() {Logger.warn("BdApi.emotes", "Addon policy for plugins #5 https://github.com/BetterDiscord/BetterDiscord/wiki/Addon-Policies#plugins");}
});
const emotes = {};
/**
* A reference string for BD's version.

View File

@ -60,11 +60,8 @@ export default new class DataStore {
const setChannelData = (channel, key, value, ext = "json") => fs.writeFileSync(path.resolve(this.baseFolder, channel, `${key}.${ext}`), JSON.stringify(value, null, 4));
const channels = ["stable", "canary", "ptb"];
let customcss = "";
let favoriteEmotes = {};
try {customcss = oldData.bdcustomcss ? atob(oldData.bdcustomcss) : "";}
catch (e) {Logger.stacktrace("DataStore:convertOldData", "Error decoding custom css", e);}
try {favoriteEmotes = oldData.bdfavemotes ? JSON.parse(atob(oldData.bdfavemotes)) : {};}
catch (e) {Logger.stacktrace("DataStore:convertOldData", "Error decoding favorite emotes", e);}
for (const channel of channels) {
if (!fs.existsSync(path.resolve(this.baseFolder, channel))) fs.mkdirSync(path.resolve(this.baseFolder, channel));
const channelData = oldData.settings[channel];
@ -77,16 +74,9 @@ export default new class DataStore {
developer: {debuggerHotkey: oldSettings["bda-gs-8"], reactDevTools: oldSettings.reactDevTools}
};
const newEmotes = {
general: {download: oldSettings["fork-es-3"], emoteMenu: oldSettings["bda-es-0"], hideEmojiMenu: !oldSettings["bda-es-9"], modifiers: oldSettings["bda-es-8"], animateOnHover: oldSettings["fork-es-2"]},
categories: {twitchglobal: oldSettings["bda-es-7"], twitchsubscriber: oldSettings["bda-es-7"], frankerfacez: oldSettings["bda-es-1"], bttv: oldSettings["bda-es-2"]}
};
setChannelData(channel, "settings", newSettings); // settingsCookie
setChannelData(channel, "emotes", newEmotes); // emotes (from settingsCookie)
setChannelData(channel, "plugins", channelData.plugins || {}); // pluginCookie
setChannelData(channel, "themes", channelData.themes || {}); // themeCookie
setChannelData(channel, "misc", {favoriteEmotes}); // favorite emotes
fs.writeFileSync(path.resolve(this.baseFolder, channel, "custom.css"), customcss); // customcss
}

View File

@ -3,275 +3,226 @@
* instead of the original function. Can also alter arguments and return values.
*/
import Logger from "common/logger";
import DiscordModules from "./discordmodules";
import WebpackModules from "./webpackmodules";
export default class Patcher {
static get patches() {return this._patches || (this._patches = []);}
/**
* Returns all the patches done by a specific caller
* @param {string} name - Name of the patch caller
* @method
*/
static getPatchesByCaller(name) {
if (!name) return [];
const patches = [];
for (const patch of this.patches) {
for (const childPatch of patch.children) {
if (childPatch.caller === name) patches.push(childPatch);
}
}
return patches;
}
/**
* Unpatches all patches passed, or when a string is passed unpatches all
* patches done by that specific caller.
* @param {Array|string} patches - Either an array of patches to unpatch or a caller name
*/
static unpatchAll(patches) {
if (typeof patches === "string") patches = this.getPatchesByCaller(patches);
for (const patch of patches) {
patch.unpatch();
}
}
static resolveModule(module) {
if (!module || typeof(module) === "function" || (typeof(module) === "object" && !Array.isArray(module))) return module;
if (typeof module === "string") return DiscordModules[module];
if (Array.isArray(module)) return WebpackModules.findByUniqueProperties(module);
return null;
}
static makeOverride(patch) {
return function () {
let returnValue;
if (!patch.children || !patch.children.length) return patch.originalFunction.apply(this, arguments);
for (const superPatch of patch.children.filter(c => c.type === "before")) {
try {
superPatch.callback(this, arguments);
}
catch (err) {
Logger.err("Patcher", `Could not fire before callback of ${patch.functionName} for ${superPatch.caller}`, err);
}
}
const insteads = patch.children.filter(c => c.type === "instead");
if (!insteads.length) {returnValue = patch.originalFunction.apply(this, arguments);}
else {
for (const insteadPatch of insteads) {
try {
const tempReturn = insteadPatch.callback(this, arguments, patch.originalFunction.bind(this));
if (typeof(tempReturn) !== "undefined") returnValue = tempReturn;
}
catch (err) {
Logger.err("Patcher", `Could not fire instead callback of ${patch.functionName} for ${insteadPatch.caller}`, err);
}
}
}
for (const slavePatch of patch.children.filter(c => c.type === "after")) {
try {
const tempReturn = slavePatch.callback(this, arguments, returnValue);
if (typeof(tempReturn) !== "undefined") returnValue = tempReturn;
}
catch (err) {
Logger.err("Patcher", `Could not fire after callback of ${patch.functionName} for ${slavePatch.caller}`, err);
}
}
return returnValue;
};
}
static rePatch(patch) {
patch.proxyFunction = patch.module[patch.functionName] = this.makeOverride(patch);
}
static makePatch(module, functionName, name) {
const patch = {
name,
module,
functionName,
originalFunction: module[functionName],
proxyFunction: null,
revert: () => { // Calling revert will destroy any patches added to the same module after this
if (patch.getter) {
Object.defineProperty(patch.module, functionName, {
...Object.getOwnPropertyDescriptor(patch.module, functionName),
get: () => patch.originalFunction,
set: undefined
});
}
else {
patch.module[patch.functionName] = patch.originalFunction;
}
patch.proxyFunction = null;
patch.children = [];
},
counter: 0,
children: []
};
patch.proxyFunction = this.makeOverride(patch);
const descriptor = Object.getOwnPropertyDescriptor(module, functionName);
if (descriptor?.get) {
patch.getter = true;
Object.defineProperty(module, functionName, {
configurable: true,
enumerable: true,
...descriptor,
get: () => patch.proxyFunction,
// eslint-disable-next-line no-setter-return
set: value => (patch.originalFunction = value)
});
}
else {
patch.getter = false;
module[functionName] = patch.proxyFunction;
}
const descriptors = Object.assign({}, Object.getOwnPropertyDescriptors(patch.originalFunction), {
__originalFunction: {
get: () => patch.originalFunction,
configurable: true,
enumerable: true,
writeable: true
},
toString: {
value: () => patch.originalFunction.toString(),
configurable: true,
enumerable: true,
writeable: true
}
});
Object.defineProperties(patch.proxyFunction, descriptors);
this.patches.push(patch);
return patch;
}
/**
* Function with no arguments and no return value that may be called to revert changes made by {@link module:Patcher}, restoring (unpatching) original method.
* @callback module:Patcher~unpatch
*/
/**
* A callback that modifies method logic. This callback is called on each call of the original method and is provided all data about original call. Any of the data can be modified if necessary, but do so wisely.
*
* The third argument for the callback will be `undefined` for `before` patches. `originalFunction` for `instead` patches and `returnValue` for `after` patches.
*
* @callback module:Patcher~patchCallback
* @param {object} thisObject - `this` in the context of the original function.
* @param {args} args - The original arguments of the original function.
* @param {(function|*)} extraValue - For `instead` patches, this is the original function from the module. For `after` patches, this is the return value of the function.
* @return {*} Makes sense only when using an `instead` or `after` patch. If something other than `undefined` is returned, the returned value replaces the value of `returnValue`. If used for `before` the return value is ignored.
*/
/**
* This method patches onto another function, allowing your code to run beforehand.
* Using this, you are also able to modify the incoming arguments before the original method is run.
*
* @param {string} caller - Name of the caller of the patch function. Using this you can undo all patches with the same name using {@link module:Patcher.unpatchAll}. Use `""` if you don't care.
* @param {object} moduleToPatch - Object with the function to be patched. Can also patch an object's prototype.
* @param {string} functionName - Name of the method to be patched
* @param {module:Patcher~patchCallback} callback - Function to run before the original method
* @param {object} options - Object used to pass additional options.
* @param {string} [options.displayName] You can provide meaningful name for class/object provided in `what` param for logging purposes. By default, this function will try to determine name automatically.
* @param {boolean} [options.forcePatch=true] Set to `true` to patch even if the function doesnt exist. (Adds noop function in place).
* @return {module:Patcher~unpatch} Function with no arguments and no return value that should be called to cancel (unpatch) this patch. You should save and run it when your plugin is stopped.
*/
static before(caller, moduleToPatch, functionName, callback, options = {}) {return this.pushChildPatch(caller, moduleToPatch, functionName, callback, Object.assign(options, {type: "before"}));}
/**
* This method patches onto another function, allowing your code to run after.
* Using this, you are also able to modify the return value, using the return of your code instead.
*
* @param {string} caller - Name of the caller of the patch function. Using this you can undo all patches with the same name using {@link module:Patcher.unpatchAll}. Use `""` if you don't care.
* @param {object} moduleToPatch - Object with the function to be patched. Can also patch an object's prototype.
* @param {string} functionName - Name of the method to be patched
* @param {module:Patcher~patchCallback} callback - Function to run instead of the original method
* @param {object} options - Object used to pass additional options.
* @param {string} [options.displayName] You can provide meaningful name for class/object provided in `what` param for logging purposes. By default, this function will try to determine name automatically.
* @param {boolean} [options.forcePatch=true] Set to `true` to patch even if the function doesnt exist. (Adds noop function in place).
* @return {module:Patcher~unpatch} Function with no arguments and no return value that should be called to cancel (unpatch) this patch. You should save and run it when your plugin is stopped.
*/
static after(caller, moduleToPatch, functionName, callback, options = {}) {return this.pushChildPatch(caller, moduleToPatch, functionName, callback, Object.assign(options, {type: "after"}));}
/**
* This method patches onto another function, allowing your code to run instead.
* Using this, you are also able to modify the return value, using the return of your code instead.
*
* @param {string} caller - Name of the caller of the patch function. Using this you can undo all patches with the same name using {@link module:Patcher.unpatchAll}. Use `""` if you don't care.
* @param {object} moduleToPatch - Object with the function to be patched. Can also patch an object's prototype.
* @param {string} functionName - Name of the method to be patched
* @param {module:Patcher~patchCallback} callback - Function to run after the original method
* @param {object} options - Object used to pass additional options.
* @param {string} [options.displayName] You can provide meaningful name for class/object provided in `what` param for logging purposes. By default, this function will try to determine name automatically.
* @param {boolean} [options.forcePatch=true] Set to `true` to patch even if the function doesnt exist. (Adds noop function in place).
* @return {module:Patcher~unpatch} Function with no arguments and no return value that should be called to cancel (unpatch) this patch. You should save and run it when your plugin is stopped.
*/
static instead(caller, moduleToPatch, functionName, callback, options = {}) {return this.pushChildPatch(caller, moduleToPatch, functionName, callback, Object.assign(options, {type: "instead"}));}
/**
* This method patches onto another function, allowing your code to run before, instead or after the original function.
* Using this you are able to modify the incoming arguments before the original function is run as well as the return
* value before the original function actually returns.
*
* @param {string} caller - Name of the caller of the patch function. Using this you can undo all patches with the same name using {@link module:Patcher.unpatchAll}. Use `""` if you don't care.
* @param {object} moduleToPatch - Object with the function to be patched. Can also patch an object's prototype.
* @param {string} functionName - Name of the method to be patched
* @param {module:Patcher~patchCallback} callback - Function to run after the original method
* @param {object} options - Object used to pass additional options.
* @param {string} [options.type=after] - Determines whether to run the function `before`, `instead`, or `after` the original.
* @param {string} [options.displayName] You can provide meaningful name for class/object provided in `what` param for logging purposes. By default, this function will try to determine name automatically.
* @param {boolean} [options.forcePatch=true] Set to `true` to patch even if the function doesnt exist. (Adds noop function in place).
* @return {module:Patcher~unpatch} Function with no arguments and no return value that should be called to cancel (unpatch) this patch. You should save and run it when your plugin is stopped.
*/
static pushChildPatch(caller, moduleToPatch, functionName, callback, options = {}) {
const {type = "after", forcePatch = true} = options;
const module = this.resolveModule(moduleToPatch);
if (!module) return null;
if (!module[functionName] && forcePatch) module[functionName] = function() {};
if (!(module[functionName] instanceof Function)) return null;
const descriptor = Object.getOwnPropertyDescriptor(module, functionName);
if (descriptor && !descriptor?.configurable) {
Logger.err("Patcher", `Cannot patch ${functionName} of Module, property is readonly.`);
return null;
}
if (typeof moduleToPatch === "string") options.displayName = moduleToPatch;
const displayName = options.displayName || module.displayName || module.name || module.constructor.displayName || module.constructor.name;
const patchId = `${displayName}.${functionName}`;
const patch = this.patches.find(p => p.module == module && p.functionName == functionName) || this.makePatch(module, functionName, patchId);
if (!patch.proxyFunction) this.rePatch(patch);
const child = {
caller,
type,
id: patch.counter,
callback,
unpatch: () => {
patch.children.splice(patch.children.findIndex(cpatch => cpatch.id === child.id && cpatch.type === type), 1);
if (patch.children.length <= 0) {
const patchNum = this.patches.findIndex(p => p.module == module && p.functionName == functionName);
if (patchNum < 0) return;
this.patches[patchNum].revert();
this.patches.splice(patchNum, 1);
}
}
};
patch.children.push(child);
patch.counter++;
return child.unpatch;
}
}
import Logger from "common/logger";
import DiscordModules from "./discordmodules";
import WebpackModules from "./webpackmodules";
export default class Patcher {
static get patches() {return this._patches || (this._patches = []);}
/**
* Returns all the patches done by a specific caller
* @param {string} name - Name of the patch caller
* @method
*/
static getPatchesByCaller(name) {
if (!name) return [];
const patches = [];
for (const patch of this.patches) {
for (const childPatch of patch.children) {
if (childPatch.caller === name) patches.push(childPatch);
}
}
return patches;
}
/**
* Unpatches all patches passed, or when a string is passed unpatches all
* patches done by that specific caller.
* @param {Array|string} patches - Either an array of patches to unpatch or a caller name
*/
static unpatchAll(patches) {
if (typeof patches === "string") patches = this.getPatchesByCaller(patches);
for (const patch of patches) {
patch.unpatch();
}
}
static resolveModule(module) {
if (!module || typeof(module) === "function" || (typeof(module) === "object" && !Array.isArray(module))) return module;
if (typeof module === "string") return DiscordModules[module];
if (Array.isArray(module)) return WebpackModules.findByUniqueProperties(module);
return null;
}
static makeOverride(patch) {
return function () {
let returnValue;
if (!patch.children || !patch.children.length) return patch.originalFunction.apply(this, arguments);
for (const superPatch of patch.children.filter(c => c.type === "before")) {
try {
superPatch.callback(this, arguments);
}
catch (err) {
Logger.err("Patcher", `Could not fire before callback of ${patch.functionName} for ${superPatch.caller}`, err);
}
}
const insteads = patch.children.filter(c => c.type === "instead");
if (!insteads.length) {returnValue = patch.originalFunction.apply(this, arguments);}
else {
for (const insteadPatch of insteads) {
try {
const tempReturn = insteadPatch.callback(this, arguments, patch.originalFunction.bind(this));
if (typeof(tempReturn) !== "undefined") returnValue = tempReturn;
}
catch (err) {
Logger.err("Patcher", `Could not fire instead callback of ${patch.functionName} for ${insteadPatch.caller}`, err);
}
}
}
for (const slavePatch of patch.children.filter(c => c.type === "after")) {
try {
const tempReturn = slavePatch.callback(this, arguments, returnValue);
if (typeof(tempReturn) !== "undefined") returnValue = tempReturn;
}
catch (err) {
Logger.err("Patcher", `Could not fire after callback of ${patch.functionName} for ${slavePatch.caller}`, err);
}
}
return returnValue;
};
}
static rePatch(patch) {
patch.proxyFunction = patch.module[patch.functionName] = this.makeOverride(patch);
}
static makePatch(module, functionName, name) {
const patch = {
name,
module,
functionName,
originalFunction: module[functionName],
proxyFunction: null,
revert: () => { // Calling revert will destroy any patches added to the same module after this
patch.module[patch.functionName] = patch.originalFunction;
patch.proxyFunction = null;
patch.children = [];
},
counter: 0,
children: []
};
patch.proxyFunction = module[functionName] = this.makeOverride(patch);
Object.assign(module[functionName], patch.originalFunction);
module[functionName].__originalFunction = patch.originalFunction;
module[functionName].toString = () => patch.originalFunction.toString();
this.patches.push(patch);
return patch;
}
/**
* Function with no arguments and no return value that may be called to revert changes made by {@link module:Patcher}, restoring (unpatching) original method.
* @callback module:Patcher~unpatch
*/
/**
* A callback that modifies method logic. This callback is called on each call of the original method and is provided all data about original call. Any of the data can be modified if necessary, but do so wisely.
*
* The third argument for the callback will be `undefined` for `before` patches. `originalFunction` for `instead` patches and `returnValue` for `after` patches.
*
* @callback module:Patcher~patchCallback
* @param {object} thisObject - `this` in the context of the original function.
* @param {arguments} args - The original arguments of the original function.
* @param {(function|*)} extraValue - For `instead` patches, this is the original function from the module. For `after` patches, this is the return value of the function.
* @return {*} Makes sense only when using an `instead` or `after` patch. If something other than `undefined` is returned, the returned value replaces the value of `returnValue`. If used for `before` the return value is ignored.
*/
/**
* This method patches onto another function, allowing your code to run beforehand.
* Using this, you are also able to modify the incoming arguments before the original method is run.
*
* @param {string} caller - Name of the caller of the patch function. Using this you can undo all patches with the same name using {@link module:Patcher.unpatchAll}. Use `""` if you don't care.
* @param {object} moduleToPatch - Object with the function to be patched. Can also patch an object's prototype.
* @param {string} functionName - Name of the method to be patched
* @param {module:Patcher~patchCallback} callback - Function to run before the original method
* @param {object} options - Object used to pass additional options.
* @param {string} [options.displayName] You can provide meaningful name for class/object provided in `what` param for logging purposes. By default, this function will try to determine name automatically.
* @param {boolean} [options.forcePatch=true] Set to `true` to patch even if the function doesnt exist. (Adds noop function in place).
* @return {module:Patcher~unpatch} Function with no arguments and no return value that should be called to cancel (unpatch) this patch. You should save and run it when your plugin is stopped.
*/
static before(caller, moduleToPatch, functionName, callback, options = {}) {return this.pushChildPatch(caller, moduleToPatch, functionName, callback, Object.assign(options, {type: "before"}));}
/**
* This method patches onto another function, allowing your code to run after.
* Using this, you are also able to modify the return value, using the return of your code instead.
*
* @param {string} caller - Name of the caller of the patch function. Using this you can undo all patches with the same name using {@link module:Patcher.unpatchAll}. Use `""` if you don't care.
* @param {object} moduleToPatch - Object with the function to be patched. Can also patch an object's prototype.
* @param {string} functionName - Name of the method to be patched
* @param {module:Patcher~patchCallback} callback - Function to run instead of the original method
* @param {object} options - Object used to pass additional options.
* @param {string} [options.displayName] You can provide meaningful name for class/object provided in `what` param for logging purposes. By default, this function will try to determine name automatically.
* @param {boolean} [options.forcePatch=true] Set to `true` to patch even if the function doesnt exist. (Adds noop function in place).
* @return {module:Patcher~unpatch} Function with no arguments and no return value that should be called to cancel (unpatch) this patch. You should save and run it when your plugin is stopped.
*/
static after(caller, moduleToPatch, functionName, callback, options = {}) {return this.pushChildPatch(caller, moduleToPatch, functionName, callback, Object.assign(options, {type: "after"}));}
/**
* This method patches onto another function, allowing your code to run instead.
* Using this, you are also able to modify the return value, using the return of your code instead.
*
* @param {string} caller - Name of the caller of the patch function. Using this you can undo all patches with the same name using {@link module:Patcher.unpatchAll}. Use `""` if you don't care.
* @param {object} moduleToPatch - Object with the function to be patched. Can also patch an object's prototype.
* @param {string} functionName - Name of the method to be patched
* @param {module:Patcher~patchCallback} callback - Function to run after the original method
* @param {object} options - Object used to pass additional options.
* @param {string} [options.displayName] You can provide meaningful name for class/object provided in `what` param for logging purposes. By default, this function will try to determine name automatically.
* @param {boolean} [options.forcePatch=true] Set to `true` to patch even if the function doesnt exist. (Adds noop function in place).
* @return {module:Patcher~unpatch} Function with no arguments and no return value that should be called to cancel (unpatch) this patch. You should save and run it when your plugin is stopped.
*/
static instead(caller, moduleToPatch, functionName, callback, options = {}) {return this.pushChildPatch(caller, moduleToPatch, functionName, callback, Object.assign(options, {type: "instead"}));}
/**
* This method patches onto another function, allowing your code to run before, instead or after the original function.
* Using this you are able to modify the incoming arguments before the original function is run as well as the return
* value before the original function actually returns.
*
* @param {string} caller - Name of the caller of the patch function. Using this you can undo all patches with the same name using {@link module:Patcher.unpatchAll}. Use `""` if you don't care.
* @param {object} moduleToPatch - Object with the function to be patched. Can also patch an object's prototype.
* @param {string} functionName - Name of the method to be patched
* @param {module:Patcher~patchCallback} callback - Function to run after the original method
* @param {object} options - Object used to pass additional options.
* @param {string} [options.type=after] - Determines whether to run the function `before`, `instead`, or `after` the original.
* @param {string} [options.displayName] You can provide meaningful name for class/object provided in `what` param for logging purposes. By default, this function will try to determine name automatically.
* @param {boolean} [options.forcePatch=true] Set to `true` to patch even if the function doesnt exist. (Adds noop function in place).
* @return {module:Patcher~unpatch} Function with no arguments and no return value that should be called to cancel (unpatch) this patch. You should save and run it when your plugin is stopped.
*/
static pushChildPatch(caller, moduleToPatch, functionName, callback, options = {}) {
const {type = "after", forcePatch = true} = options;
const module = this.resolveModule(moduleToPatch);
if (!module) return null;
if (!module[functionName] && forcePatch) module[functionName] = function() {};
if (!(module[functionName] instanceof Function)) return null;
if (typeof moduleToPatch === "string") options.displayName = moduleToPatch;
const displayName = options.displayName || module.displayName || module.name || module.constructor.displayName || module.constructor.name;
const patchId = `${displayName}.${functionName}`;
const patch = this.patches.find(p => p.module == module && p.functionName == functionName) || this.makePatch(module, functionName, patchId);
if (!patch.proxyFunction) this.rePatch(patch);
const child = {
caller,
type,
id: patch.counter,
callback,
unpatch: () => {
patch.children.splice(patch.children.findIndex(cpatch => cpatch.id === child.id && cpatch.type === type), 1);
if (patch.children.length <= 0) {
const patchNum = this.patches.findIndex(p => p.module == module && p.functionName == functionName);
if (patchNum < 0) return;
this.patches[patchNum].revert();
this.patches.splice(patchNum, 1);
}
}
};
patch.children.push(child);
patch.counter++;
return child.unpatch;
}
}

View File

@ -134,6 +134,25 @@ export class CoreUpdater {
}
}
const semverRegex = /^[0-9]+\.[0-9]+\.[0-9]+$/;
/**
* This works on basic semantic versioning e.g. "1.0.0".
*
* @param {string} currentVersion
* @param {string} content
* @returns {boolean} whether there is an update
*/
function semverComparator(currentVersion, remoteVersion) {
currentVersion = currentVersion.split(".").map((e) => {return parseInt(e);});
remoteVersion = remoteVersion.split(".").map((e) => {return parseInt(e);});
if (remoteVersion[0] > currentVersion[0]) return true;
else if (remoteVersion[0] == currentVersion[0] && remoteVersion[1] > currentVersion[1]) return true;
else if (remoteVersion[0] == currentVersion[0] && remoteVersion[1] == currentVersion[1] && remoteVersion[2] > currentVersion[2]) return true;
return false;
}
class AddonUpdater {
@ -176,7 +195,10 @@ class AddonUpdater {
if (this.pending.includes(filename)) return;
const info = this.cache[path.basename(filename)];
if (!info) return;
const hasUpdate = info.version > currentVersion;
let hasUpdate = info.update > currentVersion;
if (semverRegex.test(info.version) && semverRegex.test(currentVersion)) {
hasUpdate = semverComparator(currentVersion, info.version);
}
if (!hasUpdate) return;
this.pending.push(filename);
}

View File

@ -1,82 +0,0 @@
.bd-emote-menu {
min-height: 0;
}
.bd-emote-menu-inner {
padding: 8px 0 0 16px;
}
.bd-emote-scroller {
height: 100%;
}
.bd-emote-header {
display: flex;
align-items: center;
background: var(--background-secondary);
height: 32px;
padding: 0 4px;
position: sticky;
top: 0;
z-index: 2;
}
.bd-emote-header-inner {
cursor: pointer;
display: flex;
align-items: center;
color: var(--header-secondary);
font-size: 12px;
font-weight: 600;
transition: color 0.125s;
width: fit-content;
}
.bd-emote-header-inner:hover {
color: var(--header-primary);
}
.bd-emote-header-icon {
width: 16px;
height: 16px;
}
.bd-emote-header-icon svg {
max-height: 100%;
max-width: 100%;
}
.bd-emote-header-label {
overflow: hidden;
text-overflow: ellipsis;
text-transform: uppercase;
white-space: nowrap;
margin: 0 8px;
}
.bd-emote-collapse-icon svg {
transition: transform 0.1s;
}
.bd-emote-collapse-icon.collapsed svg {
transform: rotate(-90deg);
}
.bd-emote-item {
display: inline-flex;
justify-content: center;
align-items: center;
padding: 2px;
border-radius: 5px;
width: 30px;
height: 30px;
position: relative;
}
.bd-emote-item:hover {
background: var(--background-accent);
}
.bd-emote-item img {
max-width: 100%;
}

View File

@ -1,208 +0,0 @@
.emotewrapper {
position: relative;
display: inline-flex;
object-fit: contain;
margin: -0.1em 0.05em -0.2em 0.1em;
vertical-align: top;
}
.emotewrapper.jumboable {
margin-bottom: 0;
margin-top: 0.2em;
vertical-align: -0.3em;
}
.emote {
object-fit: contain;
width: 1.375em;
height: 1.375em;
vertical-align: bottom;
}
.emote.jumboable {
width: 3rem;
height: 3rem;
min-height: 3rem;
}
.fav {
display: none;
position: absolute;
width: 15px;
height: 15px;
right: -7px;
background: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAMAAAAoLQ9TAAAAzFBMVEUAAABQUFBMTExLS0tNTU1MTExNTU1NTU1MTExMTExNTU1LS0tEREBEREBEREBEREBJSUhLS0tLS0tEREBNTU1NTU1NTU1EREArKyhNTU1NTU0AAABMTExKSklMTExNTU1NTU1NTU1KSkpMTExKSkhNTU1KSkpISEZNTU1LS0tAQDxOTk5KSkpLS0tNTU1MTExMTEx/f39MTExMTExLS0pLS0tMTExNTU1NTU1LS0pNTU1NTU1NTU1NTU1NTU1NTUxNTU1NTU1NTUxMTEzB8C/5AAAAOnRSTlMAI8X96oWAgYSF68QBAg0PMCb9BIuLgQUD4N0Bh0mKhZSOQ4gcrKscaW8QRE6fmJyjAshASceG7cIpqQOxTQAAALVJREFUGFddx6FOA0EYAOGZvd07Qm6vVCAAgUUgQEDfX/YZMAigqaFN7iC5tsmPqGPUN/AvUVeoEbGOCElJz08Uzeixqu4AqomVVSNngOVjTqDGZSl3UFtPGV2ot2zaq96YM9p5Ddzcf/nTTAlj+/sNtNu8OcwkIsbPBtrUfMQeEhGQmHbmGIFMwLPzu6UMIwBNgToshgq8Nr2ki+Oy7ebDHp70LRPWB6OZgfWLWei7fJonOOsPCGA9kVlssOoAAAAASUVORK5CYII=");
border: none;
background-size: 100% 100%;
background-repeat: no-repeat;
background-color: #303030;
border-radius: 5px;
top: -7px;
cursor: pointer;
}
.fav.active {
background-color: yellow;
}
.emotewrapper:hover .fav {
display: block;
}
.emote.stop-animation {
animation: none;
}
.emoteflip,
.emotespinflip {
transform: scaleX(-1);
}
.emotespin {
animation: 1s emote-spin infinite linear;
}
.emote1spin {
animation: 1s emote-spin-reverse infinite linear;
}
.emotespin2 {
animation: 0.5s emote-spin infinite linear;
}
.emote2spin {
animation: 0.5s emote-spin-reverse infinite linear;
}
.emotespin3 {
animation: 0.2s emote-spin infinite linear;
}
.emote3spin {
animation: 0.2s emote-spin-reverse infinite linear;
}
.emotepulse {
animation: 1s emote-pulse infinite linear;
}
.emotetr {
transform: translateX(-3px);
}
.emotebl {
transform: translateY(-3px);
}
.emotebr {
transform: translate(-3px, -3px);
}
.emoteshake {
animation: 1s emote-shake infinite linear;
}
.emoteflap {
transform: scaleY(-1);
}
.emoteshake2 {
animation: emote-shake2 0.3s linear infinite;
}
.emoteshake3 {
animation: emote-shake3 0.1s linear infinite;
}
@keyframes emote-shake2 {
25% {
transform: translate(-1px, -1px);
}
50% {
transform: translate(-1px, 1px);
}
75% {
transform: translate(1px, 1px);
}
75% {
transform: translate(1px, -1px);
}
}
@keyframes emote-shake3 {
25% {
transform: translate(-1px, -1px);
}
50% {
transform: translate(-1px, 1px);
}
75% {
transform: translate(1px, 1px);
}
75% {
transform: translate(1px, -1px);
}
}
@keyframes emote-spin {
from {
transform: rotate(0deg);
}
to {
transform: rotate(360deg);
}
}
@keyframes emote-spin-reverse {
from {
transform: rotate(0deg);
}
to {
transform: rotate(-360deg);
}
}
@keyframes emote-pulse {
0% {
-webkit-transform: scale(1, 1);
}
50% {
-webkit-transform: scale(1.2, 1.2);
}
100% {
-webkit-transform: scale(1, 1);
}
}
@keyframes emote-shake {
10%,
90% {
transform: translate3d(-1px, 0, 0);
}
20%,
80% {
transform: translate3d(2px, 0, 0);
}
30%,
50%,
70% {
transform: translate3d(-4px, 0, 0);
}
40%,
60% {
transform: translate3d(4px, 0, 0);
}
}

View File

@ -1,82 +0,0 @@
import {Settings, React, WebpackModules, Events, Strings} from "modules";
const TooltipWrapper = WebpackModules.getByPrototypes("renderTooltip");
export default class BDEmote extends React.Component {
constructor(props) {
super(props);
this.state = {
shouldAnimate: !this.animateOnHover,
isFavorite: this.props.isFavorite
};
this.onMouseEnter = this.onMouseEnter.bind(this);
this.onMouseLeave = this.onMouseLeave.bind(this);
this.onClick = this.onClick.bind(this);
this.toggleFavorite = this.toggleFavorite.bind(this);
}
get animateOnHover() {
return Settings.get("emotes", "general", "animateOnHover");
}
get label() {
return this.props.modifier ? `${this.props.name}:${this.props.modifier}` : this.props.name;
}
get modifierClass() {
return this.props.modifier ? ` emote${this.props.modifier}` : "";
}
onMouseEnter() {
if (!this.state.shouldAnimate && this.animateOnHover) this.setState({shouldAnimate: true});
}
onMouseLeave() {
if (this.state.shouldAnimate && this.animateOnHover) this.setState({shouldAnimate: false});
}
onClick(e) {
if (this.props.onClick) this.props.onClick(e);
}
toggleFavorite(e) {
e.preventDefault();
e.stopPropagation();
if (this.state.isFavorite) Events.emit("emotes-favorite-removed", this.label);
else Events.emit("emotes-favorite-added", this.label, this.props.url);
this.setState({isFavorite: !this.state.isFavorite});
}
render() {
return React.createElement(TooltipWrapper, {
color: "primary",
position: "top",
text: this.label,
delay: 750
},
(childProps) => {
return React.createElement("div", Object.assign({
className: "emotewrapper" + (this.props.jumboable ? " jumboable" : ""),
onMouseEnter: this.onMouseEnter,
onMouseLeave: this.onMouseLeave,
onClick: this.onClick
}, childProps),
React.createElement("img", {
draggable: false,
className: "emote" + this.modifierClass + (this.props.jumboable ? " jumboable" : "") + (!this.state.shouldAnimate ? " stop-animation" : ""),
dataModifier: this.props.modifier,
alt: this.label,
src: this.props.url
}),
React.createElement("input", {
className: "fav" + (this.state.isFavorite ? " active" : ""),
title: Strings.Emotes.favoriteAction,
type: "button",
onClick: this.toggleFavorite
})
);
});
}
}

View File

@ -1,36 +0,0 @@
import {React, WebpackModules} from "modules";
import EmoteModule from "../builtins/emotes/emotes";
const ContextMenuActions = WebpackModules.getByProps("openContextMenu");
const {MenuItem, MenuGroup} = WebpackModules.find(m => m.MenuRadioItem && !m.default) ?? {MenuItem: () => null, MenuGroup: () => null};
const ContextMenu = WebpackModules.getByProps("default", "MenuStyle")?.default;
const {ComponentDispatch} = WebpackModules.getByProps("ComponentDispatch") ?? {ComponentDispatch: () => null};
export default class EmoteIcon extends React.Component {
render() {
return <div className="bd-emote-item" onClick={this.handleOnClick.bind(this)} onContextMenu={this.handleOnContextMenu.bind(this)}>
<img src={this.props.url} alt={this.props.emote} title={this.props.emote}/>
</div>;
}
handleOnClick() {
this.insertText(this.props.emote);
}
handleOnContextMenu(e) {
ContextMenuActions.openContextMenu(e, () => <ContextMenu navId="EmoteContextMenu" onClose={ContextMenuActions.closeContextMenu}>
<MenuGroup>
<MenuItem label={EmoteModule.isFavorite(this.props.emote) ? "Remove Favorite" : "Add Favorite"} id="favorite" action={this.handlefavorite.bind(this)} onClose={ContextMenuActions.closeContextMenu}/>
</MenuGroup>
</ContextMenu>);
}
handlefavorite() {
ContextMenuActions.closeContextMenu();
EmoteModule.isFavorite(this.props.emote) ? EmoteModule.removeFavorite(this.props.emote) : EmoteModule.addFavorite(this.props.emote, this.props.url);
}
insertText(emote) {
ComponentDispatch.dispatchToLastSubscribed("INSERT_TEXT", {content: emote});
}
}

View File

@ -1,13 +0,0 @@
import {React, WebpackModules} from "modules";
const {ScrollerAuto: Scroller} = WebpackModules.getByProps("ScrollerAuto") ?? {ScrollerAuto: () => null};
export default class EmoteMenuCard extends React.Component {
render() {
return <div className={`bd-emote-menu`}>
<Scroller className="bd-emote-scroller">
<div className="bd-emote-menu-inner">
{this.props.children}
</div>
</Scroller>
</div>;
}
}

View File

@ -1,18 +0,0 @@
const path = require("path");
const asar = require("asar");
const emotes = path.resolve(__dirname, "..", "assets", "emotes");
const dist = path.resolve(__dirname, "..", "dist");
const bundleFile = path.join(dist, "emotes.asar");
const makeBundle = function() {
console.log("");
console.log("Generating bundle");
asar.createPackage(emotes, bundleFile).then(() => {
console.log(` ✅ Successfully created bundle ${bundleFile}`);
}).catch(err => {
console.log(` ❌ Could not build bundle: ${err.message}`);
});
};
makeBundle();

View File

@ -15,18 +15,13 @@ const discordPath = (function() {
const basedir = path.join(process.env.LOCALAPPDATA, release.replace(/ /g, ""));
if (!fs.existsSync(basedir)) throw new Error(`Cannot find directory for ${release}`);
const version = fs.readdirSync(basedir).filter(f => fs.lstatSync(path.join(basedir, f)).isDirectory() && f.split(".").length > 1).sort().reverse()[0];
resourcePath = path.join(basedir, version, "resources");
}
else if (process.platform === "darwin") {
const appPath = releaseInput === "canary" ? path.join("/Applications", "Discord Canary.app")
: releaseInput === "ptb" ? path.join("/Applications", "Discord PTB.app")
: useBdRelease && args[3] ? args[3] ? args[2] : args[2]
: path.join("/Applications", "Discord.app");
resourcePath = path.join(appPath, "Contents", "Resources");
// To account for discord_desktop_core-1 or any other number
const coreWrap = fs.readdirSync(path.join(basedir, version, "modules")).filter(e => e.indexOf("discord_desktop_core") === 0).sort().reverse()[0];
resourcePath = path.join(basedir, version, "modules", coreWrap, "discord_desktop_core");
}
else {
const userData = process.env.XDG_CONFIG_HOME ? process.env.XDG_CONFIG_HOME : path.join(process.env.HOME, ".config");
let userData = process.env.XDG_CONFIG_HOME ? process.env.XDG_CONFIG_HOME : path.join(process.env.HOME, ".config");
if (process.platform === "darwin") userData = path.join(process.env.HOME, "Library", "Application Support");
const basedir = path.join(userData, release.toLowerCase().replace(" ", ""));
if (!fs.existsSync(basedir)) return "";
const version = fs.readdirSync(basedir).filter(f => fs.lstatSync(path.join(basedir, f)).isDirectory() && f.split(".").length > 1).sort().reverse()[0];
@ -46,50 +41,11 @@ console.log(`Injecting into ${release}`);
if (!fs.existsSync(discordPath)) throw new Error(`Cannot find directory for ${release}`);
console.log(` ✅ Found ${release} in ${discordPath}`);
const appPath = process.platform === "win32" || process.platform === "darwin" ? path.join(discordPath, "app") : discordPath;
const packageJson = path.join(appPath, "package.json");
const indexJs = path.join(appPath, "index.js");
if (!fs.existsSync(appPath)) fs.mkdirSync(appPath);
if (fs.existsSync(packageJson)) fs.unlinkSync(packageJson);
const indexJs = path.join(discordPath, "index.js");
if (fs.existsSync(indexJs)) fs.unlinkSync(indexJs);
if (process.platform === "win32" || process.platform === "darwin") {
fs.writeFileSync(packageJson, JSON.stringify({
name: "betterdiscord",
main: "index.js",
}, null, 4));
console.log(" ✅ Wrote package.json");
fs.writeFileSync(indexJs, `require("${bdPath.replace(/\\/g, "\\\\").replace(/"/g, "\\\"")}");`);
}
else {
fs.writeFileSync(indexJs, `require("${bdPath.replace(/\\/g, "\\\\").replace(/"/g, "\\\"")}");\nmodule.exports = require("./core.asar");`);
}
fs.writeFileSync(indexJs, `require("${bdPath.replace(/\\/g, "\\\\").replace(/"/g, "\\\"")}");\nmodule.exports = require("./core.asar");`);
console.log(" ✅ Wrote index.js");
console.log("");
const asarPath = path.join(discordPath, "app.asar");
const modifiedPath = path.join(discordPath, "discord.asar");
if (!fs.existsSync(modifiedPath)) {
console.log("Renaming app.asar -> discord.asar");
console.log("");
if (!fs.existsSync(asarPath)) {
console.log(" ❌ Unable to rename app.asar -> discord.asar, discord installation appears to be corrupt.");
process.exit(0);
}
try {
fs.renameSync(asarPath, modifiedPath);
console.log(" ✅ Successfully renamed app.asar -> discord.asar");
console.log("");
} catch (error) {
console.log(" ❌ Failed to rename app.asar -> discord.asar:", error);
process.exit(0);
}
}
console.log(`Injection successful, please restart ${release}.`);