Add self-update feature via GitHub Releases

Checks for updates on startup (silent, badge on button if available)
and on manual click. Downloads new portable .exe to temp dir, creates
a batch script to swap the running executable after quit, then relaunches.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
Zac
2026-02-09 22:23:48 -05:00
parent cccb20bd31
commit 7309d78344
6 changed files with 555 additions and 1 deletions
+179
View File
@@ -3,6 +3,7 @@ const path = require('path');
const fs = require('fs');
const os = require('os');
const axios = require('axios');
const https = require('https');
const { spawn } = require('child_process');
const http = require('http');
@@ -413,3 +414,181 @@ ipcMain.handle('camera-proxy-stop', async (event, { processId }) => {
}
});
// --- Self-Update Functionality ---
// Compare semver versions: returns -1 if a < b, 0 if equal, 1 if a > b
function compareVersions(a, b) {
// Strip pre-release tags (e.g. "1.2.3-beta.1" → "1.2.3")
const cleanA = a.replace(/-.*$/, '');
const cleanB = b.replace(/-.*$/, '');
const partsA = cleanA.split('.').map(Number);
const partsB = cleanB.split('.').map(Number);
for (let i = 0; i < 3; i++) {
const numA = partsA[i] || 0;
const numB = partsB[i] || 0;
if (numA < numB) return -1;
if (numA > numB) return 1;
}
return 0;
}
// Follow HTTPS redirects and return the final response (for GitHub asset downloads)
function httpsGetFollowRedirects(url, callback, redirectCount = 0) {
if (redirectCount >= 5) {
return callback(null, new Error('Too many redirects'));
}
const parsed = new URL(url);
if (parsed.protocol !== 'https:') {
return callback(null, new Error('Only HTTPS URLs are allowed'));
}
https.get(url, { headers: { 'User-Agent': 'Alta-Proxy-Tool' } }, (res) => {
if (res.statusCode >= 300 && res.statusCode < 400 && res.headers.location) {
const redirectUrl = new URL(res.headers.location, url).href;
httpsGetFollowRedirects(redirectUrl, callback, redirectCount + 1);
} else {
callback(res);
}
}).on('error', (err) => {
callback(null, err);
});
}
ipcMain.handle('get-current-version', async () => {
return { success: true, version: app.getVersion() };
});
ipcMain.handle('check-for-updates', async () => {
try {
const response = await axios.get(
'https://api.github.com/repos/PageZ948/Alta-Proxy-Tool/releases/latest',
{
timeout: 10000,
headers: { 'User-Agent': 'Alta-Proxy-Tool', 'Accept': 'application/vnd.github.v3+json' }
}
);
const release = response.data;
const latestVersion = release.tag_name.replace(/^v/, '');
const currentVersion = app.getVersion();
const updateAvailable = compareVersions(currentVersion, latestVersion) < 0;
// Find the portable .exe asset
const exeAsset = release.assets.find(a => /AltaCameraProxy-.*-portable\.exe$/i.test(a.name));
const downloadUrl = exeAsset ? exeAsset.browser_download_url : null;
return {
success: true,
updateAvailable,
currentVersion,
latestVersion,
downloadUrl,
releaseNotes: release.body || '',
releaseName: release.name || `v${latestVersion}`
};
} catch (error) {
if (error.response && error.response.status === 404) {
return { success: true, updateAvailable: false, currentVersion: app.getVersion(), message: 'No releases available yet' };
}
if (error.response && error.response.status === 403) {
return { success: false, message: 'GitHub API rate limit exceeded. Try again later.' };
}
console.error('Check for updates error:', error.message);
return { success: false, message: error.message || 'Failed to check for updates' };
}
});
ipcMain.handle('download-and-install-update', async (event, { downloadUrl }) => {
try {
// Determine the path to the currently running executable
const currentExePath = process.env.PORTABLE_EXECUTABLE_FILE || app.getPath('exe');
const currentDir = path.dirname(currentExePath);
const currentExeName = path.basename(currentExePath);
// Check write permission on the app directory
try {
fs.accessSync(currentDir, fs.constants.W_OK);
} catch {
return { success: false, message: 'No write permission to the application directory. Try running as administrator.' };
}
const tempDir = os.tmpdir();
const tempExePath = path.join(tempDir, `AltaCameraProxy-update-${Date.now()}.exe`);
// Download the file with progress reporting
await new Promise((resolve, reject) => {
httpsGetFollowRedirects(downloadUrl, (res, err) => {
if (err) return reject(err);
if (res.statusCode !== 200) {
res.resume();
return reject(new Error(`Download failed with status ${res.statusCode}`));
}
const totalSize = parseInt(res.headers['content-length'], 10) || 0;
let downloadedSize = 0;
const fileStream = fs.createWriteStream(tempExePath);
res.on('data', (chunk) => {
downloadedSize += chunk.length;
if (totalSize > 0 && mainWindow && !mainWindow.isDestroyed()) {
const percent = Math.round((downloadedSize / totalSize) * 100);
mainWindow.webContents.send('update-download-progress', { percent, downloadedSize, totalSize });
}
});
res.pipe(fileStream);
fileStream.on('finish', () => {
fileStream.close();
resolve();
});
fileStream.on('error', (err) => {
fs.unlink(tempExePath, () => {});
reject(err);
});
});
});
// Verify downloaded file size (sanity check: > 10MB for an Electron portable exe)
const stats = fs.statSync(tempExePath);
if (stats.size < 10 * 1024 * 1024) {
fs.unlinkSync(tempExePath);
return { success: false, message: 'Downloaded file is too small — update may be corrupt.' };
}
// Create batch script to replace the exe after this process exits
const batchPath = path.join(tempDir, `apt-update-${Date.now()}.bat`);
const pid = process.pid;
const batchContent = `@echo off\r\ntitle APT-Updater\r\necho Waiting for Alta Proxy Tool to close...\r\n:waitloop\r\ntasklist /fi "PID eq ${pid}" 2>nul | find "${pid}" >nul\r\nif not errorlevel 1 (\r\n timeout /t 1 /nobreak >nul\r\n goto waitloop\r\n)\r\necho Applying update...\r\ncopy /y "${tempExePath}" "${path.join(currentDir, currentExeName)}"\r\nif errorlevel 1 (\r\n echo Update failed! Could not copy new version.\r\n pause\r\n del "${tempExePath}" >nul 2>&1\r\n del "%~f0" >nul 2>&1\r\n exit /b 1\r\n)\r\necho Update complete. Launching new version...\r\nstart "" "${path.join(currentDir, currentExeName)}"\r\ndel "${tempExePath}" >nul 2>&1\r\ndel "%~f0" >nul 2>&1\r\n`;
fs.writeFileSync(batchPath, batchContent);
// Spawn the updater batch script detached
let updater;
try {
updater = spawn('cmd', ['/c', batchPath], {
detached: true,
stdio: 'ignore',
windowsHide: true
});
updater.unref();
} catch (spawnError) {
console.error('Failed to spawn updater:', spawnError);
try { fs.unlinkSync(tempExePath); } catch {}
try { fs.unlinkSync(batchPath); } catch {}
return { success: false, message: 'Failed to start updater process.' };
}
// Quit the app after a delay to let the IPC response return to renderer
setTimeout(() => {
app.quit();
}, 1500);
return { success: true, message: 'Update is being installed. The app will restart shortly.' };
} catch (error) {
console.error('Download and install update error:', error);
return { success: false, message: error.message || 'Failed to download and install update' };
}
});