File size: 8,528 Bytes
0e0fe0a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
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);
  });
});