Wrap calls to console.log through LoggerUtil (prefixes).

This commit is contained in:
Daniel Scalzi 2018-08-22 14:21:49 -04:00
parent 37606dc8d2
commit 0346597afe
No known key found for this signature in database
GPG Key ID: 5CA2F145B63535F9
12 changed files with 151 additions and 103 deletions

View File

@ -10,7 +10,10 @@
*/ */
// Requirements // Requirements
const ConfigManager = require('./configmanager') const ConfigManager = require('./configmanager')
const LoggerUtil = require('./loggerutil')
const Mojang = require('./mojang') const Mojang = require('./mojang')
const logger = LoggerUtil('%c[AuthManager]', 'color: #a02d2a; font-weight: bold')
const loggerSuccess = LoggerUtil('%c[AuthManager]', 'color: #209b07; font-weight: bold')
// Functions // Functions
@ -69,18 +72,20 @@ exports.validateSelected = async function(){
if(!isValid){ if(!isValid){
try { try {
const session = await Mojang.refresh(current.accessToken, ConfigManager.getClientToken()) const session = await Mojang.refresh(current.accessToken, ConfigManager.getClientToken())
console.log('ses', session)
ConfigManager.updateAuthAccount(current.uuid, session.accessToken) ConfigManager.updateAuthAccount(current.uuid, session.accessToken)
ConfigManager.save() ConfigManager.save()
} catch(err) { } catch(err) {
console.debug('Error while validating selected profile:', err) logger.debug('Error while validating selected profile:', err)
if(err && err.error === 'ForbiddenOperationException'){ if(err && err.error === 'ForbiddenOperationException'){
// What do we do? // What do we do?
} }
logger.log('Account access token is invalid.')
return false return false
} }
loggerSuccess.log('Account access token validated.')
return true return true
} else { } else {
loggerSuccess.log('Account access token validated.')
return true return true
} }
} }

View File

@ -1,9 +1,11 @@
const fs = require('fs') const fs = require('fs')
const mkpath = require('mkdirp') const mkpath = require('mkdirp')
const os = require('os') const os = require('os')
const path = require('path') const path = require('path')
const uuidV4 = require('uuid/v4') const uuidV4 = require('uuid/v4')
const logger = require('./loggerutil')('%c[ConfigManager]', 'color: #a02d2a; font-weight: bold')
const sysRoot = process.env.APPDATA || (process.platform == 'darwin' ? process.env.HOME + '/Library/Application Support' : process.env.HOME) const sysRoot = process.env.APPDATA || (process.platform == 'darwin' ? process.env.HOME + '/Library/Application Support' : process.env.HOME)
const dataPath = path.join(sysRoot, '.westeroscraft') const dataPath = path.join(sysRoot, '.westeroscraft')
@ -106,9 +108,9 @@ exports.load = function(){
config = JSON.parse(fs.readFileSync(filePath, 'UTF-8')) config = JSON.parse(fs.readFileSync(filePath, 'UTF-8'))
doValidate = true doValidate = true
} catch (err){ } catch (err){
console.error(err) logger.error(err)
console.log('%c[ConfigManager]', 'color: #a02d2a; font-weight: bold', 'Configuration file contains malformed JSON or is corrupt.') logger.log('Configuration file contains malformed JSON or is corrupt.')
console.log('%c[ConfigManager]', 'color: #a02d2a; font-weight: bold', 'Generating a new configuration file.') logger.log('Generating a new configuration file.')
mkpath.sync(path.join(filePath, '..')) mkpath.sync(path.join(filePath, '..'))
config = DEFAULT_CONFIG config = DEFAULT_CONFIG
exports.save() exports.save()
@ -118,7 +120,7 @@ exports.load = function(){
exports.save() exports.save()
} }
} }
console.log('%c[ConfigManager]', 'color: #a02d2a; font-weight: bold', 'Successfully Loaded') logger.log('Successfully Loaded')
} }
/** /**

View File

@ -1,4 +1,6 @@
// Work in progress // Work in progress
const logger = require('./loggerutil')('%c[DiscordWrapper]', 'color: #7289da; font-weight: bold')
const {Client} = require('discord-rpc') const {Client} = require('discord-rpc')
let client let client
@ -19,15 +21,15 @@ exports.initRPC = function(genSettings, servSettings, initialDetails = 'Waiting
} }
client.on('ready', () => { client.on('ready', () => {
console.log('%c[Discord Wrapper]', 'color: #a02d2a; font-weight: bold', 'Discord RPC Connected') logger.log('Discord RPC Connected')
client.setActivity(activity) client.setActivity(activity)
}) })
client.login({clientId: genSettings.clientId}).catch(error => { client.login({clientId: genSettings.clientId}).catch(error => {
if(error.message.includes('ENOENT')) { if(error.message.includes('ENOENT')) {
console.log('%c[Discord Wrapper]', 'color: #a02d2a; font-weight: bold', 'Unable to initialize Discord Rich Presence, no client detected.') logger.log('Unable to initialize Discord Rich Presence, no client detected.')
} else { } else {
console.log('%c[Discord Wrapper]', 'color: #a02d2a; font-weight: bold', 'Unable to initialize Discord Rich Presence: ' + error.message, error) logger.log('Unable to initialize Discord Rich Presence: ' + error.message, error)
} }
}) })
} }

View File

@ -3,6 +3,7 @@ const path = require('path')
const request = require('request') const request = require('request')
const ConfigManager = require('./configmanager') const ConfigManager = require('./configmanager')
const logger = require('./loggerutil')('%c[DistroManager]', 'color: #a02d2a; font-weight: bold')
/** /**
* Represents the download information * Represents the download information
@ -168,7 +169,7 @@ class Module {
} catch (err) { } catch (err) {
// Improper identifier // Improper identifier
console.error('Improper ID for module', this.identifier, err) logger.error('Improper ID for module', this.identifier, err)
} }
} }
@ -567,10 +568,10 @@ exports.pullLocal = function(){
exports.setDevMode = function(value){ exports.setDevMode = function(value){
if(value){ if(value){
console.log('%c[DistroManager]', 'color: #a02d2a; font-weight: bold', 'Developer mode enabled.') logger.log('Developer mode enabled.')
console.log('%c[DistroManager]', 'color: #a02d2a; font-weight: bold', 'If you don\'t know what that means, revert immediately.') logger.log('If you don\'t know what that means, revert immediately.')
} else { } else {
console.log('%c[DistroManager]', 'color: #a02d2a; font-weight: bold', 'Developer mode disabled.') logger.log('Developer mode disabled.')
} }
DEV_MODE = value DEV_MODE = value
} }
@ -585,10 +586,3 @@ exports.isDevMode = function(){
exports.getDistribution = function(){ exports.getDistribution = function(){
return data return data
} }
/*async function debug(){
const d = await exports.pullRemote()
console.log(d)
}
debug()*/
//console.log(DistroIndex.fromJSON(JSON.parse(require('fs').readFileSync('../distribution.json', 'utf-8'))))

View File

@ -0,0 +1,28 @@
class LoggerUtil {
constructor(prefix, style){
this.prefix = prefix
this.style = style
}
log(){
console.log.apply(null, [this.prefix, this.style, ...arguments])
}
info(){
console.info.apply(null, [this.prefix, this.style, ...arguments])
}
debug(){
console.debug.apply(null, [this.prefix, this.style, ...arguments])
}
error(){
console.error.apply(null, [this.prefix, this.style, ...arguments])
}
}
module.exports = function (prefix, style){
return new LoggerUtil(prefix, style)
}

View File

@ -7,6 +7,7 @@
*/ */
// Requirements // Requirements
const request = require('request') const request = require('request')
const logger = require('./loggerutil')('%c[Mojang]', 'color: #a02d2a; font-weight: bold')
// Constants // Constants
const minecraftAgent = { const minecraftAgent = {
@ -95,8 +96,8 @@ exports.status = function(){
function(error, response, body){ function(error, response, body){
if(error || response.statusCode !== 200){ if(error || response.statusCode !== 200){
console.warn('Unable to retrieve Mojang status.') logger.warn('Unable to retrieve Mojang status.')
console.debug('Error while retrieving Mojang statuses:', error) logger.debug('Error while retrieving Mojang statuses:', error)
//reject(error || response.statusCode) //reject(error || response.statusCode)
for(let i=0; i<statuses.length; i++){ for(let i=0; i<statuses.length; i++){
statuses[i].status = 'grey' statuses[i].status = 'grey'
@ -145,7 +146,7 @@ exports.authenticate = function(username, password, clientToken, requestUser = t
}, },
function(error, response, body){ function(error, response, body){
if(error){ if(error){
console.error('Error during authentication.', error) logger.error('Error during authentication.', error)
reject(error) reject(error)
} else { } else {
if(response.statusCode === 200){ if(response.statusCode === 200){
@ -179,7 +180,7 @@ exports.validate = function(accessToken, clientToken){
}, },
function(error, response, body){ function(error, response, body){
if(error){ if(error){
console.error('Error during validation.', error) logger.error('Error during validation.', error)
reject(error) reject(error)
} else { } else {
if(response.statusCode === 403){ if(response.statusCode === 403){
@ -214,7 +215,7 @@ exports.invalidate = function(accessToken, clientToken){
}, },
function(error, response, body){ function(error, response, body){
if(error){ if(error){
console.error('Error during invalidation.', error) logger.error('Error during invalidation.', error)
reject(error) reject(error)
} else { } else {
if(response.statusCode === 204){ if(response.statusCode === 204){
@ -251,7 +252,7 @@ exports.refresh = function(accessToken, clientToken, requestUser = true){
}, },
function(error, response, body){ function(error, response, body){
if(error){ if(error){
console.error('Error during refresh.', error) logger.error('Error during refresh.', error)
reject(error) reject(error)
} else { } else {
if(response.statusCode === 200){ if(response.statusCode === 200){

View File

@ -1,12 +1,13 @@
const {ipcRenderer} = require('electron') const {ipcRenderer} = require('electron')
const os = require('os') const os = require('os')
const path = require('path') const path = require('path')
const rimraf = require('rimraf') const rimraf = require('rimraf')
const ConfigManager = require('./configmanager') const ConfigManager = require('./configmanager')
const DistroManager = require('./distromanager') const DistroManager = require('./distromanager')
const logger = require('./loggerutil')('%c[Preloader]', 'color: #a02d2a; font-weight: bold')
console.log('%c[Preloader]', 'color: #a02d2a; font-weight: bold', 'Loading..') logger.log('Loading..')
// Load ConfigManager // Load ConfigManager
ConfigManager.load() ConfigManager.load()
@ -16,7 +17,7 @@ function onDistroLoad(data){
// Resolve the selected server if its value has yet to be set. // Resolve the selected server if its value has yet to be set.
if(ConfigManager.getSelectedServer() == null || data.getServer(ConfigManager.getSelectedServer()) == null){ if(ConfigManager.getSelectedServer() == null || data.getServer(ConfigManager.getSelectedServer()) == null){
console.log('%c[Preloader]', 'color: #a02d2a; font-weight: bold', 'Determining default selected server..') logger.log('Determining default selected server..')
ConfigManager.setSelectedServer(data.getMainServer().getID()) ConfigManager.setSelectedServer(data.getMainServer().getID())
ConfigManager.save() ConfigManager.save()
} }
@ -26,27 +27,27 @@ function onDistroLoad(data){
// Ensure Distribution is downloaded and cached. // Ensure Distribution is downloaded and cached.
DistroManager.pullRemote().then((data) => { DistroManager.pullRemote().then((data) => {
console.log('%c[Preloader]', 'color: #a02d2a; font-weight: bold', 'Loaded distribution index.') logger.log('Loaded distribution index.')
onDistroLoad(data) onDistroLoad(data)
}).catch((err) => { }).catch((err) => {
console.log('%c[Preloader]', 'color: #a02d2a; font-weight: bold', 'Failed to load distribution index.') logger.log('Failed to load distribution index.')
console.error(err) logger.error(err)
console.log('%c[Preloader]', 'color: #a02d2a; font-weight: bold', 'Attempting to load an older version of the distribution index.') logger.log('Attempting to load an older version of the distribution index.')
// Try getting a local copy, better than nothing. // Try getting a local copy, better than nothing.
DistroManager.pullLocal().then((data) => { DistroManager.pullLocal().then((data) => {
console.log('%c[Preloader]', 'color: #a02d2a; font-weight: bold', 'Successfully loaded an older version of the distribution index.') logger.log('Successfully loaded an older version of the distribution index.')
onDistroLoad(data) onDistroLoad(data)
}).catch((err) => { }).catch((err) => {
console.log('%c[Preloader]', 'color: #a02d2a; font-weight: bold', 'Failed to load an older version of the distribution index.') logger.log('Failed to load an older version of the distribution index.')
console.log('%c[Preloader]', 'color: #a02d2a; font-weight: bold', 'Application cannot run.') logger.log('Application cannot run.')
console.error(err) logger.error(err)
onDistroLoad(null) onDistroLoad(null)
@ -57,8 +58,8 @@ DistroManager.pullRemote().then((data) => {
// Clean up temp dir incase previous launches ended unexpectedly. // Clean up temp dir incase previous launches ended unexpectedly.
rimraf(path.join(os.tmpdir(), ConfigManager.getTempNativeFolder()), (err) => { rimraf(path.join(os.tmpdir(), ConfigManager.getTempNativeFolder()), (err) => {
if(err){ if(err){
console.warn('%c[Preloader]', 'color: #a02d2a; font-weight: bold', 'Error while cleaning natives directory', err) logger.warn('Error while cleaning natives directory', err)
} else { } else {
console.log('%c[Preloader]', 'color: #a02d2a; font-weight: bold', 'Cleaned natives directory.') logger.log('Cleaned natives directory.')
} }
}) })

View File

@ -8,9 +8,12 @@ const path = require('path')
const rimraf = require('rimraf') const rimraf = require('rimraf')
const {URL} = require('url') const {URL} = require('url')
const { Library } = require('./assetguard') const { Library } = require('./assetguard')
const ConfigManager = require('./configmanager') const ConfigManager = require('./configmanager')
const DistroManager = require('./distromanager') const DistroManager = require('./distromanager')
const LoggerUtil = require('./loggerutil')
const logger = LoggerUtil('%c[ProcessBuilder]', 'color: #003996; font-weight: bold')
class ProcessBuilder { class ProcessBuilder {
@ -37,7 +40,7 @@ class ProcessBuilder {
const tempNativePath = path.join(os.tmpdir(), ConfigManager.getTempNativeFolder(), crypto.pseudoRandomBytes(16).toString('hex')) const tempNativePath = path.join(os.tmpdir(), ConfigManager.getTempNativeFolder(), crypto.pseudoRandomBytes(16).toString('hex'))
process.throwDeprecation = true process.throwDeprecation = true
this.setupLiteLoader() this.setupLiteLoader()
console.log('%c[ProcessBuilder]', 'color: #003996; font-weight: bold', 'Using liteloader:', this.usingLiteLoader) logger.log('Using liteloader:', this.usingLiteLoader)
const modObj = this.resolveModConfiguration(ConfigManager.getModConfiguration(this.server.getID()).mods, this.server.getModules()) const modObj = this.resolveModConfiguration(ConfigManager.getModConfiguration(this.server.getID()).mods, this.server.getModules())
this.constructModList('forge', modObj.fMods, true) this.constructModList('forge', modObj.fMods, true)
if(this.usingLiteLoader){ if(this.usingLiteLoader){
@ -46,7 +49,7 @@ class ProcessBuilder {
const uberModArr = modObj.fMods.concat(modObj.lMods) const uberModArr = modObj.fMods.concat(modObj.lMods)
const args = this.constructJVMArguments(uberModArr, tempNativePath) const args = this.constructJVMArguments(uberModArr, tempNativePath)
console.log(args) logger.log('Launch Arguments:', args)
const child = child_process.spawn(ConfigManager.getJavaExecutable(), args, { const child = child_process.spawn(ConfigManager.getJavaExecutable(), args, {
cwd: this.gameDir, cwd: this.gameDir,
@ -60,19 +63,22 @@ class ProcessBuilder {
child.stdout.setEncoding('utf8') child.stdout.setEncoding('utf8')
child.stderr.setEncoding('utf8') child.stderr.setEncoding('utf8')
const loggerMCstdout = LoggerUtil('%c[Minecraft]', 'color: #36b030; font-weight: bold')
const loggerMCstderr = LoggerUtil('%c[Minecraft]', 'color: #b03030; font-weight: bold')
child.stdout.on('data', (data) => { child.stdout.on('data', (data) => {
console.log('%c[Minecraft]', 'color: #36b030; font-weight: bold', data) loggerMCstdout.log(data)
}) })
child.stderr.on('data', (data) => { child.stderr.on('data', (data) => {
console.log('%c[Minecraft]', 'color: #b03030; font-weight: bold', data) loggerMCstderr.log(data)
}) })
child.on('close', (code, signal) => { child.on('close', (code, signal) => {
console.log('%c[ProcessBuilder]', 'color: #003996; font-weight: bold', 'Exited with code', code) logger.log('Exited with code', code)
rimraf(tempNativePath, (err) => { rimraf(tempNativePath, (err) => {
if(err){ if(err){
console.warn('%c[ProcessBuilder]', 'color: #003996; font-weight: bold', 'Error while deleting temp dir', err) logger.warn('Error while deleting temp dir', err)
} else { } else {
console.log('%c[ProcessBuilder]', 'color: #003996; font-weight: bold', 'Temp dir deleted successfully.') logger.log('Temp dir deleted successfully.')
} }
}) })
}) })
@ -401,7 +407,7 @@ class ProcessBuilder {
if(!shouldExclude){ if(!shouldExclude){
fs.writeFile(path.join(tempNativePath, fileName), zipEntries[i].getData(), (err) => { fs.writeFile(path.join(tempNativePath, fileName), zipEntries[i].getData(), (err) => {
if(err){ if(err){
console.error('Error while extracting native library:', err) logger.error('Error while extracting native library:', err)
} }
}) })
} }

View File

@ -21,6 +21,8 @@ const launch_details_text = document.getElementById('launch_details_text')
const server_selection_button = document.getElementById('server_selection_button') const server_selection_button = document.getElementById('server_selection_button')
const user_text = document.getElementById('user_text') const user_text = document.getElementById('user_text')
const loggerLanding = LoggerUtil('%c[Landing]', 'color: #000668; font-weight: bold')
/* Launch Progress Wrapper Functions */ /* Launch Progress Wrapper Functions */
/** /**
@ -83,7 +85,7 @@ function setLaunchEnabled(val){
// 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..') loggerLanding.log('Launching game..')
const jExe = ConfigManager.getJavaExecutable() const jExe = ConfigManager.getJavaExecutable()
if(jExe == null){ if(jExe == null){
asyncSystemScan() asyncSystemScan()
@ -94,7 +96,7 @@ document.getElementById('launch_button').addEventListener('click', function(e){
setLaunchPercentage(0, 100) setLaunchPercentage(0, 100)
AssetGuard._validateJavaBinary(jExe).then((v) => { AssetGuard._validateJavaBinary(jExe).then((v) => {
console.log(v) loggerLanding.log('Java version meta', v)
if(v.valid){ if(v.valid){
dlAsync() dlAsync()
} else { } else {
@ -152,7 +154,7 @@ server_selection_button.onclick = (e) => {
// Update Mojang Status Color // Update Mojang Status Color
const refreshMojangStatuses = async function(){ const refreshMojangStatuses = async function(){
console.log('Refreshing Mojang Statuses..') loggerLanding.log('Refreshing Mojang Statuses..')
let status = 'grey' let status = 'grey'
let tooltipEssentialHTML = '' let tooltipEssentialHTML = ''
@ -200,8 +202,8 @@ const refreshMojangStatuses = async function(){
} }
} catch (err) { } catch (err) {
console.warn('Unable to refresh Mojang service status.') loggerLanding.warn('Unable to refresh Mojang service status.')
console.debug(err) loggerLanding.debug(err)
} }
document.getElementById('mojangStatusEssentialContainer').innerHTML = tooltipEssentialHTML document.getElementById('mojangStatusEssentialContainer').innerHTML = tooltipEssentialHTML
@ -210,7 +212,7 @@ const refreshMojangStatuses = async function(){
} }
const refreshServerStatus = async function(fade = false){ const refreshServerStatus = async function(fade = false){
console.log('Refreshing Server Status') loggerLanding.log('Refreshing Server Status')
const serv = DistroManager.getDistribution().getServer(ConfigManager.getSelectedServer()) const serv = DistroManager.getDistribution().getServer(ConfigManager.getSelectedServer())
let pLabel = 'SERVER' let pLabel = 'SERVER'
@ -225,8 +227,8 @@ const refreshServerStatus = async function(fade = false){
} }
} catch (err) { } catch (err) {
console.warn('Unable to refresh server status, assuming offline.') loggerLanding.warn('Unable to refresh server status, assuming offline.')
console.debug(err) loggerLanding.debug(err)
} }
if(fade){ if(fade){
$('#server_status_wrapper').fadeOut(250, () => { $('#server_status_wrapper').fadeOut(250, () => {
@ -261,6 +263,8 @@ function asyncSystemScan(launchAfter = true){
toggleLaunchArea(true) toggleLaunchArea(true)
setLaunchPercentage(0, 100) setLaunchPercentage(0, 100)
const loggerSysAEx = LoggerUtil('%c[SysAEx]', 'color: #353232; font-weight: bold')
// Fork a process to run validations. // Fork a process to run validations.
sysAEx = cp.fork(path.join(__dirname, 'assets', 'js', 'assetexec.js'), [ sysAEx = cp.fork(path.join(__dirname, 'assets', 'js', 'assetexec.js'), [
ConfigManager.getCommonDirectory(), ConfigManager.getCommonDirectory(),
@ -269,12 +273,14 @@ function asyncSystemScan(launchAfter = true){
stdio: 'pipe' stdio: 'pipe'
}) })
// Stdout // Stdout
sysAEx.stdio[1].setEncoding('utf8')
sysAEx.stdio[1].on('data', (data) => { sysAEx.stdio[1].on('data', (data) => {
console.log('%c[SysAEx]', 'color: #353232; font-weight: bold', data.toString('utf-8')) loggerSysAEx.log(data)
}) })
// Stderr // Stderr
sysAEx.stdio[2].setEncoding('utf8')
sysAEx.stdio[2].on('data', (data) => { sysAEx.stdio[2].on('data', (data) => {
console.log('%c[SysAEx]', 'color: #353232; font-weight: bold', data.toString('utf-8')) loggerSysAEx.log(data)
}) })
sysAEx.on('message', (m) => { sysAEx.on('message', (m) => {
@ -442,8 +448,7 @@ function dlAsync(login = true){
if(login) { if(login) {
if(ConfigManager.getSelectedAccount() == null){ if(ConfigManager.getSelectedAccount() == null){
console.error('login first.') loggerLanding.error('You must be logged into an account.')
//in devtools AuthManager.addAccount(username, pass)
return return
} }
} }
@ -452,6 +457,9 @@ function dlAsync(login = true){
toggleLaunchArea(true) toggleLaunchArea(true)
setLaunchPercentage(0, 100) setLaunchPercentage(0, 100)
const loggerAEx = LoggerUtil('%c[AEx]', 'color: #353232; font-weight: bold')
const loggerLaunchSuite = LoggerUtil('%c[LaunchSuite]', 'color: #000668; font-weight: bold')
// Start AssetExec to run validations and downloads in a forked process. // Start AssetExec to run validations and downloads in a forked process.
aEx = cp.fork(path.join(__dirname, 'assets', 'js', 'assetexec.js'), [ aEx = cp.fork(path.join(__dirname, 'assets', 'js', 'assetexec.js'), [
ConfigManager.getCommonDirectory(), ConfigManager.getCommonDirectory(),
@ -460,12 +468,14 @@ function dlAsync(login = true){
stdio: 'pipe' stdio: 'pipe'
}) })
// Stdout // Stdout
aEx.stdio[1].setEncoding('utf8')
aEx.stdio[1].on('data', (data) => { aEx.stdio[1].on('data', (data) => {
console.log('%c[AEx]', 'color: #353232; font-weight: bold', data.toString('utf-8')) loggerAEx.log(data)
}) })
// Stderr // Stderr
aEx.stdio[2].setEncoding('utf8')
aEx.stdio[2].on('data', (data) => { aEx.stdio[2].on('data', (data) => {
console.log('%c[AEx]', 'color: #353232; font-weight: bold', data.toString('utf-8')) loggerAEx.log(data)
}) })
// Establish communications between the AssetExec and current process. // Establish communications between the AssetExec and current process.
@ -475,27 +485,27 @@ function dlAsync(login = true){
switch(m.data){ switch(m.data){
case 'distribution': case 'distribution':
setLaunchPercentage(20, 100) setLaunchPercentage(20, 100)
console.log('Validated distibution index.') loggerLaunchSuite.log('Validated distibution index.')
setLaunchDetails('Loading version information..') setLaunchDetails('Loading version information..')
break break
case 'version': case 'version':
setLaunchPercentage(40, 100) setLaunchPercentage(40, 100)
console.log('Version data loaded.') loggerLaunchSuite.log('Version data loaded.')
setLaunchDetails('Validating asset integrity..') setLaunchDetails('Validating asset integrity..')
break break
case 'assets': case 'assets':
setLaunchPercentage(60, 100) setLaunchPercentage(60, 100)
console.log('Asset Validation Complete') loggerLaunchSuite.log('Asset Validation Complete')
setLaunchDetails('Validating library integrity..') setLaunchDetails('Validating library integrity..')
break break
case 'libraries': case 'libraries':
setLaunchPercentage(80, 100) setLaunchPercentage(80, 100)
console.log('Library validation complete.') loggerLaunchSuite.log('Library validation complete.')
setLaunchDetails('Validating miscellaneous file integrity..') setLaunchDetails('Validating miscellaneous file integrity..')
break break
case 'files': case 'files':
setLaunchPercentage(100, 100) setLaunchPercentage(100, 100)
console.log('File validation complete.') loggerLaunchSuite.log('File validation complete.')
setLaunchDetails('Downloading files..') setLaunchDetails('Downloading files..')
break break
} }
@ -544,7 +554,7 @@ function dlAsync(login = true){
} else if(m.context === 'error'){ } else if(m.context === 'error'){
switch(m.data){ switch(m.data){
case 'download': case 'download':
console.error(m.error) loggerLaunchSuite.error('Error while downloading:', m.error)
if(m.error.code === 'ENOENT'){ if(m.error.code === 'ENOENT'){
setOverlayContent( setOverlayContent(
@ -574,7 +584,7 @@ function dlAsync(login = true){
// If these properties are not defined it's likely an error. // If these properties are not defined it's likely an error.
if(m.result.forgeData == null || m.result.versionData == null){ if(m.result.forgeData == null || m.result.versionData == null){
console.error(m.result) loggerLaunchSuite.error('Error during validation:', m.result)
} }
forgeData = m.result.forgeData forgeData = m.result.forgeData
@ -582,7 +592,7 @@ function dlAsync(login = true){
if(login) { if(login) {
const authUser = ConfigManager.getSelectedAccount() const authUser = ConfigManager.getSelectedAccount()
console.log('authu', authUser) loggerLaunchSuite.log(`Sending selected account (${authUser.displayName}) to ProcessBuilder.`)
let pb = new ProcessBuilder(serv, versionData, forgeData, authUser) let pb = new ProcessBuilder(serv, versionData, forgeData, authUser)
setLaunchDetails('Launching game..') setLaunchDetails('Launching game..')
@ -615,7 +625,7 @@ function dlAsync(login = true){
const gameErrorListener = function(data){ const gameErrorListener = function(data){
data = data.trim() data = data.trim()
if(data.indexOf('Could not find or load main class net.minecraft.launchwrapper.Launch') > -1){ if(data.indexOf('Could not find or load main class net.minecraft.launchwrapper.Launch') > -1){
console.error('Game launch failed, LaunchWrapper was not downloaded properly.') loggerLaunchSuite.error('Game launch failed, LaunchWrapper was not downloaded properly.')
setOverlayContent( setOverlayContent(
'Error During Launch', 'Error During Launch',
'The main file, LaunchWrapper, failed to download properly. As a result, the game cannot launch.<br><br>To fix this issue, temporarily turn off your antivirus software and launch the game again.<br><br>If you have time, please <a href="https://github.com/WesterosCraftCode/ElectronLauncher/issues">submit an issue</a> and let us know what antivirus software you use. We\'ll contact them and try to straighten things out.', 'The main file, LaunchWrapper, failed to download properly. As a result, the game cannot launch.<br><br>To fix this issue, temporarily turn off your antivirus software and launch the game again.<br><br>If you have time, please <a href="https://github.com/WesterosCraftCode/ElectronLauncher/issues">submit an issue</a> and let us know what antivirus software you use. We\'ll contact them and try to straighten things out.',
@ -643,7 +653,7 @@ function dlAsync(login = true){
DiscordWrapper.initRPC(distro.discord, serv.discord) DiscordWrapper.initRPC(distro.discord, serv.discord)
hasRPC = true hasRPC = true
proc.on('close', (code, signal) => { proc.on('close', (code, signal) => {
console.log('Shutting down Discord Rich Presence..') loggerLaunchSuite.log('Shutting down Discord Rich Presence..')
DiscordWrapper.shutdownRPC() DiscordWrapper.shutdownRPC()
hasRPC = false hasRPC = false
proc = null proc = null
@ -652,7 +662,7 @@ function dlAsync(login = true){
} catch(err) { } catch(err) {
console.error('Error during launch', err) loggerLaunchSuite.error('Error during launch', err)
setOverlayContent( setOverlayContent(
'Error During Launch', 'Error During Launch',
'Please check the console for more details.', 'Please check the console for more details.',
@ -681,13 +691,13 @@ function dlAsync(login = true){
serv = data.getServer(ConfigManager.getSelectedServer()) serv = data.getServer(ConfigManager.getSelectedServer())
aEx.send({task: 'execute', function: 'validateEverything', argsArr: [ConfigManager.getSelectedServer(), DistroManager.isDevMode()]}) aEx.send({task: 'execute', function: 'validateEverything', argsArr: [ConfigManager.getSelectedServer(), DistroManager.isDevMode()]})
}, (err) => { }, (err) => {
console.log(err) loggerLaunchSuite.log('Error while fetching a fresh copy of the distribution index.', err)
refreshDistributionIndex(false, (data) => { refreshDistributionIndex(false, (data) => {
onDistroRefresh(data) onDistroRefresh(data)
serv = data.getServer(ConfigManager.getSelectedServer()) serv = data.getServer(ConfigManager.getSelectedServer())
aEx.send({task: 'execute', function: 'validateEverything', argsArr: [ConfigManager.getSelectedServer(), DistroManager.isDevMode()]}) aEx.send({task: 'execute', function: 'validateEverything', argsArr: [ConfigManager.getSelectedServer(), DistroManager.isDevMode()]})
}, (err) => { }, (err) => {
console.error('Unable to refresh distribution index.', err) loggerLaunchSuite.error('Unable to refresh distribution index.', err)
if(DistroManager.getDistribution() == null){ if(DistroManager.getDistribution() == null){
setOverlayContent( setOverlayContent(
'Fatal Error', 'Fatal Error',

View File

@ -21,6 +21,8 @@ const loginForm = document.getElementById('loginForm')
// Control variables. // Control variables.
let lu = false, lp = false let lu = false, lp = false
const loggerLogin = LoggerUtil('%c[Login]', 'color: #000668; font-weight: bold')
/** /**
* Show a login error. * Show a login error.
@ -256,7 +258,6 @@ loginButton.addEventListener('click', () => {
loginButton.innerHTML = loginButton.innerHTML.replace('LOGGING IN', 'SUCCESS') loginButton.innerHTML = loginButton.innerHTML.replace('LOGGING IN', 'SUCCESS')
$('.circle-loader').toggleClass('load-complete') $('.circle-loader').toggleClass('load-complete')
$('.checkmark').toggle() $('.checkmark').toggle()
//console.log(value)
setTimeout(() => { setTimeout(() => {
switchView(VIEWS.login, loginViewOnSuccess, 500, 500, () => { switchView(VIEWS.login, loginViewOnSuccess, 500, 500, () => {
// Temporary workaround // Temporary workaround
@ -284,7 +285,7 @@ loginButton.addEventListener('click', () => {
toggleOverlay(false) toggleOverlay(false)
}) })
toggleOverlay(true) toggleOverlay(true)
console.log(err) loggerLogin.log('Error while logging in.', err)
}) })
}) })

View File

@ -57,7 +57,7 @@ function getCurrentView(){
function showMainUI(data){ function showMainUI(data){
if(!isDev){ if(!isDev){
console.log('%c[AutoUpdater]', 'color: #a02d2a; font-weight: bold', 'Initializing..') loggerAutoUpdater.log('Initializing..')
ipcRenderer.send('autoUpdateAction', 'initAutoUpdater', ConfigManager.getAllowPrerelease()) ipcRenderer.send('autoUpdateAction', 'initAutoUpdater', ConfigManager.getAllowPrerelease())
} }
@ -73,13 +73,7 @@ function showMainUI(data){
// If this is enabled in a development environment we'll get ratelimited. // If this is enabled in a development environment we'll get ratelimited.
// The relaunch frequency is usually far too high. // The relaunch frequency is usually far too high.
if(!isDev && isLoggedIn){ if(!isDev && isLoggedIn){
validateSelectedAccount().then((v) => { validateSelectedAccount()
if(v){
console.log('%c[AuthManager]', 'color: #209b07; font-weight: bold', 'Account access token validated.')
} else {
console.log('%c[AuthManager]', 'color: #a02d2a; font-weight: bold', 'Account access token is invalid.')
}
})
} }
if(ConfigManager.isFirstLaunch()){ if(ConfigManager.isFirstLaunch()){

View File

@ -8,6 +8,11 @@
const $ = require('jquery') const $ = require('jquery')
const {ipcRenderer, remote, shell, webFrame} = require('electron') const {ipcRenderer, remote, shell, webFrame} = require('electron')
const isDev = require('electron-is-dev') const isDev = require('electron-is-dev')
const LoggerUtil = require('./assets/js/loggerutil')
const loggerUICore = LoggerUtil('%c[UICore]', 'color: #000668; font-weight: bold')
const loggerAutoUpdater = LoggerUtil('%c[AutoUpdater]', 'color: #000668; font-weight: bold')
const loggerAutoUpdaterSuccess = LoggerUtil('%c[AutoUpdater]', 'color: #209b07; font-weight: bold')
// Disable eval function. // Disable eval function.
// eslint-disable-next-line // eslint-disable-next-line
@ -33,15 +38,15 @@ if(!isDev){
ipcRenderer.on('autoUpdateNotification', (event, arg, info) => { ipcRenderer.on('autoUpdateNotification', (event, arg, info) => {
switch(arg){ switch(arg){
case 'checking-for-update': case 'checking-for-update':
console.log('%c[AutoUpdater]', 'color: #a02d2a; font-weight: bold', 'Checking for update..') loggerAutoUpdater.log('Checking for update..')
settingsUpdateButtonStatus('Checking for Updates..', true) settingsUpdateButtonStatus('Checking for Updates..', true)
break break
case 'update-available': case 'update-available':
console.log('%c[AutoUpdater]', 'color: #a02d2a; font-weight: bold', 'New update available', info.version) loggerAutoUpdaterSuccess.log('New update available', info.version)
populateSettingsUpdateInformation(info) populateSettingsUpdateInformation(info)
break break
case 'update-downloaded': case 'update-downloaded':
console.log('%c[AutoUpdater]', 'color: #a02d2a; font-weight: bold', 'Update ' + info.version + ' ready to be installed.') loggerAutoUpdaterSuccess.log('Update ' + info.version + ' ready to be installed.')
settingsUpdateButtonStatus('Install Now', false, () => { settingsUpdateButtonStatus('Install Now', false, () => {
if(!isDev){ if(!isDev){
ipcRenderer.send('autoUpdateAction', 'installUpdateNow') ipcRenderer.send('autoUpdateAction', 'installUpdateNow')
@ -50,7 +55,7 @@ if(!isDev){
showUpdateUI(info) showUpdateUI(info)
break break
case 'update-not-available': case 'update-not-available':
console.log('%c[AutoUpdater]', 'color: #a02d2a; font-weight: bold', 'No new update found.') loggerAutoUpdater.log('No new update found.')
settingsUpdateButtonStatus('Check for Updates') settingsUpdateButtonStatus('Check for Updates')
break break
case 'ready': case 'ready':
@ -62,17 +67,17 @@ if(!isDev){
case 'realerror': case 'realerror':
if(info != null && info.code != null){ if(info != null && info.code != null){
if(info.code === 'ERR_UPDATER_INVALID_RELEASE_FEED'){ if(info.code === 'ERR_UPDATER_INVALID_RELEASE_FEED'){
console.log('%c[AutoUpdater]', 'color: #a02d2a; font-weight: bold', 'No suitable releases found.') loggerAutoUpdater.log('No suitable releases found.')
} else if(info.code === 'ERR_XML_MISSED_ELEMENT'){ } else if(info.code === 'ERR_XML_MISSED_ELEMENT'){
console.log('%c[AutoUpdater]', 'color: #a02d2a; font-weight: bold', 'No releases found.') loggerAutoUpdater.log('No releases found.')
} else { } else {
console.error('%c[AutoUpdater]', 'color: #a02d2a; font-weight: bold', 'Error during update check..', info) loggerAutoUpdater.error('Error during update check..', info)
console.debug('%c[AutoUpdater]', 'color: #a02d2a; font-weight: bold', 'Error Code:', info.code) loggerAutoUpdater.debug('Error Code:', info.code)
} }
} }
break break
default: default:
console.log('%c[AutoUpdater]', 'color: #a02d2a; font-weight: bold', 'Unknown argument', arg) loggerAutoUpdater.log('Unknown argument', arg)
break break
} }
}) })
@ -115,12 +120,12 @@ function showUpdateUI(info){
/* jQuery Example /* jQuery Example
$(function(){ $(function(){
console.log('UICore Initialized'); loggerUICore.log('UICore Initialized');
})*/ })*/
document.addEventListener('readystatechange', function () { document.addEventListener('readystatechange', function () {
if (document.readyState === 'interactive'){ if (document.readyState === 'interactive'){
console.log('UICore Initializing..') loggerUICore.log('UICore Initializing..')
// Bind close button. // Bind close button.
Array.from(document.getElementsByClassName('fCb')).map((val) => { Array.from(document.getElementsByClassName('fCb')).map((val) => {
@ -183,7 +188,6 @@ document.addEventListener('readystatechange', function () {
*/ */
$(document).on('click', 'a[href^="http"]', function(event) { $(document).on('click', 'a[href^="http"]', function(event) {
event.preventDefault() event.preventDefault()
//console.log(os.homedir())
shell.openExternal(this.href) shell.openExternal(this.href)
}) })