From 5fd82b846a3348bd14f6bffabd0fe67a03e4c935 Mon Sep 17 00:00:00 2001 From: supertrio17 <57882120+supertrio17@users.noreply.github.com> Date: Wed, 25 Nov 2026 17:22:11 +0100 Subject: [PATCH 1/2] Improve Electron quest management and app settings Add Windows startup and tray support, light/dark themes, quest queue selection and ordering, Orb reward prioritization, live progress and ETA, and Discord account/Orb balance information. Preserve OrbSniper as an Electron app. --- README.md | 10 +- main.js | 203 ++++++++++++++++++++++++++++++++++--- preload.js | 5 + quest.js | 176 ++++++++++++++++++++++++++++++-- renderer/app.js | 239 +++++++++++++++++++++++++++++++++++++++++++- renderer/index.html | 62 ++++++++++++ renderer/style.css | 121 ++++++++++++++++++++++ 7 files changed, 792 insertions(+), 24 deletions(-) diff --git a/README.md b/README.md index e2f738c..950bde6 100644 --- a/README.md +++ b/README.md @@ -134,7 +134,15 @@ or just run `build.bat`. You get: | **Fix and restart** | Appears when something breaks. Force-closes every Discord process, frees the debug port and starts over | | **?** | Instructions, FAQ and warnings | -Close the window and farming stops. Discord keeps running. +When **Minimize to system tray** is enabled, the window's minimize and close buttons hide OrbSniper in the Windows tray and the worker keeps running. Choose **Quit** from the tray menu to stop the worker and exit. With tray mode disabled, closing the app exits normally. + +## Quest manager and settings + +Open **Quest queue** to see available quests, their game/task type, duration, current status and Orb reward. Uncheck quests you do not want OrbSniper to process, use the arrows to arrange the queue, enable **Only accept quests that pay Orbs**, or let the app prioritize higher Orb rewards. Manual queue order takes priority over automatic reward sorting. Queue changes apply after the current quest finishes; a reward that has already been claimed cannot be undone. + +Open **Settings** to choose the light or dark appearance, launch OrbSniper when Windows starts, and minimize it to the system tray. These preferences and the quest queue are saved locally on your PC. + +While a quest is active, the elapsed timer updates every second and the app estimates time remaining from recent progress. The main screen also shows the Discord account name and Orb balance when the running Discord client exposes that information; the balance may be unavailable on some client builds. ## Languages diff --git a/main.js b/main.js index 9872acd..49a0970 100644 --- a/main.js +++ b/main.js @@ -4,7 +4,7 @@ * Licensed under MIT. */ -const { app, BrowserWindow, ipcMain, clipboard, shell } = require("electron"); +const { app, BrowserWindow, ipcMain, clipboard, shell, Tray, Menu, nativeImage } = require("electron"); const DONATE_ADDRESS = "TJXGAkovUoA2z9C7mWBiB9SGLVQu6oSsf"; const { execFileSync, spawn } = require("child_process"); @@ -43,6 +43,151 @@ const state = { pending: new Map() // CDP message id -> handler }; +const DEFAULT_SETTINGS = Object.freeze({ + launchAtLogin: false, + minimizeToTray: false, + theme: "dark", + prioritizeOrbs: true, + orbOnly: false, + excludedQuestIds: [], + questOrder: [] +}); +let appSettings = { ...DEFAULT_SETTINGS }; +let tray = null; +let isQuitting = false; + +function cleanIdList(value) { + return Array.isArray(value) + ? [...new Set(value.map(v => String(v)).filter(v => v && v.length <= 64))].slice(0, 300) + : []; +} +function normalizeSettings(value) { + const v = value && typeof value === "object" ? value : {}; + return { + launchAtLogin: v.launchAtLogin === true, + minimizeToTray: v.minimizeToTray === true, + theme: v.theme === "light" ? "light" : "dark", + prioritizeOrbs: v.prioritizeOrbs !== false, + orbOnly: v.orbOnly === true, + excludedQuestIds: cleanIdList(v.excludedQuestIds), + questOrder: cleanIdList(v.questOrder) + }; +} +function settingsPath() { + try { return path.join(app.getPath("userData"), "settings.json"); } + catch (_) { return null; } +} +function readSettings() { + try { + const file = settingsPath(); + if (file && fs.existsSync(file)) return normalizeSettings(JSON.parse(fs.readFileSync(file, "utf8"))); + } catch (_) {} + return { ...DEFAULT_SETTINGS }; +} +function writeSettings() { + try { + const file = settingsPath(); + if (!file) return; + fs.mkdirSync(path.dirname(file), { recursive: true }); + fs.writeFileSync(file, JSON.stringify(appSettings, null, 2), "utf8"); + } catch (e) { + uiLog("[!] Could not save settings: " + ((e && e.message) || e)); + } +} +function questPreferences() { + return { + prioritizeOrbs: appSettings.prioritizeOrbs, + orbOnly: appSettings.orbOnly, + excludedQuestIds: appSettings.excludedQuestIds.slice(), + questOrder: appSettings.questOrder.slice() + }; +} +function syncEnginePreferences() { + if (!state.running || !state.ws || state.ws.readyState !== WebSocket.OPEN) return; + const value = JSON.stringify(questPreferences()); + evalInPage(`window.__ORB_PREFERENCES__ = ${value}; if (window.__ORB__) window.__ORB__.preferences = window.__ORB_PREFERENCES__;`); +} +function applyStartupSetting() { + if (process.platform !== "win32") return; + try { + const args = app.isPackaged ? [] : [app.getAppPath()]; + if (appSettings.minimizeToTray) args.push("--hidden"); + app.setLoginItemSettings({ openAtLogin: appSettings.launchAtLogin, path: process.execPath, args }); + } catch (e) { + uiLog("[!] Could not update Windows startup setting: " + ((e && e.message) || e)); + } +} +function ensureTray() { + if (tray) return true; + if (process.platform !== "win32") return false; + try { + const image = nativeImage.createFromPath(path.join(__dirname, "icon.ico")); + if (!image || image.isEmpty()) return false; + tray = new Tray(image.resize({ width: 16, height: 16 })); + tray.setToolTip("OrbSniper"); + tray.setContextMenu(Menu.buildFromTemplate([ + { label: "Open OrbSniper", click: showMainWindow }, + { type: "separator" }, + { label: state.running ? "Quest worker: running" : "Quest worker: stopped", enabled: false }, + { type: "separator" }, + { label: "Quit", click: quitApplication } + ])); + tray.on("click", showMainWindow); + tray.on("double-click", showMainWindow); + return true; + } catch (_) { + tray = null; + return false; + } +} +function syncTray() { + if (appSettings.minimizeToTray) ensureTray(); + else if (tray) { try { tray.destroy(); } catch (_) {} tray = null; } +} +function updateTrayStatus() { + if (!tray) return; + try { + tray.setToolTip(state.running ? "OrbSniper — running" : "OrbSniper — stopped"); + tray.setContextMenu(Menu.buildFromTemplate([ + { label: "Open OrbSniper", click: showMainWindow }, + { type: "separator" }, + { label: state.running ? "Quest worker: running" : "Quest worker: stopped", enabled: false }, + { type: "separator" }, + { label: "Quit", click: quitApplication } + ])); + } catch (_) {} +} +function showMainWindow() { + if (!win || win.isDestroyed()) return; + win.show(); + if (win.isMinimized()) win.restore(); + win.focus(); +} +function hideMainWindow() { + if (!win || win.isDestroyed()) return false; + if (appSettings.minimizeToTray && ensureTray()) { win.hide(); return true; } + win.minimize(); + return false; +} +function quitApplication() { + if (isQuitting) return; + isQuitting = true; + const wasRunning = state.running; + if (wasRunning) stopFlow(); + if (tray) { try { tray.destroy(); } catch (_) {} tray = null; } + // Let the stop flag reach Discord before Electron tears down its CDP socket. + if (wasRunning) setTimeout(() => app.quit(), 350); + else app.quit(); +} +function saveSettings(patch) { + appSettings = normalizeSettings({ ...appSettings, ...(patch && typeof patch === "object" ? patch : {}) }); + writeSettings(); + applyStartupSetting(); + syncTray(); + syncEnginePreferences(); + return { ...appSettings }; +} + // ---------- UI helpers ---------- function send(channel, payload) { if (win && !win.isDestroyed()) win.webContents.send(channel, payload); @@ -50,7 +195,7 @@ function send(channel, payload) { function uiLog(msg) { send("sniper:log", msg); } function say(key, level, ...args) { send("sniper:say", { key, level, args }); } function phase(p) { send("sniper:phase", p); } -function setRunning(v) { state.running = v; send("sniper:running", v); } +function setRunning(v) { state.running = v; send("sniper:running", v); updateTrayStatus(); } // Every failure path must go through here. Leaving state.running true was what // wedged the UI: the Start button stayed disabled and runFlow() returned early @@ -404,7 +549,9 @@ function injectEngine() { let code; try { - code = fs.readFileSync(path.join(__dirname, "quest.js"), "utf8").replace("__ORB_SESSION__", session); + const preferences = JSON.stringify(questPreferences()); + code = `window.__ORB_PREFERENCES__ = ${preferences};\n` + + fs.readFileSync(path.join(__dirname, "quest.js"), "utf8").replace("__ORB_SESSION__", session); } catch (e) { state.injecting = false; fail("l_injectfail", "err", String((e && e.message) || e)); @@ -455,7 +602,16 @@ function handleEngineEvent(e) { send("sniper:tally", { total: e.total, done: e.done, left: e.left, manual: e.manual }); return; case "progress": - send("sniper:progress", { quest: e.quest, task: e.task, done: e.done, need: e.need, elapsed: e.elapsed }); + send("sniper:progress", { quest: e.quest, task: e.task, game: e.game, done: e.done, need: e.need, elapsed: e.elapsed }); + return; + case "quests": + send("sniper:quests", e.quests || []); + return; + case "account": + send("sniper:account", e.account || null); + return; + case "balance": + send("sniper:balance", { value: e.value == null ? null : e.value }); return; case "all_done": send("sniper:done", { done: e.done, manual: e.manual }); @@ -743,6 +899,8 @@ ipcMain.handle("sniper:repair", async () => { ipcMain.handle("sniper:stop", () => { stopFlow(); return true; }); ipcMain.handle("sniper:skip", () => { evalInPage("window.__ORB__ && (window.__ORB__.skip = true)"); return true; }); +ipcMain.handle("app:getSettings", () => ({ ...appSettings })); +ipcMain.handle("app:saveSettings", (_e, patch) => saveSettings(patch)); ipcMain.handle("app:copy", (_e, text) => { clipboard.writeText(String(text || "")); return true; }); ipcMain.handle("app:version", () => VERSION); ipcMain.handle("app:donateAddress", () => DONATE_ADDRESS); @@ -752,8 +910,12 @@ ipcMain.handle("app:open", (_e, url) => { shell.openExternal(u); return true; }); -ipcMain.handle("win:minimize", () => { if (win) win.minimize(); }); -ipcMain.handle("win:close", () => { if (win) win.close(); }); +ipcMain.handle("win:minimize", () => hideMainWindow()); +ipcMain.handle("win:close", () => { + if (appSettings.minimizeToTray && ensureTray()) { if (win) win.hide(); return true; } + quitApplication(); + return true; +}); // ---------- window ---------- function createWindow() { @@ -767,9 +929,9 @@ function createWindow() { // Shown straight away instead of on ready-to-show: the window is up a // good part of a second sooner, and painting it in the page's own // background colour means there is no white flash before the UI arrives. - backgroundColor: "#06070a", + backgroundColor: appSettings.theme === "light" ? "#f3f5f8" : "#06070a", icon: path.join(__dirname, "icon.ico"), - show: true, + show: !(process.argv.includes("--hidden") && appSettings.minimizeToTray), webPreferences: { preload: path.join(__dirname, "preload.js"), contextIsolation: true, @@ -779,16 +941,33 @@ function createWindow() { }); win.setMenuBarVisibility(false); win.loadFile(path.join(__dirname, "renderer", "index.html")); + win.on("close", (event) => { + if (!isQuitting && appSettings.minimizeToTray && ensureTray()) { + event.preventDefault(); + win.hide(); + } + }); win.on("closed", () => { win = null; }); + if (!win.isVisible() && appSettings.minimizeToTray) ensureTray(); } const gotLock = app.requestSingleInstanceLock(); if (!gotLock) { app.quit(); } else { - app.on("second-instance", () => { - if (win) { if (win.isMinimized()) win.restore(); win.focus(); } + app.on("second-instance", () => showMainWindow()); + app.whenReady().then(() => { + appSettings = readSettings(); + applyStartupSetting(); + syncTray(); + createWindow(); + }); + app.on("activate", () => showMainWindow()); + app.on("before-quit", () => { + isQuitting = true; + if (state.running) stopFlow(); + }); + app.on("window-all-closed", () => { + if (!appSettings.minimizeToTray) app.quit(); }); - app.whenReady().then(createWindow); - app.on("window-all-closed", () => app.quit()); } diff --git a/preload.js b/preload.js index df60b3e..c5852bb 100644 --- a/preload.js +++ b/preload.js @@ -9,12 +9,17 @@ contextBridge.exposeInMainWorld("sniper", { openExternal: (url) => ipcRenderer.invoke("app:open", url), getVersion: () => ipcRenderer.invoke("app:version"), getDonateAddress: () => ipcRenderer.invoke("app:donateAddress"), + getSettings: () => ipcRenderer.invoke("app:getSettings"), + saveSettings: (patch) => ipcRenderer.invoke("app:saveSettings", patch), minimize: () => ipcRenderer.invoke("win:minimize"), close: () => ipcRenderer.invoke("win:close"), onLog: (cb) => ipcRenderer.on("sniper:log", (_, m) => cb(m)), onSay: (cb) => ipcRenderer.on("sniper:say", (_, m) => cb(m)), onEvent: (cb) => ipcRenderer.on("sniper:event", (_, m) => cb(m)), onProgress: (cb) => ipcRenderer.on("sniper:progress", (_, m) => cb(m)), + onQuests: (cb) => ipcRenderer.on("sniper:quests", (_, m) => cb(m)), + onAccount: (cb) => ipcRenderer.on("sniper:account", (_, m) => cb(m)), + onBalance: (cb) => ipcRenderer.on("sniper:balance", (_, m) => cb(m)), onTally: (cb) => ipcRenderer.on("sniper:tally", (_, m) => cb(m)), onPhase: (cb) => ipcRenderer.on("sniper:phase", (_, m) => cb(m)), onDone: (cb) => ipcRenderer.on("sniper:done", (_, m) => cb(m)), diff --git a/quest.js b/quest.js index ff42932..ea9c02f 100644 --- a/quest.js +++ b/quest.js @@ -35,7 +35,21 @@ if (prev.alive) { emit({ ev: "dup" }); return; } } - const ORB = { alive: true, session: SESSION, skip: false, stop: false }; + const DEFAULT_PREFERENCES = { + prioritizeOrbs: true, + orbOnly: false, + excludedQuestIds: [], + questOrder: [] + }; + const ORB = { + alive: true, + session: SESSION, + skip: false, + stop: false, + preferences: Object.assign({}, DEFAULT_PREFERENCES, + window.__ORB_PREFERENCES__ && typeof window.__ORB_PREFERENCES__ === "object" + ? window.__ORB_PREFERENCES__ : {}) + }; window.__ORB__ = ORB; const STALL_TIMEOUT_MS = 3 * 60 * 1000; // auto-skip a quest with no progress @@ -92,7 +106,9 @@ RunningGameStore: ["getRunningGames", "getGameForPID"], ApplicationStreamingStore: ["getStreamerActiveStreamMetadata"], ChannelStore: ["getSortedPrivateChannels"], - GuildChannelStore: ["getAllGuilds"] + GuildChannelStore: ["getAllGuilds"], + UserStore: ["getCurrentUser"], + VirtualCurrencyStore: ["getCurrentBalance"] }; const found = {}; @@ -187,6 +203,7 @@ let api = null; let apiStyle = null; + let apiUser = null; for (const cand of apiCandidates) { for (const style of ["object", "positional"]) { @@ -202,6 +219,7 @@ if (!answersLikeApi(res)) continue; api = cand; apiStyle = style; + apiUser = res.body; break; } if (api) break; @@ -231,6 +249,8 @@ const ChannelStore = found.ChannelStore; const GuildChannelStore = found.GuildChannelStore; + await reportAccount(); + const manualClaim = new Set(); const SUPPORTED = ["WATCH_VIDEO", "PLAY_ON_DESKTOP", "PLAY_ON_DESKTOP_V2", "STREAM_ON_DESKTOP", "PLAY_ACTIVITY", "WATCH_VIDEO_ON_MOBILE"]; const isApp = typeof DiscordNative !== "undefined"; @@ -243,6 +263,129 @@ }; const nameOf = (quest) => quest?.config?.messages?.questName ?? "quest"; + function orbRewardOf(quest) { + const rewards = quest?.config?.rewardsConfig?.rewards + ?? quest?.config?.rewards_config?.rewards + ?? []; + let orbs = 0; + let premiumOrbs = 0; + for (const reward of Array.isArray(rewards) ? rewards : []) { + const base = Number(reward?.orbQuantity ?? reward?.orb_quantity ?? 0); + const premium = Number(reward?.premiumOrbQuantity ?? reward?.premium_orb_quantity ?? 0); + if (Number.isFinite(base) && base > 0) orbs += base; + if (Number.isFinite(premium) && premium > 0) premiumOrbs += premium; + } + return { orbs, premiumOrbs }; + } + + function currentPreferences() { + const p = ORB.preferences && typeof ORB.preferences === "object" ? ORB.preferences : DEFAULT_PREFERENCES; + return { + prioritizeOrbs: p.prioritizeOrbs !== false, + orbOnly: p.orbOnly === true, + excludedQuestIds: new Set(Array.isArray(p.excludedQuestIds) ? p.excludedQuestIds.map(String) : []), + questOrder: Array.isArray(p.questOrder) ? p.questOrder.map(String) : [] + }; + } + + function preferenceReason(quest) { + const p = currentPreferences(); + if (p.excludedQuestIds.has(String(quest.id))) return "excluded"; + if (p.orbOnly) { + const reward = orbRewardOf(quest); + if (reward.orbs <= 0 && reward.premiumOrbs <= 0) return "no_orbs"; + } + return null; + } + + function sortQuests(quests) { + const p = currentPreferences(); + const positions = new Map(p.questOrder.map((id, index) => [id, index])); + return [...quests].sort((a, b) => { + const ai = positions.has(String(a.id)) ? positions.get(String(a.id)) : Number.MAX_SAFE_INTEGER; + const bi = positions.has(String(b.id)) ? positions.get(String(b.id)) : Number.MAX_SAFE_INTEGER; + if (ai !== bi) return ai - bi; + if (p.prioritizeOrbs) { + const ar = orbRewardOf(a); + const br = orbRewardOf(b); + const diff = Math.max(br.orbs, br.premiumOrbs) - Math.max(ar.orbs, ar.premiumOrbs); + if (diff) return diff; + } + const ae = new Date(a?.config?.expiresAt || 0).getTime() || Number.MAX_SAFE_INTEGER; + const be = new Date(b?.config?.expiresAt || 0).getTime() || Number.MAX_SAFE_INTEGER; + return ae - be; + }); + } + + function questSnapshot(quest) { + const task = taskOf(quest); + const tc = quest?.config?.taskConfig || quest?.config?.taskConfigV2; + const target = Number(tc?.tasks?.[task]?.target || 0); + const progress = Number(quest?.userStatus?.progress?.[task]?.value || 0); + const reward = orbRewardOf(quest); + const status = quest?.userStatus?.claimedAt ? "claimed" + : quest?.userStatus?.completedAt ? "completed" + : quest?.userStatus?.enrolledAt ? "enrolled" : "available"; + return { + id: String(quest.id), + name: nameOf(quest), + game: quest?.config?.application?.name ?? quest?.config?.messages?.gameTitle ?? "", + task: task || "UNSUPPORTED", + target, + progress: Math.max(0, progress), + orbs: reward.orbs, + premiumOrbs: reward.premiumOrbs, + status, + expiresAt: quest?.config?.expiresAt ?? null + }; + } + + function numericBalance(value) { + if (typeof value === "number" && Number.isFinite(value)) return value; + if (typeof value === "string" && value.trim() !== "" && Number.isFinite(Number(value))) return Number(value); + if (value && typeof value === "object") { + for (const key of ["balance", "amount", "value", "quantity", "total"]) { + const n = numericBalance(value[key]); + if (n !== null) return n; + } + } + return null; + } + + async function reportAccount() { + let user = apiUser; + try { user = found.UserStore?.getCurrentUser?.() || user; } catch (_) {} + const accountId = user?.id == null ? null : String(user.id); + if (user) { + emit({ + ev: "account", + account: { + id: accountId, + username: user.username || user.globalName || user.global_name || user.tag || "", + displayName: user.globalName || user.global_name || user.username || "Discord account" + } + }); + } + + let balance = null; + try { + balance = numericBalance( + found.VirtualCurrencyStore?.getCurrentBalance?.() ?? found.VirtualCurrencyStore?.balance + ); + } catch (_) {} + if (balance === null) { + try { + const response = await apiGet("/users/@me/virtual-currency/balance"); + let currentUser = null; + try { currentUser = found.UserStore?.getCurrentUser?.()?.id ?? apiUser?.id ?? null; } catch (_) {} + if (accountId === null || currentUser === null || String(currentUser) === accountId) { + balance = numericBalance(response?.body?.balance); + } + } catch (_) {} + } + emit({ ev: "balance", value: balance }); + } + // Discord answers with plain objects, not Errors. // An error page is thousands of characters of markup. Never let it reach // the console: report what it means instead of what it says. @@ -383,7 +526,7 @@ return null; }; const report = () => emit({ - ev: "progress", quest: questName, task: taskName, + ev: "progress", quest: questName, task: taskName, game: gameName, done: Math.round(secondsDone), need: secondsNeeded, elapsed: Date.now() - startedAt }); const progress = (value) => { @@ -569,6 +712,7 @@ const enrollFailedAt = new Map(); const claimFailedAt = new Map(); const notifiedUnsupported = new Set(); + const notifiedFiltered = new Set(); let workedThisSession = false; let announcedIdle = false; let announcedDone = false; @@ -577,7 +721,7 @@ // subtract everything we had filed away, so a quest we abandoned vanished // from the count and the app announced that everything was finished. function tally(all) { - const doable = all.filter((q) => taskOf(q)); + const doable = all.filter((q) => taskOf(q) && !preferenceReason(q)); return { total: doable.length, done: doable.filter((q) => q.userStatus?.claimedAt).length, @@ -591,11 +735,21 @@ const now = Date.now(); const all = [...QuestsStore.quests.values()] .filter((q) => { try { return new Date(q.config.expiresAt).getTime() > now; } catch (_) { return false; } }); + const ordered = sortQuests(all); + emit({ ev: "quests", quests: ordered.map(questSnapshot) }); // 1) claim what is already finished - for (const q of all) { + for (const q of ordered) { if (ORB.stop) return tally(all); if (processed.has(q.id)) continue; + const filterReason = preferenceReason(q); + if (filterReason) { + if (!notifiedFiltered.has(q.id)) { + notifiedFiltered.add(q.id); + emit({ ev: "quest_filtered", quest: nameOf(q), reason: filterReason }); + } + continue; + } if (!q.userStatus?.completedAt) continue; if (q.userStatus.claimedAt) { processed.add(q.id); continue; } const failedAt = claimFailedAt.get(q.id) ?? 0; @@ -609,10 +763,18 @@ } } - // 2) work the active ones - for (const q of all) { + // 2) work the active ones in the saved queue order + for (const q of ordered) { if (ORB.stop) return tally(all); if (processed.has(q.id)) continue; + const filterReason = preferenceReason(q); + if (filterReason) { + if (!notifiedFiltered.has(q.id)) { + notifiedFiltered.add(q.id); + emit({ ev: "quest_filtered", quest: nameOf(q), reason: filterReason }); + } + continue; + } if (q.userStatus?.completedAt) continue; if (now < (retryAt.get(q.id) ?? 0)) continue; diff --git a/renderer/app.js b/renderer/app.js index 143d384..a86a6e5 100644 --- a/renderer/app.js +++ b/renderer/app.js @@ -14,6 +14,13 @@ let running = false; let claimed = 0; let stickToBottom = true; let tally = { total: 0, done: 0, left: 0, manual: 0 }; +let appSettings = { + launchAtLogin: false, minimizeToTray: false, theme: "dark", + prioritizeOrbs: true, orbOnly: false, excludedQuestIds: [], questOrder: [] +}; +let questItems = []; +let currentProgress = null; +let currentProgressAt = 0; // ---------- i18n ---------- function t(key, ...args) { @@ -72,6 +79,12 @@ function closeLangMenu() { // counter, for one, never moved on German, French, Polish or Turkish. // Now the engine sends structured events and the text is built from the key. const EVENTS = { + // Metadata is forwarded through dedicated preload listeners; these entries + // also keep the engine-to-UI event contract explicit and testable. + quests: () => ["l_watching", "info"], + account: () => ["l_watching", "info"], + balance: () => ["l_watching", "info"], + quest_filtered: (e) => ["l_skipped", "warn", e.quest], started: () => ["l_watching", "info"], takeover: () => ["l_takeover", "info"], dup: () => ["l_dup", "warn"], @@ -110,6 +123,17 @@ const EVENTS = { function onEngineEvent(e) { if (!e || !e.ev) return; + if (e.ev === "quest_filtered") { + const reason = e.reason === "no_orbs" ? "has no Orb reward" : "is excluded from your queue"; + pushLine(`Skipped ${e.quest}: ${reason}.`, "warn"); + return; + } + + if (e.ev === "quest_done") { + currentProgress = null; + $("f-remaining").textContent = "0:00"; + } + if (e.ev === "claimed") { claimed++; $("f-claimed").textContent = String(claimed); @@ -155,6 +179,7 @@ function setStatus(title, hint, beacon, stateCls) { } function setIdle() { + currentProgress = null; running = false; setStatus(t("st_idle"), t("hint_idle"), "", ""); $("bar").hidden = true; @@ -300,20 +325,195 @@ function setPhase(phase) { setButtons(); } -// ---------- current quest ---------- +// ---------- quest queue and appearance ---------- const fmtTime = (ms) => { - const s = Math.max(0, Math.floor(ms / 1000)); - return `${Math.floor(s / 60)}:${String(s % 60).padStart(2, "0")}`; + const total = Math.max(0, Math.floor(ms / 1000)); + const h = Math.floor(total / 3600); + const m = Math.floor((total % 3600) / 60); + const sec = total % 60; + return h ? `${h}:${String(m).padStart(2, "0")}:${String(sec).padStart(2, "0")}` + : `${m}:${String(sec).padStart(2, "0")}`; }; +const fmtSeconds = (seconds) => fmtTime(Math.max(0, Number(seconds) || 0) * 1000); +const orbCount = (q) => Math.max(0, Number(q && q.orbs) || 0); +const premiumOrbCount = (q) => Math.max(0, Number(q && q.premiumOrbs) || 0); + +function applyTheme() { + document.documentElement.dataset.theme = appSettings.theme === "light" ? "light" : "dark"; +} +function syncSettingsControls() { + $("setting-startup").checked = !!appSettings.launchAtLogin; + $("setting-tray").checked = !!appSettings.minimizeToTray; + $("setting-theme").value = appSettings.theme === "light" ? "light" : "dark"; + $("setting-orb-only").checked = !!appSettings.orbOnly; + $("setting-prioritize").checked = appSettings.prioritizeOrbs !== false; +} +async function persistSettings(patch) { + appSettings = Object.assign({}, appSettings, patch || {}); + applyTheme(); + syncSettingsControls(); + renderQuestQueue(); + try { + const saved = await window.sniper.saveSettings(appSettings); + if (saved) appSettings = Object.assign({}, appSettings, saved); + applyTheme(); + syncSettingsControls(); + renderQuestQueue(); + } catch (_) { + toast("Could not save settings."); + } +} +function orderedQuestItems() { + const order = new Map((appSettings.questOrder || []).map((id, i) => [String(id), i])); + return [...questItems].sort((a, b) => { + const ai = order.has(String(a.id)) ? order.get(String(a.id)) : Number.MAX_SAFE_INTEGER; + const bi = order.has(String(b.id)) ? order.get(String(b.id)) : Number.MAX_SAFE_INTEGER; + if (ai !== bi) return ai - bi; + if (appSettings.prioritizeOrbs) { + const rewardDiff = Math.max(orbCount(b), premiumOrbCount(b)) - Math.max(orbCount(a), premiumOrbCount(a)); + if (rewardDiff) return rewardDiff; + } + const ae = Date.parse(a.expiresAt || "") || Number.MAX_SAFE_INTEGER; + const be = Date.parse(b.expiresAt || "") || Number.MAX_SAFE_INTEGER; + return ae - be; + }); +} +function renderQuestQueue() { + const container = $("quest-list"); + if (!container) return; + container.replaceChildren(); + const ordered = orderedQuestItems(); + if (!ordered.length) { + const empty = document.createElement("div"); + empty.className = "queue-empty"; + empty.textContent = "No quests received yet. Start OrbSniper and wait for Discord's next quest scan."; + container.append(empty); + $("queue-total").textContent = "0 quests selected · 0 Orbs"; + return; + } + const excluded = new Set((appSettings.excludedQuestIds || []).map(String)); + let selectedCount = 0; + let selectedOrbs = 0; + let selectedPremiumOrbs = 0; + + ordered.forEach((q, index) => { + const id = String(q.id); + const reward = orbCount(q); + const premium = premiumOrbCount(q); + const allowed = !excluded.has(id); + const eligible = allowed && (!appSettings.orbOnly || reward > 0 || premium > 0); + if (eligible) { + selectedCount++; + selectedOrbs += reward; + selectedPremiumOrbs += premium; + } + + const row = document.createElement("div"); + row.className = "quest-row" + (allowed ? "" : " excluded"); + + const include = document.createElement("input"); + include.type = "checkbox"; + include.className = "quest-include"; + include.checked = allowed; + include.setAttribute("aria-label", `Include ${q.name} in the quest queue`); + include.addEventListener("change", () => { + const next = new Set((appSettings.excludedQuestIds || []).map(String)); + if (include.checked) next.delete(id); else next.add(id); + persistSettings({ excludedQuestIds: [...next] }); + }); + + const info = document.createElement("div"); + info.className = "quest-info"; + const title = document.createElement("div"); + title.className = "quest-title"; + title.textContent = q.name || "Discord Quest"; + const details = document.createElement("div"); + details.className = "quest-sub"; + const duration = q.target ? fmtSeconds(q.target) : "duration unknown"; + const game = q.game || "Discord"; + const task = String(q.task || "task").replace(/_/g, " ").toLowerCase(); + details.textContent = `${game} · ${task} · ${duration}`; + info.append(title, details); + + const rewardEl = document.createElement("div"); + rewardEl.className = "quest-reward" + (reward + premium > 0 ? "" : " no-orbs"); + rewardEl.textContent = reward + premium > 0 + ? `${reward.toLocaleString()} Orbs${premium ? ` + ${premium.toLocaleString()} Premium` : ""}` + : "No Orb reward"; + + const status = document.createElement("div"); + status.className = "quest-status"; + status.textContent = q.status || "available"; + + const actions = document.createElement("div"); + actions.className = "quest-actions"; + const up = document.createElement("button"); + up.type = "button"; + up.className = "queue-move"; + up.textContent = "↑"; + up.title = "Move earlier"; + up.disabled = index === 0; + up.addEventListener("click", () => moveQuest(id, -1)); + const down = document.createElement("button"); + down.type = "button"; + down.className = "queue-move"; + down.textContent = "↓"; + down.title = "Move later"; + down.disabled = index === ordered.length - 1; + down.addEventListener("click", () => moveQuest(id, 1)); + actions.append(up, down); + + row.append(include, info, rewardEl, status, actions); + container.append(row); + }); + + const premiumText = selectedPremiumOrbs ? ` · + ${selectedPremiumOrbs.toLocaleString()} Premium Orbs` : ""; + $("queue-total").textContent = + `${selectedCount} quests selected · ${selectedOrbs.toLocaleString()} Orbs${premiumText}`; +} +function moveQuest(id, delta) { + const ordered = orderedQuestItems().map(q => String(q.id)); + const from = ordered.indexOf(String(id)); + const to = from + delta; + if (from < 0 || to < 0 || to >= ordered.length) return; + [ordered[from], ordered[to]] = [ordered[to], ordered[from]]; + persistSettings({ questOrder: ordered }); +} + +// ---------- current quest ---------- +function tickProgress() { + if (!currentProgress) return; + const p = currentProgress; + const elapsed = Math.max(0, Number(p.elapsed) || 0) + Math.max(0, Date.now() - currentProgressAt); + const done = Math.max(0, Number(p.done) || 0); + const need = Math.max(0, Number(p.need) || 0); + const elapsedSinceStart = Math.max(0, elapsed - (p.baseElapsed || 0)) / 1000; + const progressSinceStart = Math.max(0, done - (p.baseDone || 0)); + const rate = elapsedSinceStart >= 3 && progressSinceStart > 0 + ? Math.max(0.1, Math.min(3, progressSinceStart / elapsedSinceStart)) + : 1; + const remaining = need > done ? (need - done) / rate : 0; + $("f-time").textContent = fmtTime(elapsed); + $("f-remaining").textContent = need ? fmtSeconds(remaining) : "—"; +} function updateQuest(p) { if (!p || !p.quest) return; + if (!currentProgress || currentProgress.quest !== p.quest) { + currentProgress = { ...p, baseDone: Number(p.done) || 0, baseElapsed: Number(p.elapsed) || 0 }; + } else { + currentProgress = { ...currentProgress, ...p }; + } + currentProgressAt = Date.now(); + const pct = p.need > 0 ? Math.min(100, Math.round((p.done / p.need) * 100)) : 0; setProgress(pct); $("facts").hidden = false; $("f-target").textContent = p.quest; $("f-pct").textContent = pct + "%"; - $("f-time").textContent = fmtTime(p.elapsed); + const task = String(p.task || "").replace(/_/g, " ").toLowerCase(); + $("f-meta").textContent = [p.game, task].filter(Boolean).join(" · ") || "Discord Quest"; + tickProgress(); $("status-text").textContent = t("st_running"); $("status-hint").textContent = t("hint_quest", p.quest); } @@ -365,6 +565,14 @@ document.addEventListener("DOMContentLoaded", () => { applyLang(); setIdle(); + applyTheme(); + window.sniper.getSettings().then((saved) => { + if (saved) appSettings = Object.assign({}, appSettings, saved); + applyTheme(); + syncSettingsControls(); + renderQuestQueue(); + }).catch(() => {}); + setInterval(tickProgress, 1000); window.sniper.getVersion().then((v) => { if (v) $("tb-ver").textContent = "v" + v; }).catch(() => {}); @@ -383,6 +591,7 @@ document.addEventListener("DOMContentLoaded", () => { }); const beginRun = () => { + currentProgress = null; running = true; claimed = 0; tally = { total: 0, done: 0, left: 0, manual: 0 }; @@ -470,6 +679,13 @@ document.addEventListener("DOMContentLoaded", () => { $("gh-handle").textContent = GITHUB_URL.replace(/^https:\/\/github\.com\//, ""); $("btn-help").addEventListener("click", () => showModal("modal-help")); + $("btn-settings").addEventListener("click", () => showModal("modal-settings")); + $("btn-quests").addEventListener("click", () => showModal("modal-quests")); + $("setting-startup").addEventListener("change", () => persistSettings({ launchAtLogin: $("setting-startup").checked })); + $("setting-tray").addEventListener("change", () => persistSettings({ minimizeToTray: $("setting-tray").checked })); + $("setting-theme").addEventListener("change", () => persistSettings({ theme: $("setting-theme").value })); + $("setting-orb-only").addEventListener("change", () => persistSettings({ orbOnly: $("setting-orb-only").checked })); + $("setting-prioritize").addEventListener("change", () => persistSettings({ prioritizeOrbs: $("setting-prioritize").checked })); $("btn-donate").addEventListener("click", () => showModal("modal-donate")); $("scrim").addEventListener("click", closeModal); document.querySelectorAll("[data-close]").forEach((b) => b.addEventListener("click", closeModal)); @@ -487,6 +703,21 @@ document.addEventListener("DOMContentLoaded", () => { window.sniper.onEvent(onEngineEvent); window.sniper.onPhase(setPhase); window.sniper.onProgress(updateQuest); + window.sniper.onQuests((items) => { + questItems = Array.isArray(items) ? items : []; + renderQuestQueue(); + }); + window.sniper.onAccount((account) => { + if (!account) return; + const name = account.displayName || account.username || "Discord account"; + const username = account.username && account.username !== name ? ` · @${account.username}` : ""; + $("f-account").textContent = name + username; + $("account-strip").hidden = false; + }); + window.sniper.onBalance(({ value }) => { + $("f-orbs").textContent = value == null ? "—" : Number(value).toLocaleString(); + if (value != null) $("account-strip").hidden = false; + }); window.sniper.onTally(renderTally); window.sniper.onRunning((isRunning) => { running = isRunning; setButtons(); }); diff --git a/renderer/index.html b/renderer/index.html index 1d9cbbc..009e900 100644 --- a/renderer/index.html +++ b/renderer/index.html @@ -31,6 +31,12 @@
+ + @@ -72,6 +78,14 @@Choose which quests are eligible. Use the arrows to move a quest earlier or later in your queue. New quests are added automatically according to your reward priority. Changes to the current quest take effect after it finishes; already claimed rewards cannot be undone.
+Settings are saved locally on this PC. Your queue choices are applied to the running quest worker immediately.
+