mirror of
https://gitlab.com/vyla-entertainment/home.git
synced 2026-11-16 07:07:20 -05:00
huge rewrite
This commit is contained in:
318
main.js
318
main.js
@@ -5,6 +5,7 @@ const express = require('express');
|
||||
const ServiceManager = require('./service-manager');
|
||||
const Patcher = require('./patcher');
|
||||
const UpdateClient = require('./update-client');
|
||||
const FileUpdater = require('./file-updater');
|
||||
|
||||
function getDefaultAppData() {
|
||||
if (process.platform === 'darwin') {
|
||||
@@ -32,8 +33,6 @@ function debugLog(msg) {
|
||||
debugLog("--- Node.js Process Started ---");
|
||||
|
||||
let serviceManager;
|
||||
let expressApp;
|
||||
let expressServer;
|
||||
let updateDecisionHandler = null;
|
||||
|
||||
debugLog(`AppData Dir: ${APPDATA_DIR}`);
|
||||
@@ -43,68 +42,6 @@ function sendToTauri(event, data) {
|
||||
process.stdout.write(JSON.stringify({ event, data }) + '\n');
|
||||
}
|
||||
|
||||
function sameTabNavMiddleware(rootDir) {
|
||||
return (req, res, next) => {
|
||||
if (req.method !== 'GET') return next();
|
||||
const isHtmlRequest = req.path === '/' || req.path.endsWith('/') || req.path.endsWith('.html');
|
||||
if (!isHtmlRequest) return next();
|
||||
|
||||
const filePath = req.path === '/' || req.path.endsWith('/')
|
||||
? path.join(rootDir, req.path, 'index.html')
|
||||
: path.join(rootDir, req.path);
|
||||
|
||||
fs.readFile(filePath, 'utf8', (err, data) => {
|
||||
if (err) return next();
|
||||
const injected = data.replace(
|
||||
'</head>',
|
||||
`<script>
|
||||
document.addEventListener('click', function(e) {
|
||||
const a = e.target.closest('a[target]');
|
||||
if (a && a.target === '_blank') a.removeAttribute('target');
|
||||
}, true);
|
||||
window.open = function(url) {
|
||||
if (url) window.location.href = url;
|
||||
return window;
|
||||
};
|
||||
</script></head>`
|
||||
);
|
||||
res.set('Content-Type', 'text/html');
|
||||
res.set('Cache-Control', 'no-store, no-cache, must-revalidate, private');
|
||||
res.set('Expires', '-1');
|
||||
res.set('Pragma', 'no-cache');
|
||||
res.send(injected);
|
||||
});
|
||||
};
|
||||
}
|
||||
|
||||
const cmdApp = express();
|
||||
cmdApp.use((req, res, next) => {
|
||||
res.header('Access-Control-Allow-Origin', '*');
|
||||
res.header('Access-Control-Allow-Methods', 'GET,POST,OPTIONS');
|
||||
res.header('Access-Control-Allow-Headers', '*');
|
||||
if (req.method === 'OPTIONS') return res.sendStatus(200);
|
||||
next();
|
||||
});
|
||||
cmdApp.all('/update/:choice', (req, res) => {
|
||||
const c = String(req.params.choice).toLowerCase();
|
||||
if (updateDecisionHandler) {
|
||||
if (c === 'yes' || c === 'true' || c === 'install') updateDecisionHandler(true);
|
||||
if (c === 'no' || c === 'false' || c === 'skip') updateDecisionHandler(false);
|
||||
}
|
||||
res.sendStatus(200);
|
||||
});
|
||||
cmdApp.get('/__tauri_cmd/:cmd', (req, res) => {
|
||||
const cmd = req.params.cmd;
|
||||
if (updateDecisionHandler) {
|
||||
if (cmd === 'update_yes' || cmd === 'update_install') updateDecisionHandler(true);
|
||||
if (cmd === 'update_no' || cmd === 'update_skip') updateDecisionHandler(false);
|
||||
}
|
||||
debugLog(`[CMD-SERVER:4892] Command received: ${req.params.cmd} (window: ${req.query.window || 'main'})`);
|
||||
sendToTauri('tauri-cmd', { cmd: req.params.cmd, url: req.query.url, window: req.query.window });
|
||||
res.sendStatus(200);
|
||||
});
|
||||
cmdApp.listen(4892, '127.0.0.1', () => debugLog("[CMD-SERVER] Dedicated command server listening on port 4892"));
|
||||
|
||||
process.stdin.resume();
|
||||
process.stdin.on('end', () => {
|
||||
debugLog('stdin closed - parent died. Self-terminating...');
|
||||
@@ -146,6 +83,85 @@ function getReplacementsConfig() {
|
||||
}
|
||||
|
||||
const updateClient = new UpdateClient(APPDATA_DIR);
|
||||
const fileUpdater = new FileUpdater(APPDATA_DIR, updateClient);
|
||||
let lastFilePercent = -1;
|
||||
fileUpdater.onProgress = (downloaded, total) => {
|
||||
const percent = total > 0 ? Math.round((downloaded / total) * 100) : 0;
|
||||
if (percent === lastFilePercent) return;
|
||||
lastFilePercent = percent;
|
||||
sendToTauri('download-progress', { downloaded, total, percent });
|
||||
};
|
||||
|
||||
function withTimeout(promise, ms) {
|
||||
return Promise.race([promise, new Promise((resolve) => setTimeout(() => resolve(null), ms))]);
|
||||
}
|
||||
|
||||
function portInUse(port) {
|
||||
return new Promise((resolve) => {
|
||||
const socket = new (require('net').Socket)();
|
||||
socket.setTimeout(500);
|
||||
socket.once('connect', () => {
|
||||
socket.destroy();
|
||||
resolve(true);
|
||||
});
|
||||
socket.once('error', () => resolve(false));
|
||||
socket.once('timeout', () => {
|
||||
socket.destroy();
|
||||
resolve(false);
|
||||
});
|
||||
socket.connect(port, '127.0.0.1');
|
||||
});
|
||||
}
|
||||
|
||||
function promptUser(event, payload, timeoutMs = 120000) {
|
||||
return new Promise((resolve) => {
|
||||
const token = require('crypto').randomBytes(24).toString('hex');
|
||||
const app = express();
|
||||
let server = null;
|
||||
let finished = false;
|
||||
let timer = null;
|
||||
|
||||
const finish = (result) => {
|
||||
if (finished) return;
|
||||
finished = true;
|
||||
clearTimeout(timer);
|
||||
if (server) server.close();
|
||||
resolve(result);
|
||||
};
|
||||
|
||||
timer = setTimeout(() => finish(null), timeoutMs);
|
||||
|
||||
app.use((req, res, next) => {
|
||||
const ip = req.socket.remoteAddress;
|
||||
if (ip !== '127.0.0.1' && ip !== '::1' && ip !== '::ffff:127.0.0.1') {
|
||||
return res.status(403).end();
|
||||
}
|
||||
res.header('Access-Control-Allow-Origin', '*');
|
||||
res.header('Access-Control-Allow-Methods', 'POST,OPTIONS');
|
||||
res.header('Access-Control-Allow-Headers', 'Content-Type');
|
||||
if (req.method === 'OPTIONS') return res.sendStatus(200);
|
||||
next();
|
||||
});
|
||||
|
||||
app.post('/prompt/answer', express.json({ limit: '64kb' }), (req, res) => {
|
||||
const body = req.body || {};
|
||||
if (body.token !== token) return res.status(403).end();
|
||||
res.sendStatus(200);
|
||||
finish({
|
||||
accept: body.accept === true,
|
||||
files: Array.isArray(body.files) ? body.files.map(String) : []
|
||||
});
|
||||
});
|
||||
|
||||
server = app.listen(4891, '127.0.0.1', () => {
|
||||
sendToTauri(event, { ...payload, token });
|
||||
});
|
||||
server.on('error', (err) => {
|
||||
debugLog(`Prompt server bind error: ${err.message}`);
|
||||
finish(null);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
async function start() {
|
||||
debugLog("Inside start() function");
|
||||
@@ -212,6 +228,7 @@ async function start() {
|
||||
|
||||
debugLog('Extraction complete. Applying patches...');
|
||||
sendToTauri('status', { message: 'Applying configuration patches...' });
|
||||
fileUpdater.snapshotBase();
|
||||
patcher.applyPatches(getReplacementsConfig());
|
||||
|
||||
sendToTauri('status', { message: 'Migrating security credentials...' });
|
||||
@@ -246,44 +263,12 @@ async function start() {
|
||||
const localSha = patcher.getCurrentSha();
|
||||
debugLog(`Is First Run: ${isFirstRun}, Local Version: ${localVersion}, Local SHA: ${localSha}`);
|
||||
|
||||
function findLocalZip() {
|
||||
const searchRoots = [__dirname, process.cwd(), path.join(__dirname, '../../..')];
|
||||
for (const root of searchRoots) {
|
||||
let cur = root;
|
||||
for (let i = 0; i < 6; i++) {
|
||||
try {
|
||||
const zp = path.join(cur, 'update-payload.zip');
|
||||
if (fs.existsSync(zp)) {
|
||||
const mp = path.join(cur, 'manifest.json');
|
||||
return { zipPath: zp, manifestPath: fs.existsSync(mp) ? mp : null };
|
||||
}
|
||||
const parent = path.dirname(cur);
|
||||
if (parent === cur) break;
|
||||
cur = parent;
|
||||
} catch (e) { }
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
let localZipPath = null;
|
||||
let localManifestPath = null;
|
||||
let localZipManifest = null;
|
||||
|
||||
sendToTauri('status', { message: 'Connecting to update servers...' });
|
||||
let release = null;
|
||||
try {
|
||||
debugLog("Fetching updates from updateClient...");
|
||||
release = await updateClient.checkForUpdates();
|
||||
debugLog(`Update check finished. Found: ${release ? release.version : 'None'}`);
|
||||
|
||||
let appPkgVer = '0.0.0';
|
||||
try {
|
||||
appPkgVer = JSON.parse(fs.readFileSync(path.join(__dirname, 'package.json'), 'utf8')).version || '0.0.0';
|
||||
} catch (e) { }
|
||||
|
||||
if (release && release.version) {
|
||||
}
|
||||
} catch (e) {
|
||||
debugLog(`Update check failed (offline?): ${e.message}`);
|
||||
sendToTauri('status', { message: `Update server check skipped (${e.message})` });
|
||||
@@ -306,39 +291,32 @@ async function start() {
|
||||
const versionNewer = isNewer(release.version, localVersion);
|
||||
const sameVerNewBuild = normalizeVer(release.version) === normalizeVer(localVersion) &&
|
||||
!!release.sha256 && !!localSha && release.sha256 !== localSha;
|
||||
const hasUpdate = (versionNewer || sameVerNewBuild) && !localZipPath;
|
||||
const hasUpdate = versionNewer;
|
||||
|
||||
if (isFirstRun) {
|
||||
debugLog("First run with no local payload. Installing remote build...");
|
||||
sendToTauri('status', { message: 'First run detected. Preparing initial installation...' });
|
||||
await installBuild(release);
|
||||
} else if (hasUpdate) {
|
||||
|
||||
debugLog("Update available. Prompting user...");
|
||||
sendToTauri('status', { message: `New update available (${release.version}).` });
|
||||
|
||||
try {
|
||||
if (process.platform === 'win32') {
|
||||
require('child_process').spawnSync('powershell.exe', [
|
||||
'-NoProfile', '-NonInteractive', '-Command',
|
||||
`Get-NetTCPConnection -LocalPort 4891 -ErrorAction SilentlyContinue | ForEach-Object { Stop-Process -Id $_.OwningProcess -Force }`
|
||||
], { stdio: 'ignore', windowsHide: true });
|
||||
} else {
|
||||
require('child_process').spawnSync('fuser', ['-k', '-9', `4891/tcp`], { stdio: 'ignore' });
|
||||
}
|
||||
} catch (e) { }
|
||||
|
||||
const tempApp = express();
|
||||
let userDecision = null;
|
||||
updateDecisionHandler = (val) => { userDecision = val; };
|
||||
|
||||
tempApp.use((req, res, next) => {
|
||||
const clientIp = req.socket.remoteAddress;
|
||||
if (clientIp !== '127.0.0.1' && clientIp !== '::1' && clientIp !== '::ffff:127.0.0.1') {
|
||||
return res.status(403).end();
|
||||
}
|
||||
res.header('Access-Control-Allow-Origin', '*');
|
||||
res.header('Access-Control-Allow-Methods', 'GET,POST,OPTIONS');
|
||||
res.header('Access-Control-Allow-Headers', '*');
|
||||
if (req.method === 'OPTIONS') return res.sendStatus(200);
|
||||
next();
|
||||
});
|
||||
|
||||
tempApp.get('/update/info', (req, res) => {
|
||||
res.json({ available: true, current: localVersion, latest: release.version });
|
||||
});
|
||||
@@ -364,7 +342,11 @@ async function start() {
|
||||
});
|
||||
});
|
||||
|
||||
sendToTauri('update-available', { current: localVersion, latest: release.version });
|
||||
if (!tempServer) {
|
||||
userDecision = false;
|
||||
} else {
|
||||
sendToTauri('update-available', { current: localVersion, latest: release.version });
|
||||
}
|
||||
|
||||
let waitLoops = 0;
|
||||
while (userDecision === null) {
|
||||
@@ -401,6 +383,7 @@ async function start() {
|
||||
sendToTauri('status', { message: 'Extracting local baseline payload...' });
|
||||
patcher.purgeOldCode();
|
||||
patcher.extractZipPayload(localZip);
|
||||
fileUpdater.snapshotBase();
|
||||
patcher.applyPatches(getReplacementsConfig());
|
||||
patcher.bridgeCredentials(serviceManager.credentialManager);
|
||||
|
||||
@@ -420,23 +403,93 @@ async function start() {
|
||||
|
||||
sendToTauri('status', { message: 'Validating critical components...' });
|
||||
if (!patcher.verifyExtraction()) {
|
||||
throw new Error('No application files found. Ensure you ran "npm run build:payload" and the extraction succeeded.');
|
||||
throw new Error('Could not download the app files. Check your internet connection and relaunch.');
|
||||
}
|
||||
|
||||
if (process.env.VYLA_TEST_UI === '1') {
|
||||
const fakeFiles = [
|
||||
{ path: 'frontend/server.js', status: 'modified', size: 1024 },
|
||||
{ path: 'frontend/public/app.js', status: 'modified', size: 2048 },
|
||||
{ path: 'player/server.js', status: 'modified', size: 512 },
|
||||
{ path: 'player/lib/new-file.js', status: 'added', size: 256 }
|
||||
];
|
||||
const filesAnswer = await promptUser('files-available', { files: fakeFiles });
|
||||
debugLog(`TEST files answer: ${JSON.stringify(filesAnswer)}`);
|
||||
if (filesAnswer && filesAnswer.accept) {
|
||||
for (let i = 1; i <= filesAnswer.files.length; i++) {
|
||||
sendToTauri('extract-progress', {
|
||||
file: filesAnswer.files[i - 1],
|
||||
done: i,
|
||||
total: filesAnswer.files.length,
|
||||
percent: Math.round((i / filesAnswer.files.length) * 100)
|
||||
});
|
||||
await new Promise((r) => setTimeout(r, 400));
|
||||
}
|
||||
}
|
||||
const sdkAnswer = await promptUser('sdk-available', { current: '1.19.0', latest: '1.20.0' });
|
||||
debugLog(`TEST sdk answer: ${JSON.stringify(sdkAnswer)}`);
|
||||
sendToTauri('status', { message: sdkAnswer && sdkAnswer.accept ? 'TEST: SDK accepted' : 'TEST: SDK skipped' });
|
||||
await new Promise((r) => setTimeout(r, 1500));
|
||||
}
|
||||
|
||||
sendToTauri('status', { message: 'Checking UI files and SDK...' });
|
||||
const [filesCheck, sdkCheck] = await Promise.all([
|
||||
withTimeout(fileUpdater.checkFiles().catch((e) => {
|
||||
debugLog(`File check failed: ${e.message}`);
|
||||
return null;
|
||||
}), 180000),
|
||||
withTimeout(fileUpdater.checkSdk().catch((e) => {
|
||||
debugLog(`SDK check failed: ${e.message}`);
|
||||
return null;
|
||||
}), 12000)
|
||||
]);
|
||||
|
||||
if (filesCheck && filesCheck.changes.length > 0) {
|
||||
sendToTauri('status', { message: `${filesCheck.changes.length} file update(s) available.` });
|
||||
const answer = await promptUser('files-available', {
|
||||
files: filesCheck.changes.map((c) => ({ path: c.path, status: c.status, size: c.size }))
|
||||
});
|
||||
if (answer && answer.accept) {
|
||||
const allowed = new Set(answer.files);
|
||||
const selected = filesCheck.changes.filter((c) => allowed.has(c.path));
|
||||
if (selected.length > 0) {
|
||||
try {
|
||||
await fileUpdater.applyFiles(selected, filesCheck.seq, getReplacementsConfig(), (file, done, total) => {
|
||||
sendToTauri('extract-progress', { file, done, total, percent: Math.round((done / total) * 100) });
|
||||
});
|
||||
sendToTauri('status', { message: `Updated ${selected.length} file(s).` });
|
||||
} catch (e) {
|
||||
debugLog(`File update failed: ${e.message}`);
|
||||
sendToTauri('status', { message: `File update failed: ${e.message}` });
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (sdkCheck && sdkCheck.outdated) {
|
||||
sendToTauri('status', { message: `SDK update available (${sdkCheck.latest}).` });
|
||||
const answer = await promptUser('sdk-available', { current: sdkCheck.current, latest: sdkCheck.latest });
|
||||
if (answer && answer.accept) {
|
||||
try {
|
||||
sendToTauri('status', { message: `Installing SDK ${sdkCheck.latest}...` });
|
||||
await fileUpdater.installSdk(sdkCheck);
|
||||
sendToTauri('status', { message: `SDK updated to ${sdkCheck.latest}.` });
|
||||
} catch (e) {
|
||||
debugLog(`SDK install failed: ${e.message}`);
|
||||
sendToTauri('status', { message: `SDK update failed: ${e.message}` });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
sendToTauri('status', { message: 'Loading encrypted credentials...' });
|
||||
serviceManager.credentialManager.loadCredentials();
|
||||
|
||||
sendToTauri('status', { message: 'Installing dependencies...' });
|
||||
const npmCmd = process.platform === 'win32' ? 'npm.cmd' : 'npm';
|
||||
const frontendDir = path.join(APPDATA_DIR, 'frontend');
|
||||
if (fs.existsSync(path.join(frontendDir, 'package.json'))) {
|
||||
const { spawnSync } = require('child_process');
|
||||
spawnSync(npmCmd, ['install'], {
|
||||
cwd: frontendDir,
|
||||
stdio: 'ignore',
|
||||
windowsHide: true,
|
||||
shell: process.platform === 'win32'
|
||||
});
|
||||
const busyPorts = [];
|
||||
for (const port of [3000, 4890]) {
|
||||
if (await portInUse(port)) busyPorts.push(port);
|
||||
}
|
||||
if (busyPorts.length > 0) {
|
||||
throw new Error(`Port ${busyPorts.join(' and ')} is already in use by another program. Close it or any other running Vyla Home, then relaunch.`);
|
||||
}
|
||||
|
||||
sendToTauri('status', { message: 'Starting services (player, frontend)...' });
|
||||
@@ -447,7 +500,11 @@ async function start() {
|
||||
debugLog("Backend services spawn requested.");
|
||||
|
||||
sendToTauri('status', { message: 'Waiting for microservices to bind...' });
|
||||
await serviceManager.waitForPorts([3000, 4890]);
|
||||
try {
|
||||
await serviceManager.waitForPorts([3000, 4890], 60000);
|
||||
} catch (e) {
|
||||
throw new Error(`${e.message}. Check logs in ${LOGS_DIR}`);
|
||||
}
|
||||
debugLog("Ports 3000 and 4890 are ready.");
|
||||
|
||||
sendToTauri('status', { message: 'All backend services running and healthy.' });
|
||||
@@ -462,18 +519,7 @@ async function start() {
|
||||
|
||||
process.on('exit', () => {
|
||||
if (serviceManager) {
|
||||
for (const name of Object.keys(serviceManager.processes)) {
|
||||
const proc = serviceManager.processes[name];
|
||||
if (proc && proc.child && proc.child.pid) {
|
||||
try {
|
||||
if (process.platform === 'win32') {
|
||||
require('child_process').spawnSync('taskkill', ['/F', '/T', '/PID', proc.child.pid.toString()], { stdio: 'ignore', windowsHide: true });
|
||||
} else {
|
||||
process.kill(-proc.child.pid, 'SIGKILL');
|
||||
}
|
||||
} catch (e) { }
|
||||
}
|
||||
}
|
||||
serviceManager.stopAll();
|
||||
}
|
||||
});
|
||||
|
||||
@@ -484,4 +530,4 @@ process.on('SIGTERM', () => {
|
||||
process.exit(0);
|
||||
});
|
||||
|
||||
start();
|
||||
start();
|
||||
|
||||
Reference in New Issue
Block a user