Files
BizGaze_Remote/desktop/main.js
T

185 lines
9.0 KiB
JavaScript
Raw Normal View History

// Biz Connect — technician desktop client (Electron main process).
//
// This is a thin shell: it loads the live Connect web UI from the server origin, so every
// relative /api and /ws URL in the web app keeps working unchanged. What it adds over a
// browser tab:
// - native full-screen capture for "Share Screen" (setDisplayMediaRequestHandler)
// - a real desktop window (no browser chrome), persisted login session
// - external links open in the user's browser, not inside the app
//
// Server origin is configurable so the same build works against prod or a dev server.
const { app, BrowserWindow, session, desktopCapturer, shell, Menu, ipcMain, nativeImage } = require('electron');
const path = require('path');
const fs = require('fs');
const os = require('os');
const crypto = require('crypto');
// A stable per-install id (persisted in userData), so the server can count installs and
// associate them with the user who signs in. Created once, then reused across launches.
function getInstallId() {
try {
const p = path.join(app.getPath('userData'), 'install-id');
if (fs.existsSync(p)) { const v = fs.readFileSync(p, 'utf8').trim(); if (v) return v; }
const id = crypto.randomUUID();
fs.writeFileSync(p, id);
return id;
} catch (_) { return 'unknown'; }
}
// The renderer (web app) reads this synchronously to report telemetry after login.
ipcMain.on('get-install-info', (e) => {
e.returnValue = { installId: getInstallId(), appVersion: app.getVersion(), os: process.platform + ' ' + os.release() };
});
// Auto-update: only NATIVE shell changes (this .exe) need this — all web/UI changes arrive
// live from the server. Checks the self-hosted feed (publish config in package.json →
// https://remote.bizgaze.com/downloads/latest.yml), downloads in the background, and installs
// on the next restart. No-op in dev (unpackaged).
let autoUpdater = null;
try { ({ autoUpdater } = require('electron-updater')); } catch (_) { /* not installed in dev */ }
// Native Windows toast WITH a reply box, via node-notifier's bundled SnoreToast engine.
// node-notifier's API doesn't expose the reply text box, but its WindowsToaster forwards raw
// options to SnoreToast — so we inject `-tb` (text box) + `-p` (avatar image) and reuse its
// named-pipe + result parsing (exit 5 = TextEntered). Installed-app only (needs the
// AppUserModelID shortcut the NSIS installer registers). No PowerShell 7 required.
let WindowsToaster = null;
try { WindowsToaster = require('node-notifier').WindowsToaster; } catch (_) { /* optional */ }
// Write the avatar the renderer drew (a data: URL) to a temp PNG for SnoreToast's -p image.
function writeTempPng(dataUrl) {
try {
if (!dataUrl || !/^data:image\/png;base64,/.test(dataUrl)) return null;
const p = path.join(app.getPath('temp'), 'bizc-toast-' + crypto.randomBytes(4).toString('hex') + '.png');
fs.writeFileSync(p, Buffer.from(dataUrl.split(',')[1], 'base64'));
return p;
} catch (_) { return null; }
}
// Resolves with {text} (replied), {open} (toast clicked), or null (dismissed/timeout).
ipcMain.handle('reply-notification', (_e, payload = {}) => new Promise((resolve) => {
if (!WindowsToaster) return resolve(null);
const img = writeTempPng(payload.avatar);
let done = false;
const finish = (v) => { if (!done) { done = true; if (img) { try { fs.unlinkSync(img); } catch (_) {} } resolve(v); } };
try {
const toaster = new WindowsToaster({ withFallback: false });
toaster.notify({
title: payload.title || 'Biz Connect',
message: payload.body || ' ',
appID: 'com.bizgaze.connect.desktop',
tb: true, // -tb : reply text box
w: true, // -w : wait for the user to reply / click before returning
...(img ? { icon: img } : {}), // mapped to -p (image)
}, (err, response, metadata) => {
// Log the raw result once so the exact reply field can be confirmed on a real machine.
try { fs.appendFileSync(path.join(app.getPath('userData'), 'toast-debug.log'), JSON.stringify({ t: Date.now(), err: err && err.message, response, metadata }) + '\n'); } catch (_) {}
const meta = metadata || {};
const known = ['click', 'activate', 'activated', 'timeout', 'timedout', 'dismissed'];
const respStr = String(response || '').trim();
let text = String(meta.text || meta.value || meta.reply || '').trim();
if (!text && respStr && !known.includes(respStr.toLowerCase())) text = respStr; // some builds return the reply as the response
const act = String(response || meta.action || meta.activationType || '').toLowerCase();
if (text) finish({ kind: payload.kind, id: payload.id, text });
else if (act.includes('activat') || act === 'click') finish({ kind: payload.kind, id: payload.id, open: true });
else finish(null);
});
} catch (_) { finish(null); }
}));
// Windows attributes notifications to the AppUserModelID. Without setting it, toasts read
// "electron.app.<name>"; setting it to the installer's appId makes Windows resolve the
// installed "Biz Connect" shortcut, so notifications show "Biz Connect".
app.setAppUserModelId('com.bizgaze.connect.desktop');
// Renderer asks (via preload) to raise the window — e.g. when an OS notification is clicked.
ipcMain.on('focus-window', () => {
if (!win) return;
if (win.isMinimized()) win.restore();
win.show();
win.focus();
});
// Unread badge on the taskbar icon. The renderer computes the count (chats with unread) and
// draws the badge image (it has a canvas); Windows shows it via an overlay icon, macOS/Linux
// via the dock badge count.
ipcMain.on('set-unread', (_e, { count, dataUrl } = {}) => {
try {
if (typeof app.setBadgeCount === 'function') app.setBadgeCount(count || 0); // macOS/Linux dock
if (!win) return;
const overlay = (count > 0 && dataUrl) ? nativeImage.createFromDataURL(dataUrl) : null;
win.setOverlayIcon(overlay, count > 0 ? (count + ' unread chats') : ''); // Windows taskbar
} catch (_) {}
});
const SERVER_URL = (process.env.SERVER_URL || 'https://remote.bizgaze.com').replace(/\/+$/, '');
let win;
function createWindow() {
win = new BrowserWindow({
width: 1200,
height: 800,
minWidth: 880,
minHeight: 600,
title: 'Biz Connect',
backgroundColor: '#0f1830',
webPreferences: {
preload: path.join(__dirname, 'preload.js'),
contextIsolation: true,
nodeIntegration: false,
// Persist cookies/localStorage so the technician stays logged in between launches.
partition: 'persist:bizconnect',
},
});
// Open the landing page (same entry as the website): the "before login" screen with the
// no-login "Share my screen" option + sign-in. It redirects logged-in users straight to /home.
win.loadURL(SERVER_URL + '/');
// Open target=_blank / external links in the system browser instead of a new Electron window.
win.webContents.setWindowOpenHandler(({ url }) => {
if (!url.startsWith(SERVER_URL)) { shell.openExternal(url); return { action: 'deny' }; }
return { action: 'allow' };
});
}
// The full Connect experience needs several web capabilities that Electron denies by
// default. We grant them for our own trusted origin:
// - media → camera + mic for meetings/calls (getUserMedia)
// - display-capture → "Share my screen" (getDisplayMedia)
// - notifications → in-app alerts
// - clipboard, fullscreen, pointerLock → chat paste + meeting UX
// Without this, meetings silently have no camera/mic and notifications never fire.
const GRANTED = new Set([
'media', 'display-capture', 'notifications',
'clipboard-read', 'clipboard-sanitized-write', 'fullscreen', 'pointerLock',
]);
function configureSession() {
const ses = session.fromPartition('persist:bizconnect');
// getDisplayMedia needs an explicit source. Default to the primary display + loopback audio.
// A production build can swap this for a source-picker window.
ses.setDisplayMediaRequestHandler((request, callback) => {
desktopCapturer.getSources({ types: ['screen', 'window'] }).then((sources) => {
callback(sources.length ? { video: sources[0], audio: 'loopback' } : {});
}).catch(() => callback({}));
}, { useSystemPicker: false });
// Async grant (getUserMedia, notifications, …)
ses.setPermissionRequestHandler((_wc, permission, callback) => callback(GRANTED.has(permission)));
// Sync check (some getUserMedia paths query this before requesting)
ses.setPermissionCheckHandler((_wc, permission) => GRANTED.has(permission));
}
app.whenReady().then(() => {
configureSession();
createWindow();
Menu.setApplicationMenu(null); // hide the default menu bar; the web UI is the chrome
app.on('activate', () => { if (BrowserWindow.getAllWindows().length === 0) createWindow(); });
// Check for shell updates on launch, then every 6 hours. Only in packaged builds.
if (app.isPackaged && autoUpdater) {
const check = () => autoUpdater.checkForUpdatesAndNotify().catch(() => {});
check();
setInterval(check, 6 * 60 * 60 * 1000);
}
});
app.on('window-all-closed', () => { if (process.platform !== 'darwin') app.quit(); });