Integrate java download with AG2, remove AG1.

This commit is contained in:
Daniel Scalzi 2023-03-18 02:49:10 -04:00
parent 15f7560916
commit 16ad59685e
No known key found for this signature in database
GPG Key ID: 9E3E2AFE45328AA5
6 changed files with 342 additions and 1002 deletions

View File

@ -1,74 +0,0 @@
let target = require('./assetguard')[process.argv[2]]
if(target == null){
process.send({context: 'error', data: null, error: 'Invalid class name'})
console.error('Invalid class name passed to argv[2], cannot continue.')
process.exit(1)
}
let tracker = new target(...(process.argv.splice(3)))
const { LoggerUtil } = require('helios-core')
const logger = LoggerUtil.getLogger('AssetExec')
//const tracker = new AssetGuard(process.argv[2], process.argv[3])
logger.info('AssetExec Started')
// Temporary for debug purposes.
process.on('unhandledRejection', r => console.log(r))
let percent = 0
function assignListeners(){
tracker.on('validate', (data) => {
process.send({context: 'validate', data})
})
tracker.on('progress', (data, acc, total) => {
const currPercent = parseInt((acc/total) * 100)
if (currPercent !== percent) {
percent = currPercent
process.send({context: 'progress', data, value: acc, total, percent})
}
})
tracker.on('complete', (data, ...args) => {
process.send({context: 'complete', data, args})
})
tracker.on('error', (data, error) => {
process.send({context: 'error', data, error})
})
}
assignListeners()
process.on('message', (msg) => {
if(msg.task === 'execute'){
const func = msg.function
let nS = tracker[func] // Nonstatic context
let iS = target[func] // Static context
if(typeof nS === 'function' || typeof iS === 'function'){
const f = typeof nS === 'function' ? nS : iS
const res = f.apply(f === nS ? tracker : null, msg.argsArr)
if(res instanceof Promise){
res.then((v) => {
process.send({result: v, context: func})
}).catch((err) => {
process.send({result: err.message || err, context: func})
})
} else {
process.send({result: res, context: func})
}
} else {
process.send({context: 'error', data: null, error: `Function ${func} not found on ${process.argv[2]}`})
}
} else if(msg.task === 'changeContext'){
target = require('./assetguard')[msg.class]
if(target == null){
process.send({context: 'error', data: null, error: `Invalid class ${msg.class}`})
} else {
tracker = new target(...(msg.args))
assignListeners()
}
}
})
process.on('disconnect', () => {
logger.info('AssetExec Disconnected')
process.exit(0)
})

View File

@ -1,449 +0,0 @@
// Requirements
const async = require('async')
const child_process = require('child_process')
const crypto = require('crypto')
const EventEmitter = require('events')
const fs = require('fs-extra')
const { LoggerUtil } = require('helios-core')
const { javaExecFromRoot, latestOpenJDK } = require('helios-core/java')
const StreamZip = require('node-stream-zip')
const path = require('path')
const request = require('request')
const tar = require('tar-fs')
const zlib = require('zlib')
const isDev = require('./isdev')
// Classes
/** Class representing a base asset. */
class Asset {
/**
* Create an asset.
*
* @param {any} id The id of the asset.
* @param {string} hash The hash value of the asset.
* @param {number} size The size in bytes of the asset.
* @param {string} from The url where the asset can be found.
* @param {string} to The absolute local file path of the asset.
*/
constructor(id, hash, size, from, to){
this.id = id
this.hash = hash
this.size = size
this.from = from
this.to = to
}
}
/**
* Class representing a download tracker. This is used to store meta data
* about a download queue, including the queue itself.
*/
class DLTracker {
/**
* Create a DLTracker
*
* @param {Array.<Asset>} dlqueue An array containing assets queued for download.
* @param {number} dlsize The combined size of each asset in the download queue array.
* @param {function(Asset)} callback Optional callback which is called when an asset finishes downloading.
*/
constructor(dlqueue, dlsize, callback = null){
this.dlqueue = dlqueue
this.dlsize = dlsize
this.callback = callback
}
}
class Util {
/**
* Returns true if the actual version is greater than
* or equal to the desired version.
*
* @param {string} desired The desired version.
* @param {string} actual The actual version.
*/
static mcVersionAtLeast(desired, actual){
const des = desired.split('.')
const act = actual.split('.')
for(let i=0; i<des.length; i++){
if(!(parseInt(act[i]) >= parseInt(des[i]))){
return false
}
}
return true
}
}
/**
* Central object class used for control flow. This object stores data about
* categories of downloads. Each category is assigned an identifier with a
* DLTracker object as its value. Combined information is also stored, such as
* the total size of all the queued files in each category. This event is used
* to emit events so that external modules can listen into processing done in
* this module.
*/
class AssetGuard extends EventEmitter {
static logger = LoggerUtil.getLogger('AssetGuard')
/**
* Create an instance of AssetGuard.
* On creation the object's properties are never-null default
* values. Each identifier is resolved to an empty DLTracker.
*
* @param {string} commonPath The common path for shared game files.
* @param {string} javaexec The path to a java executable which will be used
* to finalize installation.
*/
constructor(commonPath, javaexec){
super()
this.totaldlsize = 0
this.progress = 0
this.assets = new DLTracker([], 0)
this.libraries = new DLTracker([], 0)
this.files = new DLTracker([], 0)
this.forge = new DLTracker([], 0)
this.java = new DLTracker([], 0)
this.extractQueue = []
this.commonPath = commonPath
this.javaexec = javaexec
}
// Static Utility Functions
// #region
// Static Hash Validation Functions
// #region
/**
* Calculates the hash for a file using the specified algorithm.
*
* @param {Buffer} buf The buffer containing file data.
* @param {string} algo The hash algorithm.
* @returns {string} The calculated hash in hex.
*/
static _calculateHash(buf, algo){
return crypto.createHash(algo).update(buf).digest('hex')
}
/**
* Validate that a file exists and matches a given hash value.
*
* @param {string} filePath The path of the file to validate.
* @param {string} algo The hash algorithm to check against.
* @param {string} hash The existing hash to check against.
* @returns {boolean} True if the file exists and calculated hash matches the given hash, otherwise false.
*/
static _validateLocal(filePath, algo, hash){
if(fs.existsSync(filePath)){
//No hash provided, have to assume it's good.
if(hash == null){
return true
}
let buf = fs.readFileSync(filePath)
let calcdhash = AssetGuard._calculateHash(buf, algo)
return calcdhash === hash.toLowerCase()
}
return false
}
// #endregion
// Miscellaneous Static Functions
// #region
/**
* Extracts and unpacks a file from .pack.xz format.
*
* @param {Array.<string>} filePaths The paths of the files to be extracted and unpacked.
* @returns {Promise.<void>} An empty promise to indicate the extraction has completed.
*/
static _extractPackXZ(filePaths, javaExecutable){
const extractLogger = LoggerUtil.getLogger('PackXZExtract')
extractLogger.info('Starting')
return new Promise((resolve, reject) => {
let libPath
if(isDev){
libPath = path.join(process.cwd(), 'libraries', 'java', 'PackXZExtract.jar')
} else {
if(process.platform === 'darwin'){
libPath = path.join(process.cwd(),'Contents', 'Resources', 'libraries', 'java', 'PackXZExtract.jar')
} else {
libPath = path.join(process.cwd(), 'resources', 'libraries', 'java', 'PackXZExtract.jar')
}
}
const filePath = filePaths.join(',')
const child = child_process.spawn(javaExecutable, ['-jar', libPath, '-packxz', filePath])
child.stdout.on('data', (data) => {
extractLogger.info(data.toString('utf8'))
})
child.stderr.on('data', (data) => {
extractLogger.info(data.toString('utf8'))
})
child.on('close', (code, signal) => {
extractLogger.info('Exited with code', code)
resolve()
})
})
}
// #endregion
// #endregion
// Java (Category=''') Validation (download) Functions
// #region
_enqueueOpenJDK(dataDir, mcVersion){
return new Promise((resolve, reject) => {
const major = Util.mcVersionAtLeast('1.17', mcVersion) ? '17' : '8'
latestOpenJDK(major).then(verData => {
if(verData != null){
dataDir = path.join(dataDir, 'runtime', 'x64')
const fDir = path.join(dataDir, verData.name)
const jre = new Asset(verData.name, null, verData.size, verData.uri, fDir)
this.java = new DLTracker([jre], jre.size, (a, self) => {
if(verData.name.endsWith('zip')){
this._extractJdkZip(a.to, dataDir, self)
} else {
// Tar.gz
let h = null
fs.createReadStream(a.to)
.on('error', err => AssetGuard.logger.error(err))
.pipe(zlib.createGunzip())
.on('error', err => AssetGuard.logger.error(err))
.pipe(tar.extract(dataDir, {
map: (header) => {
if(h == null){
h = header.name
}
}
}))
.on('error', err => AssetGuard.logger.error(err))
.on('finish', () => {
fs.unlink(a.to, err => {
if(err){
AssetGuard.logger.error(err)
}
if(h.indexOf('/') > -1){
h = h.substring(0, h.indexOf('/'))
}
const pos = path.join(dataDir, h)
self.emit('complete', 'java', javaExecFromRoot(pos))
})
})
}
})
resolve(true)
} else {
resolve(false)
}
})
})
}
async _extractJdkZip(zipPath, runtimeDir, self) {
const zip = new StreamZip.async({
file: zipPath,
storeEntries: true
})
let pos = ''
try {
const entries = await zip.entries()
pos = path.join(runtimeDir, Object.keys(entries)[0])
AssetGuard.logger.info('Extracting jdk..')
await zip.extract(null, runtimeDir)
AssetGuard.logger.info('Cleaning up..')
await fs.remove(zipPath)
AssetGuard.logger.info('Jdk extraction complete.')
} catch(err) {
AssetGuard.logger.error(err)
} finally {
zip.close()
self.emit('complete', 'java', javaExecFromRoot(pos))
}
}
// #endregion
// #endregion
// Control Flow Functions
// #region
/**
* Initiate an async download process for an AssetGuard DLTracker.
*
* @param {string} identifier The identifier of the AssetGuard DLTracker.
* @param {number} limit Optional. The number of async processes to run in parallel.
* @returns {boolean} True if the process began, otherwise false.
*/
startAsyncProcess(identifier, limit = 5){
const self = this
const dlTracker = this[identifier]
const dlQueue = dlTracker.dlqueue
if(dlQueue.length > 0){
AssetGuard.logger.info('DLQueue', dlQueue)
async.eachLimit(dlQueue, limit, (asset, cb) => {
fs.ensureDirSync(path.join(asset.to, '..'))
let req = request(asset.from)
req.pause()
req.on('response', (resp) => {
if(resp.statusCode === 200){
let doHashCheck = false
const contentLength = parseInt(resp.headers['content-length'])
if(contentLength !== asset.size){
AssetGuard.logger.warn(`WARN: Got ${contentLength} bytes for ${asset.id}: Expected ${asset.size}`)
doHashCheck = true
// Adjust download
this.totaldlsize -= asset.size
this.totaldlsize += contentLength
}
let writeStream = fs.createWriteStream(asset.to)
writeStream.on('close', () => {
if(dlTracker.callback != null){
dlTracker.callback.apply(dlTracker, [asset, self])
}
if(doHashCheck){
const v = AssetGuard._validateLocal(asset.to, asset.type != null ? 'md5' : 'sha1', asset.hash)
if(v){
AssetGuard.logger.warn(`Hashes match for ${asset.id}, byte mismatch is an issue in the distro index.`)
} else {
AssetGuard.logger.error(`Hashes do not match, ${asset.id} may be corrupted.`)
}
}
cb()
})
req.pipe(writeStream)
req.resume()
} else {
req.abort()
AssetGuard.logger.error(`Failed to download ${asset.id}(${typeof asset.from === 'object' ? asset.from.url : asset.from}). Response code ${resp.statusCode}`)
self.progress += asset.size*1
self.emit('progress', 'download', self.progress, self.totaldlsize)
cb()
}
})
req.on('error', (err) => {
self.emit('error', 'download', err)
})
req.on('data', (chunk) => {
self.progress += chunk.length
self.emit('progress', 'download', self.progress, self.totaldlsize)
})
}, (err) => {
if(err){
AssetGuard.logger.warn('An item in ' + identifier + ' failed to process')
} else {
AssetGuard.logger.info('All ' + identifier + ' have been processed successfully')
}
//self.totaldlsize -= dlTracker.dlsize
//self.progress -= dlTracker.dlsize
self[identifier] = new DLTracker([], 0)
if(self.progress >= self.totaldlsize) {
if(self.extractQueue.length > 0){
self.emit('progress', 'extract', 1, 1)
//self.emit('extracting')
AssetGuard._extractPackXZ(self.extractQueue, self.javaexec).then(() => {
self.extractQueue = []
self.emit('complete', 'download')
})
} else {
self.emit('complete', 'download')
}
}
})
return true
} else {
return false
}
}
/**
* This function will initiate the download processed for the specified identifiers. If no argument is
* given, all identifiers will be initiated. Note that in order for files to be processed you need to run
* the processing function corresponding to that identifier. If you run this function without processing
* the files, it is likely nothing will be enqueued in the object and processing will complete
* immediately. Once all downloads are complete, this function will fire the 'complete' event on the
* global object instance.
*
* @param {Array.<{id: string, limit: number}>} identifiers Optional. The identifiers to process and corresponding parallel async task limit.
*/
processDlQueues(identifiers = [{id:'assets', limit:20}, {id:'libraries', limit:5}, {id:'files', limit:5}, {id:'forge', limit:5}]){
return new Promise((resolve, reject) => {
let shouldFire = true
// Assign dltracking variables.
this.totaldlsize = 0
this.progress = 0
for(let iden of identifiers){
this.totaldlsize += this[iden.id].dlsize
}
this.once('complete', (data) => {
resolve()
})
for(let iden of identifiers){
let r = this.startAsyncProcess(iden.id, iden.limit)
if(r) shouldFire = false
}
if(shouldFire){
this.emit('complete', 'download')
}
})
}
// #endregion
}
module.exports = {
AssetGuard
}

View File

@ -12,19 +12,21 @@ const {
const { const {
RestResponseStatus, RestResponseStatus,
isDisplayableError, isDisplayableError,
mcVersionAtLeast validateLocalFile
} = require('helios-core/common') } = require('helios-core/common')
const { const {
FullRepair, FullRepair,
DistributionIndexProcessor, DistributionIndexProcessor,
MojangIndexProcessor MojangIndexProcessor,
downloadFile
} = require('helios-core/dl') } = require('helios-core/dl')
const { const {
getDefaultSemverRange,
validateSelectedJvm, validateSelectedJvm,
ensureJavaDirIsRoot, ensureJavaDirIsRoot,
javaExecFromRoot, javaExecFromRoot,
discoverBestJvmInstallation discoverBestJvmInstallation,
latestOpenJDK,
extractJdk
} = require('helios-core/java') } = require('helios-core/java')
// Internal Requirements // Internal Requirements
@ -99,25 +101,25 @@ function setLaunchEnabled(val){
} }
// Bind launch button // Bind launch button
document.getElementById('launch_button').addEventListener('click', async (e) => { document.getElementById('launch_button').addEventListener('click', async e => {
loggerLanding.info('Launching game..') loggerLanding.info('Launching game..')
const mcVersion = (await DistroAPI.getDistribution()).getServerById(ConfigManager.getSelectedServer()).rawServer.minecraftVersion const server = (await DistroAPI.getDistribution()).getServerById(ConfigManager.getSelectedServer())
const mcVersion = server.rawServer.minecraftVersion
const jExe = ConfigManager.getJavaExecutable(ConfigManager.getSelectedServer()) const jExe = ConfigManager.getJavaExecutable(ConfigManager.getSelectedServer())
if(jExe == null){ if(jExe == null){
await asyncSystemScan(mcVersion) await asyncSystemScan(server.effectiveJavaOptions)
} else { } else {
setLaunchDetails(Lang.queryJS('landing.launch.pleaseWait')) setLaunchDetails(Lang.queryJS('landing.launch.pleaseWait'))
toggleLaunchArea(true) toggleLaunchArea(true)
setLaunchPercentage(0, 100) setLaunchPercentage(0, 100)
// TODO Update to use semver range const details = await validateSelectedJvm(ensureJavaDirIsRoot(jExe), server.effectiveJavaOptions.supported)
const details = await validateSelectedJvm(ensureJavaDirIsRoot(execPath), getDefaultSemverRange(mcVer))
if(details != null){ if(details != null){
loggerLanding.info('Jvm Details', details) loggerLanding.info('Jvm Details', details)
await dlAsync() await dlAsync()
} else { } else {
await asyncSystemScan(mcVersion) await asyncSystemScan(server.effectiveJavaOptions)
} }
} }
}) })
@ -290,25 +292,20 @@ function showLaunchFailure(title, desc){
/* System (Java) Scan */ /* System (Java) Scan */
let extractListener
/** /**
* Asynchronously scan the system for valid Java installations. * Asynchronously scan the system for valid Java installations.
* *
* @param {string} mcVersion The Minecraft version we are scanning for.
* @param {boolean} launchAfter Whether we should begin to launch after scanning. * @param {boolean} launchAfter Whether we should begin to launch after scanning.
*/ */
async function asyncSystemScan(mcVersion, launchAfter = true){ async function asyncSystemScan(effectiveJavaOptions, launchAfter = true){
setLaunchDetails('Checking system info..') setLaunchDetails('Checking system info..')
toggleLaunchArea(true) toggleLaunchArea(true)
setLaunchPercentage(0, 100) setLaunchPercentage(0, 100)
const javaVer = mcVersionAtLeast('1.17', mcVersion) ? '17' : '8'
const jvmDetails = await discoverBestJvmInstallation( const jvmDetails = await discoverBestJvmInstallation(
ConfigManager.getDataDirectory(), ConfigManager.getDataDirectory(),
getDefaultSemverRange(mcVersion) effectiveJavaOptions.supported
) )
if(jvmDetails == null) { if(jvmDetails == null) {
@ -316,15 +313,14 @@ async function asyncSystemScan(mcVersion, launchAfter = true){
// Show this information to the user. // Show this information to the user.
setOverlayContent( setOverlayContent(
'No Compatible<br>Java Installation Found', 'No Compatible<br>Java Installation Found',
`In order to join WesterosCraft, you need a 64-bit installation of Java ${javaVer}. Would you like us to install a copy?`, `In order to join WesterosCraft, you need a 64-bit installation of Java ${effectiveJavaOptions.suggestedMajor}. Would you like us to install a copy?`,
'Install Java', 'Install Java',
'Install Manually' 'Install Manually'
) )
setOverlayHandler(() => { setOverlayHandler(() => {
setLaunchDetails('Preparing Java Download..') setLaunchDetails('Preparing Java Download..')
// TODO Kick off JDK download. downloadJava(effectiveJavaOptions, launchAfter)
toggleOverlay(false) toggleOverlay(false)
}) })
setDismissHandler(() => { setDismissHandler(() => {
@ -332,7 +328,7 @@ async function asyncSystemScan(mcVersion, launchAfter = true){
//$('#overlayDismiss').toggle(false) //$('#overlayDismiss').toggle(false)
setOverlayContent( setOverlayContent(
'Java is Required<br>to Launch', 'Java is Required<br>to Launch',
`A valid x64 installation of Java ${javaVer} is required to launch.<br><br>Please refer to our <a href="https://github.com/dscalzi/HeliosLauncher/wiki/Java-Management#manually-installing-a-valid-version-of-java">Java Management Guide</a> for instructions on how to manually install Java.`, `A valid x64 installation of Java ${effectiveJavaOptions.suggestedMajor} is required to launch.<br><br>Please refer to our <a href="https://github.com/dscalzi/HeliosLauncher/wiki/Java-Management#manually-installing-a-valid-version-of-java">Java Management Guide</a> for instructions on how to manually install Java.`,
'I Understand', 'I Understand',
'Go Back' 'Go Back'
) )
@ -343,9 +339,7 @@ async function asyncSystemScan(mcVersion, launchAfter = true){
setDismissHandler(() => { setDismissHandler(() => {
toggleOverlay(false, true) toggleOverlay(false, true)
// TODO Change this flow asyncSystemScan(effectiveJavaOptions, launchAfter)
// Should be a separate function probably.
asyncSystemScan()
}) })
$('#overlayContent').fadeIn(250) $('#overlayContent').fadeIn(250)
}) })
@ -362,95 +356,73 @@ async function asyncSystemScan(mcVersion, launchAfter = true){
settingsJavaExecVal.value = javaExec settingsJavaExecVal.value = javaExec
await populateJavaExecDetails(settingsJavaExecVal.value) await populateJavaExecDetails(settingsJavaExecVal.value)
// TODO Callback hell, refactor
// TODO Move this out, separate concerns. // TODO Move this out, separate concerns.
if(launchAfter){ if(launchAfter){
await dlAsync() await dlAsync()
} }
} }
// TODO Integrate into assetguard 2. }
// if(m.context === '_enqueueOpenJDK'){
// if(m.result === true){ async function downloadJava(effectiveJavaOptions, launchAfter = true) {
// // Oracle JRE enqueued successfully, begin download. // TODO Error handling.
// setLaunchDetails('Downloading Java..') // asset can be null.
// sysAEx.send({task: 'execute', function: 'processDlQueues', argsArr: [[{id:'java', limit:1}]]}) const asset = await latestOpenJDK(
effectiveJavaOptions.suggestedMajor,
ConfigManager.getDataDirectory(),
effectiveJavaOptions.distribution)
// } else { let received = 0
await downloadFile(asset.url, asset.path, ({ transferred }) => {
received += transferred
setDownloadPercentage(transferred/asset.size)
})
setDownloadPercentage(100)
// // Oracle JRE enqueue failed. Probably due to a change in their website format. if(received != asset.size) {
// // User will have to follow the guide to install Java. loggerLanding.warn(`Java Download: Expected ${asset.size} bytes but received ${received}`)
// setOverlayContent( if(!await validateLocalFile(asset.path, asset.algo, asset.hash)) {
// 'Unexpected Issue:<br>Java Download Failed', log.error(`Hashes do not match, ${asset.id} may be corrupted.`)
// 'Unfortunately we\'ve encountered an issue while attempting to install Java. You will need to manually install a copy. Please check out our <a href="https://github.com/dscalzi/HeliosLauncher/wiki">Troubleshooting Guide</a> for more details and instructions.',
// 'I Understand'
// )
// setOverlayHandler(() => {
// toggleOverlay(false)
// toggleLaunchArea(false)
// })
// toggleOverlay(true)
// sysAEx.disconnect()
// } // TODO Make error handling graceful.
throw new Error('JDK download had problems')
}
}
// } else if(m.context === 'progress'){ // Extract
// Show installing progress bar.
remote.getCurrentWindow().setProgressBar(2)
// switch(m.data){ const newJavaExec = await extractJdk(asset.path)
// case 'download':
// // Downloading..
// setDownloadPercentage(m.value, m.total, m.percent)
// break
// }
// } else if(m.context === 'complete'){ // Wait for extration to complete.
const eLStr = 'Extracting'
let dotStr = ''
setLaunchDetails(eLStr)
const extractListener = setInterval(() => {
if(dotStr.length >= 3){
dotStr = ''
} else {
dotStr += '.'
}
setLaunchDetails(eLStr + dotStr)
}, 750)
// switch(m.data){ // Extraction complete, remove the loading from the OS progress bar.
// case 'download': { remote.getCurrentWindow().setProgressBar(-1)
// // Show installing progress bar.
// remote.getCurrentWindow().setProgressBar(2)
// // Wait for extration to complete. // Extraction completed successfully.
// const eLStr = 'Extracting' ConfigManager.setJavaExecutable(ConfigManager.getSelectedServer(), newJavaExec)
// let dotStr = '' ConfigManager.save()
// setLaunchDetails(eLStr)
// extractListener = setInterval(() => {
// if(dotStr.length >= 3){
// dotStr = ''
// } else {
// dotStr += '.'
// }
// setLaunchDetails(eLStr + dotStr)
// }, 750)
// break
// }
// case 'java':
// // Download & extraction complete, remove the loading from the OS progress bar.
// remote.getCurrentWindow().setProgressBar(-1)
// // Extraction completed successfully. clearInterval(extractListener)
// ConfigManager.setJavaExecutable(ConfigManager.getSelectedServer(), m.args[0]) setLaunchDetails('Java Installed!')
// ConfigManager.save()
// if(extractListener != null){ // TODO Callback hell
// clearInterval(extractListener) // Refactor the launch functions
// extractListener = null asyncSystemScan(effectiveJavaOptions, launchAfter)
// }
// setLaunchDetails('Java Installed!')
// if(launchAfter){
// await dlAsync()
// }
// sysAEx.disconnect()
// break
// }
// } else if(m.context === 'error'){
// console.log(m.error)
// }
} }
@ -513,7 +485,7 @@ async function dlAsync(login = true) {
}) })
fullRepairModule.childProcess.on('close', (code, _signal) => { fullRepairModule.childProcess.on('close', (code, _signal) => {
if(code !== 0){ if(code !== 0){
loggerLaunchSuite.error(`AssetExec exited with code ${code}, assuming error.`) loggerLaunchSuite.error(`Full Repair Module exited with code ${code}, assuming error.`)
showLaunchFailure('Error During Launch', 'See console (CTRL + Shift + i) for more details.') showLaunchFailure('Error During Launch', 'See console (CTRL + Shift + i) for more details.')
} }
}) })

View File

@ -1349,13 +1349,12 @@ function populateMemoryStatus(){
* @param {string} execPath The executable path to populate against. * @param {string} execPath The executable path to populate against.
*/ */
async function populateJavaExecDetails(execPath){ async function populateJavaExecDetails(execPath){
const mcVer = (await DistroAPI.getDistribution()).getServerById(ConfigManager.getSelectedServer()).rawServer.minecraftVersion const server = (await DistroAPI.getDistribution()).getServerById(ConfigManager.getSelectedServer())
// TODO Update to use semver range const details = await validateSelectedJvm(ensureJavaDirIsRoot(execPath), server.effectiveJavaOptions.supported)
const details = await validateSelectedJvm(ensureJavaDirIsRoot(execPath), getDefaultSemverRange(mcVer))
if(details != null) { if(details != null) {
settingsJavaExecDetails.innerHTML = `Selected: Java ${details.semverStr} (${vendor})` settingsJavaExecDetails.innerHTML = `Selected: Java ${details.semverStr} (${details.vendor})`
} else { } else {
settingsJavaExecDetails.innerHTML = 'Invalid Selection' settingsJavaExecDetails.innerHTML = 'Invalid Selection'
} }
@ -1363,23 +1362,26 @@ async function populateJavaExecDetails(execPath){
// TODO Update to use semver range // TODO Update to use semver range
async function populateJavaReqDesc() { async function populateJavaReqDesc() {
const mcVer = (await DistroAPI.getDistribution()).getServerById(ConfigManager.getSelectedServer()).rawServer.minecraftVersion const server = (await DistroAPI.getDistribution()).getServerById(ConfigManager.getSelectedServer())
if(mcVersionAtLeast('1.17', mcVer)) { settingsJavaReqDesc.innerHTML = `Requires Java ${server.effectiveJavaOptions.suggestedMajor} x64.`
settingsJavaReqDesc.innerHTML = 'Requires Java 17 x64.'
} else {
settingsJavaReqDesc.innerHTML = 'Requires Java 8 x64.'
}
} }
// TODO Update to use semver range // TODO Update to use semver range
async function populateJvmOptsLink() { async function populateJvmOptsLink() {
const mcVer = (await DistroAPI.getDistribution()).getServerById(ConfigManager.getSelectedServer()).rawServer.minecraftVersion const server = (await DistroAPI.getDistribution()).getServerById(ConfigManager.getSelectedServer())
if(mcVersionAtLeast('1.17', mcVer)) { const major = server.effectiveJavaOptions.suggestedMajor
settingsJvmOptsLink.innerHTML = 'Available Options for Java 17 (HotSpot VM)' settingsJvmOptsLink.innerHTML = `Available Options for Java ${major} (HotSpot VM)`
settingsJvmOptsLink.href = 'https://docs.oracle.com/en/java/javase/17/docs/specs/man/java.html#extra-options-for-java' if(major >= 12) {
} else { settingsJvmOptsLink.href = `https://docs.oracle.com/en/java/javase/${major}/docs/specs/man/java.html#extra-options-for-java`
settingsJvmOptsLink.innerHTML = 'Available Options for Java 8 (HotSpot VM)' }
settingsJvmOptsLink.href = `https://docs.oracle.com/javase/8/docs/technotes/tools/${process.platform === 'win32' ? 'windows' : 'unix'}/java.html` else if(major >= 11) {
settingsJvmOptsLink.href = 'https://docs.oracle.com/en/java/javase/11/tools/java.html#GUID-3B1CE181-CD30-4178-9602-230B800D4FAE'
}
else if(major >= 9) {
settingsJvmOptsLink.href = `https://docs.oracle.com/javase/${major}/tools/java.htm`
}
else {
settingsJvmOptsLink.href = `https://docs.oracle.com/javase/${major}/docs/technotes/tools/${process.platform === 'win32' ? 'windows' : 'unix'}/java.html`
} }
} }

616
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@ -36,10 +36,7 @@
"helios-core": "~0.2.0-pre.1", "helios-core": "~0.2.0-pre.1",
"helios-distribution-types": "^1.1.0", "helios-distribution-types": "^1.1.0",
"jquery": "^3.6.1", "jquery": "^3.6.1",
"node-stream-zip": "^1.15.0", "semver": "^7.3.8"
"request": "^2.88.2",
"semver": "^7.3.8",
"tar-fs": "^2.1.1"
}, },
"devDependencies": { "devDependencies": {
"electron": "^23.0.0", "electron": "^23.0.0",