/* * Vencord, a Discord client mod * Copyright (c) 2026 Vendicated and contributors * SPDX-License-Identifier: GPL-3.0-or-later */ 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 { RenderModalProps } from "@vencord/discord-types"; import { ChannelStore, GuildMemberStore, GuildStore, Modal, openModal, PresenceStore, React, Select, TextInput, UserStore, VoiceStateStore, } from "@webpack/common"; const Native = VencordNative.pluginHelpers.WatchCord as PluginNative< typeof import("./native") >; interface WatchItem { id: string; odUserId: string; guildId: string; watchVoice: boolean; watchStatus: boolean; watchMessage: boolean; watchTyping: boolean; playVoiceSound: boolean; playStatusSound: boolean; } interface LogEntry { timestamp: string; type: "voice" | "status" | "message" | "typing"; message: string; } // In-memory logs (synced to file) 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: { type: OptionType.STRING, description: "Discord Webhook URL (optional - leave empty to disable)", default: "", }, enableNotifications: { type: OptionType.BOOLEAN, description: "Show desktop notifications", default: true, }, debugMode: { type: OptionType.BOOLEAN, description: "Log verbose debug information to the DevTools console (filter by 'WatchCord')", default: false, }, watchListManager: { type: OptionType.COMPONENT, description: "Manage watched users", component: () => , }, logsViewer: { type: OptionType.COMPONENT, description: "View activity logs", component: () => , }, }); // Helper functions function getTimestamp(): string { return new Date().toLocaleString(); } // Debug logging — only active when the "debugMode" setting is enabled. // Filter the DevTools console by "WatchCord" to see the trace. function debugLog(...args: any[]) { if (!settings.store.debugMode) return; 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 { 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. // 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, watchStatus: item?.watchStatus ?? false, watchMessage: item?.watchMessage ?? false, watchTyping: item?.watchTyping ?? false, playVoiceSound: item?.playVoiceSound ?? false, playStatusSound: item?.playStatusSound ?? false, })); } catch (e) { debugLog("getWatchList failed to parse stored value:", e); return []; } } function setWatchList(list: WatchItem[]) { Vencord.Settings.plugins.WatchCord.watchList = JSON.stringify(list); } async function addLog(type: LogEntry["type"], message: string) { const entry: LogEntry = { timestamp: getTimestamp(), type, message, }; logs.unshift(entry); // Keep only last 500 logs in memory if (logs.length > 500) logs = logs.slice(0, 500); // 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 { await Native.appendLog(logLine); } catch (e) { console.error("WatchCord: Failed to save log", e); } } async function sendWebhookMessage(message: string) { const { webhookUrl } = settings.store; if (webhookUrl) { try { 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); } } } function showNotification(title: string, body: string) { 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 { audioContext ??= new (window.AudioContext || (window as any).webkitAudioContext)(); if (audioContext.state === "suspended") void audioContext.resume(); const oscillator = audioContext.createOscillator(); const gainNode = audioContext.createGain(); oscillator.connect(gainNode); gainNode.connect(audioContext.destination); oscillator.frequency.value = 800; // Frequency in Hz oscillator.type = "sine"; gainNode.gain.setValueAtTime(0.3, audioContext.currentTime); gainNode.gain.exponentialRampToValueAtTime( 0.01, audioContext.currentTime + 0.5 ); oscillator.start(audioContext.currentTime); oscillator.stop(audioContext.currentTime + 0.5); } catch (e) { console.error("WatchCord: Failed to play sound", e); } } function getChannelName(channel: any): string { if (!channel) return "Unknown"; if (channel.name) return channel.name; // DM / group DM channels have no name — use the recipient's username const recipient = channel.rawRecipients?.[0] ?? channel.recipients?.[0]; return recipient?.username ?? "DM"; } // Shared handler for TYPING_START (fires for other users' typing) function handleTypingEvent(event: any) { debugLog("TYPING_START fired →", event); const userId = event.userId ?? event.user_id; const channelId = event.channelId ?? event.channel_id; if (!userId || !channelId) { debugLog( "TYPING_START → skip: missing userId/channelId", { userId, channelId } ); return; } const watchList = getWatchList(); if (watchList.length === 0) { debugLog("TYPING_START → skip: watch list is empty"); return; } const channel = ChannelStore.getChannel(channelId); // guildId is undefined for DMs — derive it from the channel as a fallback const guildId = event.guildId ?? event.guild_id ?? channel?.guild_id; const match = watchList.find( item => item.odUserId === userId && item.watchTyping && (item.guildId === "*" || item.guildId === guildId) ); 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); const guild = guildId ? GuildStore.getGuild(guildId) : undefined; const guildName = guild?.name || "DM"; const logMessage = `<@${userId}>(${username}-${userId}) started typing in ${channelName}(${channelId}) in ${guildName}`; debugLog("TYPING_START → MATCH, logging:", logMessage); addLog("typing", logMessage); sendWebhookMessage( `\`[${getTimestamp()}]\` ⌨️ <@${userId}>(${username}) started typing in ${guildId ? `<#${channelId}>` : channelName} in ${guildName}` ); } else { const candidate = watchList.find(i => i.odUserId === userId); debugLog("TYPING_START → no match:", { userId, guildId, candidateFound: !!candidate, reason: !candidate ? "user is not in the watch list" : !candidate.watchTyping ? "watchTyping is OFF for this entry (tick it in the watch list)" : `guild mismatch (entry guildId=${candidate.guildId}, event guildId=${guildId})`, }); } } // Watch List Manager Component function WatchListManager() { const [watchList, setWatchListState] = React.useState( getWatchList() ); const [newUserId, setNewUserId] = React.useState(""); const [newGuildId, setNewGuildId] = React.useState("*"); const [watchVoice, setWatchVoice] = React.useState(true); const [watchStatus, setWatchStatus] = React.useState(true); const [watchMessage, setWatchMessage] = React.useState(false); const [watchTyping, setWatchTyping] = React.useState(false); const [playVoiceSound, setPlayVoiceSound] = React.useState(false); const [playStatusSound, setPlayStatusSound] = React.useState(false); const guilds = Object.values(GuildStore.getGuilds()) as any[]; const addEntry = () => { if (!newUserId.trim()) return; const newItem: WatchItem = { id: Date.now().toString(), odUserId: newUserId.trim(), guildId: newGuildId, watchVoice, watchStatus, watchMessage, watchTyping, playVoiceSound, playStatusSound, }; const newList = [...watchList, newItem]; setWatchListState(newList); setWatchList(newList); setNewUserId(""); // Seed current state so the very first change after adding is logged seedUserState(newItem.odUserId); }; const removeEntry = (id: string) => { const newList = watchList.filter(i => i.id !== id); setWatchListState(newList); setWatchList(newList); }; const toggleEntryFlag = ( id: string, flag: keyof Pick< WatchItem, | "watchVoice" | "watchStatus" | "watchMessage" | "watchTyping" | "playVoiceSound" | "playStatusSound" > ) => { const newList = watchList.map(i => i.id === id ? { ...i, [flag]: !i[flag] } : i ); setWatchListState(newList); setWatchList(newList); }; const getUserDisplay = (odUserId: string) => { const user = UserStore.getUser(odUserId); return user ? `${user.username} (${odUserId})` : odUserId; }; const getGuildDisplay = (guildId: string) => { if (guildId === "*") return "All Servers"; const guild = GuildStore.getGuild(guildId); return guild ? guild.name : guildId; }; return (
Add New Watch Entry User ID Server setWatchVoice(e.target.checked)} /> Watch Voice
Current Watch List ({watchList.length}) {watchList.length === 0 ? ( No users being watched ) : ( watchList.map(item => (
User:{" "} {getUserDisplay(item.odUserId)} Server:{" "} {getGuildDisplay(item.guildId)}
{( [ ["watchVoice", "Voice"], ["watchStatus", "Status"], ["watchMessage", "Messages"], ["watchTyping", "Typing"], ["playVoiceSound", "🔔 Voice"], ["playStatusSound", "🔔 Status"], ] as const ).map(([flag, label]) => ( ))}
)) )} ); } // Logs Viewer Component function LogsViewer() { const [displayLogs, setDisplayLogs] = React.useState(logs); const [filter, setFilter] = React.useState< "all" | "voice" | "status" | "message" | "typing" >("all"); React.useEffect(() => { const interval = setInterval(() => { setDisplayLogs([...logs]); }, 1000); return () => clearInterval(interval); }, []); const filteredLogs = filter === "all" ? displayLogs : displayLogs.filter(l => l.type === filter); const clearLogs = async () => { logs = []; setDisplayLogs([]); try { await Native.clearLogs(); } catch (e) { console.error("WatchCord: Failed to clear logs", e); } }; const openLogFile = async () => { try { await Native.openLogFile(); } catch (e) { console.error("WatchCord: Failed to open log file", e); } }; const openStatusChangeFile = async () => { try { await Native.openStatusChangeFile(); } catch (e) { console.error("WatchCord: Failed to open status change file", e); } }; const clearStatusChanges = async () => { try { await Native.clearStatusChanges(); } catch (e) { console.error("WatchCord: Failed to clear status changes", e); } }; return (