-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathserver.js
More file actions
348 lines (300 loc) · 10.8 KB
/
Copy pathserver.js
File metadata and controls
348 lines (300 loc) · 10.8 KB
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
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
const express = require('express');
const cors = require('cors');
const path = require('path');
const { spawn } = require('child_process');
const WebSocket = require('ws');
const http = require('http');
const fs = require('fs');
const app = express();
const server = http.createServer(app);
const wss = new WebSocket.Server({ server, path: '/ws' });
const PORT = process.env.PORT || 3000;
const SCRIPT_PATH = path.join(__dirname, 'Invoke-M365AppsHelper.ps1');
// Track current process
let currentProcess = null;
console.log(`[Server] Script path: ${SCRIPT_PATH}`);
console.log(`[Server] Script exists: ${fs.existsSync(SCRIPT_PATH)}`);
// Middleware
app.use(cors());
app.use(express.json());
app.use(express.static(path.join(__dirname, 'src')));
// Store active connections
const clients = new Set();
// WebSocket connection handler
wss.on('connection', (ws) => {
console.log('[WebSocket] Client connected');
clients.add(ws);
ws.send(JSON.stringify({
type: 'status',
message: 'Ready',
severity: 'idle'
}));
ws.on('close', () => {
console.log('[WebSocket] Client disconnected');
clients.delete(ws);
});
ws.on('error', (error) => {
console.error('[WebSocket] Error:', error.message);
});
});
// Broadcast to all connected clients
function broadcast(message) {
clients.forEach((client) => {
if (client.readyState === WebSocket.OPEN) {
try {
client.send(JSON.stringify(message));
} catch (error) {
console.error('[Broadcast] Error:', error.message);
}
}
});
}
// API: Execute PowerShell script
app.post('/api/execute', (req, res) => {
const {
configXml,
logName = path.join(process.env.APPDATA || '', 'M365AppsHelper', 'Output', 'Logs', 'Invoke-M365AppsHelper.log'),
noZip = false,
onlineMode = false,
skipAPICheck = false,
pmpcCustomApp = false,
createIntuneWin = false,
apiRetryDelaySeconds = 3,
apiMaxExtendedAttempts = 10,
setupUrl = 'https://officecdn.microsoft.com/pr/wsus/setup.exe',
officeVersionUrl = 'https://clients.config.office.net/releases/v1.0/OfficeReleases',
officeIconUrl = 'https://patchmypc.com/scupcatalog/downloads/icons/Microsoft.png',
} = req.body;
console.log('[Execute] Received from frontend:');
console.log(' noZip:', noZip, '(type:', typeof noZip, ')');
console.log(' onlineMode:', onlineMode, '(type:', typeof onlineMode, ')');
console.log(' pmpcCustomApp:', pmpcCustomApp, '(type:', typeof pmpcCustomApp, ')');
console.log(' createIntuneWin:', createIntuneWin, '(type:', typeof createIntuneWin, ')');
// NoZip should ONLY be passed if PMPCCustomApp is selected AND noZip checkbox is checked AND OnlineMode is NOT active
const effectiveNoZip = Boolean(pmpcCustomApp && noZip && !onlineMode);
// CreateIntuneWin can work with OnlineMode, so don't add !onlineMode condition
const effectiveCreateIntuneWin = Boolean(createIntuneWin);
console.log('[Execute] After processing:');
console.log(' effectiveNoZip:', effectiveNoZip);
console.log(' effectiveCreateIntuneWin:', effectiveCreateIntuneWin);
console.log(' Starting deployment with config:', configXml);
console.log('[Execute] PMPCCustomApp:', pmpcCustomApp, '| OnlineMode:', onlineMode, '| EffectiveNoZip:', effectiveNoZip);
broadcast({
type: 'log',
message: 'Starting Office deployment package creation...',
severity: 'info',
timestamp: new Date().toISOString()
});
// Build PowerShell command - use absolute paths to avoid issues
const workingDir = path.dirname(SCRIPT_PATH);
// Helper to resolve paths only when they are not already absolute
const resolvePathIfNeeded = (p) => {
if (!p || p === 'undefined' || !p.trim()) return null;
return path.isAbsolute(p) ? p : path.resolve(workingDir, p);
};
let args = [
'-NoProfile',
'-ExecutionPolicy', 'Bypass',
'-File', SCRIPT_PATH
];
const cfgPath = resolvePathIfNeeded(configXml);
const logPath = resolvePathIfNeeded(logName);
if (cfgPath) {
args.push('-ConfigXML');
args.push(cfgPath);
}
if (logPath) {
args.push('-LogName');
args.push(logPath);
}
if (setupUrl) args.push('-SetupUrl', setupUrl);
if (officeVersionUrl) args.push('-OfficeVersionUrl', officeVersionUrl);
if (officeIconUrl) args.push('-OfficeIconUrl', officeIconUrl);
if (apiRetryDelaySeconds) args.push('-ApiRetryDelaySeconds', apiRetryDelaySeconds.toString());
if (apiMaxExtendedAttempts) args.push('-ApiMaxExtendedAttempts', apiMaxExtendedAttempts.toString());
if (effectiveNoZip) args.push('-NoZip');
if (onlineMode) args.push('-OnlineMode');
if (skipAPICheck) args.push('-SkipAPICheck');
if (pmpcCustomApp) args.push('-PMPCCustomApp');
if (effectiveCreateIntuneWin) args.push('-CreateIntuneWin');
console.log('[Execute] Full command:');
console.log(' Executable:', 'pwsh.exe');
console.log(' Arguments:', JSON.stringify(args, null, 2));
// Spawn PowerShell process (use pwsh.exe for PowerShell 7+, fallback to powershell.exe)
const psExecutable = 'pwsh.exe'; // PowerShell 7+ required for null-coalescing operators
const ps = spawn(psExecutable, args, {
stdio: ['pipe', 'pipe', 'pipe'],
shell: false,
cwd: path.dirname(SCRIPT_PATH)
});
// Track current process
currentProcess = ps;
let output = '';
let errors = '';
let progressCounter = 0;
let actualPackagePath = null; // Store the actual package folder path
ps.stdout.on('data', (data) => {
const message = data.toString().trim();
if (message) {
output += message + '\n';
console.log('[PS Output]', message);
// Capture the actual package path from success messages
const packagePathMatch = message.match(/M365 Office deployment package created (?:with zip compression |without zip compression )?at (.+?)$/i);
if (packagePathMatch && packagePathMatch[1]) {
actualPackagePath = packagePathMatch[1].trim();
console.log('[Package Path] Captured:', actualPackagePath);
}
// Determine if this is a details/instruction message (for PatchMyPC custom app info, configuration details, etc.)
const detailsKeywords = ['PatchMyPC', 'Custom App', 'Configuration', 'Channel:', 'Version:', 'contains:', 'Package Contents', 'custom app information'];
const isDetailsMessage = detailsKeywords.some(keyword => message.includes(keyword));
// Check for progress markers
if (message.includes('[PROGRESS]')) {
// Extract progress message
const progressMsg = message.replace('[PROGRESS]', '').trim();
// Send status update
broadcast({
type: 'status',
message: progressMsg,
severity: 'running'
});
// Update progress bar
if (message.includes('Downloading')) {
progressCounter = Math.min(progressCounter + 15, 85);
} else if (message.includes('complete') || message.includes('Complete')) {
progressCounter = 95;
}
broadcast({
type: 'progress',
percent: progressCounter,
speed: progressMsg
});
console.log('[Progress]', progressMsg, `${progressCounter}%`);
} else {
// Send message to appropriate log section
broadcast({
type: isDetailsMessage ? 'details' : 'log',
message,
severity: 'info',
timestamp: new Date().toISOString()
});
// Also detect regular downloading messages for progress
if (message.toLowerCase().includes('downloading')) {
progressCounter += 10;
if (progressCounter <= 90) {
broadcast({
type: 'progress',
percent: progressCounter,
speed: 'Downloading files...'
});
}
}
}
}
});
ps.stderr.on('data', (data) => {
const message = data.toString().trim();
if (message) {
errors += message + '\n';
console.log('[PS Error]', message);
broadcast({
type: 'log',
message,
severity: 'error',
timestamp: new Date().toISOString()
});
}
});
ps.on('close', (code) => {
console.log('[Execute] Process closed with code:', code);
if (code === 0) {
// Send final progress
broadcast({
type: 'progress',
percent: 100,
speed: 'Complete'
});
broadcast({
type: 'complete',
success: true,
message: 'Office package created successfully!',
outputPath: actualPackagePath, // Captured path from script logs if available
code
});
} else {
broadcast({
type: 'complete',
success: false,
message: `Process exited with code ${code}`,
code,
errors
});
}
});
ps.on('error', (err) => {
console.error('[Execute] Process error:', err.message);
broadcast({
type: 'log',
message: `Process error: ${err.message}`,
severity: 'error',
timestamp: new Date().toISOString()
});
broadcast({
type: 'complete',
success: false,
message: `Failed to start PowerShell: ${err.message}`,
code: -1,
errors: err.message
});
});
res.json({ success: true, message: 'Process started' });
});
// API: Stop running process
app.post('/api/stop', (req, res) => {
if (currentProcess && !currentProcess.killed) {
console.log('[Stop] Terminating process PID:', currentProcess.pid);
broadcast({
type: 'log',
message: 'Stop signal received, terminating process...',
severity: 'warning',
timestamp: new Date().toISOString()
});
currentProcess.kill('SIGTERM');
// Force kill after 3 seconds if not already dead
setTimeout(() => {
if (currentProcess && !currentProcess.killed) {
console.log('[Stop] Force killing process');
currentProcess.kill('SIGKILL');
}
}, 3000);
res.json({ success: true, message: 'Stop signal sent' });
} else {
res.status(400).json({ success: false, message: 'No process running' });
}
});
// API: Get available XML files
app.get('/api/xml-files', (req, res) => {
try {
const currentDir = process.cwd();
const files = fs.readdirSync(currentDir)
.filter(f => f.endsWith('.xml'))
.map(f => ({ name: f, path: path.join(currentDir, f) }));
res.json(files);
} catch (error) {
res.status(400).json({ error: error.message });
}
});
// Serve index.html for all other routes (SPA)
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname, 'src', 'index.html'));
});
server.listen(PORT, () => {
console.log(`\n✓ M365 Office UI running on http://localhost:${PORT}`);
console.log('✓ WebSocket server ready for real-time updates\n');
});
// Graceful shutdown
process.on('SIGINT', () => {
console.log('\nShutting down...');
server.close(() => {
process.exit(0);
});
});