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

@ -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}`);

@ -19,7 +19,7 @@
import * as DataStore from "@api/DataStore";
import { Devs } from "@utils/constants";
import definePlugin from "@utils/types";
import { ChannelStore, FluxDispatcher, NavigationRouter, SelectedChannelStore, SelectedGuildStore } from "@webpack/common";
import { ChannelStore, NavigationRouter, SelectedChannelStore, SelectedGuildStore } from "@webpack/common";
export interface LogoutEvent {
type: "LOGOUT";
@ -37,63 +37,54 @@ interface PreviousChannel {
channelId: string | null;
}
let isSwitchingAccount = false;
let previousCache: PreviousChannel | undefined;
function attemptToNavigateToChannel(guildId: string | null, channelId: string) {
if (!ChannelStore.hasChannel(channelId)) return;
NavigationRouter.transitionTo(`/channels/${guildId ?? "@me"}/${channelId}`);
}
export default definePlugin({
name: "KeepCurrentChannel",
description: "Attempt to navigate to the channel you were in before switching accounts or loading Discord.",
authors: [Devs.Nuckyz],
isSwitchingAccount: false,
previousCache: {} as PreviousChannel,
attemptToNavigateToChannel(guildId: string | null, channelId: string) {
if (!ChannelStore.hasChannel(channelId)) return;
NavigationRouter.transitionTo(`/channels/${guildId ?? "@me"}/${channelId}`);
flux: {
LOGOUT(e: LogoutEvent) {
({ isSwitchingAccount } = e);
},
onLogout(e: LogoutEvent) {
this.isSwitchingAccount = e.isSwitchingAccount;
CONNECTION_OPEN() {
if (!isSwitchingAccount) return;
isSwitchingAccount = false;
if (previousCache?.channelId)
attemptToNavigateToChannel(previousCache.guildId, previousCache.channelId);
},
onConnectionOpen() {
if (!this.isSwitchingAccount) return;
this.isSwitchingAccount = false;
async CHANNEL_SELECT({ guildId, channelId }: ChannelSelectEvent) {
if (isSwitchingAccount) return;
if (this.previousCache.channelId) this.attemptToNavigateToChannel(this.previousCache.guildId, this.previousCache.channelId);
},
async onChannelSelect({ guildId, channelId }: ChannelSelectEvent) {
if (this.isSwitchingAccount) return;
this.previousCache = {
previousCache = {
guildId,
channelId
};
await DataStore.set("KeepCurrentChannel_previousData", this.previousCache);
await DataStore.set("KeepCurrentChannel_previousData", previousCache);
}
},
async start() {
const previousData = await DataStore.get<PreviousChannel>("KeepCurrentChannel_previousData");
if (previousData) {
this.previousCache = previousData;
if (this.previousCache.channelId) this.attemptToNavigateToChannel(this.previousCache.guildId, this.previousCache.channelId);
} else {
this.previousCache = {
previousCache = await DataStore.get<PreviousChannel>("KeepCurrentChannel_previousData");
if (!previousCache) {
previousCache = {
guildId: SelectedGuildStore.getGuildId(),
channelId: SelectedChannelStore.getChannelId() ?? null
};
await DataStore.set("KeepCurrentChannel_previousData", this.previousCache);
await DataStore.set("KeepCurrentChannel_previousData", previousCache);
} else if (previousCache.channelId) {
attemptToNavigateToChannel(previousCache.guildId, previousCache.channelId);
}
FluxDispatcher.subscribe("LOGOUT", this.onLogout.bind(this));
FluxDispatcher.subscribe("CONNECTION_OPEN", this.onConnectionOpen.bind(this));
FluxDispatcher.subscribe("CHANNEL_SELECT", this.onChannelSelect.bind(this));
},
stop() {
FluxDispatcher.unsubscribe("LOGOUT", this.onLogout);
FluxDispatcher.unsubscribe("CONNECTION_OPEN", this.onConnectionOpen);
FluxDispatcher.unsubscribe("CHANNEL_SELECT", this.onChannelSelect);
}
});

@ -23,7 +23,7 @@ import { getCurrentChannel } from "@utils/discord";
import { useForceUpdater } from "@utils/misc";
import definePlugin from "@utils/types";
import { findStoreLazy } from "@webpack";
import { FluxDispatcher, Tooltip } from "@webpack/common";
import { Tooltip } from "@webpack/common";
const counts = {} as Record<string, [number, number]>;
let forceUpdate: () => void;
@ -107,7 +107,8 @@ export default definePlugin({
}
}],
onGuildMemberListUpdate({ guildId, groups, memberCount, id }) {
flux: {
GUILD_MEMBER_LIST_UPDATE({ guildId, groups, memberCount, id }) {
// eeeeeh - sometimes it has really wrong counts??? like 10 times less than actual
// but if we only listen to everyone updates, sometimes we never get the count?
// this seems to work but isn't optional
@ -120,14 +121,7 @@ export default definePlugin({
}
counts[guildId] = [memberCount, count];
forceUpdate?.();
},
start() {
FluxDispatcher.subscribe("GUILD_MEMBER_LIST_UPDATE", this.onGuildMemberListUpdate);
},
stop() {
FluxDispatcher.unsubscribe("GUILD_MEMBER_LIST_UPDATE", this.onGuildMemberListUpdate);
}
},
render: () => (

@ -21,7 +21,7 @@ import { makeRange } from "@components/PluginSettings/components/SettingSliderCo
import { Devs } from "@utils/constants";
import { sleep } from "@utils/misc";
import definePlugin, { OptionType } from "@utils/types";
import { FluxDispatcher, SelectedChannelStore, UserStore } from "@webpack/common";
import { SelectedChannelStore, UserStore } from "@webpack/common";
import { Message, ReactionEmoji } from "discord-types/general";
interface IMessageCreate {
@ -80,14 +80,15 @@ export default definePlugin({
description: "🗿🗿🗿🗿🗿🗿🗿🗿",
settings,
async onMessage(e: IMessageCreate) {
if (e.optimistic || e.type !== "MESSAGE_CREATE") return;
if (e.message.state === "SENDING") return;
if (settings.store.ignoreBots && e.message.author?.bot) return;
if (!e.message.content) return;
if (e.channelId !== SelectedChannelStore.getChannelId()) return;
flux: {
async MESSAGE_CREATE({ optimistic, type, message, channelId }: IMessageCreate) {
if (optimistic || type !== "MESSAGE_CREATE") return;
if (message.state === "SENDING") return;
if (settings.store.ignoreBots && message.author?.bot) return;
if (!message.content) return;
if (channelId !== SelectedChannelStore.getChannelId()) return;
const moyaiCount = getMoyaiCount(e.message.content);
const moyaiCount = getMoyaiCount(message.content);
for (let i = 0; i < moyaiCount; i++) {
boom();
@ -95,35 +96,24 @@ export default definePlugin({
}
},
onReaction(e: IReactionAdd) {
if (e.optimistic || e.type !== "MESSAGE_REACTION_ADD") return;
if (settings.store.ignoreBots && UserStore.getUser(e.userId)?.bot) return;
if (e.channelId !== SelectedChannelStore.getChannelId()) return;
MESSAGE_REACTION_ADD({ optimistic, type, channelId, userId, emoji }: IReactionAdd) {
if (optimistic || type !== "MESSAGE_REACTION_ADD") return;
if (settings.store.ignoreBots && UserStore.getUser(userId)?.bot) return;
if (channelId !== SelectedChannelStore.getChannelId()) return;
const name = e.emoji.name.toLowerCase();
const name = emoji.name.toLowerCase();
if (name !== MOYAI && !name.includes("moyai") && !name.includes("moai")) return;
boom();
},
onVoiceChannelEffect(e: IVoiceChannelEffectSendEvent) {
if (!e.emoji?.name) return;
const name = e.emoji.name.toLowerCase();
VOICE_CHANNEL_EFFECT_SEND({ emoji }: IVoiceChannelEffectSendEvent) {
if (!emoji?.name) return;
const name = emoji.name.toLowerCase();
if (name !== MOYAI && !name.includes("moyai") && !name.includes("moai")) return;
boom();
},
start() {
FluxDispatcher.subscribe("MESSAGE_CREATE", this.onMessage);
FluxDispatcher.subscribe("MESSAGE_REACTION_ADD", this.onReaction);
FluxDispatcher.subscribe("VOICE_CHANNEL_EFFECT_SEND", this.onVoiceChannelEffect);
},
stop() {
FluxDispatcher.unsubscribe("MESSAGE_CREATE", this.onMessage);
FluxDispatcher.unsubscribe("MESSAGE_REACTION_ADD", this.onReaction);
FluxDispatcher.unsubscribe("VOICE_CHANNEL_EFFECT_SEND", this.onVoiceChannelEffect);
}
}
});

@ -1,41 +0,0 @@
/*
* Vencord, a modification for Discord's desktop app
* Copyright (c) 2023 Vendicated and contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
import { FluxEvents } from "@webpack/types";
import { onChannelDelete, onGuildDelete, onRelationshipRemove } from "./functions";
import { syncAndRunChecks, syncFriends, syncGroups, syncGuilds } from "./utils";
export const FluxHandlers: Partial<Record<FluxEvents, Array<(data: any) => void>>> = {
GUILD_CREATE: [syncGuilds],
GUILD_DELETE: [onGuildDelete],
CHANNEL_CREATE: [syncGroups],
CHANNEL_DELETE: [onChannelDelete],
RELATIONSHIP_ADD: [syncFriends],
RELATIONSHIP_UPDATE: [syncFriends],
RELATIONSHIP_REMOVE: [syncFriends, onRelationshipRemove],
CONNECTION_OPEN: [syncAndRunChecks]
};
export function forEachEvent(fn: (event: FluxEvents, handler: (data: any) => void) => void) {
for (const event in FluxHandlers) {
for (const cb of FluxHandlers[event]) {
fn(event as FluxEvents, cb);
}
}
}

@ -18,12 +18,10 @@
import { Devs } from "@utils/constants";
import definePlugin from "@utils/types";
import { FluxDispatcher } from "@webpack/common";
import { forEachEvent } from "./events";
import { removeFriend, removeGroup, removeGuild } from "./functions";
import { onChannelDelete, onGuildDelete, onRelationshipRemove, removeFriend, removeGroup, removeGuild } from "./functions";
import settings from "./settings";
import { syncAndRunChecks } from "./utils";
import { syncAndRunChecks, syncFriends, syncGroups, syncGuilds } from "./utils";
export default definePlugin({
name: "RelationshipNotifier",
@ -55,15 +53,24 @@ export default definePlugin({
}
],
flux: {
GUILD_CREATE: syncGuilds,
GUILD_DELETE: onGuildDelete,
CHANNEL_CREATE: syncGroups,
CHANNEL_DELETE: onChannelDelete,
RELATIONSHIP_ADD: syncFriends,
RELATIONSHIP_UPDATE: syncFriends,
RELATIONSHIP_REMOVE(e) {
onRelationshipRemove(e);
syncFriends();
},
CONNECTION_OPEN: syncAndRunChecks
},
async start() {
setTimeout(() => {
syncAndRunChecks();
}, 5000);
forEachEvent((ev, cb) => FluxDispatcher.subscribe(ev, cb));
},
stop() {
forEachEvent((ev, cb) => FluxDispatcher.unsubscribe(ev, cb));
},
removeFriend,

@ -22,7 +22,7 @@ import ErrorBoundary from "@components/ErrorBoundary";
import { Devs } from "@utils/constants";
import { useForceUpdater } from "@utils/misc";
import definePlugin, { OptionType } from "@utils/types";
import { FluxDispatcher, GuildStore,PresenceStore, RelationshipStore } from "@webpack/common";
import { GuildStore, PresenceStore, RelationshipStore } from "@webpack/common";
enum IndicatorType {
SERVER = 1 << 0,
@ -71,6 +71,24 @@ function ServersIndicator() {
);
}
function handlePresenceUpdate() {
onlineFriends = 0;
const relations = RelationshipStore.getRelationships();
for (const id of Object.keys(relations)) {
const type = relations[id];
// FRIEND relationship type
if (type === 1 && PresenceStore.getStatus(id) !== "offline") {
onlineFriends += 1;
}
}
forceUpdateFriendCount?.();
}
function handleGuildUpdate() {
guildCount = GuildStore.getGuildCount();
forceUpdateGuildCount?.();
}
export default definePlugin({
name: "ServerListIndicators",
description: "Add online friend count or server count in the server list",
@ -99,37 +117,21 @@ export default definePlugin({
</ErrorBoundary>;
},
handlePresenceUpdate() {
onlineFriends = 0;
const relations = RelationshipStore.getRelationships();
for (const id of Object.keys(relations)) {
const type = relations[id];
// FRIEND relationship type
if (type === 1 && PresenceStore.getStatus(id) !== "offline") {
onlineFriends += 1;
}
}
forceUpdateFriendCount?.();
flux: {
PRESENCE_UPDATES: handlePresenceUpdate,
GUILD_CREATE: handleGuildUpdate,
GUILD_DELETE: handleGuildUpdate,
},
handleGuildUpdate() {
guildCount = GuildStore.getGuildCount();
forceUpdateGuildCount?.();
},
start() {
this.handlePresenceUpdate();
this.handleGuildUpdate();
addServerListElement(ServerListRenderPosition.Above, this.renderIndicator);
FluxDispatcher.subscribe("PRESENCE_UPDATES", this.handlePresenceUpdate);
FluxDispatcher.subscribe("GUILD_CREATE", this.handleGuildUpdate);
FluxDispatcher.subscribe("GUILD_DELETE", this.handleGuildUpdate);
handlePresenceUpdate();
handleGuildUpdate();
},
stop() {
removeServerListElement(ServerListRenderPosition.Above, this.renderIndicator);
FluxDispatcher.unsubscribe("PRESENCE_UPDATES", this.handlePresenceUpdate);
FluxDispatcher.unsubscribe("GUILD_CREATE", this.handleGuildUpdate);
FluxDispatcher.unsubscribe("GUILD_DELETE", this.handleGuildUpdate);
}
});

@ -21,7 +21,7 @@ import { Devs, SUPPORT_CHANNEL_ID } from "@utils/constants";
import { makeCodeblock } from "@utils/misc";
import definePlugin from "@utils/types";
import { isOutdated } from "@utils/updater";
import { Alerts, FluxDispatcher, Forms, UserStore } from "@webpack/common";
import { Alerts, Forms, UserStore } from "@webpack/common";
import gitHash from "~git-hash";
import plugins from "~plugins";
@ -69,18 +69,16 @@ ${makeCodeblock(Object.keys(plugins).filter(Vencord.Plugins.isPluginEnabled).joi
}
}],
rememberDismiss() {
DataStore.set(REMEMBER_DISMISS_KEY, gitHash);
},
start() {
FluxDispatcher.subscribe("CHANNEL_SELECT", async ({ channelId }) => {
flux: {
async CHANNEL_SELECT({ channelId }) {
if (channelId !== SUPPORT_CHANNEL_ID) return;
const myId = BigInt(UserStore.getCurrentUser().id);
if (Object.values(Devs).some(d => d.id === myId)) return;
if (isOutdated && gitHash !== await DataStore.get(REMEMBER_DISMISS_KEY)) {
const rememberDismiss = () => DataStore.set(REMEMBER_DISMISS_KEY, gitHash);
Alerts.show({
title: "Hold on!",
body: <div>
@ -90,10 +88,10 @@ ${makeCodeblock(Object.keys(plugins).filter(Vencord.Plugins.isPluginEnabled).joi
to do so, in case you can't access the Updater page.
</Forms.FormText>
</div>,
onCancel: this.rememberDismiss,
onConfirm: this.rememberDismiss
onCancel: rememberDismiss,
onConfirm: rememberDismiss
});
}
});
}
}
});

@ -24,7 +24,7 @@ import { Margins } from "@utils/margins";
import { wordsToTitle } from "@utils/text";
import definePlugin, { OptionType, PluginOptionsItem } from "@utils/types";
import { findByPropsLazy } from "@webpack";
import { Button, ChannelStore, FluxDispatcher, Forms, SelectedChannelStore, useMemo, UserStore } from "@webpack/common";
import { Button, ChannelStore, Forms, SelectedChannelStore, useMemo, UserStore } from "@webpack/common";
interface VoiceState {
userId: string;
@ -137,7 +137,19 @@ function updateStatuses(type: string, { deaf, mute, selfDeaf, selfMute, userId,
}
*/
function handleVoiceStates({ voiceStates }: { voiceStates: VoiceState[]; }) {
function playSample(tempSettings: any, type: string) {
const settings = Object.assign({}, Settings.plugins.VcNarrator, tempSettings);
speak(formatText(settings[type + "Message"], UserStore.getCurrentUser().username, "general"), settings);
}
export default definePlugin({
name: "VcNarrator",
description: "Announces when users join, leave, or move voice channels via narrator",
authors: [Devs.Ven],
flux: {
VOICE_STATE_UPDATES({ voiceStates }: { voiceStates: VoiceState[]; }) {
const myChanId = SelectedChannelStore.getVoiceChannelId();
const myId = UserStore.getCurrentUser().id;
@ -160,36 +172,26 @@ function handleVoiceStates({ voiceStates }: { voiceStates: VoiceState[]; }) {
// updateStatuses(type, state, isMe);
}
}
},
function handleToggleSelfMute() {
AUDIO_TOGGLE_SELF_MUTE() {
const chanId = SelectedChannelStore.getVoiceChannelId()!;
const s = VoiceStateStore.getVoiceStateForChannel(chanId) as VoiceState;
if (!s) return;
const event = s.mute || s.selfMute ? "unmute" : "mute";
speak(formatText(Settings.plugins.VcNarrator[event + "Message"], "", ChannelStore.getChannel(chanId).name));
}
},
function handleToggleSelfDeafen() {
AUDIO_TOGGLE_SELF_DEAF() {
const chanId = SelectedChannelStore.getVoiceChannelId()!;
const s = VoiceStateStore.getVoiceStateForChannel(chanId) as VoiceState;
if (!s) return;
const event = s.deaf || s.selfDeaf ? "undeafen" : "deafen";
speak(formatText(Settings.plugins.VcNarrator[event + "Message"], "", ChannelStore.getChannel(chanId).name));
}
function playSample(tempSettings: any, type: string) {
const settings = Object.assign({}, Settings.plugins.VcNarrator, tempSettings);
speak(formatText(settings[type + "Message"], UserStore.getCurrentUser().username, "general"), settings);
}
export default definePlugin({
name: "VcNarrator",
description: "Announces when users join, leave, or move voice channels via narrator",
authors: [Devs.Ven],
}
},
start() {
if (typeof speechSynthesis === "undefined" || speechSynthesis.getVoices().length === 0) {
@ -199,15 +201,6 @@ export default definePlugin({
return;
}
FluxDispatcher.subscribe("VOICE_STATE_UPDATES", handleVoiceStates);
FluxDispatcher.subscribe("AUDIO_TOGGLE_SELF_MUTE", handleToggleSelfMute);
FluxDispatcher.subscribe("AUDIO_TOGGLE_SELF_DEAF", handleToggleSelfDeafen);
},
stop() {
FluxDispatcher.unsubscribe("VOICE_STATE_UPDATES", handleVoiceStates);
FluxDispatcher.subscribe("AUDIO_TOGGLE_SELF_MUTE", handleToggleSelfMute);
FluxDispatcher.subscribe("AUDIO_TOGGLE_SELF_DEAF", handleToggleSelfDeafen);
},
optionsCache: null as Record<string, PluginOptionsItem> | null,

@ -17,6 +17,7 @@
*/
import { Command } from "@api/Commands";
import { FluxEvents } from "@webpack/types";
import { Promisable } from "type-fest";
// exists to export default definePlugin({...})
@ -101,6 +102,12 @@ export interface PluginDef {
settingsAboutComponent?: React.ComponentType<{
tempSettings?: Record<string, any>;
}>;
/**
* Allows you to subscribe to Flux events
*/
flux?: {
[E in FluxEvents]?: (event: any) => void;
};
}
export enum OptionType {