|
| 1 | +// ── Discord Rich Presence (zero-dependency IPC client) ──────────────────────── |
| 2 | +// Talks directly to the local Discord client trough native node net/fs |
| 3 | +// |
| 4 | +// Protocol summary (see discord/discord-rpc docs): |
| 5 | +// Frame = uint32LE opcode + uint32LE payloadLength + JSON payload (utf8) |
| 6 | +// Opcodes: 0 HANDSHAKE, 1 FRAME, 2 CLOSE |
| 7 | + |
| 8 | +const net = require("net"); |
| 9 | +const fs = require("fs"); |
| 10 | +const path = require("path"); |
| 11 | + |
| 12 | +const CLIENT_ID = "1522558650076627076"; |
| 13 | + |
| 14 | +const MIN_SEND_INTERVAL_MS = 15000; |
| 15 | +// How long to wait before retrying a failed/absent Discord connection. |
| 16 | +const RECONNECT_DELAY_MS = 15000; |
| 17 | + |
| 18 | +const OP = { HANDSHAKE: 0, FRAME: 1, CLOSE: 2 }; |
| 19 | + |
| 20 | +function candidatePipePaths() { |
| 21 | + if (process.platform === "win32") { |
| 22 | + return Array.from({ length: 10 }, (_, i) => `\\\\.\\pipe\\discord-ipc-${i}`); |
| 23 | + } |
| 24 | + const base = |
| 25 | + process.env.XDG_RUNTIME_DIR || |
| 26 | + process.env.TMPDIR || |
| 27 | + process.env.TMP || |
| 28 | + process.env.TEMP || |
| 29 | + "/tmp"; |
| 30 | + const dirs = [ |
| 31 | + base, |
| 32 | + path.join(base, "app/com.discordapp.Discord"), // flatpak |
| 33 | + path.join(base, "snap.discord"), // snap |
| 34 | + ]; |
| 35 | + const paths = []; |
| 36 | + for (const dir of dirs) { |
| 37 | + for (let i = 0; i < 10; i++) paths.push(path.join(dir, `discord-ipc-${i}`)); |
| 38 | + } |
| 39 | + return paths; |
| 40 | +} |
| 41 | + |
| 42 | +function makeNonce() { |
| 43 | + return `${Date.now().toString(36)}${Math.random().toString(36).slice(2)}`; |
| 44 | +} |
| 45 | + |
| 46 | +function encodeFrame(op, obj) { |
| 47 | + const payload = Buffer.from(JSON.stringify(obj), "utf8"); |
| 48 | + const header = Buffer.alloc(8); |
| 49 | + header.writeUInt32LE(op, 0); |
| 50 | + header.writeUInt32LE(payload.length, 4); |
| 51 | + return Buffer.concat([header, payload]); |
| 52 | +} |
| 53 | + |
| 54 | +// ── Module state ─────────────────────────────────────────────────────────── |
| 55 | +let enabled = false; |
| 56 | +let socket = null; |
| 57 | +let ready = false; |
| 58 | +let recvBuffer = Buffer.alloc(0); |
| 59 | +let reconnectTimer = null; |
| 60 | + |
| 61 | +let pendingActivity = undefined; // undefined = nothing queued yet |
| 62 | +let hasPending = false; |
| 63 | +let lastSentAt = 0; |
| 64 | +let flushTimer = null; |
| 65 | + |
| 66 | +function clearReconnectTimer() { |
| 67 | + if (reconnectTimer) { |
| 68 | + clearTimeout(reconnectTimer); |
| 69 | + reconnectTimer = null; |
| 70 | + } |
| 71 | +} |
| 72 | + |
| 73 | +function clearFlushTimer() { |
| 74 | + if (flushTimer) { |
| 75 | + clearTimeout(flushTimer); |
| 76 | + flushTimer = null; |
| 77 | + } |
| 78 | +} |
| 79 | + |
| 80 | +function scheduleReconnect() { |
| 81 | + if (!enabled || reconnectTimer) return; |
| 82 | + reconnectTimer = setTimeout(() => { |
| 83 | + reconnectTimer = null; |
| 84 | + if (enabled) connect(); |
| 85 | + }, RECONNECT_DELAY_MS); |
| 86 | +} |
| 87 | + |
| 88 | +function teardownSocket() { |
| 89 | + ready = false; |
| 90 | + recvBuffer = Buffer.alloc(0); |
| 91 | + if (socket) { |
| 92 | + socket.removeAllListeners(); |
| 93 | + socket.destroy(); |
| 94 | + socket = null; |
| 95 | + } |
| 96 | +} |
| 97 | + |
| 98 | +function onSocketDown() { |
| 99 | + teardownSocket(); |
| 100 | + scheduleReconnect(); |
| 101 | +} |
| 102 | + |
| 103 | +function handleFrame(op, obj) { |
| 104 | + if (op === OP.FRAME && obj && obj.cmd === "DISPATCH" && obj.evt === "READY") { |
| 105 | + ready = true; |
| 106 | + flush(); |
| 107 | + } |
| 108 | +} |
| 109 | + |
| 110 | +function onData(chunk) { |
| 111 | + recvBuffer = Buffer.concat([recvBuffer, chunk]); |
| 112 | + while (recvBuffer.length >= 8) { |
| 113 | + const op = recvBuffer.readUInt32LE(0); |
| 114 | + const len = recvBuffer.readUInt32LE(4); |
| 115 | + if (recvBuffer.length < 8 + len) break; |
| 116 | + const payload = recvBuffer.subarray(8, 8 + len); |
| 117 | + recvBuffer = recvBuffer.subarray(8 + len); |
| 118 | + try { |
| 119 | + handleFrame(op, JSON.parse(payload.toString("utf8"))); |
| 120 | + } catch { |
| 121 | + } |
| 122 | + } |
| 123 | +} |
| 124 | + |
| 125 | +function tryPaths(paths, index) { |
| 126 | + if (!enabled || index >= paths.length) { |
| 127 | + scheduleReconnect(); |
| 128 | + return; |
| 129 | + } |
| 130 | + const target = paths[index]; |
| 131 | + const sock = net.createConnection(target); |
| 132 | + let settled = false; |
| 133 | + |
| 134 | + const failNext = () => { |
| 135 | + if (settled) return; |
| 136 | + settled = true; |
| 137 | + clearTimeout(timeout); |
| 138 | + sock.removeAllListeners(); |
| 139 | + sock.destroy(); |
| 140 | + tryPaths(paths, index + 1); |
| 141 | + }; |
| 142 | + |
| 143 | + const timeout = setTimeout(failNext, 1000); |
| 144 | + |
| 145 | + sock.once("connect", () => { |
| 146 | + if (settled) return; |
| 147 | + settled = true; |
| 148 | + clearTimeout(timeout); |
| 149 | + socket = sock; |
| 150 | + socket.on("data", onData); |
| 151 | + socket.on("close", onSocketDown); |
| 152 | + socket.on("error", onSocketDown); |
| 153 | + socket.write(encodeFrame(OP.HANDSHAKE, { v: 1, client_id: CLIENT_ID })); |
| 154 | + }); |
| 155 | + sock.once("error", failNext); |
| 156 | +} |
| 157 | + |
| 158 | +function connect() { |
| 159 | + if (!enabled || socket) return; |
| 160 | + clearReconnectTimer(); |
| 161 | + tryPaths(candidatePipePaths(), 0); |
| 162 | +} |
| 163 | + |
| 164 | +function doSend() { |
| 165 | + if (!hasPending || !socket || !ready) return; |
| 166 | + const activity = pendingActivity; |
| 167 | + hasPending = false; |
| 168 | + lastSentAt = Date.now(); |
| 169 | + try { |
| 170 | + socket.write( |
| 171 | + encodeFrame(OP.FRAME, { |
| 172 | + cmd: "SET_ACTIVITY", |
| 173 | + args: { pid: process.pid, activity: activity || null }, |
| 174 | + nonce: makeNonce(), |
| 175 | + }), |
| 176 | + ); |
| 177 | + } catch { |
| 178 | + onSocketDown(); |
| 179 | + } |
| 180 | +} |
| 181 | + |
| 182 | +function flush() { |
| 183 | + if (!hasPending || !socket || !ready) return; |
| 184 | + clearFlushTimer(); |
| 185 | + const elapsed = Date.now() - lastSentAt; |
| 186 | + if (elapsed >= MIN_SEND_INTERVAL_MS) { |
| 187 | + doSend(); |
| 188 | + } else { |
| 189 | + flushTimer = setTimeout(() => { |
| 190 | + flushTimer = null; |
| 191 | + flush(); |
| 192 | + }, MIN_SEND_INTERVAL_MS - elapsed); |
| 193 | + } |
| 194 | +} |
| 195 | + |
| 196 | +// ── Public API ──────────────────────────────────────────────────────────── |
| 197 | + |
| 198 | +function setEnabled(next) { |
| 199 | + next = !!next; |
| 200 | + if (next === enabled) return; |
| 201 | + enabled = next; |
| 202 | + if (enabled) { |
| 203 | + connect(); |
| 204 | + } else { |
| 205 | + clearReconnectTimer(); |
| 206 | + clearFlushTimer(); |
| 207 | + hasPending = false; |
| 208 | + pendingActivity = undefined; |
| 209 | + teardownSocket(); |
| 210 | + } |
| 211 | +} |
| 212 | + |
| 213 | +/** activity: null clears presence, otherwise a Discord activity payload. */ |
| 214 | +function updateActivity(activity) { |
| 215 | + if (!enabled) return; |
| 216 | + pendingActivity = activity; |
| 217 | + hasPending = true; |
| 218 | + flush(); |
| 219 | +} |
| 220 | + |
| 221 | +function shutdown() { |
| 222 | + clearReconnectTimer(); |
| 223 | + clearFlushTimer(); |
| 224 | + teardownSocket(); |
| 225 | +} |
| 226 | + |
| 227 | +function register(ipcMain) { |
| 228 | + ipcMain.handle("discord-rpc-set-enabled", (_e, next) => { |
| 229 | + setEnabled(next); |
| 230 | + }); |
| 231 | + ipcMain.handle("discord-rpc-update-activity", (_e, activity) => { |
| 232 | + updateActivity(activity); |
| 233 | + }); |
| 234 | +} |
| 235 | + |
| 236 | +module.exports = { register, setEnabled, updateActivity, shutdown }; |
0 commit comments