SmartySmile's picture
Upload 45 files
0e0fe0a verified
Raw History Blame Contribute Delete
8.53 kB
const { app, BrowserWindow, Menu, ipcMain } = require('electron');
const path = require('path');
const { spawn } = require('child_process');
const fs = require('fs');
const express = require('express');
const expressApp = express();
const PORT = 3000;
let mainWindow;
let runningApps = {};
// Create Express server
expressApp.use(express.json());
expressApp.use(express.static('public'));
// Serve the UI
expressApp.get('/', (req, res) => {
res.sendFile(path.join(__dirname, 'public', 'index.html'));
});
// API endpoint to get available apps
expressApp.get('/api/apps', (req, res) => {
console.log('\n=== APP DISCOVERY REQUEST ===');
const appsData = discoverApps();
console.log(`Total apps found: ${appsData.length}\n`);
res.json(appsData);
});
// API endpoint to launch an app
expressApp.post('/api/apps/:appId/launch', (req, res) => {
const { appId } = req.params;
const apps = discoverApps();
const app = apps.find(a => a.id === appId);
if (!app) {
return res.status(404).json({ error: 'App not found' });
}
launchApp(app);
res.json({ status: 'launching', url: app.url });
});
// API endpoint to get app status
expressApp.get('/api/apps/:appId/status', (req, res) => {
const { appId } = req.params;
const isRunning = runningApps[appId];
res.json({ running: !!isRunning });
});
// API endpoint to stop an app
expressApp.post('/api/apps/:appId/stop', (req, res) => {
const { appId } = req.params;
if (runningApps[appId]) {
runningApps[appId].kill();
delete runningApps[appId];
res.json({ status: 'stopped' });
} else {
res.json({ status: 'not running' });
}
});
function discoverApps() {
const apps = [];
const rootDir = path.join(__dirname);
console.log(`📁 Scanning from: ${rootDir}`);
// Recursive directory scanner
function scanDir(currentPath, depth = 0) {
// Limit depth to 5 levels
if (depth > 5) {
console.log(`⏹️ Depth limit reached at: ${currentPath}`);
return;
}
try {
const entries = fs.readdirSync(currentPath, { withFileTypes: true });
console.log(`📂 Level ${depth}: Scanning ${entries.length} items in ${path.basename(currentPath)}`);
for (const entry of entries) {
// Skip hidden files and common folders
if (entry.name.startsWith('.') || ['node_modules', '.git', 'obj', 'bin'].includes(entry.name)) {
continue;
}
if (entry.isDirectory()) {
const fullPath = path.join(currentPath, entry.name);
// Check if this directory contains .csproj files
try {
const dirContents = fs.readdirSync(fullPath);
const csprojFiles = dirContents.filter(f => f.endsWith('.csproj'));
if (csprojFiles.length > 0) {
console.log(`✅ Found .csproj file(s) in ${entry.name}: ${csprojFiles.join(', ')}`);
// Process each .csproj file
for (const csprojFile of csprojFiles) {
const appName = csprojFile.replace('.csproj', '');
const launchSettingsPath = path.join(fullPath, 'Properties', 'launchSettings.json');
console.log(` Checking for launchSettings at: ${launchSettingsPath}`);
if (fs.existsSync(launchSettingsPath)) {
try {
let settingsContent = fs.readFileSync(launchSettingsPath, 'utf8');
// Remove BOM if present
if (settingsContent.charCodeAt(0) === 0xFEFF) {
settingsContent = settingsContent.slice(1);
}
const launchSettings = JSON.parse(settingsContent);
// Try to find an HTTP profile
const httpProfile = launchSettings.profiles?.http ||
launchSettings.profiles?.https ||
Object.values(launchSettings.profiles || {})[0];
if (httpProfile && httpProfile.applicationUrl) {
const url = httpProfile.applicationUrl.split(';')[0]; // Get first URL if multiple
const appId = appName.toLowerCase().replace(/[^a-z0-9]/g, '-');
console.log(`🎯 REGISTERED: ${appName} (ID: ${appId})`);
console.log(` URL: ${url}`);
console.log(` Path: ${fullPath}\n`);
apps.push({
id: appId,
name: appName,
displayName: formatAppName(appName),
path: fullPath,
url: url,
description: `${appName} - ASP.NET Core MVC Application`
});
} else {
console.log(` ⚠️ No HTTP/HTTPS profile found in launchSettings\n`);
}
} catch (parseError) {
console.log(` ❌ Error parsing launchSettings.json: ${parseError.message}\n`);
}
} else {
console.log(` ⚠️ launchSettings.json not found\n`);
}
}
}
} catch (readError) {
// Silently skip folders we can't read
}
// Recursively scan subdirectories
scanDir(fullPath, depth + 1);
}
}
} catch (scanError) {
console.error(`❌ Error scanning ${currentPath}: ${scanError.message}`);
}
}
scanDir(rootDir);
console.log(`\n✨ Discovery complete: ${apps.length} MVC app(s) found\n`);
return apps;
}
function formatAppName(name) {
return name.replace(/([A-Z])/g, ' $1').trim().replace(/\b\w/g, l => l.toUpperCase());
}
function launchApp(app) {
if (runningApps[app.id]) {
console.log(`${app.name} is already running`);
return;
}
console.log(`Launching ${app.name} from ${app.path}...`);
const dotnetPath = 'dotnet';
const child = spawn(dotnetPath, ['run', '--project', app.path], {
cwd: app.path,
stdio: 'pipe',
shell: true,
env: { ...process.env, ASPNETCORE_ENVIRONMENT: 'Development' }
});
child.stdout.on('data', (data) => {
console.log(`[${app.name}] ${data}`);
});
child.stderr.on('data', (data) => {
console.error(`[${app.name}] ${data}`);
});
child.on('error', (error) => {
console.error(`Failed to launch ${app.name}:`, error.message);
delete runningApps[app.id];
});
child.on('exit', (code) => {
console.log(`${app.name} exited with code ${code}`);
delete runningApps[app.id];
});
runningApps[app.id] = child;
console.log(`${app.name} launched successfully`);
}
// Create Electron window
function createWindow() {
mainWindow = new BrowserWindow({
width: 1200,
height: 800,
webPreferences: {
nodeIntegration: false,
contextIsolation: true,
preload: path.join(__dirname, 'preload.js')
},
icon: path.join(__dirname, 'public', 'app-icon.png')
});
mainWindow.loadURL(`http://localhost:${PORT}`);
// Open DevTools in development mode
// mainWindow.webContents.openDevTools();
mainWindow.on('closed', () => {
// Kill all running apps
Object.values(runningApps).forEach(app => {
try {
app.kill();
} catch (e) {
// Already dead
}
});
mainWindow = null;
});
}
// Start Express server
const server = expressApp.listen(PORT, () => {
console.log(`Express server running on port ${PORT}`);
});
// Electron app events
app.on('ready', createWindow);
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') {
app.quit();
}
});
app.on('activate', () => {
if (mainWindow === null) {
createWindow();
}
});
// Graceful shutdown
process.on('SIGINT', () => {
console.log('Shutting down gracefully...');
server.close(() => {
Object.values(runningApps).forEach(proc => {
try {
proc.kill();
} catch (e) {
// Already dead
}
});
process.exit(0);
});
});