Skip to content

Commit

Permalink
Cleanups Part II
Browse files Browse the repository at this point in the history
- Set Webpack devtool to false to disable generation of map files.
- Further code formatting.
- Added discordmodules.js/utilities.js (ported from BetterDiscord).
  Exposing and managing the modules in one central
  location is smarter than doing it on a per-file basis.
  This also allows for easier updating.
- Changed UserSettingsStore to reflect the changes
  made in BetterDiscord 1.6.2.
- Updated .gitignore.
  • Loading branch information
tsukasa committed Aug 12, 2022
1 parent 04bf528 commit cca38dd
Show file tree
Hide file tree
Showing 29 changed files with 839 additions and 569 deletions.
2 changes: 1 addition & 1 deletion .gitignore
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
/betterdiscord
/node_modules
/dist/*.js.map
/.idea
20 changes: 13 additions & 7 deletions backend/src/index.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
import IPC from "common/ipc";
import {IPCEvents} from "common/constants";
import DOM from "common/dom";
import ipcRenderer from "common/ipc";
import Logger from "common/logger";

Logger.log("Backend", "Initializing modules");

const ipcMain = new IPC("backend");
const ipcMain = new ipcRenderer("backend");

Logger.log("Backend", "Registering events");

Expand All @@ -21,8 +21,8 @@ ipcMain.on(IPCEvents.MAKE_REQUESTS, (event, data) => {
fetch(data.url)
.catch(console.error.bind(null, "REQUEST FAILED:"))
.then(res => res.text()).then(text => {
ipcMain.reply(event, text);
})
ipcMain.reply(event, text);
})
});

ipcMain.on(IPCEvents.GET_RESOURCE_URL, (event, data) => {
Expand All @@ -31,11 +31,17 @@ ipcMain.on(IPCEvents.GET_RESOURCE_URL, (event, data) => {

const SCRIPT_URL = (() => {
switch (ENV) {
case "production": return chrome.runtime.getURL("dist/frontend.js");
case "development": return "http://127.0.0.1:5500/frontend.js";
default: throw new Error("Unknown Environment")
case "production":
return chrome.runtime.getURL("dist/frontend.js");

case "development":
return "http://127.0.0.1:5500/frontend.js";

default:
throw new Error("Unknown Environment");
}
})();

Logger.log("Backend", "Loading frontend script from", SCRIPT_URL);

DOM.injectJS("BetterDiscordBrowser-frontend", SCRIPT_URL, false);
2 changes: 1 addition & 1 deletion common/constants.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,5 +2,5 @@ export const IPCEvents = {
INJECT_CSS: "bdbrowser-inject-css",
MAKE_REQUESTS: "bdbrowser-make-requests",
INJECT_THEME: "bdbrowser-inject-theme",
GET_RESOURCE_URL: "bdbrowser-get-extresourceurl"
GET_RESOURCE_URL: "bdbrowser-get-extension-resourceurl"
};
9 changes: 5 additions & 4 deletions common/dom.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
export default class DOM {
export default class DOM
{
/**@returns {HTMLElement} */
static createElement(type, options = {}, ...children) {
const node = document.createElement(type);

Object.assign(node, options);

for (const child of children) {
Expand Down Expand Up @@ -51,9 +52,9 @@ export default class DOM {
});

this.headAppend(script);

if (silent) script.addEventListener("load", () => {script.remove();}, {once: true});
}
}

DOM.headAppend = document.head.append.bind(document.head);
DOM.headAppend = document.head.append.bind(document.head);
40 changes: 26 additions & 14 deletions common/ipc.js
Original file line number Diff line number Diff line change
@@ -1,42 +1,54 @@
export default class IPC {
constructor(context) {
if (!context) throw new Error("Context is required");
export default class IPC
{
constructor(context)
{
if (!context)
throw new Error("Context is required");

this.context = context;
}

createHash() {
createHash()
{
return Math.random().toString(36).substr(2, 10);
}

reply(message, data) {
reply(message, data)
{
this.send(message.event + "-reply", data, void 0, message.hash);
}

on(event, listener, once = false) {
on(event, listener, once = false)
{
const wrappedListener = message => {
if (message.data.event !== event || message.data.context === this.context) return;
if (message.data.event !== event || message.data.context === this.context)
return;

const returnValue = listener(message.data, message.data.data);

if (returnValue == true && once) {
if (returnValue == true && once)
{
window.removeEventListener("message", wrappedListener);
}
};

window.addEventListener("message", wrappedListener);
}

send(event, data, callback = null, hash) {
if (!hash) hash = this.createHash();
send(event, data, callback = null, hash)
{
if (!hash)
hash = this.createHash();

if (callback) {
if (callback)
{
this.on(event + "-reply", message => {
if (message.hash === hash) {
if (message.hash === hash)
{
callback(message.data);
return true;
}

return false;
}, true);
}
Expand All @@ -49,4 +61,4 @@ export default class IPC {
data
});
}
};
};
37 changes: 28 additions & 9 deletions common/logger.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
export default class Logger {
static _parseType(type) {
switch (type) {
export default class Logger
{
static _parseType(type)
{
switch (type)
{
case "info":
case "warn":
case "error":
Expand All @@ -10,13 +13,29 @@ export default class Logger {
}
}

static _log(type, module, ...nessage) {
static _log(type, module, ...nessage)
{
type = this._parseType(type);
console[type](`%c[BetterDiscord]%c %c[${module}]%c`, "color: #3E82E5; font-weight: 700;", "", "color: #396CB8", "", ...nessage);
}

static log(module, ...message) {this._log("log", module, ...message);}
static info(module, ...message) {this._log("info", module, ...message);}
static warn(module, ...message) {this._log("warn", module, ...message);}
static error(module, ...message) {this._log("error", module, ...message);}
}
static log(module, ...message)
{
this._log("log", module, ...message);
}

static info(module, ...message)
{
this._log("info", module, ...message);
}

static warn(module, ...message)
{
this._log("warn", module, ...message);
}

static error(module, ...message)
{
this._log("error", module, ...message);
}
}
3 changes: 1 addition & 2 deletions dist/backend.js

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 1 addition & 2 deletions dist/frontend.js

Large diffs are not rendered by default.

76 changes: 34 additions & 42 deletions frontend/src/index.js
Original file line number Diff line number Diff line change
@@ -1,34 +1,37 @@
import ipcRenderer from "./ipc";
import DOM from "common/dom";
import Logger from "common/logger";
import require from "./modules/require";
import {IPCEvents} from "common/constants";
import ipcRenderer from "./ipc";
import DiscordModules from "./modules/discordmodules";
import * as DiscordNative from "./modules/discordnative";
import {default as fetchAPI} from "./modules/fetch";
import Filesystem from "./modules/fs";
import * as Monaco from "./modules/monaco";
import process from "./modules/process";
import fs from "./modules/fs";
import { IPCEvents } from "common/constants";
import { default as fetchAPI } from "./modules/fetch";
import * as monaco from "./modules/monaco";
import DOM from "common/dom";
import Webpack from "webpack";
import * as localStorage from "./modules/localStorage";
import require from "./modules/require";

Object.defineProperty(Webpack.findByProps("requireModule"), "canBootstrapNewUpdater", {
value: false,
configurable: true
});
Object.defineProperty(
DiscordModules.ElectronModule,
"canBootstrapNewUpdater",
{
value: false,
configurable: true
}
);

window.fallbackClassName = "bdfdb_is_garbage";
window.fallbackClassName = "bdfdb_fallbackClass";
window.value = null;
window.firstArray = [];
window.user = "";

window.global = window;
window.DiscordNative = DiscordNative;
window.require = require;
window.process = process;
window.fs = fs;

window.fetchWithoutCSP = fetchAPI;
window.monaco = monaco;
window.fs = Filesystem;
window.DiscordNative = DiscordNative;
window.IPC = ipcRenderer;
window.monaco = Monaco;
window.process = process;
window.require = require;

Logger.log("Frontend", `Loading, Environment = ${ENV}`);

Expand All @@ -38,39 +41,28 @@ DOM.injectCSS("BetterDiscordWebStyles", `.CodeMirror {height: 100% !important;}`

// const getConfig = key => new Promise(resolve => chrome.storage.sync.get(key, resolve));

ipcRenderer.send(IPCEvents.GET_RESOURCE_URL, { url: "dist/betterdiscord.js" }, async resource_url => {
ipcRenderer.send(IPCEvents.GET_RESOURCE_URL, {url: "dist/betterdiscord.js"}, async resource_url => {
ipcRenderer.send(IPCEvents.MAKE_REQUESTS, {
url: ENV === "development" ? "http://127.0.0.1:5500/betterdiscord.js" : resource_url
},
async bd => {
const Dispatcher = Webpack.findByProps("dispatch", "subscribe", "wait", "unsubscribe");
const UserStore = Webpack.findByProps("getCurrentUser");

Logger.log("Frontend", "Dispatcher:", Dispatcher);
Logger.log("Frontend", "UserStore:", UserStore);

}, async bd => {
const callback = async () => {
Dispatcher.unsubscribe("CONNECTION_OPEN", callback);
DiscordModules.Dispatcher.unsubscribe("CONNECTION_OPEN", callback);

Logger.log("Frontend", `Loading BetterDiscord from ${resource_url}...`);

try
{
eval(`((fetch) => {${bd}})(window.fetchWithoutCSP)`);
}
catch (error)
{
try {
eval(`((fetch) => {
${bd}
})(window.fetchWithoutCSP)`);
} catch (error) {
Logger.error("Frontend", "Failed to load BetterDiscord:\n", error);
}
};

if (!UserStore?.getCurrentUser())
{
if (!DiscordModules.UserStore?.getCurrentUser()) {
Logger.log("Frontend", "getCurrentUser failed, registering callback.");
Dispatcher.subscribe("CONNECTION_OPEN", callback);
}
else
{
DiscordModules.Dispatcher.subscribe("CONNECTION_OPEN", callback);
} else {
Logger.log("Frontend", "getCurrentUser succeeded, running setImmediate().");
setImmediate(callback);
}
Expand Down
18 changes: 18 additions & 0 deletions frontend/src/modules/discordmodules.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import Utilities from "utilities";
import Webpack from "webpack";

export default Utilities.memoizeObject({
/* Current User Info, State and Settings */
get UserSettingsStore() { return Webpack.findByProps("getAllSettings", "theme"); },

/* User Stores and Utils */
get UserStore() { return Webpack.findByProps("getCurrentUser"); },

/* Electron & Other Internals with Utils */
get ElectronModule() { return Webpack.findByProps("setBadge"); },
get Dispatcher() { return Webpack.findByProps("dispatch", "subscribe", "wait", "unsubscribe"); },
get RouterModule() { return Webpack.findByProps("listeners", "flushRoute"); },

/* Other Utils */
get StorageModule() { return Webpack.findByProps("get", "set", "stringify"); }
});
44 changes: 28 additions & 16 deletions frontend/src/modules/discordnative.js
Original file line number Diff line number Diff line change
@@ -1,21 +1,33 @@
import process from "./process";

export const app = {
getReleaseChannel() {
return globals.releaseChannel;
},

getVersion() {
return "1.0.9005"
},

async getPath(path) {
switch (path) {
case "appData":
return process.env.APPDATA;

default:
throw new Error("Cannot find path: " + path);
}
}
};

export const globals = {
get releaseChannel() {
if (location.href.includes("canary")) return "canary";
if (location.href.includes("ptb")) return "ptb";
return "stable";
}
}
get releaseChannel() {
if (location.href.includes("canary"))
return "canary";

export const app = {
getReleaseChannel() {return globals.releaseChannel;},
getVersion() {return "1.0.9002"},
async getPath(path) {
switch (path) {
case "appData": return process.env.APPDATA;
if (location.href.includes("ptb"))
return "ptb";

default: throw new Error("Cannot find path: " + path);
}
}
};
return "stable";
}
}
Loading

0 comments on commit cca38dd

Please sign in to comment.