Skip to content

Commit

Permalink
Merge branch 'waitForStoreName' of https://github.com/YofukashiNo/rep…
Browse files Browse the repository at this point in the history
…lugged into context-menu-api-fix
  • Loading branch information
yofukashino committed Jul 6, 2024
2 parents 911a259 + d264019 commit d3f66b2
Show file tree
Hide file tree
Showing 11 changed files with 138 additions and 69 deletions.
4 changes: 2 additions & 2 deletions src/preload.ts
Original file line number Diff line number Diff line change
Expand Up @@ -129,8 +129,8 @@ export type RepluggedNativeType = typeof RepluggedNative;
contextBridge.exposeInMainWorld("RepluggedNative", RepluggedNative);

// webFrame.executeJavaScript returns a Promise, but we don't have any use for it
void webFrame.executeJavaScript(
'void import("replugged://renderer").then(() => console.log("renderer loaded"));',
void webFrame.executeJavaScript('void import("replugged://renderer");', true, () =>
console.log("renderer loaded"),
);

try {
Expand Down
39 changes: 31 additions & 8 deletions src/renderer/apis/commands.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,11 +12,16 @@ import type {
} from "../../types";
// eslint-disable-next-line no-duplicate-imports
import { ApplicationCommandOptionType } from "../../types";
import { constants, i18n, messages, users } from "../modules/common";
import { constants, i18n, messages, users, fluxDispatcher } from "../modules/common";
import type {
SendMessageForReplyOptions,
SendMessageOptionsForReply,
} from "../modules/common/messages";
import type { Store } from "../modules/common/flux";
import { Logger } from "../modules/logger";
import { filters, getByStoreName, waitForModule } from "../modules/webpack";
import icon from "../assets/logo.png";

const logger = Logger.api("Commands");

let RepluggedUser: User | undefined;
Expand All @@ -29,7 +34,7 @@ interface CommandsAndSection {
void waitForModule<typeof User>(filters.bySource("hasHadPremium(){")).then((User) => {
RepluggedUser = new User({
avatar: "replugged",
id: "69",
id: "replugged",
bot: true,
username: "Replugged",
system: true,
Expand Down Expand Up @@ -97,7 +102,18 @@ async function executeCommand<T extends CommandOptions>(
command: RepluggedCommand<T>,
): Promise<void> {
try {
const PendingReplyStore = getByStoreName<
Store & {
getPendingReply: (channelId: string) => SendMessageForReplyOptions;
}
>("PendingReplyStore")!;

const currentChannelId = currentInfo.channel.id;
const replyOptions: SendMessageOptionsForReply = messages.getSendMessageOptionsForReply(
PendingReplyStore.getPendingReply(currentChannelId),
);
if (replyOptions?.messageReference)
fluxDispatcher.dispatch({ type: "DELETE_PENDING_REPLY", channelId: currentChannelId });
const loadingMessage = messages.createBotMessage({
channelId: currentChannelId,
content: "",
Expand All @@ -121,6 +137,7 @@ async function executeCommand<T extends CommandOptions>(
},
type: 20,
author: RepluggedUser ?? loadingMessage.author,
...replyOptions,
});
messages.receiveMessage(currentChannelId, loadingMessage, true);
const interaction = new CommandInteraction({ options: args, ...currentInfo });
Expand All @@ -130,12 +147,17 @@ async function executeCommand<T extends CommandOptions>(
if ((!result?.result && !result?.embeds) || !currentChannelId) return;

if (result.send) {
void messages.sendMessage(currentChannelId, {
content: result.result!,
invalidEmojis: [],
validNonShortcutEmojis: [],
tts: false,
});
void messages.sendMessage(
currentChannelId,
{
content: result.result!,
invalidEmojis: [],
validNonShortcutEmojis: [],
tts: false,
},
undefined,
replyOptions,
);
} else {
const botMessage = messages.createBotMessage({
channelId: currentChannelId,
Expand All @@ -159,6 +181,7 @@ async function executeCommand<T extends CommandOptions>(
},
type: 20,
author: RepluggedUser ?? botMessage.author,
...replyOptions,
});
messages.receiveMessage(currentChannelId, botMessage, true);
}
Expand Down
2 changes: 1 addition & 1 deletion src/renderer/coremods/messagePopover/plaintextPatches.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ export default [
match:
/(Fragment,{children:\[)(.{0,200}children:\[.{0,20}?(\w{1,3})\({.{0,5}\s?key:"copy-id".{0,20}channel:(.{1,3})[,}].{0,20}message:(.{1,3})[,}])/,
replace: (_, prefix, suffix, makeButton, channel, message) =>
`${prefix}...replugged.coremods.coremods.messagePopover._buildPopoverElements(${message},${channel},${makeButton}),${suffix}`,
`${prefix}...(replugged.coremods.coremods.messagePopover?._buildPopoverElements?.(${message},${channel},${makeButton})??[]),${suffix}`,
},
],
},
Expand Down
2 changes: 1 addition & 1 deletion src/renderer/coremods/notices/plaintextPatches.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ export default [
{
match: /(\w+\.base,children:\[)(.+?}\)),/,
replace: (_, prefix, noticeWrapper) =>
`${prefix}${coremodStr}.AnnouncementContainer({originalRes:${noticeWrapper}}),`,
`${prefix}${coremodStr}?.AnnouncementContainer?.({originalRes:${noticeWrapper}}),`,
},
],
},
Expand Down
4 changes: 2 additions & 2 deletions src/renderer/coremods/settings/plaintextPatches.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ export default [
{
match: /this\.props\.sections\.filter\((.+?)\)}/,
replace: (_, sections) =>
`${coremodStr}.insertSections(this.props.sections.filter(${sections}))};`,
`${coremodStr}?.insertSections?.(this.props.sections.filter(${sections}))??this.props.sections.filter(${sections})};`,
},
],
},
Expand All @@ -18,7 +18,7 @@ export default [
replacements: [
{
match: /appArch,children:.{0,200}?className:\w+\.line,.{0,100}children:\w+}\):null/,
replace: `$&,${coremodStr}.VersionInfo()`,
replace: `$&,${coremodStr}?.VersionInfo?.()`,
},
],
},
Expand Down
3 changes: 0 additions & 3 deletions src/renderer/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,14 +6,11 @@ type DiscordSplashWindow = Window & {
DiscordSplash?: object;
};

await window.replugged.util.sleep(500);

// Splash screen
if ((window as DiscordSplashWindow).DiscordSplash) {
await replugged.ignition.startSplash();
} else {
console.log("Igniting");

await replugged.plugins.loadAll();
await replugged.ignition.ignite();
}
13 changes: 8 additions & 5 deletions src/renderer/managers/ignition.ts
Original file line number Diff line number Diff line change
Expand Up @@ -84,14 +84,17 @@ Load order:
export async function ignite(): Promise<void> {
// This is the function that will be called when loading the window.
// Plaintext patches are executed before Discord's preload.
await coremods.runPlaintextPatches();
await plugins.loadAll();
await plugins.runPlaintextPatches();
await Promise.all([
coremods.runPlaintextPatches(),
plugins.loadAll(),
plugins.runPlaintextPatches(),
]);
// These next things will happen after Discord's preload is called.
// We schedule them here, but they cannot block the ignite function from returning.

await waitForReady;
signalStart();
(async () => {
await waitForReady;
signalStart();
await commonReady();
await componentsReady();
await start();
Expand Down
86 changes: 61 additions & 25 deletions src/renderer/modules/injector.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ enum InjectionTypes {
export type BeforeCallback<A extends unknown[] = unknown[]> = (
args: A,
self: ObjectExports,
) => A | undefined | void;
) => Promise<A | undefined | void> | A | undefined | void;

/**
* Code to run instead of the original function
Expand All @@ -36,7 +36,7 @@ export type InsteadCallback<A extends unknown[] = unknown[], R = unknown> = (
args: A,
orig: (...args: A) => R,
self: ObjectExports,
) => R | void;
) => Promise<R | void> | R | void;

/**
* Code to run after the original function
Expand All @@ -49,7 +49,7 @@ export type AfterCallback<A extends unknown[] = unknown[], R = unknown> = (
args: A,
res: R,
self: ObjectExports,
) => R | undefined | void;
) => Promise<R | undefined | void> | R | undefined | void;

interface ObjectInjections {
injections: Map<
Expand Down Expand Up @@ -97,39 +97,75 @@ function replaceMethod<T extends Record<U, AnyFunction>, U extends keyof T & str

const originalFunc = obj[funcName];

// @ts-expect-error https://github.com/microsoft/TypeScript/issues/48992
obj[funcName] = function (...args: unknown[]): unknown {
const injectionsForProp = objInjections.injections.get(funcName)!;
if (originalFunc[Symbol.toStringTag] !== "AsyncFunction") {
// @ts-expect-error https://github.com/microsoft/TypeScript/issues/48992
obj[funcName] = function (...args: unknown[]): unknown {
const injectionsForProp = objInjections.injections.get(funcName)!;

for (const b of injectionsForProp.before) {
const newArgs = b.call(this, args, this);
if (Array.isArray(newArgs)) {
args = newArgs;
for (const b of injectionsForProp.before) {
const newArgs = b.call(this, args, this);
if (Array.isArray(newArgs)) {
args = newArgs;
}
}
}

let res: unknown;
let res: unknown;

if (injectionsForProp.instead.size === 0) {
res = originalFunc.apply(this, args);
} else {
for (const i of injectionsForProp.instead) {
const newResult = i.call(this, args, originalFunc, this);
if (newResult !== void 0) {
res = newResult;
}
}
}

if (injectionsForProp.instead.size === 0) {
res = originalFunc.apply(this, args);
} else {
for (const i of injectionsForProp.instead) {
const newResult = i.call(this, args, originalFunc, this);
for (const a of injectionsForProp.after) {
const newResult = a.call(this, args, res, this);
if (newResult !== void 0) {
res = newResult;
}
}
}

for (const a of injectionsForProp.after) {
const newResult = a.call(this, args, res, this);
if (newResult !== void 0) {
res = newResult;
return res;
};
} else {
// @ts-expect-error https://github.com/microsoft/TypeScript/issues/48992
obj[funcName] = async function (...args: unknown[]): unknown {
const injectionsForProp = objInjections.injections.get(funcName)!;

for (const b of injectionsForProp.before) {
const newArgs = await b.call(this, args, this);
if (Array.isArray(newArgs)) {
args = newArgs;
}
}
}

return res;
};
let res: unknown;

if (injectionsForProp.instead.size === 0) {
res = await originalFunc.apply(this, args);
} else {
for (const i of injectionsForProp.instead) {
const newResult = await i.call(this, args, originalFunc, this);
if (newResult !== void 0) {
res = newResult;
}
}
}

for (const a of injectionsForProp.after) {
const newResult = await a.call(this, args, res, this);
if (newResult !== void 0) {
res = newResult;
}
}

return res;
};
}

Object.defineProperties(obj[funcName], Object.getOwnPropertyDescriptors(originalFunc));
obj[funcName].toString = originalFunc.toString.bind(originalFunc);
Expand Down
9 changes: 5 additions & 4 deletions src/renderer/modules/webpack/filters.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { getExportsForProps } from "./get-modules";
import { sourceStrings } from "./patch-load";
import type { RawModule } from "../../../types";
import { Store } from "@common/flux";
import { Store } from "../common/flux";

/**
* Get a module that has all the given properties on one of its exports
Expand Down Expand Up @@ -69,9 +69,10 @@ export const byStoreName = (name: string) => {
if (!m.exports || typeof m.exports !== "object" || typeof m.exports !== "object") {
return false;
}
return (
(m.exports as { default?: Store & { constructor: { displayName: string } } }).default
?.constructor.displayName === name
return ["default", "Z", "ZP"].some(
(key) =>
(m.exports as { [key: string]: Store & { constructor: { displayName: string } } })[key]
?.constructor.displayName === name,
);
};
};
7 changes: 5 additions & 2 deletions src/renderer/modules/webpack/helpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -255,6 +255,9 @@ export async function waitForStoreName<T extends Store>(
name: string,
options?: { timeout: number },
): Promise<T | undefined> {
const module = await waitForModule<{ default?: T } & T>(filters.byStoreName(name), options);
return module.default ?? module;
const module = await waitForModule<{ default?: T; ZP?: T; Z?: T } & T>(
filters.byStoreName(name),
options,
);
return module.default ?? module.ZP ?? module.Z ?? module;
}
Loading

0 comments on commit d3f66b2

Please sign in to comment.