From 92c5042c5eb47aabd58f594b886c363eba71e10a Mon Sep 17 00:00:00 2001 From: Burrowdev Date: Sun, 18 Oct 2026 18:52:34 +0300 Subject: [PATCH] feat: discord rich presence Client 1.3.0 shows "Playing Burrow" on the player's Discord profile while the game is open: where they are (the game's ajPresence, dens and player parties never named), the time since they started and a button to the download page. It goes through the Discord app's local IPC socket (no packages; Windows pipe, Linux and macOS sockets, Flatpak and Snap too) and retries quietly while Discord is not running. The server names its Discord application in its flashvars (discordAppId); none, no presence. --- app/discord.js | 190 +++++++++++++++++++++++++++++++++++++++++++++ app/gamePreload.js | 1 + app/index.html | 18 +++++ app/main.js | 7 ++ app/preload.js | 2 + 5 files changed, 218 insertions(+) create mode 100644 app/discord.js diff --git a/app/discord.js b/app/discord.js new file mode 100644 index 0000000..5a7abff --- /dev/null +++ b/app/discord.js @@ -0,0 +1,190 @@ +"use strict"; + +// Discord rich presence: "Playing Burrow" on the player's Discord profile, +// with where they are in the game, the time since they started and a button +// to the download page. it goes through the Discord app on this computer +// (its local IPC socket, as Discord's own SDK does), so nothing about it +// leaves the computer from here. the server names its Discord application +// (its flashvars' discordAppId); a server that names none gets no presence. +// Discord not running, or started later: tried again now and then, quietly. + +const crypto = require("crypto"); +const net = require("net"); +const path = require("path"); + +const OP_HANDSHAKE = 0; +const OP_FRAME = 1; +const OP_CLOSE = 2; +const OP_PING = 3; +const OP_PONG = 4; +const RETRY_MS = 30000; +const MAX_FRAME = 64 * 1024; + +// where the Discord app listens: a named pipe on Windows; elsewhere a socket +// in the runtime or temporary folder, or inside a Flatpak or Snap Discord's. +const socketPaths = () => { + const numbers = [...Array(10).keys()]; + if (process.platform === "win32") { + return numbers.map(n => `\\\\?\\pipe\\discord-ipc-${n}`); + } + const bases = [...new Set([process.env.XDG_RUNTIME_DIR, process.env.TMPDIR, process.env.TMP, process.env.TEMP, "/tmp"].filter(Boolean))]; + const inside = ["", "app/com.discordapp.Discord", "app/com.discordapp.DiscordCanary", "snap.discord", "snap.discord-canary"]; + return bases.flatMap(base => inside.flatMap(folder => numbers.map(n => path.join(base, folder, `discord-ipc-${n}`)))); +}; + +let wanted = null; // {appId, activity} to show, or null +let socket = null; +let socketAppId = null; +let ready = false; +let retry = null; +let buffer = Buffer.alloc(0); + +const frame = (op, data) => { + const body = Buffer.from(JSON.stringify(data)); + const head = Buffer.alloc(8); + head.writeInt32LE(op, 0); + head.writeInt32LE(body.length, 4); + return Buffer.concat([head, body]); +}; + +const send = () => { + if (!socket || !ready || !wanted || wanted.appId !== socketAppId) { + return; + } + socket.write(frame(OP_FRAME, {cmd: "SET_ACTIVITY", args: {pid: process.pid, activity: wanted.activity}, + nonce: crypto.randomUUID()})); +}; + +const drop = () => { + if (socket) { + socket.removeAllListeners(); + socket.on("error", () => {}); + socket.destroy(); + } + socket = null; + socketAppId = null; + ready = false; + buffer = Buffer.alloc(0); +}; + +const later = () => { + if (!retry && wanted) { + retry = setTimeout(() => { + retry = null; + connect(); + }, RETRY_MS); + } +}; + +const onData = chunk => { + buffer = Buffer.concat([buffer, chunk]); + while (buffer.length >= 8) { + const op = buffer.readInt32LE(0); + const length = buffer.readInt32LE(4); + if (length < 0 || length > MAX_FRAME) { + drop(); + later(); + return; + } + if (buffer.length < 8 + length) { + return; + } + const body = buffer.subarray(8, 8 + length); + buffer = buffer.subarray(8 + length); + let data = {}; + try { + data = JSON.parse(body.toString("utf8")); + } + catch (err) { + // not ours to understand; go on + } + if (op === OP_PING) { + socket.write(frame(OP_PONG, data)); + } + else if (op === OP_CLOSE) { + drop(); + later(); + return; + } + else if (op === OP_FRAME && data.evt === "READY") { + ready = true; + send(); + } + } +}; + +// tries each place Discord may listen, in turn. +const connect = (places = socketPaths()) => { + if (!wanted || socket) { + return; + } + if (!places.length) { + later(); + return; + } + const appId = wanted.appId; + const attempt = net.createConnection(places[0]); + attempt.once("error", () => { + attempt.destroy(); + if (socket === null) { + connect(places.slice(1)); + } + }); + attempt.once("connect", () => { + if (!wanted || wanted.appId !== appId) { + attempt.destroy(); + connect(); + return; + } + socket = attempt; + socketAppId = appId; + socket.removeAllListeners("error"); + socket.on("data", onData); + socket.on("error", () => {}); + socket.on("close", () => { + if (socket === attempt) { + drop(); + later(); + } + }); + socket.write(frame(OP_HANDSHAKE, {v: 1, client_id: appId})); + }); +}; + +// what to show: {appId, state, start, url} while the game is open, or null. +const set = info => { + const appId = info && /^\d{5,25}$/.test(String(info.appId)) ? String(info.appId) : null; + if (!appId) { + if (wanted) { + wanted = null; + if (socket && ready) { + socket.write(frame(OP_FRAME, {cmd: "SET_ACTIVITY", args: {pid: process.pid}, nonce: crypto.randomUUID()})); + } + } + return; + } + const activity = { + details: "Playing Burrow", + timestamps: {start: Number.isFinite(info.start) ? Math.floor(info.start) : Date.now()}, + assets: {large_image: "burrow", large_text: "Burrow"}, + instance: false, + }; + if (typeof info.state === "string" && info.state.trim().length >= 2) { + activity.state = info.state.trim().slice(0, 100); + } + if (typeof info.url === "string" && /^https:\/\/[^\s]{1,200}$/.test(info.url)) { + activity.buttons = [{label: "Play Burrow", url: info.url}]; + } + wanted = {appId, activity}; + if (socket && socketAppId !== appId) { + drop(); + } + if (socket) { + send(); + } + else if (!retry) { + connect(); + } +}; + +module.exports = {set}; diff --git a/app/gamePreload.js b/app/gamePreload.js index cbc08f9..6446ee9 100644 --- a/app/gamePreload.js +++ b/app/gamePreload.js @@ -6,6 +6,7 @@ const sendWhitelist = new Set() .add("initialized") .add("fps") .add("openPage") + .add("presence") .add("printImage") .add("reloadGame") .add("reportError") diff --git a/app/index.html b/app/index.html index bf3f9e5..878befe 100644 --- a/app/index.html +++ b/app/index.html @@ -1058,7 +1058,20 @@ } }; + // Discord rich presence (discord.js), while the game is open: the + // server's Discord application (flashvars discordAppId), where the + // player is and since when they have played. + const showPresence = state => { + if (!session || !session.flashVars || !session.flashVars.discordAppId) { + return; + } + session.presenceState = state || session.presenceState || ""; + window.client.presence({appId: session.flashVars.discordAppId, state: session.presenceState, + start: session.since || Date.now(), url: session.flashVars.presenceUrl}); + }; + const closeGame = message => { + window.client.presence(null); $("fps").textContent = ""; if (webview) { webview.remove(); @@ -1153,6 +1166,10 @@ // main.js opens http and https addresses only window.client.openPage(String(event.args[0])); } + else if (event.channel === "presence") { + // where the player is now (the game's AJClient.presenceRoom) + showPresence(String(event.args[0] || "")); + } }); $("loading").hidden = false; clearTimeout(loadingTimer); @@ -1176,6 +1193,7 @@ session = await login(); setStatus("", false, statusId); openGame(); + showPresence(""); } catch (err) { $("log-in").disabled = false; diff --git a/app/main.js b/app/main.js index 2ceb762..5c89737 100644 --- a/app/main.js +++ b/app/main.js @@ -4,6 +4,7 @@ const {app, BrowserWindow, ipcMain, net, session, shell, webContents} = require( const fs = require("fs"); const path = require("path"); const device = require("./device.js"); +const discord = require("./discord.js"); const relay = require("./relay.js"); const updater = require("./updater.js"); @@ -426,6 +427,12 @@ ipcMain.on("openPage", (event, url) => { } }); +// Discord rich presence (discord.js): {appId, state, start, url} while the +// game is open, null when it is not. +ipcMain.on("presence", (event, info) => { + discord.set(info && typeof info === "object" ? info : null); +}); + ipcMain.on("toggleFullscreen", () => { if (win) { win.setFullScreen(!win.isFullScreen()); diff --git a/app/preload.js b/app/preload.js index 72b4238..b223c2f 100644 --- a/app/preload.js +++ b/app/preload.js @@ -26,6 +26,8 @@ contextBridge.exposeInMainWorld("client", { showFile: file => ipcRenderer.send("showFile", file), toggleFullscreen: () => ipcRenderer.send("toggleFullscreen"), openPage: url => ipcRenderer.send("openPage", url), + // Discord rich presence (discord.js): {appId, state, start, url}, or null. + presence: info => ipcRenderer.send("presence", info), onFullscreen: listener => ipcRenderer.on("fullscreen", (event, on) => listener(on)), onShortcut: listener => ipcRenderer.on("shortcut", (event, key) => listener(key)), });