This commit is contained in:
parent
24975c2e0d
commit
3acd082fb0
28 changed files with 3454 additions and 836 deletions
143
main.js
143
main.js
|
|
@ -1,8 +1,6 @@
|
|||
const { app, BrowserWindow, session, desktopCapturer, ipcMain, clipboard } = require('electron');
|
||||
const { autoUpdater } = require('electron-updater');
|
||||
const path = require('path');
|
||||
const fs = require('fs');
|
||||
const url = require('url');
|
||||
|
||||
const updateState = {
|
||||
status: 'idle', // idle | checking | available | downloading | downloaded | not-available | error
|
||||
|
|
@ -19,33 +17,6 @@ function broadcastUpdateState() {
|
|||
}
|
||||
}
|
||||
|
||||
function getStorageFilePath() {
|
||||
return path.join(app.getPath('userData'), 'renderer-storage.json');
|
||||
}
|
||||
|
||||
function readPersistentStore() {
|
||||
const filePath = getStorageFilePath();
|
||||
try {
|
||||
if (!fs.existsSync(filePath)) return {};
|
||||
const raw = fs.readFileSync(filePath, 'utf8');
|
||||
const parsed = JSON.parse(raw);
|
||||
return parsed && typeof parsed === 'object' ? parsed : {};
|
||||
} catch (err) {
|
||||
console.error('Failed to read persistent store', err);
|
||||
return {};
|
||||
}
|
||||
}
|
||||
|
||||
function writePersistentStore(store) {
|
||||
const filePath = getStorageFilePath();
|
||||
try {
|
||||
fs.mkdirSync(path.dirname(filePath), { recursive: true });
|
||||
fs.writeFileSync(filePath, JSON.stringify(store), 'utf8');
|
||||
} catch (err) {
|
||||
console.error('Failed to write persistent store', err);
|
||||
}
|
||||
}
|
||||
|
||||
function isNewerVersionAvailable(info) {
|
||||
const next = info && typeof info.version === 'string' ? info.version : '';
|
||||
return Boolean(next) && next !== app.getVersion();
|
||||
|
|
@ -84,8 +55,9 @@ async function runUpdateCheck(reason = 'manual') {
|
|||
}
|
||||
|
||||
function createWindow() {
|
||||
// Create a persistent session for chattz to keep the user logged in
|
||||
const sess = session.fromPartition('persist:chattz');
|
||||
const backendUrl = (process.env.CHATTZ_URL || process.env.APP_BASE_URL || 'http://localhost:3000').replace(/\/$/, '');
|
||||
const backendOrigin = new URL(backendUrl).origin;
|
||||
|
||||
const win = new BrowserWindow({
|
||||
width: 1200,
|
||||
|
|
@ -94,7 +66,6 @@ function createWindow() {
|
|||
webPreferences: {
|
||||
nodeIntegration: false,
|
||||
contextIsolation: true,
|
||||
webSecurity: false, // Required for cross-origin fetch/ws from file:// with cookies
|
||||
session: sess,
|
||||
preload: path.join(__dirname, 'desktop', 'preload.js')
|
||||
}
|
||||
|
|
@ -103,32 +74,33 @@ function createWindow() {
|
|||
win.setAutoHideMenuBar(true);
|
||||
win.setMenuBarVisibility(true);
|
||||
|
||||
// Auto-approve media permissions (camera, microphone)
|
||||
sess.setPermissionCheckHandler((webContents, permission) => {
|
||||
if (permission === 'media' || permission === 'clipboard-read' || permission === 'clipboard-write') {
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
const origin = safeOrigin(webContents.getURL());
|
||||
if (origin !== backendOrigin) return false;
|
||||
return permission === 'media' || permission === 'clipboard-write';
|
||||
});
|
||||
|
||||
sess.setPermissionRequestHandler((webContents, permission, callback) => {
|
||||
if (permission === 'media' || permission === 'clipboard-read' || permission === 'clipboard-write') {
|
||||
const origin = safeOrigin(webContents.getURL());
|
||||
if (origin === backendOrigin && (permission === 'media' || permission === 'clipboard-write')) {
|
||||
callback(true);
|
||||
} else {
|
||||
callback(false);
|
||||
}
|
||||
});
|
||||
|
||||
// Handle screen share requests
|
||||
sess.setDisplayMediaRequestHandler((request, callback) => {
|
||||
const origin = safeOrigin(request.frame?.url || win.webContents.getURL());
|
||||
if (origin !== backendOrigin) {
|
||||
callback(null);
|
||||
return;
|
||||
}
|
||||
desktopCapturer.getSources({ types: ['screen', 'window'] }).then((sources) => {
|
||||
// Provide the first screen source by default, or implement a picker window here
|
||||
if (sources && sources.length > 0) {
|
||||
// We prefer a screen over a window if available, simple heuristic
|
||||
const screenSource = sources.find(s => s.id.startsWith('screen')) || sources[0];
|
||||
callback({ video: screenSource, audio: 'loopback' });
|
||||
} else {
|
||||
callback(null); // Reject safely
|
||||
callback(null);
|
||||
}
|
||||
}).catch(err => {
|
||||
console.error("Failed to get desktop sources for screen share", err);
|
||||
|
|
@ -136,55 +108,9 @@ function createWindow() {
|
|||
});
|
||||
});
|
||||
|
||||
const backendUrl = (process.env.CHATTZ_URL || 'https://discord.flegr.me').replace(/\/$/, '');
|
||||
const indexPath = path.join(__dirname, 'desktop', 'index.html');
|
||||
|
||||
const loadDesktopApp = (queryParams = '') => {
|
||||
const options = {};
|
||||
if (queryParams) {
|
||||
try {
|
||||
options.query = Object.fromEntries(new URLSearchParams(queryParams));
|
||||
} catch (e) {
|
||||
console.error("Failed to parse query params", e);
|
||||
}
|
||||
}
|
||||
|
||||
// Use setImmediate to ensure the current navigation tick is cleared,
|
||||
// which prevents ERR_ABORTED (-3) on some platforms when interrupting a redirect.
|
||||
setImmediate(() => {
|
||||
if (win.isDestroyed()) return;
|
||||
win.loadFile(indexPath, options).catch((err) => {
|
||||
// Ignore aborted errors as they often happen during fast redirects
|
||||
if (err.toString().includes('-3') || err.code === -3) return;
|
||||
console.error(`Failed to load desktop file: ${err}`);
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
// Intercept navigations/redirects that return to the backend with a token
|
||||
// after the OAuth login flow. Two handlers are needed because:
|
||||
// - will-navigate fires for client-side navigations (location.href, link clicks)
|
||||
// - will-redirect fires for server-side 302 redirects (OAuth callback chain)
|
||||
const interceptLoginRedirect = (event, navigatedUrl) => {
|
||||
try {
|
||||
const urlObj = new URL(navigatedUrl);
|
||||
const backendObj = new URL(backendUrl);
|
||||
if (urlObj.origin === backendObj.origin && urlObj.pathname === '/') {
|
||||
if (urlObj.searchParams.has('token')) {
|
||||
console.log("Detected login success redirect, returning to desktop UI...");
|
||||
event.preventDefault();
|
||||
loadDesktopApp(urlObj.search.slice(1));
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
}
|
||||
};
|
||||
|
||||
win.webContents.on('will-navigate', interceptLoginRedirect);
|
||||
win.webContents.on('will-redirect', interceptLoginRedirect);
|
||||
|
||||
loadDesktopApp();
|
||||
win.loadURL(backendUrl).catch((err) => {
|
||||
console.error(`Failed to load desktop app: ${err}`);
|
||||
});
|
||||
|
||||
// Ensure renderer receives latest updater state after any (re)load.
|
||||
// Delay broadcast by 300ms to give the renderer time to register its
|
||||
|
|
@ -203,40 +129,11 @@ app.commandLine.appendSwitch('disable-webrtc-hw-encoding'); // Sometime helps re
|
|||
app.commandLine.appendSwitch('log-level', '3'); // Silences standard Chromium warning logs (like SRTP transport unprotect logs which are benign timing issues)
|
||||
|
||||
app.whenReady().then(() => {
|
||||
// Register IPC handlers once (before creating any windows)
|
||||
ipcMain.handle('get-config', () => {
|
||||
return {
|
||||
backendUrl: (process.env.CHATTZ_URL || 'https://discord.flegr.me').replace(/\/$/, '')
|
||||
};
|
||||
});
|
||||
|
||||
ipcMain.handle('clipboard-write', (event, text) => {
|
||||
clipboard.writeText(text);
|
||||
return true;
|
||||
});
|
||||
|
||||
ipcMain.handle('storage-get', (event, key) => {
|
||||
if (typeof key !== 'string' || key.length === 0) return null;
|
||||
const store = readPersistentStore();
|
||||
return Object.prototype.hasOwnProperty.call(store, key) ? store[key] : null;
|
||||
});
|
||||
|
||||
ipcMain.handle('storage-set', (event, key, value) => {
|
||||
if (typeof key !== 'string' || key.length === 0) return false;
|
||||
const store = readPersistentStore();
|
||||
store[key] = value;
|
||||
writePersistentStore(store);
|
||||
return true;
|
||||
});
|
||||
|
||||
ipcMain.handle('storage-remove', (event, key) => {
|
||||
if (typeof key !== 'string' || key.length === 0) return false;
|
||||
const store = readPersistentStore();
|
||||
delete store[key];
|
||||
writePersistentStore(store);
|
||||
return true;
|
||||
});
|
||||
|
||||
ipcMain.handle('get-update-state', () => ({ ...updateState }));
|
||||
ipcMain.handle('check-for-updates-now', async () => {
|
||||
await runUpdateCheck('renderer-direct');
|
||||
|
|
@ -314,3 +211,11 @@ app.on('window-all-closed', () => {
|
|||
app.quit();
|
||||
}
|
||||
});
|
||||
|
||||
function safeOrigin(value) {
|
||||
try {
|
||||
return new URL(value).origin;
|
||||
} catch (_) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue