-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathjava_handler.json
More file actions
442 lines (442 loc) · 35.8 KB
/
java_handler.json
File metadata and controls
442 lines (442 loc) · 35.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
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
[
" * install-java - เธ”เธฒเธงเธเนเนเธซเธฅเธ”เนเธฅเธฐเธ•เธดเธ”เธ•เธฑเนเธ Java (with progress events)",
" */",
" ipcMain.handle(\"install-java\", async (_event, majorVersion: number) => {",
" const https = await import(\"node:https\");",
" const { createWriteStream } = await import(\"node:fs\");",
" const { spawn } = await import(\"node:child_process\");",
" const native = getNativeModule() as any;",
"",
" console.log(`[Java] Starting installation of Java ${majorVersion}`);",
"",
" // Helper to send progress to renderer",
" const sendProgress = (phase: string, percent: number, message: string) => {",
" const mainWindow = getMainWindow();",
" if (mainWindow) {",
" mainWindow.webContents.send(\"java-install-progress\", {",
" majorVersion,",
" phase,",
" percent,",
" message,",
" });",
" }",
" };",
"",
" try {",
" const featureVersion = majorVersion;",
"",
" const javaBaseDir = path.join(getAppDataDir(), \"java\");",
" if (!fs.existsSync(javaBaseDir)) {",
" fs.mkdirSync(javaBaseDir, { recursive: true });",
" }",
"",
" const existingJava = path.join(",
" javaBaseDir,",
" `jdk-${majorVersion}`,",
" \"bin\",",
" \"java.exe\",",
" );",
" if (fs.existsSync(existingJava)) {",
" console.log(",
" `[Java] Java ${majorVersion} already exists at ${existingJava}`,",
" );",
" return { ok: true, path: existingJava };",
" }",
"",
" if (typeof native.installJavaRuntime === \"function\") {",
" try {",
" sendProgress(\"fetch\", 10, \"Preparing Java installation...\");",
" const installedPath = (await native.installJavaRuntime(",
" majorVersion,",
" javaBaseDir,",
" )) as string;",
" sendProgress(\"complete\", 100, \"Java installation complete\");",
" return { ok: true, path: installedPath };",
" } catch (nativeInstallError: any) {",
" console.warn(\"[Java] Native installJavaRuntime failed, fallback to JS:\", nativeInstallError?.message || nativeInstallError);",
" }",
" }",
"",
" sendProgress(\"fetch\", 0, \"เธเธณเธฅเธฑเธเธ”เธถเธเธเนเธญเธกเธนเธฅ...\");",
" console.log(",
" `[Java] Fetching Azul Zulu metadata for Java ${featureVersion}...`,",
" );",
"",
" const azulOs =",
" process.platform === \"win32\"",
" ? \"windows\"",
" : process.platform === \"darwin\"",
" ? \"macos\"",
" : \"linux\";",
" const azulArch =",
" process.arch === \"arm64\"",
" ? \"aarch64\"",
" : process.arch === \"ia32\"",
" ? \"x86\"",
" : \"x64\";",
" const azulQuery = new URLSearchParams({",
" java_version: `${featureVersion}`,",
" os: azulOs,",
" arch: azulArch,",
" archive_type: \"zip\",",
" java_package_type: \"jdk\",",
" javafx_bundled: \"false\",",
" release_status: \"ga\",",
" availability_types: \"CA\",",
" certifications: \"tck\",",
" java_package_features: \"headful\",",
" latest: \"true\",",
" page: \"1\",",
" page_size: \"100\",",
" });",
" const apiUrl = `https://api.azul.com/metadata/v1/zulu/packages/?${azulQuery.toString()}`;",
" const apiResponse = await new Promise<any>((resolve, reject) => {",
" https",
" .get(apiUrl, (res) => {",
" let data = \"\";",
" res.on(\"data\", (chunk) => (data += chunk));",
" res.on(\"end\", () => {",
" try {",
" resolve(JSON.parse(data));",
" } catch (e) {",
" reject(",
" new Error(`Invalid API response: ${data.substring(0, 200)}`),",
" );",
" }",
" });",
" })",
" .on(\"error\", reject);",
" });",
"",
" const zuluPackage = Array.isArray(apiResponse)",
" ? (apiResponse.find((entry: any) => entry?.latest && entry?.download_url) ??",
" apiResponse.find((entry: any) => entry?.download_url))",
" : null;",
" if (!zuluPackage) {",
" console.log(",
" `[Java] No Java ${majorVersion} found in Azul Zulu metadata`,",
" );",
" return {",
" ok: false,",
" error: `Java ${majorVersion} not found from Azul Zulu`,",
" };",
" }",
"",
" const downloadUrl = zuluPackage.download_url;",
" const fileName =",
" zuluPackage.name ||",
" (typeof downloadUrl === \"string\"",
" ? downloadUrl.split(\"/\").pop()?.split(\"?\")[0]",
" : undefined);",
" const fileSize =",
" zuluPackage.size ||",
" zuluPackage.download_size ||",
" zuluPackage.filesize ||",
" 0;",
" if (!downloadUrl || !fileName)",
" return { ok: false, error: \"เนเธกเนเธเธ download URL\" };",
"",
" const fileSizeMB = Math.round(fileSize / 1024 / 1024);",
" sendProgress(",
" \"download\",",
" 0,",
" `เธเธณเธฅเธฑเธเธ”เธฒเธงเธเนเนเธซเธฅเธ” ${fileName} (${fileSizeMB}MB)...`,",
" );",
" console.log(`[Java] Downloading ${fileName} (${fileSizeMB}MB)...`);",
" const zipPath = path.join(javaBaseDir, fileName);",
"",
" if (typeof native.downloadFile === \"function\") {",
" sendProgress(\"download\", 25, \"Downloading with native core...\");",
" const nativeResult = (await native.downloadFile(",
" downloadUrl,",
" zipPath,",
" undefined,",
" undefined,",
" )) as { success?: boolean; error?: string };",
" if (!nativeResult?.success) {",
" throw new Error(nativeResult?.error || \"Native Java download failed\");",
" }",
" sendProgress(\"download\", 100, \"Download complete\");",
" } else {",
" await new Promise<void>((resolve, reject) => {",
" const download = (url: string) => {",
" https",
" .get(url, (res) => {",
" if (res.statusCode === 301 || res.statusCode === 302) {",
" if (res.headers.location) download(res.headers.location);",
" return;",
" }",
" if (res.statusCode !== 200) {",
" reject(new Error(`HTTP ${res.statusCode}`));",
" return;",
" }",
" const file = createWriteStream(zipPath);",
" let downloaded = 0;",
" const total =",
" parseInt(res.headers[\"content-length\"] || \"0\", 10) ||",
" fileSize;",
"",
" res.on(\"data\", (chunk) => {",
" downloaded += chunk.length;",
" const percent =",
" total > 0 ? Math.round((downloaded / total) * 100) : 0;",
" if (percent % 5 === 0 || downloaded === total) {",
" const downloadedMB = Math.round(downloaded / 1024 / 1024);",
" const totalMB = Math.round(total / 1024 / 1024);",
" sendProgress(",
" \"download\",",
" percent,",
" `Downloading ${downloadedMB}/${totalMB} MB (${percent}%)`,",
" );",
" }",
" });",
"",
" res.pipe(file);",
" file.on(\"finish\", () => {",
" file.close();",
" console.log(`[Java] Download complete: ${zipPath}`);",
" resolve();",
" });",
" })",
" .on(\"error\", reject);",
" };",
" download(downloadUrl);",
" });",
" }",
"",
" const extractDir = path.join(javaBaseDir, `temp-${majorVersion}`);",
" sendProgress(\"extract\", 0, \"เธเธณเธฅเธฑเธเนเธ•เธเนเธเธฅเน...\");",
" console.log(`[Java] Extracting to ${extractDir}...`);",
" if (fs.existsSync(extractDir)) fs.rmSync(extractDir, { recursive: true });",
" fs.mkdirSync(extractDir, { recursive: true });",
"",
" const toSignedExitCode = (code: number | null): number | null => {",
" if (code === null) return null;",
" return code > 0x7fffffff ? code - 0x100000000 : code;",
" };",
"",
" const runExtractAttempt = (",
" label: string,",
" command: string,",
" args: string[],",
" ): Promise<void> => {",
" return new Promise<void>((resolve, reject) => {",
" let stderr = \"\";",
" let stdout = \"\";",
" const child = spawn(command, args, {",
" windowsHide: true,",
" });",
"",
" child.stdout?.on(\"data\", (chunk) => {",
" stdout += chunk.toString();",
" });",
"",
" child.stderr?.on(\"data\", (chunk) => {",
" stderr += chunk.toString();",
" });",
"",
" child.on(\"close\", (code) => {",
" if (code === 0) {",
" resolve();",
" return;",
" }",
"",
" const signedCode = toSignedExitCode(code);",
" const codeText =",
" signedCode !== null && signedCode !== code",
" ? `${code} (signed ${signedCode})`",
" : `${code}`;",
" const detail = [stderr.trim(), stdout.trim()]",
" .filter(Boolean)",
" .join(\"\\n\");",
" reject(",
" new Error(",
" `${label} failed with code ${codeText}${detail ? `: ${detail}` : \"\"}`,",
" ),",
" );",
" });",
"",
" child.on(\"error\", (err) => {",
" reject(new Error(`${label} spawn error: ${err.message}`));",
" });",
" });",
" };",
"",
" let extractedByNative = false;",
" if (typeof native.extractZipAsync === \"function\" || typeof native.extractZip === \"function\") {",
" try {",
" const nativeExtract =",
" typeof native.extractZipAsync === \"function\"",
" ? await native.extractZipAsync(zipPath, extractDir, undefined)",
" : await native.extractZip(zipPath, extractDir, undefined);",
" if (nativeExtract?.success === false) {",
" throw new Error(nativeExtract?.error || \"Native extract returned unsuccessful result\");",
" }",
" extractedByNative = true;",
" sendProgress(\"extract\", 100, \"Extraction complete\");",
" } catch (nativeExtractError: any) {",
" console.warn(\"[Java] Native extract failed, fallback to shell tools:\", nativeExtractError?.message || nativeExtractError);",
" if (fs.existsSync(extractDir))",
" fs.rmSync(extractDir, { recursive: true, force: true });",
" fs.mkdirSync(extractDir, { recursive: true });",
" }",
" }",
"",
" if (!extractedByNative) {",
" const psZipPath = zipPath.replace(/'/g, \"''\");",
" const psExtractDir = extractDir.replace(/'/g, \"''\");",
" const extractAttempts = [",
" {",
" label: \"PowerShell Expand-Archive\",",
" command: \"powershell\",",
" args: [",
" \"-NoProfile\",",
" \"-Command\",",
" `$ErrorActionPreference = 'Stop'; Expand-Archive -LiteralPath '${psZipPath}' -DestinationPath '${psExtractDir}' -Force`,",
" ],",
" },",
" {",
" label: \"PowerShell ZipFile\",",
" command: \"powershell\",",
" args: [",
" \"-NoProfile\",",
" \"-Command\",",
" `$ErrorActionPreference = 'Stop'; Add-Type -AssemblyName System.IO.Compression.FileSystem; [System.IO.Compression.ZipFile]::ExtractToDirectory('${psZipPath}', '${psExtractDir}', $true)`,",
" ],",
" },",
" {",
" label: \"tar\",",
" command: \"tar\",",
" args: [\"-xf\", zipPath, \"-C\", extractDir],",
" },",
" ] as const;",
"",
" // Update progress periodically during extraction",
" let extractPercent = 0;",
" const progressInterval = setInterval(() => {",
" extractPercent = Math.min(extractPercent + 10, 90);",
" sendProgress(",
" \"extract\",",
" extractPercent,",
" `Extracting files... ${extractPercent}%`,",
" );",
" }, 1000);",
"",
" try {",
" let extracted = false;",
" let lastError: Error | null = null;",
"",
" for (const attempt of extractAttempts) {",
" try {",
" console.log(`[Java] Extract attempt: ${attempt.label}`);",
" await runExtractAttempt(attempt.label, attempt.command, [",
" ...attempt.args,",
" ]);",
" extracted = true;",
" break;",
" } catch (error: any) {",
" lastError =",
" error instanceof Error ? error : new Error(String(error));",
" console.warn(",
" `[Java] ${attempt.label} failed: ${lastError.message}`,",
" );",
" if (fs.existsSync(extractDir))",
" fs.rmSync(extractDir, { recursive: true, force: true });",
" fs.mkdirSync(extractDir, { recursive: true });",
" }",
" }",
"",
" if (!extracted) {",
" throw lastError || new Error(\"Extract failed\");",
" }",
"",
" sendProgress(\"extract\", 100, \"Extraction complete\");",
" } finally {",
" clearInterval(progressInterval);",
" }",
"",
"",
" }",
" fs.unlinkSync(zipPath);",
"",
" const extractedDirs = fs.readdirSync(extractDir);",
" if (extractedDirs.length === 0) {",
" console.log(`[Java] No directories found after extract`);",
" return { ok: false, error: \"Extract failed - no directories\" };",
" }",
"",
" sendProgress(\"install\", 90, \"เธเธณเธฅเธฑเธเธ•เธดเธ”เธ•เธฑเนเธ...\");",
" const sourcePath = path.join(extractDir, extractedDirs[0]);",
" const targetPath = path.join(javaBaseDir, `jdk-${majorVersion}`);",
"",
" if (fs.existsSync(targetPath)) fs.rmSync(targetPath, { recursive: true });",
" fs.renameSync(sourcePath, targetPath);",
" fs.rmSync(extractDir, { recursive: true });",
"",
" const javaExePath = path.join(targetPath, \"bin\", \"java.exe\");",
" if (!fs.existsSync(javaExePath))",
" return { ok: false, error: \"เนเธกเนเธเธ java.exe\" };",
"",
" sendProgress(\"complete\", 100, \"เธ•เธดเธ”เธ•เธฑเนเธเธชเธณเน€เธฃเนเธ!\");",
" return { ok: true, path: javaExePath };",
" } catch (error: any) {",
" sendProgress(\"error\", 0, error.message);",
" return { ok: false, error: error.message };",
" }",
" });",
"",
" /**",
" * delete-java - เธฅเธ Java เธ—เธตเนเธ•เธดเธ”เธ•เธฑเนเธเนเธ”เธข launcher",
" */",
" ipcMain.handle(\"delete-java\", async (_event, majorVersion: number) => {",
" try {",
" const javaBaseDir = path.join(getAppDataDir(), \"java\");",
" const javaDir = path.join(javaBaseDir, `jdk-${majorVersion}`);",
"",
" if (!fs.existsSync(javaDir)) {",
" return { ok: true, message: `เนเธกเนเธเธ Java ${majorVersion}` };",
" }",
"",
" fs.rmSync(javaDir, { recursive: true, force: true });",
" return { ok: true, message: `เธฅเธ Java ${majorVersion} เธชเธณเน€เธฃเนเธ` };",
" } catch (error: any) {",
" return { ok: false, error: error.message };",
" }",
" });",
"",
" ipcMain.handle(",
" \"minecraft-get-profile\",",
" async (_event, options?: { forceRefresh?: boolean }) => {",
" try {",
" const session = getSession();",
" if (!session || session.type !== \"microsoft\") {",
" return { ok: false, error: \"Microsoft account is required.\" };",
" }",
"",
" const forceRefresh = !!options?.forceRefresh;",
" const sessionKey = getMinecraftProfileCacheKey(session);",
" if (!forceRefresh) {",
" const cachedProfile = getCachedMinecraftProfile(sessionKey);",
" if (cachedProfile) {",
" return { ok: true, profile: cachedProfile.profile };",
" }",
" }",
"",
" const refreshResult = await refreshMicrosoftTokenIfNeeded();",
" if (!refreshResult.ok) {",
" return {",
" ok: false,",
" error: refreshResult.error || \"Could not refresh Microsoft token.\",",
" requiresRelogin: refreshResult.requiresRelogin || false,",
" };",
" }",
"",
" const accessToken =",
" refreshResult.session?.accessToken || session.accessToken;",
" if (!accessToken) {",
" return { ok: false, error: \"Microsoft access token not found.\" };",
" }",
"",
" const profileResult = await fetchMinecraftProfile(accessToken);",
" if (profileResult.ok && profileResult.profile) {"
]