feat: auto-managed flux subscriptions via plugin.flux (#959)

This commit is contained in:
V 2023-04-22 03:18:19 +02:00 committed by GitHub
parent c6f0c84935
commit 63fc354d48
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
10 changed files with 210 additions and 253 deletions

View file

@ -20,6 +20,8 @@ import { registerCommand, unregisterCommand } from "@api/Commands";
import { Settings } from "@api/settings";
import Logger from "@utils/Logger";
import { Patch, Plugin } from "@utils/types";
import { FluxDispatcher } from "@webpack/common";
import { FluxEvents } from "@webpack/types";
import Plugins from "~plugins";
@ -111,56 +113,64 @@ export function startDependenciesRecursive(p: Plugin) {
}
export const startPlugin = traceFunction("startPlugin", function startPlugin(p: Plugin) {
const { name, commands, flux } = p;
if (p.start) {
logger.info("Starting plugin", p.name);
logger.info("Starting plugin", name);
if (p.started) {
logger.warn(`${p.name} already started`);
logger.warn(`${name} already started`);
return false;
}
try {
p.start();
p.started = true;
} catch (e) {
logger.error(`Failed to start ${p.name}\n`, e);
logger.error(`Failed to start ${name}\n`, e);
return false;
}
}
if (p.commands?.length) {
logger.info("Registering commands of plugin", p.name);
for (const cmd of p.commands) {
if (commands?.length) {
logger.info("Registering commands of plugin", name);
for (const cmd of commands) {
try {
registerCommand(cmd, p.name);
registerCommand(cmd, name);
} catch (e) {
logger.error(`Failed to register command ${cmd.name}\n`, e);
return false;
}
}
}
if (flux) {
for (const event in flux) {
FluxDispatcher.subscribe(event as FluxEvents, flux[event]);
}
}
return true;
}, p => `startPlugin ${p.name}`);
export const stopPlugin = traceFunction("stopPlugin", function stopPlugin(p: Plugin) {
const { name, commands, flux } = p;
if (p.stop) {
logger.info("Stopping plugin", p.name);
logger.info("Stopping plugin", name);
if (!p.started) {
logger.warn(`${p.name} already stopped`);
logger.warn(`${name} already stopped`);
return false;
}
try {
p.stop();
p.started = false;
} catch (e) {
logger.error(`Failed to stop ${p.name}\n`, e);
logger.error(`Failed to stop ${name}\n`, e);
return false;
}
}
if (p.commands?.length) {
logger.info("Unregistering commands of plugin", p.name);
for (const cmd of p.commands) {
if (commands?.length) {
logger.info("Unregistering commands of plugin", name);
for (const cmd of commands) {
try {
unregisterCommand(cmd.name);
} catch (e) {
@ -170,5 +180,11 @@ export const stopPlugin = traceFunction("stopPlugin", function stopPlugin(p: Plu
}
}
if (flux) {
for (const event in flux) {
FluxDispatcher.unsubscribe(event as FluxEvents, flux[event]);
}
}
return true;
}, p => `stopPlugin ${p.name}`);