diff --git a/watchCord/README.md b/watchCord/README.md index 32b89b9..2cf2ecc 100644 --- a/watchCord/README.md +++ b/watchCord/README.md @@ -338,10 +338,10 @@ For debugging and advanced analysis, WatchCord logs the **complete status change ## 🎨 UI Features -### Toolbar Button -- **Location**: Top toolbar (next to inbox) -- **Icon**: Eye/watch icon -- **Action**: Opens Vencord plugin settings +### Toolbox Actions +- **Location**: Vencord Toolbox button in Discord's title bar (requires the built-in **VencordToolbox** plugin) +- **Open WatchCord**: Opens a modal with the watch list manager and the logs viewer +- **Open WatchCord Log File**: Opens `watchcord-logs.txt` in your default text editor ### Notification Sound - **Type**: Procedurally generated beep diff --git a/watchCord/index.tsx b/watchCord/index.tsx index 628114e..6c6c735 100644 --- a/watchCord/index.tsx +++ b/watchCord/index.tsx @@ -5,25 +5,26 @@ */ import { definePluginSettings } from "@api/Settings"; +import { Button } from "@components/Button"; import ErrorBoundary from "@components/ErrorBoundary"; +import { Heading } from "@components/Heading"; +import { Paragraph } from "@components/Paragraph"; import definePlugin, { OptionType, PluginNative } from "@utils/types"; -import { findComponentByCodeLazy } from "@webpack"; +import { RenderModalProps } from "@vencord/discord-types"; import { - Button, ChannelStore, - Forms, + GuildMemberStore, GuildStore, + Modal, + openModal, PresenceStore, React, Select, - SettingsRouter, TextInput, UserStore, VoiceStateStore, } from "@webpack/common"; -const HeaderBarIcon = findComponentByCodeLazy(".HEADER_BAR_BADGE_BOTTOM,", 'position:"bottom"'); - const Native = VencordNative.pluginHelpers.WatchCord as PluginNative< typeof import("./native") >; @@ -50,6 +51,10 @@ interface LogEntry { let logs: LogEntry[] = []; const previousStatuses: Map = new Map(); const previousVoiceChannels: Map = new Map(); +// Last time a typing event was logged per user+channel. Discord re-sends +// TYPING_START every ~8s while someone keeps typing, so we throttle it. +const lastTypingLogged: Map = new Map(); +const TYPING_THROTTLE_MS = 15_000; const settings = definePluginSettings({ webhookUrl: { @@ -91,17 +96,30 @@ function debugLog(...args: any[]) { console.log("[WatchCord]", ...args); } +// getWatchList() runs on every PRESENCE_UPDATES / TYPING_START event, so +// cache the parsed result and only re-parse when the stored string changes. +let cachedWatchListRaw: string | undefined; +let cachedWatchList: WatchItem[] = []; + function getWatchList(): WatchItem[] { + const stored = Vencord.Settings.plugins.WatchCord?.watchList; + if (stored === cachedWatchListRaw) return cachedWatchList; + cachedWatchListRaw = stored; + cachedWatchList = parseWatchList(stored); + return cachedWatchList; +} + +function parseWatchList(stored: string | undefined): WatchItem[] { try { - const stored = Vencord.Settings.plugins.WatchCord?.watchList; if (!stored) return []; const parsed = JSON.parse(stored); if (!Array.isArray(parsed)) return []; // Normalize entries so legacy data missing newer fields (e.g. // watchMessage / watchTyping) still loads with sensible defaults. - return parsed.map((item: any) => ({ - id: item?.id ?? Date.now().toString(), + // The id fallback must be stable, otherwise remove/toggle can't find the entry. + return parsed.map((item: any, index: number) => ({ + id: item?.id ?? `legacy-${index}-${item?.odUserId ?? ""}`, odUserId: item?.odUserId ?? "", guildId: item?.guildId ?? "*", watchVoice: item?.watchVoice ?? false, @@ -132,8 +150,8 @@ async function addLog(type: LogEntry["type"], message: string) { // Keep only last 500 logs in memory if (logs.length > 500) logs = logs.slice(0, 500); - // Format log line - const logLine = `[${entry.timestamp}] [${type.toUpperCase()}] ${message}`; + // Format log line (escape newlines so one event stays on one line in the file) + const logLine = `[${entry.timestamp}] [${type.toUpperCase()}] ${message.replace(/\r?\n/g, "\\n")}`; // Save to file try { @@ -147,10 +165,8 @@ async function sendWebhookMessage(message: string) { const { webhookUrl } = settings.store; if (webhookUrl) { try { - await Native.sendWebhook( - webhookUrl, - message - ); + const res = await Native.sendWebhook(webhookUrl, message); + if (!res.ok) console.error("WatchCord: Webhook request failed", res.error); } catch (e) { console.error("WatchCord: Failed to send webhook", e); } @@ -158,15 +174,23 @@ async function sendWebhookMessage(message: string) { } function showNotification(title: string, body: string) { - if (settings.store.enableNotifications) { + if (!settings.store.enableNotifications) return; + try { new Notification(title, { body }); + } catch (e) { + console.error("WatchCord: Failed to show notification", e); } } +// Reuse one AudioContext: creating a new one per beep leaks contexts and +// Chromium stops allowing new ones after a while. +let audioContext: AudioContext | null = null; + function playNotificationSound() { try { - const audioContext = new (window.AudioContext || + audioContext ??= new (window.AudioContext || (window as any).webkitAudioContext)(); + if (audioContext.state === "suspended") void audioContext.resume(); const oscillator = audioContext.createOscillator(); const gainNode = audioContext.createGain(); @@ -231,6 +255,15 @@ function handleTypingEvent(event: any) { ); if (match) { + const throttleKey = `${userId}:${channelId}`; + const now = Date.now(); + const last = lastTypingLogged.get(throttleKey); + if (last !== undefined && now - last < TYPING_THROTTLE_MS) { + debugLog("TYPING_START → skip: throttled (still typing)"); + return; + } + lastTypingLogged.set(throttleKey, now); + const user = UserStore.getUser(userId); const username = user?.username || "Unknown"; const channelName = getChannelName(channel); @@ -291,6 +324,8 @@ function WatchListManager() { setWatchListState(newList); setWatchList(newList); setNewUserId(""); + // Seed current state so the very first change after adding is logged + seedUserState(newItem.odUserId); }; const removeEntry = (id: string) => { @@ -331,23 +366,23 @@ function WatchListManager() { return (
- - Add New Watch Entry +
+ Add New Watch Entry - + User ID - + - Server - +