Rewrote frontend download download function to make use of forked processes. This means that the download runs in full async (essentially in a separate thread). Updated the discord wrapper to be more dynamic. Updated auth manager to use async/await.

This commit is contained in:
Daniel Scalzi 2018-01-18 23:45:50 -05:00
parent 1d10b0209a
commit d4d7be7c47
5 changed files with 249 additions and 112 deletions

View File

@ -1,3 +1,4 @@
const cp = require('child_process')
const path = require('path') const path = require('path')
const {AssetGuard} = require(path.join(__dirname, 'assets', 'js', 'assetguard.js')) const {AssetGuard} = require(path.join(__dirname, 'assets', 'js', 'assetguard.js'))
const ProcessBuilder = require(path.join(__dirname, 'assets', 'js', 'processbuilder.js')) const ProcessBuilder = require(path.join(__dirname, 'assets', 'js', 'processbuilder.js'))
@ -8,14 +9,25 @@ const AuthManager = require(path.join(__dirname, 'assets', 'js', 'authmanager.js
let mojangStatusListener let mojangStatusListener
// Launch Elements
let launch_content, launch_details, launch_progress, launch_progress_label, launch_details_text
// Synchronous Listener // Synchronous Listener
document.addEventListener('readystatechange', function(){ document.addEventListener('readystatechange', function(){
if (document.readyState === 'interactive'){ if (document.readyState === 'interactive'){
// Save a reference to the launch elements.
launch_content = document.getElementById('launch_content')
launch_details = document.getElementById('launch_details')
launch_progress = document.getElementById('launch_progress')
launch_progress_label = document.getElementById('launch_progress_label')
launch_details_text = document.getElementById('launch_details_text')
// Bind launch button // Bind launch button
document.getElementById('launch_button').addEventListener('click', function(e){ document.getElementById('launch_button').addEventListener('click', function(e){
console.log('Launching game..') console.log('Launching game..')
testdownloads() //testdownloads()
dlAsync()
}) })
// TODO convert this to dropdown menu. // TODO convert this to dropdown menu.
@ -58,104 +70,180 @@ document.addEventListener('readystatechange', function(){
} }
}, false) }, false)
// Keep reference to AssetGuard object temporarily // Keep reference to Minecraft Process
let tracker; let proc
// Is DiscordRPC enabled
let hasRPC = false
// Joined server regex
const servJoined = /[[0-2][0-9]:[0-6][0-9]:[0-6][0-9]\] \[Client thread\/INFO\]: \[CHAT\] [a-zA-Z0-9_]{1,16} joined the game/g
const gameJoined = /\[[0-2][0-9]:[0-6][0-9]:[0-6][0-9]\] \[Client thread\/WARN\]: Skipping bad option: lastServer:/g
const gameJoined2 = /\[[0-2][0-9]:[0-6][0-9]:[0-6][0-9]\] \[Client thread\/INFO\]: Created: \d+x\d+ textures-atlas/g
testdownloads = async function(){ let aEx
let currentProc
let serv
let versionData
let forgeData
function dlAsync(login = true){
// Login parameter is temporary for debug purposes. Allows testing the validation/downloads without
// launching the game.
if(login) {
if(ConfigManager.getSelectedAccount() == null){ if(ConfigManager.getSelectedAccount() == null){
console.error('login first.') console.error('login first.')
//in devtools AuthManager.addAccount(username, pass) //in devtools AuthManager.addAccount(username, pass)
return return
} }
}
const content = document.getElementById('launch_content') launch_details_text.innerHTML = 'Please wait..'
const details = document.getElementById('launch_details') launch_progress.setAttribute('max', '100')
const progress = document.getElementById('launch_progress') launch_details.style.display = 'flex'
const progress_text = document.getElementById('launch_progress_label') launch_content.style.display = 'none'
const det_text = document.getElementById('launch_details_text')
det_text.innerHTML = 'Please wait..' aEx = cp.fork(path.join(__dirname, 'assets', 'js', 'assetexec.js'), [
progress.setAttribute('max', '100') ConfigManager.getGameDirectory(),
details.style.display = 'flex' ConfigManager.getJavaExecutable()
content.style.display = 'none' ])
tracker = new AssetGuard(ConfigManager.getGameDirectory(), ConfigManager.getJavaExecutable()) aEx.on('message', (m) => {
if(currentProc === 'validateDistribution'){
det_text.innerHTML = 'Loading server information..' launch_progress.setAttribute('value', 20)
const serv = await tracker.validateDistribution(ConfigManager.getSelectedServer()) launch_progress_label.innerHTML = '20%'
progress.setAttribute('value', 20) serv = m.result
progress_text.innerHTML = '20%'
console.log('forge stuff done') console.log('forge stuff done')
det_text.innerHTML = 'Loading version information..' // Begin version load.
const versionData = await tracker.loadVersionData(serv.mc_version) launch_details_text.innerHTML = 'Loading version information..'
progress.setAttribute('value', 40) currentProc = 'loadVersionData'
progress_text.innerHTML = '40%' aEx.send({task: 0, content: currentProc, argsArr: [serv.mc_version]})
det_text.innerHTML = 'Validating asset integrity..' } else if(currentProc === 'loadVersionData'){
await tracker.validateAssets(versionData)
progress.setAttribute('value', 60) launch_progress.setAttribute('value', 40)
progress_text.innerHTML = '60%' launch_progress_label.innerHTML = '40%'
versionData = m.result
// Begin asset validation.
launch_details_text.innerHTML = 'Validating asset integrity..'
currentProc = 'validateAssets'
aEx.send({task: 0, content: currentProc, argsArr: [versionData]})
} else if(currentProc === 'validateAssets'){
launch_progress.setAttribute('value', 60)
launch_progress_label.innerHTML = '60%'
console.log('assets done') console.log('assets done')
det_text.innerHTML = 'Validating library integrity..' // Begin library validation.
await tracker.validateLibraries(versionData) launch_details_text.innerHTML = 'Validating library integrity..'
progress.setAttribute('value', 80) currentProc = 'validateLibraries'
progress_text.innerHTML = '80%' aEx.send({task: 0, content: currentProc, argsArr: [versionData]})
} else if(currentProc === 'validateLibraries'){
launch_progress.setAttribute('value', 80)
launch_progress_label.innerHTML = '80%'
console.log('libs done') console.log('libs done')
det_text.innerHTML = 'Validating miscellaneous file integrity..' // Begin miscellaneous validation.
await tracker.validateMiscellaneous(versionData) launch_details_text.innerHTML = 'Validating miscellaneous file integrity..'
progress.setAttribute('value', 100) currentProc = 'validateMiscellaneous'
progress_text.innerHTML = '100%' aEx.send({task: 0, content: currentProc, argsArr: [versionData]})
} else if(currentProc === 'validateMiscellaneous'){
launch_progress.setAttribute('value', 100)
launch_progress_label.innerHTML = '100%'
console.log('files done') console.log('files done')
det_text.innerHTML = 'Downloading files..' launch_details_text.innerHTML = 'Downloading files..'
tracker.on('totaldlprogress', function(data){ currentProc = 'processDlQueues'
progress.setAttribute('max', data.total) aEx.send({task: 0, content: currentProc})
progress.setAttribute('value', data.acc)
progress_text.innerHTML = parseInt((data.acc/data.total)*100) + '%'
})
tracker.on('dlcomplete', async function(){ } else if(currentProc === 'processDlQueues'){
if(m.task === 0){
remote.getCurrentWindow().setProgressBar(m.value/m.total)
launch_progress.setAttribute('max', m.total)
launch_progress.setAttribute('value', m.value)
launch_progress_label.innerHTML = m.percent + '%'
} else if(m.task === 1){
remote.getCurrentWindow().setProgressBar(-1)
det_text.innerHTML = 'Preparing to launch..' launch_details_text.innerHTML = 'Preparing to launch..'
const forgeData = await tracker.loadForgeData(serv.id) currentProc = 'loadForgeData'
const authUser = await AuthManager.validateSelected() aEx.send({task: 0, content: currentProc, argsArr: [serv.id]})
} else {
console.error('Unknown download data type.', m)
}
} else if(currentProc === 'loadForgeData'){
forgeData = m.result
if(login) {
//if(!(await AuthManager.validateSelected())){
//
//}
const authUser = ConfigManager.getSelectedAccount();
console.log('authu', authUser)
let pb = new ProcessBuilder(ConfigManager.getGameDirectory(), serv, versionData, forgeData, authUser) let pb = new ProcessBuilder(ConfigManager.getGameDirectory(), serv, versionData, forgeData, authUser)
det_text.innerHTML = 'Launching game..' launch_details_text.innerHTML = 'Launching game..'
let proc;
try{ try{
proc = pb.build() proc = pb.build()
det_text.innerHTML = 'Done. Enjoy the server!' launch_details_text.innerHTML = 'Done. Enjoy the server!'
const tempListener = function(data){ const tempListener = function(data){
if(data.indexOf('[Client thread/INFO]: -- System Details --') > -1){ if(data.indexOf('[Client thread/INFO]: -- System Details --') > -1){
details.style.display = 'none' launch_details.style.display = 'none'
content.style.display = 'inline-flex' launch_content.style.display = 'inline-flex'
if(hasRPC){
DiscordWrapper.updateDetails('Loading game..')
}
proc.stdout.removeListener('data', tempListener) proc.stdout.removeListener('data', tempListener)
} }
} }
const gameStateChange = function(data){
if(servJoined.test(data)){
DiscordWrapper.updateDetails('Exploring the Realm!')
} else if(gameJoined.test(data)){
DiscordWrapper.updateDetails('Idling on Main Menu')
}
}
proc.stdout.on('data', tempListener) proc.stdout.on('data', tempListener)
proc.stdout.on('data', gameStateChange)
// Init Discord Hook (Untested) // Init Discord Hook (Untested)
const distro = AssetGuard.retrieveDistributionDataSync(ConfigManager.getGameDirectory) const distro = AssetGuard.retrieveDistributionDataSync(ConfigManager.getGameDirectory)
if(distro.discord != null && serv.discord != null){ if(distro.discord != null && serv.discord != null){
DiscordWrapper.initRPC(distro.discord, serv.discord) DiscordWrapper.initRPC(distro.discord, serv.discord)
hasRPC = true
proc.on('close', (code, signal) => { proc.on('close', (code, signal) => {
console.log('Shutting down Discord Rich Presence..')
DiscordWrapper.shutdownRPC() DiscordWrapper.shutdownRPC()
hasRPC = false
proc = null
}) })
} }
} catch(err) { } catch(err) {
//det_text.innerHTML = 'Error: ' + err.message; //launch_details_text.innerHTML = 'Error: ' + err.message;
det_text.innerHTML = 'Error: See log for details..'; launch_details_text.innerHTML = 'Error: See log for details..';
console.log(err) console.log(err)
setTimeout(function(){ setTimeout(function(){
details.style.display = 'none' launch_details.style.display = 'none'
content.style.display = 'inline-flex' launch_content.style.display = 'inline-flex'
}, 5000) }, 5000)
} }
// Remove reference to tracker. }
tracker = null
}) // Disconnect from AssetExec
tracker.processDlQueues() aEx.disconnect()
}
})
launch_details_text.innerHTML = 'Loading server information..'
currentProc = 'validateDistribution'
aEx.send({task: 0, content: currentProc, argsArr: [ConfigManager.getSelectedServer()]})
} }

View File

@ -0,0 +1,37 @@
const {AssetGuard} = require('./assetguard.js')
const tracker = new AssetGuard(process.argv[2], process.argv[3])
console.log('AssetExec Started')
// Temporary for debug purposes.
process.on('unhandledRejection', r => console.log(r))
tracker.on('totaldlprogress', (data) => {
process.send({task: 0, total: data.total, value: data.acc, percent: parseInt((data.acc/data.total)*100)})
})
tracker.on('dlcomplete', () => {
process.send({task: 1})
})
process.on('message', (msg) => {
if(msg.task === 0){
const func = msg.content
if(typeof tracker[func] === 'function'){
const f = tracker[func]
const res = f.apply(tracker, msg.argsArr)
if(res instanceof Promise){
res.then((v) => {
process.send({result: v})
})
} else {
process.send({result: res})
}
}
}
})
process.on('disconnect', () => {
console.log('AssetExec Disconnected')
process.exit(0)
})

View File

@ -498,7 +498,6 @@ class AssetGuard extends EventEmitter {
*/ */
startAsyncProcess(identifier, limit = 5){ startAsyncProcess(identifier, limit = 5){
const self = this const self = this
let win = remote.getCurrentWindow()
let acc = 0 let acc = 0
const concurrentDlTracker = this[identifier] const concurrentDlTracker = this[identifier]
const concurrentDlQueue = concurrentDlTracker.dlqueue.slice(0) const concurrentDlQueue = concurrentDlTracker.dlqueue.slice(0)
@ -526,7 +525,6 @@ class AssetGuard extends EventEmitter {
req.abort() req.abort()
console.log('Failed to download ' + asset.from + '. Response code', resp.statusCode) console.log('Failed to download ' + asset.from + '. Response code', resp.statusCode)
self.progress += asset.size*1 self.progress += asset.size*1
win.setProgressBar(self.progress/self.totaldlsize)
self.emit('totaldlprogress', {acc: self.progress, total: self.totaldlsize}) self.emit('totaldlprogress', {acc: self.progress, total: self.totaldlsize})
cb() cb()
} }
@ -536,8 +534,6 @@ class AssetGuard extends EventEmitter {
self.progress += chunk.length self.progress += chunk.length
acc += chunk.length acc += chunk.length
self.emit(identifier + 'dlprogress', acc) self.emit(identifier + 'dlprogress', acc)
//console.log(identifier + ' Progress', acc/this[identifier].dlsize)
win.setProgressBar(self.progress/self.totaldlsize)
self.emit('totaldlprogress', {acc: self.progress, total: self.totaldlsize}) self.emit('totaldlprogress', {acc: self.progress, total: self.totaldlsize})
}) })
}, function(err){ }, function(err){
@ -552,7 +548,6 @@ class AssetGuard extends EventEmitter {
self.progress -= self[identifier].dlsize self.progress -= self[identifier].dlsize
self[identifier] = new DLTracker([], 0) self[identifier] = new DLTracker([], 0)
if(self.totaldlsize === 0) { if(self.totaldlsize === 0) {
win.setProgressBar(-1)
self.emit('dlcomplete') self.emit('dlcomplete')
} }
}) })
@ -811,6 +806,10 @@ class AssetGuard extends EventEmitter {
}*/ }*/
const serv = AssetGuard.getServerById(self.basePath, serverpackid) const serv = AssetGuard.getServerById(self.basePath, serverpackid)
if(serv == null) {
console.error('Invalid server pack id:', serverpackid)
}
self.forge = self._parseDistroModules(serv.modules, serv.mc_version) self.forge = self._parseDistroModules(serv.modules, serv.mc_version)
//Correct our workaround here. //Correct our workaround here.
let decompressqueue = self.forge.callback let decompressqueue = self.forge.callback
@ -944,7 +943,6 @@ class AssetGuard extends EventEmitter {
*/ */
processDlQueues(identifiers = [{id:'assets', limit:20}, {id:'libraries', limit:5}, {id:'files', limit:5}, {id:'forge', limit:5}]){ processDlQueues(identifiers = [{id:'assets', limit:20}, {id:'libraries', limit:5}, {id:'files', limit:5}, {id:'forge', limit:5}]){
this.progress = 0; this.progress = 0;
let win = remote.getCurrentWindow()
let shouldFire = true let shouldFire = true

View File

@ -1,25 +1,30 @@
const ConfigManager = require('./configmanager.js') const ConfigManager = require('./configmanager.js')
const Mojang = require('./mojang.js') const Mojang = require('./mojang.js')
exports.addAccount = function(username, password){ exports.addAccount = async function(username, password){
return new Promise(async function(resolve, reject){
const session = await Mojang.authenticate(username, password, ConfigManager.getClientToken) const session = await Mojang.authenticate(username, password, ConfigManager.getClientToken)
const ret = ConfigManager.addAuthAccount(session.selectedProfile.id, session.accessToken, username, session.selectedProfile.name) const ret = ConfigManager.addAuthAccount(session.selectedProfile.id, session.accessToken, username, session.selectedProfile.name)
ConfigManager.save() ConfigManager.save()
resolve(ret) return ret
})
} }
exports.validateSelected = function(){ exports.validateSelected = async function(){
return new Promise(async function(resolve, reject){
const current = ConfigManager.getSelectedAccount() const current = ConfigManager.getSelectedAccount()
if(!await Mojang.validate(current.accessToken, ConfigManager.getClientToken)){ const isValid = await Mojang.validate(current.accessToken, ConfigManager.getClientToken())
const session = Mojang.refresh(current.accessToken, ConfigManager.getClientToken) console.log(isValid)
const ret = ConfigManager.updateAuthAccount(current.uuid, session.accessToken) if(!isValid){
try {
const session = await Mojang.refresh(current.accessToken, ConfigManager.getClientToken())
console.log('ses', session)
ConfigManager.updateAuthAccount(current.uuid, session.accessToken)
ConfigManager.save() ConfigManager.save()
resolve(ret) } catch(err) {
if(err && err.message === 'ForbiddenOperationException'){
return false
}
}
return true
} else { } else {
resolve(current) return true
} }
})
} }

View File

@ -3,16 +3,15 @@ const {Client} = require('discord-rpc')
const ConfigManager = require('./configmanager.js') const ConfigManager = require('./configmanager.js')
let rpc let rpc
let activity
exports.initRPC = function(genSettings, servSettings){ exports.initRPC = function(genSettings, servSettings, initialDetails = 'Waiting for Client..'){
rpc = new Client({ transport: 'ipc' }); rpc = new Client({ transport: 'ipc' })
rpc.on('ready', () => { rpc.on('ready', () => {
const activity = { activity = {
// state = top text details: initialDetails,
// details = bottom text
state: 'Server: ' + servSettings.shortId, state: 'Server: ' + servSettings.shortId,
details: 'Exploring the wall',
largeImageKey: servSettings.largeImageKey, largeImageKey: servSettings.largeImageKey,
largeImageText: servSettings.largeImageText, largeImageText: servSettings.largeImageText,
smallImageKey: genSettings.smallImageKey, smallImageKey: genSettings.smallImageKey,
@ -33,8 +32,18 @@ exports.initRPC = function(genSettings, servSettings){
}) })
} }
exports.updateDetails = function(details){
if(activity == null){
console.error('Discord RPC is not initialized and therefore cannot be updated.')
}
activity.details = details
rpc.setActivity(activity)
}
exports.shutdownRPC = function(){ exports.shutdownRPC = function(){
if(!rpc) return
rpc.setActivity({}) rpc.setActivity({})
rpc.destroy() rpc.destroy()
rpc = null rpc = null
activity = null
} }