Mise a jour

This commit is contained in:
FullGreenDev 2020-12-02 21:14:17 +01:00
parent d8201e3624
commit 244c77832b
12 changed files with 719 additions and 711 deletions

View File

@ -47,6 +47,18 @@
</div> </div>
</div> </div>
</div> </div>
<div id="loading-view" style="display: none;">
<div class="loading-container">
<div class="paladium-loader"></div>
<div class="loading-text">
<p id="loading-splash-text"></p>
<p class="loading-sudmitted-text">Proposé par FullGreen.Sky</p>
<p id="loading-statut-text">Chargement en cours</p>
</div>
</div>
</div>
<script> <script>
// Load language // Load language
for (let key of Object.keys(Lang.query('html'))) { for (let key of Object.keys(Lang.query('html'))) {

View File

@ -1,7 +1,7 @@
let target = require('./assetguard')[process.argv[2]] let target = require('./assetguard')[process.argv[2]]
if(target == null){ if (target == null) {
process.send({context: 'error', data: null, error: 'Invalid class name'}) process.send({ context: 'error', data: null, error: 'Nom de classe non valide' })
console.error('Invalid class name passed to argv[2], cannot continue.') console.error('Nom de classe non valide transmis à argv[2], impossible de continuer.')
process.exit(1) process.exit(1)
} }
let tracker = new target(...(process.argv.splice(3))) let tracker = new target(...(process.argv.splice(3)))
@ -13,51 +13,52 @@ console.log('AssetExec Started')
process.on('unhandledRejection', r => console.log(r)) process.on('unhandledRejection', r => console.log(r))
let percent = 0 let percent = 0
function assignListeners(){
function assignListeners() {
tracker.on('validate', (data) => { tracker.on('validate', (data) => {
process.send({context: 'validate', data}) process.send({ context: 'validate', data })
}) })
tracker.on('progress', (data, acc, total) => { tracker.on('progress', (data, acc, total) => {
const currPercent = parseInt((acc/total) * 100) const currPercent = parseInt((acc / total) * 100)
if (currPercent !== percent) { if (currPercent !== percent) {
percent = currPercent percent = currPercent
process.send({context: 'progress', data, value: acc, total, percent}) process.send({ context: 'progress', data, value: acc, total, percent })
} }
}) })
tracker.on('complete', (data, ...args) => { tracker.on('complete', (data, ...args) => {
process.send({context: 'complete', data, args}) process.send({ context: 'complete', data, args })
}) })
tracker.on('error', (data, error) => { tracker.on('error', (data, error) => {
process.send({context: 'error', data, error}) process.send({ context: 'error', data, error })
}) })
} }
assignListeners() assignListeners()
process.on('message', (msg) => { process.on('message', (msg) => {
if(msg.task === 'execute'){ if (msg.task === 'execute') {
const func = msg.function const func = msg.function
let nS = tracker[func] // Nonstatic context let nS = tracker[func] // Nonstatic context
let iS = target[func] // Static context let iS = target[func] // Static context
if(typeof nS === 'function' || typeof iS === 'function'){ if (typeof nS === 'function' || typeof iS === 'function') {
const f = typeof nS === 'function' ? nS : iS const f = typeof nS === 'function' ? nS : iS
const res = f.apply(f === nS ? tracker : null, msg.argsArr) const res = f.apply(f === nS ? tracker : null, msg.argsArr)
if(res instanceof Promise){ if (res instanceof Promise) {
res.then((v) => { res.then((v) => {
process.send({result: v, context: func}) process.send({ result: v, context: func })
}).catch((err) => { }).catch((err) => {
process.send({result: err.message || err, context: func}) process.send({ result: err.message || err, context: func })
}) })
} else { } else {
process.send({result: res, context: func}) process.send({ result: res, context: func })
} }
} else { } else {
process.send({context: 'error', data: null, error: `Function ${func} not found on ${process.argv[2]}`}) process.send({ context: 'error', data: null, error: `Function ${func} not found on ${process.argv[2]}` })
} }
} else if(msg.task === 'changeContext'){ } else if (msg.task === 'changeContext') {
target = require('./assetguard')[msg.class] target = require('./assetguard')[msg.class]
if(target == null){ if (target == null) {
process.send({context: 'error', data: null, error: `Invalid class ${msg.class}`}) process.send({ context: 'error', data: null, error: `Classe invalide ${msg.class}` })
} else { } else {
tracker = new target(...(msg.args)) tracker = new target(...(msg.args))
assignListeners() assignListeners()
@ -66,6 +67,6 @@ process.on('message', (msg) => {
}) })
process.on('disconnect', () => { process.on('disconnect', () => {
console.log('AssetExec Disconnected') console.log('AssetExec déconnecté')
process.exit(0) process.exit(0)
}) })

File diff suppressed because it is too large Load Diff

View File

@ -10,9 +10,9 @@
*/ */
// Requirements // Requirements
const ConfigManager = require('./configmanager') const ConfigManager = require('./configmanager')
const LoggerUtil = require('./loggerutil') const LoggerUtil = require('./loggerutil')
const Mojang = require('./mojang') const Mojang = require('./mojang')
const logger = LoggerUtil('%c[AuthManager]', 'color: #a02d2a; font-weight: bold') const logger = LoggerUtil('%c[AuthManager]', 'color: #a02d2a; font-weight: bold')
const loggerSuccess = LoggerUtil('%c[AuthManager]', 'color: #209b07; font-weight: bold') const loggerSuccess = LoggerUtil('%c[AuthManager]', 'color: #209b07; font-weight: bold')
// Functions // Functions
@ -26,12 +26,12 @@ const loggerSuccess = LoggerUtil('%c[AuthManager]', 'color: #209b07; font-weight
* @param {string} password The account password. * @param {string} password The account password.
* @returns {Promise.<Object>} Promise which resolves the resolved authenticated account object. * @returns {Promise.<Object>} Promise which resolves the resolved authenticated account object.
*/ */
exports.addAccount = async function(username, password){ exports.addAccount = async function(username, password) {
try { try {
const session = await Mojang.authenticate(username, password, ConfigManager.getClientToken()) const session = await Mojang.authenticate(username, password, ConfigManager.getClientToken())
if(session.selectedProfile != null){ if (session.selectedProfile != null) {
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)
if(ConfigManager.getClientToken() == null){ if (ConfigManager.getClientToken() == null) {
ConfigManager.setClientToken(session.clientToken) ConfigManager.setClientToken(session.clientToken)
} }
ConfigManager.save() ConfigManager.save()
@ -39,8 +39,8 @@ exports.addAccount = async function(username, password){
} else { } else {
throw new Error('NotPaidAccount') throw new Error('NotPaidAccount')
} }
} catch (err){ } catch (err) {
return Promise.reject(err) return Promise.reject(err)
} }
} }
@ -52,14 +52,14 @@ exports.addAccount = async function(username, password){
* @param {string} uuid The UUID of the account to be removed. * @param {string} uuid The UUID of the account to be removed.
* @returns {Promise.<void>} Promise which resolves to void when the action is complete. * @returns {Promise.<void>} Promise which resolves to void when the action is complete.
*/ */
exports.removeAccount = async function(uuid){ exports.removeAccount = async function(uuid) {
try { try {
const authAcc = ConfigManager.getAuthAccount(uuid) const authAcc = ConfigManager.getAuthAccount(uuid)
await Mojang.invalidate(authAcc.accessToken, ConfigManager.getClientToken()) await Mojang.invalidate(authAcc.accessToken, ConfigManager.getClientToken())
ConfigManager.removeAuthAccount(uuid) ConfigManager.removeAuthAccount(uuid)
ConfigManager.save() ConfigManager.save()
return Promise.resolve() return Promise.resolve()
} catch (err){ } catch (err) {
return Promise.reject(err) return Promise.reject(err)
} }
} }
@ -74,26 +74,26 @@ exports.removeAccount = async function(uuid){
* @returns {Promise.<boolean>} Promise which resolves to true if the access token is valid, * @returns {Promise.<boolean>} Promise which resolves to true if the access token is valid,
* otherwise false. * otherwise false.
*/ */
exports.validateSelected = async function(){ exports.validateSelected = async function() {
const current = ConfigManager.getSelectedAccount() const current = ConfigManager.getSelectedAccount()
const isValid = await Mojang.validate(current.accessToken, ConfigManager.getClientToken()) const isValid = await Mojang.validate(current.accessToken, ConfigManager.getClientToken())
if(!isValid){ if (!isValid) {
try { try {
const session = await Mojang.refresh(current.accessToken, ConfigManager.getClientToken()) const session = await Mojang.refresh(current.accessToken, ConfigManager.getClientToken())
ConfigManager.updateAuthAccount(current.uuid, session.accessToken) ConfigManager.updateAuthAccount(current.uuid, session.accessToken)
ConfigManager.save() ConfigManager.save()
} catch(err) { } catch (err) {
logger.debug('Error while validating selected profile:', err) logger.debug('Erreur lors de la validation du profil sélectionné:', 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.') logger.log('Le jeton d\'accès au compte n\'est pas valide.')
return false return false
} }
loggerSuccess.log('Account access token validated.') loggerSuccess.log('Jeton d\'accès au compte validé.')
return true return true
} else { } else {
loggerSuccess.log('Account access token validated.') loggerSuccess.log('Jeton d\'accès au compte validé.')
return true return true
} }
} }

View File

@ -144,8 +144,8 @@ exports.load = function() {
doValidate = true doValidate = true
} catch (err) { } catch (err) {
logger.error(err) logger.error(err)
logger.log('Configuration file contains malformed JSON or is corrupt.') logger.log('Le fichier de configuration contient un JSON mal formé ou corrompu.')
logger.log('Generating a new configuration file.') logger.log('Génération d\'un nouveau fichier de configuration.')
fs.ensureDirSync(path.join(configPath, '..')) fs.ensureDirSync(path.join(configPath, '..'))
config = DEFAULT_CONFIG config = DEFAULT_CONFIG
exports.save() exports.save()
@ -155,7 +155,7 @@ exports.load = function() {
exports.save() exports.save()
} }
} }
logger.log('Successfully Loaded') logger.log('Chargé avec succès')
} }
/** /**

View File

@ -1,5 +1,5 @@
const fs = require('fs-extra') const fs = require('fs-extra')
const path = require('path') const path = require('path')
const { shell } = require('electron') const { shell } = require('electron')
// Group #1: File Name (without .disabled, if any) // Group #1: File Name (without .disabled, if any)
@ -35,16 +35,16 @@ exports.validateDir = function(dir) {
*/ */
exports.scanForDropinMods = function(modsDir, version) { exports.scanForDropinMods = function(modsDir, version) {
const modsDiscovered = [] const modsDiscovered = []
if(fs.existsSync(modsDir)){ if (fs.existsSync(modsDir)) {
let modCandidates = fs.readdirSync(modsDir) let modCandidates = fs.readdirSync(modsDir)
let verCandidates = [] let verCandidates = []
const versionDir = path.join(modsDir, version) const versionDir = path.join(modsDir, version)
if(fs.existsSync(versionDir)){ if (fs.existsSync(versionDir)) {
verCandidates = fs.readdirSync(versionDir) verCandidates = fs.readdirSync(versionDir)
} }
for(let file of modCandidates){ for (let file of modCandidates) {
const match = MOD_REGEX.exec(file) const match = MOD_REGEX.exec(file)
if(match != null){ if (match != null) {
modsDiscovered.push({ modsDiscovered.push({
fullName: match[0], fullName: match[0],
name: match[1], name: match[1],
@ -53,9 +53,9 @@ exports.scanForDropinMods = function(modsDir, version) {
}) })
} }
} }
for(let file of verCandidates){ for (let file of verCandidates) {
const match = MOD_REGEX.exec(file) const match = MOD_REGEX.exec(file)
if(match != null){ if (match != null) {
modsDiscovered.push({ modsDiscovered.push({
fullName: path.join(version, match[0]), fullName: path.join(version, match[0]),
name: match[1], name: match[1],
@ -78,8 +78,8 @@ exports.addDropinMods = function(files, modsdir) {
exports.validateDir(modsdir) exports.validateDir(modsdir)
for(let f of files) { for (let f of files) {
if(MOD_REGEX.exec(f.name) != null) { if (MOD_REGEX.exec(f.name) != null) {
fs.moveSync(f.path, path.join(modsdir, f.name)) fs.moveSync(f.path, path.join(modsdir, f.name))
} }
} }
@ -94,9 +94,9 @@ exports.addDropinMods = function(files, modsdir) {
* *
* @returns {boolean} True if the mod was deleted, otherwise false. * @returns {boolean} True if the mod was deleted, otherwise false.
*/ */
exports.deleteDropinMod = function(modsDir, fullName){ exports.deleteDropinMod = function(modsDir, fullName) {
const res = shell.moveItemToTrash(path.join(modsDir, fullName)) const res = shell.moveItemToTrash(path.join(modsDir, fullName))
if(!res){ if (!res) {
shell.beep() shell.beep()
} }
return res return res
@ -113,13 +113,13 @@ exports.deleteDropinMod = function(modsDir, fullName){
* @returns {Promise.<void>} A promise which resolves when the mod has * @returns {Promise.<void>} A promise which resolves when the mod has
* been toggled. If an IO error occurs the promise will be rejected. * been toggled. If an IO error occurs the promise will be rejected.
*/ */
exports.toggleDropinMod = function(modsDir, fullName, enable){ exports.toggleDropinMod = function(modsDir, fullName, enable) {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
const oldPath = path.join(modsDir, fullName) const oldPath = path.join(modsDir, fullName)
const newPath = path.join(modsDir, enable ? fullName.substring(0, fullName.indexOf(DISABLED_EXT)) : fullName + DISABLED_EXT) const newPath = path.join(modsDir, enable ? fullName.substring(0, fullName.indexOf(DISABLED_EXT)) : fullName + DISABLED_EXT)
fs.rename(oldPath, newPath, (err) => { fs.rename(oldPath, newPath, (err) => {
if(err){ if (err) {
reject(err) reject(err)
} else { } else {
resolve() resolve()
@ -134,7 +134,7 @@ exports.toggleDropinMod = function(modsDir, fullName, enable){
* @param {string} fullName The fullName of the discovered mod to toggle. * @param {string} fullName The fullName of the discovered mod to toggle.
* @returns {boolean} True if the mod is enabled, otherwise false. * @returns {boolean} True if the mod is enabled, otherwise false.
*/ */
exports.isDropinModEnabled = function(fullName){ exports.isDropinModEnabled = function(fullName) {
return !fullName.endsWith(DISABLED_EXT) return !fullName.endsWith(DISABLED_EXT)
} }
@ -146,17 +146,17 @@ exports.isDropinModEnabled = function(fullName){
* @returns {{fullName: string, name: string}[]} * @returns {{fullName: string, name: string}[]}
* An array of objects storing metadata about each discovered shaderpack. * An array of objects storing metadata about each discovered shaderpack.
*/ */
exports.scanForShaderpacks = function(instanceDir){ exports.scanForShaderpacks = function(instanceDir) {
const shaderDir = path.join(instanceDir, SHADER_DIR) const shaderDir = path.join(instanceDir, SHADER_DIR)
const packsDiscovered = [{ const packsDiscovered = [{
fullName: 'OFF', fullName: 'OFF',
name: 'Off (Default)' name: 'Off (Default)'
}] }]
if(fs.existsSync(shaderDir)){ if (fs.existsSync(shaderDir)) {
let modCandidates = fs.readdirSync(shaderDir) let modCandidates = fs.readdirSync(shaderDir)
for(let file of modCandidates){ for (let file of modCandidates) {
const match = SHADER_REGEX.exec(file) const match = SHADER_REGEX.exec(file)
if(match != null){ if (match != null) {
packsDiscovered.push({ packsDiscovered.push({
fullName: match[0], fullName: match[0],
name: match[1] name: match[1]
@ -175,17 +175,17 @@ exports.scanForShaderpacks = function(instanceDir){
* *
* @returns {string} The file name of the enabled shaderpack. * @returns {string} The file name of the enabled shaderpack.
*/ */
exports.getEnabledShaderpack = function(instanceDir){ exports.getEnabledShaderpack = function(instanceDir) {
exports.validateDir(instanceDir) exports.validateDir(instanceDir)
const optionsShaders = path.join(instanceDir, SHADER_CONFIG) const optionsShaders = path.join(instanceDir, SHADER_CONFIG)
if(fs.existsSync(optionsShaders)){ if (fs.existsSync(optionsShaders)) {
const buf = fs.readFileSync(optionsShaders, {encoding: 'utf-8'}) const buf = fs.readFileSync(optionsShaders, { encoding: 'utf-8' })
const match = SHADER_OPTION.exec(buf) const match = SHADER_OPTION.exec(buf)
if(match != null){ if (match != null) {
return match[1] return match[1]
} else { } else {
console.warn('WARNING: Shaderpack regex failed.') console.warn('AVERTISSEMENT: Shaderpack regex a échoué.')
} }
} }
return 'OFF' return 'OFF'
@ -197,18 +197,18 @@ exports.getEnabledShaderpack = function(instanceDir){
* @param {string} instanceDir The path to the server instance directory. * @param {string} instanceDir The path to the server instance directory.
* @param {string} pack the file name of the shaderpack. * @param {string} pack the file name of the shaderpack.
*/ */
exports.setEnabledShaderpack = function(instanceDir, pack){ exports.setEnabledShaderpack = function(instanceDir, pack) {
exports.validateDir(instanceDir) exports.validateDir(instanceDir)
const optionsShaders = path.join(instanceDir, SHADER_CONFIG) const optionsShaders = path.join(instanceDir, SHADER_CONFIG)
let buf let buf
if(fs.existsSync(optionsShaders)){ if (fs.existsSync(optionsShaders)) {
buf = fs.readFileSync(optionsShaders, {encoding: 'utf-8'}) buf = fs.readFileSync(optionsShaders, { encoding: 'utf-8' })
buf = buf.replace(SHADER_OPTION, `shaderPack=${pack}`) buf = buf.replace(SHADER_OPTION, `shaderPack=${pack}`)
} else { } else {
buf = `shaderPack=${pack}` buf = `shaderPack=${pack}`
} }
fs.writeFileSync(optionsShaders, buf, {encoding: 'utf-8'}) fs.writeFileSync(optionsShaders, buf, { encoding: 'utf-8' })
} }
/** /**
@ -223,8 +223,8 @@ exports.addShaderpacks = function(files, instanceDir) {
exports.validateDir(p) exports.validateDir(p)
for(let f of files) { for (let f of files) {
if(SHADER_REGEX.exec(f.name) != null) { if (SHADER_REGEX.exec(f.name) != null) {
fs.moveSync(f.path, path.join(p, f.name)) fs.moveSync(f.path, path.join(p, f.name))
} }
} }

View File

@ -7,7 +7,7 @@
*/ */
// Requirements // Requirements
const request = require('request') const request = require('request')
const logger = require('./loggerutil')('%c[Mojang]', 'color: #a02d2a; font-weight: bold') const logger = require('./loggerutil')('%c[Mojang]', 'color: #a02d2a; font-weight: bold')
// Constants // Constants
const minecraftAgent = { const minecraftAgent = {
@ -15,8 +15,7 @@ const minecraftAgent = {
version: 1 version: 1
} }
const authpath = 'https://authserver.mojang.com' const authpath = 'https://authserver.mojang.com'
const statuses = [ const statuses = [{
{
service: 'sessionserver.mojang.com', service: 'sessionserver.mojang.com',
status: 'grey', status: 'grey',
name: 'Multiplayer Session Service', name: 'Multiplayer Session Service',
@ -64,8 +63,8 @@ const statuses = [
* @param {string} status A valid status code. * @param {string} status A valid status code.
* @returns {string} The hex color of the status code. * @returns {string} The hex color of the status code.
*/ */
exports.statusToHex = function(status){ exports.statusToHex = function(status) {
switch(status.toLowerCase()){ switch (status.toLowerCase()) {
case 'green': case 'green':
return '#a5c325' return '#a5c325'
case 'yellow': case 'yellow':
@ -86,33 +85,32 @@ exports.statusToHex = function(status){
* *
* @see http://wiki.vg/Mojang_API#API_Status * @see http://wiki.vg/Mojang_API#API_Status
*/ */
exports.status = function(){ exports.status = function() {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
request.get('https://status.mojang.com/check', request.get('https://status.mojang.com/check', {
{
json: true, json: true,
timeout: 2500 timeout: 2500
}, },
function(error, response, body){ function(error, response, body) {
if(error || response.statusCode !== 200){ if (error || response.statusCode !== 200) {
logger.warn('Unable to retrieve Mojang status.') logger.warn('Impossible de récupérer le statut Mojang.')
logger.debug('Error while retrieving Mojang statuses:', error) logger.debug('Erreur lors de la récupération des statuts Mojang:', 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'
} }
resolve(statuses) resolve(statuses)
} else { } else {
for(let i=0; i<body.length; i++){ for (let i = 0; i < body.length; i++) {
const key = Object.keys(body[i])[0] const key = Object.keys(body[i])[0]
inner: inner:
for(let j=0; j<statuses.length; j++){ for (let j = 0; j < statuses.length; j++) {
if(statuses[j].service === key) { if (statuses[j].service === key) {
statuses[j].status = body[i][key] statuses[j].status = body[i][key]
break inner break inner
}
} }
}
} }
resolve(statuses) resolve(statuses)
} }
@ -131,7 +129,7 @@ exports.status = function(){
* *
* @see http://wiki.vg/Authentication#Authenticate * @see http://wiki.vg/Authentication#Authenticate
*/ */
exports.authenticate = function(username, password, clientToken, requestUser = true, agent = minecraftAgent){ exports.authenticate = function(username, password, clientToken, requestUser = true, agent = minecraftAgent) {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
const body = { const body = {
@ -140,24 +138,23 @@ exports.authenticate = function(username, password, clientToken, requestUser = t
password, password,
requestUser requestUser
} }
if(clientToken != null){ if (clientToken != null) {
body.clientToken = clientToken body.clientToken = clientToken
} }
request.post(authpath + '/authenticate', request.post(authpath + '/authenticate', {
{
json: true, json: true,
body body
}, },
function(error, response, body){ function(error, response, body) {
if(error){ if (error) {
logger.error('Error during authentication.', error) logger.error('Erreur lors de l\'authentification.', error)
reject(error) reject(error)
} else { } else {
if(response.statusCode === 200){ if (response.statusCode === 200) {
resolve(body) resolve(body)
} else { } else {
reject(body || {code: 'ENOTFOUND'}) reject(body || { code: 'ENOTFOUND' })
} }
} }
}) })
@ -173,25 +170,24 @@ exports.authenticate = function(username, password, clientToken, requestUser = t
* *
* @see http://wiki.vg/Authentication#Validate * @see http://wiki.vg/Authentication#Validate
*/ */
exports.validate = function(accessToken, clientToken){ exports.validate = function(accessToken, clientToken) {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
request.post(authpath + '/validate', request.post(authpath + '/validate', {
{
json: true, json: true,
body: { body: {
accessToken, accessToken,
clientToken clientToken
} }
}, },
function(error, response, body){ function(error, response, body) {
if(error){ if (error) {
logger.error('Error during validation.', error) logger.error('Erreur lors de l\'authentification.', error)
reject(error) reject(error)
} else { } else {
if(response.statusCode === 403){ if (response.statusCode === 403) {
resolve(false) resolve(false)
} else { } else {
// 204 if valid // 204 if valid
resolve(true) resolve(true)
} }
} }
@ -208,22 +204,21 @@ exports.validate = function(accessToken, clientToken){
* *
* @see http://wiki.vg/Authentication#Invalidate * @see http://wiki.vg/Authentication#Invalidate
*/ */
exports.invalidate = function(accessToken, clientToken){ exports.invalidate = function(accessToken, clientToken) {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
request.post(authpath + '/invalidate', request.post(authpath + '/invalidate', {
{
json: true, json: true,
body: { body: {
accessToken, accessToken,
clientToken clientToken
} }
}, },
function(error, response, body){ function(error, response, body) {
if(error){ if (error) {
logger.error('Error during invalidation.', error) logger.error('Erreur lors de l\'authentification', error)
reject(error) reject(error)
} else { } else {
if(response.statusCode === 204){ if (response.statusCode === 204) {
resolve() resolve()
} else { } else {
reject(body) reject(body)
@ -244,10 +239,9 @@ exports.invalidate = function(accessToken, clientToken){
* *
* @see http://wiki.vg/Authentication#Refresh * @see http://wiki.vg/Authentication#Refresh
*/ */
exports.refresh = function(accessToken, clientToken, requestUser = true){ exports.refresh = function(accessToken, clientToken, requestUser = true) {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
request.post(authpath + '/refresh', request.post(authpath + '/refresh', {
{
json: true, json: true,
body: { body: {
accessToken, accessToken,
@ -255,12 +249,12 @@ exports.refresh = function(accessToken, clientToken, requestUser = true){
requestUser requestUser
} }
}, },
function(error, response, body){ function(error, response, body) {
if(error){ if (error) {
logger.error('Error during refresh.', error) logger.error('Erreur lors de l\'actualisation.', error)
reject(error) reject(error)
} else { } else {
if(response.statusCode === 200){ if (response.statusCode === 200) {
resolve(body) resolve(body)
} else { } else {
reject(body) reject(body)

View File

@ -1,12 +1,12 @@
const {ipcRenderer} = require('electron') const { ipcRenderer } = require('electron')
const fs = require('fs-extra') const fs = require('fs-extra')
const os = require('os') const os = require('os')
const path = require('path') const path = require('path')
const ConfigManager = require('./configmanager') const ConfigManager = require('./configmanager')
const DistroManager = require('./distromanager') const DistroManager = require('./distromanager')
const LangLoader = require('./langloader') const LangLoader = require('./langloader')
const logger = require('./loggerutil')('%c[Preloader]', 'color: #a02d2a; font-weight: bold') const logger = require('./loggerutil')('%c[Preloader]', 'color: #a02d2a; font-weight: bold')
logger.log('Loading..') logger.log('Loading..')
@ -16,12 +16,12 @@ ConfigManager.load()
// Load Strings // Load Strings
LangLoader.loadLanguage('en_US') LangLoader.loadLanguage('en_US')
function onDistroLoad(data){ function onDistroLoad(data) {
if(data != null){ if (data != null) {
// 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) {
logger.log('Determining default selected server..') logger.log('Determination du serveur par default..')
ConfigManager.setSelectedServer(data.getMainServer().getID()) ConfigManager.setSelectedServer(data.getMainServer().getID())
ConfigManager.save() ConfigManager.save()
} }
@ -31,26 +31,26 @@ function onDistroLoad(data){
// Ensure Distribution is downloaded and cached. // Ensure Distribution is downloaded and cached.
DistroManager.pullRemote().then((data) => { DistroManager.pullRemote().then((data) => {
logger.log('Loaded distribution index.') logger.log('Index de distribution chargé.')
onDistroLoad(data) onDistroLoad(data)
}).catch((err) => { }).catch((err) => {
logger.log('Failed to load distribution index.') logger.log('Impossible de charger une ancienne version de distribution.')
logger.error(err) logger.error(err)
logger.log('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) => {
logger.log('Successfully loaded an older version of the distribution index.') logger.log('Une ancienne version du fichier de distribution a été chargé avec succes')
onDistroLoad(data) onDistroLoad(data)
}).catch((err) => { }).catch((err) => {
logger.log('Failed to load an older version of the distribution index.') logger.log('Impossible de charger une ancienne version de distribution.')
logger.log('Application cannot run.') logger.log('L\'application de peux pas demaré.')
logger.error(err) logger.error(err)
onDistroLoad(null) onDistroLoad(null)
@ -61,9 +61,9 @@ DistroManager.pullRemote().then((data) => {
// Clean up temp dir incase previous launches ended unexpectedly. // Clean up temp dir incase previous launches ended unexpectedly.
fs.remove(path.join(os.tmpdir(), ConfigManager.getTempNativeFolder()), (err) => { fs.remove(path.join(os.tmpdir(), ConfigManager.getTempNativeFolder()), (err) => {
if(err){ if (err) {
logger.warn('Error while cleaning natives directory', err) logger.warn('Erreur durant le nettoyage du dossier des natives', err)
} else { } else {
logger.log('Cleaned natives directory.') logger.log('Dossier des natives nettoyé.')
} }
}) })

View File

@ -1,21 +1,21 @@
const AdmZip = require('adm-zip') const AdmZip = require('adm-zip')
const child_process = require('child_process') const child_process = require('child_process')
const crypto = require('crypto') const crypto = require('crypto')
const fs = require('fs-extra') const fs = require('fs-extra')
const os = require('os') const os = require('os')
const path = require('path') const path = require('path')
const { URL } = require('url') const { URL } = require('url')
const { Util, Library } = require('./assetguard') const { Util, Library } = require('./assetguard')
const ConfigManager = require('./configmanager') const ConfigManager = require('./configmanager')
const DistroManager = require('./distromanager') const DistroManager = require('./distromanager')
const LoggerUtil = require('./loggerutil') const LoggerUtil = require('./loggerutil')
const logger = LoggerUtil('%c[ProcessBuilder]', 'color: #003996; font-weight: bold') const logger = LoggerUtil('%c[ProcessBuilder]', 'color: #003996; font-weight: bold')
class ProcessBuilder { class ProcessBuilder {
constructor(distroServer, versionData, forgeData, authUser, launcherVersion){ constructor(distroServer, versionData, forgeData, authUser, launcherVersion) {
this.gameDir = path.join(ConfigManager.getInstanceDirectory(), distroServer.getID()) this.gameDir = path.join(ConfigManager.getInstanceDirectory(), distroServer.getID())
this.commonDir = ConfigManager.getCommonDirectory() this.commonDir = ConfigManager.getCommonDirectory()
this.server = distroServer this.server = distroServer
@ -31,30 +31,30 @@ class ProcessBuilder {
this.usingLiteLoader = false this.usingLiteLoader = false
this.llPath = null this.llPath = null
} }
/** /**
* Convienence method to run the functions typically used to build a process. * Convienence method to run the functions typically used to build a process.
*/ */
build(){ build() {
fs.ensureDirSync(this.gameDir) fs.ensureDirSync(this.gameDir)
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()
logger.log('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())
// Mod list below 1.13 // Mod list below 1.13
if(!Util.mcVersionAtLeast('1.13', this.server.getMinecraftVersion())){ if (!Util.mcVersionAtLeast('1.13', this.server.getMinecraftVersion())) {
this.constructJSONModList('forge', modObj.fMods, true) this.constructJSONModList('forge', modObj.fMods, true)
if(this.usingLiteLoader){ if (this.usingLiteLoader) {
this.constructJSONModList('liteloader', modObj.lMods, true) this.constructJSONModList('liteloader', modObj.lMods, true)
} }
} }
const uberModArr = modObj.fMods.concat(modObj.lMods) const uberModArr = modObj.fMods.concat(modObj.lMods)
let args = this.constructJVMArguments(uberModArr, tempNativePath) let args = this.constructJVMArguments(uberModArr, tempNativePath)
if(Util.mcVersionAtLeast('1.13', this.server.getMinecraftVersion())){ if (Util.mcVersionAtLeast('1.13', this.server.getMinecraftVersion())) {
//args = args.concat(this.constructModArguments(modObj.fMods)) //args = args.concat(this.constructModArguments(modObj.fMods))
args = args.concat(this.constructModList(modObj.fMods)) args = args.concat(this.constructModList(modObj.fMods))
} }
@ -66,7 +66,7 @@ class ProcessBuilder {
detached: ConfigManager.getLaunchDetached() detached: ConfigManager.getLaunchDetached()
}) })
if(ConfigManager.getLaunchDetached()){ if (ConfigManager.getLaunchDetached()) {
child.unref() child.unref()
} }
@ -85,10 +85,10 @@ class ProcessBuilder {
child.on('close', (code, signal) => { child.on('close', (code, signal) => {
logger.log('Exited with code', code) logger.log('Exited with code', code)
fs.remove(tempNativePath, (err) => { fs.remove(tempNativePath, (err) => {
if(err){ if (err) {
logger.warn('Error while deleting temp dir', err) logger.warn('Erreur lors de la suppression du répertoire temporaire', err)
} else { } else {
logger.log('Temp dir deleted successfully.') logger.log('Répertoire temporaire supprimé avec succès.')
} }
}) })
}) })
@ -113,7 +113,7 @@ class ProcessBuilder {
* @param {Object} required Optional. The required object from the mod's distro declaration. * @param {Object} required Optional. The required object from the mod's distro declaration.
* @returns {boolean} True if the mod is enabled, false otherwise. * @returns {boolean} True if the mod is enabled, false otherwise.
*/ */
static isModEnabled(modCfg, required = null){ static isModEnabled(modCfg, required = null) {
return modCfg != null ? ((typeof modCfg === 'boolean' && modCfg) || (typeof modCfg === 'object' && (typeof modCfg.value !== 'undefined' ? modCfg.value : true))) : required != null ? required.isDefault() : true return modCfg != null ? ((typeof modCfg === 'boolean' && modCfg) || (typeof modCfg === 'object' && (typeof modCfg.value !== 'undefined' ? modCfg.value : true))) : required != null ? required.isDefault() : true
} }
@ -123,19 +123,19 @@ class ProcessBuilder {
* launch options. Note that liteloader is only allowed as a top level * launch options. Note that liteloader is only allowed as a top level
* mod. It must not be declared as a submodule. * mod. It must not be declared as a submodule.
*/ */
setupLiteLoader(){ setupLiteLoader() {
for(let ll of this.server.getModules()){ for (let ll of this.server.getModules()) {
if(ll.getType() === DistroManager.Types.LiteLoader){ if (ll.getType() === DistroManager.Types.LiteLoader) {
if(!ll.getRequired().isRequired()){ if (!ll.getRequired().isRequired()) {
const modCfg = ConfigManager.getModConfiguration(this.server.getID()).mods const modCfg = ConfigManager.getModConfiguration(this.server.getID()).mods
if(ProcessBuilder.isModEnabled(modCfg[ll.getVersionlessID()], ll.getRequired())){ if (ProcessBuilder.isModEnabled(modCfg[ll.getVersionlessID()], ll.getRequired())) {
if(fs.existsSync(ll.getArtifact().getPath())){ if (fs.existsSync(ll.getArtifact().getPath())) {
this.usingLiteLoader = true this.usingLiteLoader = true
this.llPath = ll.getArtifact().getPath() this.llPath = ll.getArtifact().getPath()
} }
} }
} else { } else {
if(fs.existsSync(ll.getArtifact().getPath())){ if (fs.existsSync(ll.getArtifact().getPath())) {
this.usingLiteLoader = true this.usingLiteLoader = true
this.llPath = ll.getArtifact().getPath() this.llPath = ll.getArtifact().getPath()
} }
@ -153,25 +153,25 @@ class ProcessBuilder {
* @returns {{fMods: Array.<Object>, lMods: Array.<Object>}} An object which contains * @returns {{fMods: Array.<Object>, lMods: Array.<Object>}} An object which contains
* a list of enabled forge mods and litemods. * a list of enabled forge mods and litemods.
*/ */
resolveModConfiguration(modCfg, mdls){ resolveModConfiguration(modCfg, mdls) {
let fMods = [] let fMods = []
let lMods = [] let lMods = []
for(let mdl of mdls){ for (let mdl of mdls) {
const type = mdl.getType() const type = mdl.getType()
if(type === DistroManager.Types.ForgeMod || type === DistroManager.Types.LiteMod || type === DistroManager.Types.LiteLoader){ if (type === DistroManager.Types.ForgeMod || type === DistroManager.Types.LiteMod || type === DistroManager.Types.LiteLoader) {
const o = !mdl.getRequired().isRequired() const o = !mdl.getRequired().isRequired()
const e = ProcessBuilder.isModEnabled(modCfg[mdl.getVersionlessID()], mdl.getRequired()) const e = ProcessBuilder.isModEnabled(modCfg[mdl.getVersionlessID()], mdl.getRequired())
if(!o || (o && e)){ if (!o || (o && e)) {
if(mdl.hasSubModules()){ if (mdl.hasSubModules()) {
const v = this.resolveModConfiguration(modCfg[mdl.getVersionlessID()].mods, mdl.getSubModules()) const v = this.resolveModConfiguration(modCfg[mdl.getVersionlessID()].mods, mdl.getSubModules())
fMods = fMods.concat(v.fMods) fMods = fMods.concat(v.fMods)
lMods = lMods.concat(v.lMods) lMods = lMods.concat(v.lMods)
if(mdl.type === DistroManager.Types.LiteLoader){ if (mdl.type === DistroManager.Types.LiteLoader) {
continue continue
} }
} }
if(mdl.type === DistroManager.Types.ForgeMod){ if (mdl.type === DistroManager.Types.ForgeMod) {
fMods.push(mdl) fMods.push(mdl)
} else { } else {
lMods.push(mdl) lMods.push(mdl)
@ -194,19 +194,19 @@ class ProcessBuilder {
* Test to see if this version of forge requires the absolute: prefix * Test to see if this version of forge requires the absolute: prefix
* on the modListFile repository field. * on the modListFile repository field.
*/ */
_requiresAbsolute(){ _requiresAbsolute() {
try { try {
if(this._lteMinorVersion(9)) { if (this._lteMinorVersion(9)) {
return false return false
} }
const ver = this.forgeData.id.split('-')[2] const ver = this.forgeData.id.split('-')[2]
const pts = ver.split('.') const pts = ver.split('.')
const min = [14, 23, 3, 2655] const min = [14, 23, 3, 2655]
for(let i=0; i<pts.length; i++){ for (let i = 0; i < pts.length; i++) {
const parsed = Number.parseInt(pts[i]) const parsed = Number.parseInt(pts[i])
if(parsed < min[i]){ if (parsed < min[i]) {
return false return false
} else if(parsed > min[i]){ } else if (parsed > min[i]) {
return true return true
} }
} }
@ -214,7 +214,7 @@ class ProcessBuilder {
// We know old forge versions follow this format. // We know old forge versions follow this format.
// Error must be caused by newer version. // Error must be caused by newer version.
} }
// Equal or errored // Equal or errored
return true return true
} }
@ -226,24 +226,24 @@ class ProcessBuilder {
* @param {Array.<Object>} mods An array of mods to add to the mod list. * @param {Array.<Object>} mods An array of mods to add to the mod list.
* @param {boolean} save Optional. Whether or not we should save the mod list file. * @param {boolean} save Optional. Whether or not we should save the mod list file.
*/ */
constructJSONModList(type, mods, save = false){ constructJSONModList(type, mods, save = false) {
const modList = { const modList = {
repositoryRoot: ((type === 'forge' && this._requiresAbsolute()) ? 'absolute:' : '') + path.join(this.commonDir, 'modstore') repositoryRoot: ((type === 'forge' && this._requiresAbsolute()) ? 'absolute:' : '') + path.join(this.commonDir, 'modstore')
} }
const ids = [] const ids = []
if(type === 'forge'){ if (type === 'forge') {
for(let mod of mods){ for (let mod of mods) {
ids.push(mod.getExtensionlessID()) ids.push(mod.getExtensionlessID())
} }
} else { } else {
for(let mod of mods){ for (let mod of mods) {
ids.push(mod.getExtensionlessID() + '@' + mod.getExtension()) ids.push(mod.getExtensionlessID() + '@' + mod.getExtension())
} }
} }
modList.modRef = ids modList.modRef = ids
if(save){ if (save) {
const json = JSON.stringify(modList, null, 4) const json = JSON.stringify(modList, null, 4)
fs.writeFileSync(type === 'forge' ? this.fmlDir : this.llDir, json, 'UTF-8') fs.writeFileSync(type === 'forge' ? this.fmlDir : this.llDir, json, 'UTF-8')
} }
@ -271,7 +271,7 @@ class ProcessBuilder {
// } else { // } else {
// return [] // return []
// } // }
// } // }
/** /**
@ -284,7 +284,7 @@ class ProcessBuilder {
return mod.getExtensionlessID() return mod.getExtensionlessID()
}).join('\n') }).join('\n')
if(writeBuffer) { if (writeBuffer) {
fs.writeFileSync(this.forgeModListFile, writeBuffer, 'UTF-8') fs.writeFileSync(this.forgeModListFile, writeBuffer, 'UTF-8')
return [ return [
'--fml.mavenRoots', '--fml.mavenRoots',
@ -298,12 +298,12 @@ class ProcessBuilder {
} }
_processAutoConnectArg(args){ _processAutoConnectArg(args) {
if(ConfigManager.getAutoConnect() && this.server.isAutoConnect()){ if (ConfigManager.getAutoConnect() && this.server.isAutoConnect()) {
const serverURL = new URL('my://' + this.server.getAddress()) const serverURL = new URL('my://' + this.server.getAddress())
args.push('--server') args.push('--server')
args.push(serverURL.hostname) args.push(serverURL.hostname)
if(serverURL.port){ if (serverURL.port) {
args.push('--port') args.push('--port')
args.push(serverURL.port) args.push(serverURL.port)
} }
@ -317,8 +317,8 @@ class ProcessBuilder {
* @param {string} tempNativePath The path to store the native libraries. * @param {string} tempNativePath The path to store the native libraries.
* @returns {Array.<string>} An array containing the full JVM arguments for this process. * @returns {Array.<string>} An array containing the full JVM arguments for this process.
*/ */
constructJVMArguments(mods, tempNativePath){ constructJVMArguments(mods, tempNativePath) {
if(Util.mcVersionAtLeast('1.13', this.server.getMinecraftVersion())){ if (Util.mcVersionAtLeast('1.13', this.server.getMinecraftVersion())) {
return this._constructJVMArguments113(mods, tempNativePath) return this._constructJVMArguments113(mods, tempNativePath)
} else { } else {
return this._constructJVMArguments112(mods, tempNativePath) return this._constructJVMArguments112(mods, tempNativePath)
@ -333,7 +333,7 @@ class ProcessBuilder {
* @param {string} tempNativePath The path to store the native libraries. * @param {string} tempNativePath The path to store the native libraries.
* @returns {Array.<string>} An array containing the full JVM arguments for this process. * @returns {Array.<string>} An array containing the full JVM arguments for this process.
*/ */
_constructJVMArguments112(mods, tempNativePath){ _constructJVMArguments112(mods, tempNativePath) {
let args = [] let args = []
@ -342,7 +342,7 @@ class ProcessBuilder {
args.push(this.classpathArg(mods, tempNativePath).join(process.platform === 'win32' ? ';' : ':')) args.push(this.classpathArg(mods, tempNativePath).join(process.platform === 'win32' ? ';' : ':'))
// Java Arguments // Java Arguments
if(process.platform === 'darwin'){ if (process.platform === 'darwin') {
args.push('-Xdock:name=HeliosLauncher') args.push('-Xdock:name=HeliosLauncher')
args.push('-Xdock:icon=' + path.join(__dirname, '..', 'images', 'minecraft.icns')) args.push('-Xdock:icon=' + path.join(__dirname, '..', 'images', 'minecraft.icns'))
} }
@ -370,7 +370,7 @@ class ProcessBuilder {
* @param {string} tempNativePath The path to store the native libraries. * @param {string} tempNativePath The path to store the native libraries.
* @returns {Array.<string>} An array containing the full JVM arguments for this process. * @returns {Array.<string>} An array containing the full JVM arguments for this process.
*/ */
_constructJVMArguments113(mods, tempNativePath){ _constructJVMArguments113(mods, tempNativePath) {
const argDiscovery = /\${*(.*)}/ const argDiscovery = /\${*(.*)}/
@ -380,7 +380,7 @@ class ProcessBuilder {
//args.push('-Dlog4j.configurationFile=D:\\WesterosCraft\\game\\common\\assets\\log_configs\\client-1.12.xml') //args.push('-Dlog4j.configurationFile=D:\\WesterosCraft\\game\\common\\assets\\log_configs\\client-1.12.xml')
// Java Arguments // Java Arguments
if(process.platform === 'darwin'){ if (process.platform === 'darwin') {
args.push('-Xdock:name=HeliosLauncher') args.push('-Xdock:name=HeliosLauncher')
args.push('-Xdock:icon=' + path.join(__dirname, '..', 'images', 'minecraft.icns')) args.push('-Xdock:icon=' + path.join(__dirname, '..', 'images', 'minecraft.icns'))
} }
@ -394,27 +394,27 @@ class ProcessBuilder {
// Vanilla Arguments // Vanilla Arguments
args = args.concat(this.versionData.arguments.game) args = args.concat(this.versionData.arguments.game)
for(let i=0; i<args.length; i++){ for (let i = 0; i < args.length; i++) {
if(typeof args[i] === 'object' && args[i].rules != null){ if (typeof args[i] === 'object' && args[i].rules != null) {
let checksum = 0 let checksum = 0
for(let rule of args[i].rules){ for (let rule of args[i].rules) {
if(rule.os != null){ if (rule.os != null) {
if(rule.os.name === Library.mojangFriendlyOS() if (rule.os.name === Library.mojangFriendlyOS() &&
&& (rule.os.version == null || new RegExp(rule.os.version).test(os.release))){ (rule.os.version == null || new RegExp(rule.os.version).test(os.release))) {
if(rule.action === 'allow'){ if (rule.action === 'allow') {
checksum++ checksum++
} }
} else { } else {
if(rule.action === 'disallow'){ if (rule.action === 'disallow') {
checksum++ checksum++
} }
} }
} else if(rule.features != null){ } else if (rule.features != null) {
// We don't have many 'features' in the index at the moment. // We don't have many 'features' in the index at the moment.
// This should be fine for a while. // This should be fine for a while.
if(rule.features.has_custom_resolution != null && rule.features.has_custom_resolution === true){ if (rule.features.has_custom_resolution != null && rule.features.has_custom_resolution === true) {
if(ConfigManager.getFullscreen()){ if (ConfigManager.getFullscreen()) {
args[i].value = [ args[i].value = [
'--fullscreen', '--fullscreen',
'true' 'true'
@ -426,10 +426,10 @@ class ProcessBuilder {
} }
// TODO splice not push // TODO splice not push
if(checksum === args[i].rules.length){ if (checksum === args[i].rules.length) {
if(typeof args[i].value === 'string'){ if (typeof args[i].value === 'string') {
args[i] = args[i].value args[i] = args[i].value
} else if(typeof args[i].value === 'object'){ } else if (typeof args[i].value === 'object') {
//args = args.concat(args[i].value) //args = args.concat(args[i].value)
args.splice(i, 1, ...args[i].value) args.splice(i, 1, ...args[i].value)
} }
@ -440,11 +440,11 @@ class ProcessBuilder {
args[i] = null args[i] = null
} }
} else if(typeof args[i] === 'string'){ } else if (typeof args[i] === 'string') {
if(argDiscovery.test(args[i])){ if (argDiscovery.test(args[i])) {
const identifier = args[i].match(argDiscovery)[1] const identifier = args[i].match(argDiscovery)[1]
let val = null let val = null
switch(identifier){ switch (identifier) {
case 'auth_player_name': case 'auth_player_name':
val = this.authUser.displayName.trim() val = this.authUser.displayName.trim()
break break
@ -492,7 +492,7 @@ class ProcessBuilder {
val = this.classpathArg(mods, tempNativePath).join(process.platform === 'win32' ? ';' : ':') val = this.classpathArg(mods, tempNativePath).join(process.platform === 'win32' ? ';' : ':')
break break
} }
if(val != null){ if (val != null) {
args[i] = val args[i] = val
} }
} }
@ -503,19 +503,19 @@ class ProcessBuilder {
let isAutoconnectBroken let isAutoconnectBroken
try { try {
isAutoconnectBroken = Util.isAutoconnectBroken(this.forgeData.id.split('-')[2]) isAutoconnectBroken = Util.isAutoconnectBroken(this.forgeData.id.split('-')[2])
} catch(err) { } catch (err) {
logger.error(err) logger.error(err)
logger.error('Forge version format changed.. assuming autoconnect works.') logger.error('Le format de la version de Forge a changé ... en supposant que la connexion automatique fonctionne.')
logger.debug('Forge version:', this.forgeData.id) logger.debug('Forge version:', this.forgeData.id)
} }
if(isAutoconnectBroken) { if (isAutoconnectBroken) {
logger.error('Server autoconnect disabled on Forge 1.15.2 for builds earlier than 31.2.15 due to OpenGL Stack Overflow issue.') logger.error('Connexion automatique du serveur désactivée sur Forge 1.15.2 pour les versions antérieures à 31.2.15 en raison d\'un problème d\' OpenGL.')
logger.error('Please upgrade your Forge version to at least 31.2.15!') logger.error('Veuillez mettre à jour votre version de Forge au moins au 31.2.15!')
} else { } else {
this._processAutoConnectArg(args) this._processAutoConnectArg(args)
} }
// Forge Specific Arguments // Forge Specific Arguments
args = args.concat(this.forgeData.arguments.game) args = args.concat(this.forgeData.arguments.game)
@ -533,16 +533,16 @@ class ProcessBuilder {
* *
* @returns {Array.<string>} An array containing the arguments required by forge. * @returns {Array.<string>} An array containing the arguments required by forge.
*/ */
_resolveForgeArgs(){ _resolveForgeArgs() {
const mcArgs = this.forgeData.minecraftArguments.split(' ') const mcArgs = this.forgeData.minecraftArguments.split(' ')
const argDiscovery = /\${*(.*)}/ const argDiscovery = /\${*(.*)}/
// Replace the declared variables with their proper values. // Replace the declared variables with their proper values.
for(let i=0; i<mcArgs.length; ++i){ for (let i = 0; i < mcArgs.length; ++i) {
if(argDiscovery.test(mcArgs[i])){ if (argDiscovery.test(mcArgs[i])) {
const identifier = mcArgs[i].match(argDiscovery)[1] const identifier = mcArgs[i].match(argDiscovery)[1]
let val = null let val = null
switch(identifier){ switch (identifier) {
case 'auth_player_name': case 'auth_player_name':
val = this.authUser.displayName.trim() val = this.authUser.displayName.trim()
break break
@ -575,7 +575,7 @@ class ProcessBuilder {
val = this.versionData.type val = this.versionData.type
break break
} }
if(val != null){ if (val != null) {
mcArgs[i] = val mcArgs[i] = val
} }
} }
@ -585,7 +585,7 @@ class ProcessBuilder {
this._processAutoConnectArg(mcArgs) this._processAutoConnectArg(mcArgs)
// Prepare game resolution // Prepare game resolution
if(ConfigManager.getFullscreen()){ if (ConfigManager.getFullscreen()) {
mcArgs.push('--fullscreen') mcArgs.push('--fullscreen')
mcArgs.push(true) mcArgs.push(true)
} else { } else {
@ -594,18 +594,18 @@ class ProcessBuilder {
mcArgs.push('--height') mcArgs.push('--height')
mcArgs.push(ConfigManager.getGameHeight()) mcArgs.push(ConfigManager.getGameHeight())
} }
// Mod List File Argument // Mod List File Argument
mcArgs.push('--modListFile') mcArgs.push('--modListFile')
if(this._lteMinorVersion(9)) { if (this._lteMinorVersion(9)) {
mcArgs.push(path.basename(this.fmlDir)) mcArgs.push(path.basename(this.fmlDir))
} else { } else {
mcArgs.push('absolute:' + this.fmlDir) mcArgs.push('absolute:' + this.fmlDir)
} }
// LiteLoader // LiteLoader
if(this.usingLiteLoader){ if (this.usingLiteLoader) {
mcArgs.push('--modRepo') mcArgs.push('--modRepo')
mcArgs.push(this.llDir) mcArgs.push(this.llDir)
@ -626,9 +626,9 @@ class ProcessBuilder {
const ext = '.jar' const ext = '.jar'
const extLen = ext.length const extLen = ext.length
for(let i=0; i<list.length; i++) { for (let i = 0; i < list.length; i++) {
const extIndex = list[i].indexOf(ext) const extIndex = list[i].indexOf(ext)
if(extIndex > -1 && extIndex !== list[i].length - extLen) { if (extIndex > -1 && extIndex !== list[i].length - extLen) {
list[i] = list[i].substring(0, extIndex + extLen) list[i] = list[i].substring(0, extIndex + extLen)
} }
} }
@ -644,14 +644,14 @@ class ProcessBuilder {
* @param {string} tempNativePath The path to store the native libraries. * @param {string} tempNativePath The path to store the native libraries.
* @returns {Array.<string>} An array containing the paths of each library required by this process. * @returns {Array.<string>} An array containing the paths of each library required by this process.
*/ */
classpathArg(mods, tempNativePath){ classpathArg(mods, tempNativePath) {
let cpArgs = [] let cpArgs = []
// Add the version.jar to the classpath. // Add the version.jar to the classpath.
const version = this.versionData.id const version = this.versionData.id
cpArgs.push(path.join(this.commonDir, 'versions', version, version + '.jar')) cpArgs.push(path.join(this.commonDir, 'versions', version, version + '.jar'))
if(this.usingLiteLoader){ if (this.usingLiteLoader) {
cpArgs.push(this.llPath) cpArgs.push(this.llPath)
} }
@ -664,7 +664,7 @@ class ProcessBuilder {
// Merge libraries, server libs with the same // Merge libraries, server libs with the same
// maven identifier will override the mojang ones. // maven identifier will override the mojang ones.
// Ex. 1.7.10 forge overrides mojang's guava with newer version. // Ex. 1.7.10 forge overrides mojang's guava with newer version.
const finalLibs = {...mojangLibs, ...servLibs} const finalLibs = {...mojangLibs, ...servLibs }
cpArgs = cpArgs.concat(Object.values(finalLibs)) cpArgs = cpArgs.concat(Object.values(finalLibs))
this._processClassPathList(cpArgs) this._processClassPathList(cpArgs)
@ -681,15 +681,15 @@ class ProcessBuilder {
* @param {string} tempNativePath The path to store the native libraries. * @param {string} tempNativePath The path to store the native libraries.
* @returns {{[id: string]: string}} An object containing the paths of each library mojang declares. * @returns {{[id: string]: string}} An object containing the paths of each library mojang declares.
*/ */
_resolveMojangLibraries(tempNativePath){ _resolveMojangLibraries(tempNativePath) {
const libs = {} const libs = {}
const libArr = this.versionData.libraries const libArr = this.versionData.libraries
fs.ensureDirSync(tempNativePath) fs.ensureDirSync(tempNativePath)
for(let i=0; i<libArr.length; i++){ for (let i = 0; i < libArr.length; i++) {
const lib = libArr[i] const lib = libArr[i]
if(Library.validateRules(lib.rules, lib.natives)){ if (Library.validateRules(lib.rules, lib.natives)) {
if(lib.natives == null){ if (lib.natives == null) {
const dlInfo = lib.downloads const dlInfo = lib.downloads
const artifact = dlInfo.artifact const artifact = dlInfo.artifact
const to = path.join(this.libPath, artifact.path) const to = path.join(this.libPath, artifact.path)
@ -699,35 +699,35 @@ class ProcessBuilder {
// Extract the native library. // Extract the native library.
const exclusionArr = lib.extract != null ? lib.extract.exclude : ['META-INF/'] const exclusionArr = lib.extract != null ? lib.extract.exclude : ['META-INF/']
const artifact = lib.downloads.classifiers[lib.natives[Library.mojangFriendlyOS()].replace('${arch}', process.arch.replace('x', ''))] const artifact = lib.downloads.classifiers[lib.natives[Library.mojangFriendlyOS()].replace('${arch}', process.arch.replace('x', ''))]
// Location of native zip. // Location of native zip.
const to = path.join(this.libPath, artifact.path) const to = path.join(this.libPath, artifact.path)
let zip = new AdmZip(to) let zip = new AdmZip(to)
let zipEntries = zip.getEntries() let zipEntries = zip.getEntries()
// Unzip the native zip. // Unzip the native zip.
for(let i=0; i<zipEntries.length; i++){ for (let i = 0; i < zipEntries.length; i++) {
const fileName = zipEntries[i].entryName const fileName = zipEntries[i].entryName
let shouldExclude = false let shouldExclude = false
// Exclude noted files. // Exclude noted files.
exclusionArr.forEach(function(exclusion){ exclusionArr.forEach(function(exclusion) {
if(fileName.indexOf(exclusion) > -1){ if (fileName.indexOf(exclusion) > -1) {
shouldExclude = true shouldExclude = true
} }
}) })
// Extract the file. // Extract the file.
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) {
logger.error('Error while extracting native library:', err) logger.error('Erreur durant l\'extraction de la bibliotheque de native:', err)
} }
}) })
} }
} }
} }
} }
@ -744,30 +744,30 @@ class ProcessBuilder {
* @param {Array.<Object>} mods An array of enabled mods which will be launched with this process. * @param {Array.<Object>} mods An array of enabled mods which will be launched with this process.
* @returns {{[id: string]: string}} An object containing the paths of each library this server requires. * @returns {{[id: string]: string}} An object containing the paths of each library this server requires.
*/ */
_resolveServerLibraries(mods){ _resolveServerLibraries(mods) {
const mdls = this.server.getModules() const mdls = this.server.getModules()
let libs = {} let libs = {}
// Locate Forge/Libraries // Locate Forge/Libraries
for(let mdl of mdls){ for (let mdl of mdls) {
const type = mdl.getType() const type = mdl.getType()
if(type === DistroManager.Types.ForgeHosted || type === DistroManager.Types.Library){ if (type === DistroManager.Types.ForgeHosted || type === DistroManager.Types.Library) {
libs[mdl.getVersionlessID()] = mdl.getArtifact().getPath() libs[mdl.getVersionlessID()] = mdl.getArtifact().getPath()
if(mdl.hasSubModules()){ if (mdl.hasSubModules()) {
const res = this._resolveModuleLibraries(mdl) const res = this._resolveModuleLibraries(mdl)
if(res.length > 0){ if (res.length > 0) {
libs = {...libs, ...res} libs = {...libs, ...res }
} }
} }
} }
} }
//Check for any libraries in our mod list. //Check for any libraries in our mod list.
for(let i=0; i<mods.length; i++){ for (let i = 0; i < mods.length; i++) {
if(mods.sub_modules != null){ if (mods.sub_modules != null) {
const res = this._resolveModuleLibraries(mods[i]) const res = this._resolveModuleLibraries(mods[i])
if(res.length > 0){ if (res.length > 0) {
libs = {...libs, ...res} libs = {...libs, ...res }
} }
} }
} }
@ -781,20 +781,20 @@ class ProcessBuilder {
* @param {Object} mdl A module object from the server distro index. * @param {Object} mdl A module object from the server distro index.
* @returns {Array.<string>} An array containing the paths of each library this module requires. * @returns {Array.<string>} An array containing the paths of each library this module requires.
*/ */
_resolveModuleLibraries(mdl){ _resolveModuleLibraries(mdl) {
if(!mdl.hasSubModules()){ if (!mdl.hasSubModules()) {
return [] return []
} }
let libs = [] let libs = []
for(let sm of mdl.getSubModules()){ for (let sm of mdl.getSubModules()) {
if(sm.getType() === DistroManager.Types.Library){ if (sm.getType() === DistroManager.Types.Library) {
libs.push(sm.getArtifact().getPath()) libs.push(sm.getArtifact().getPath())
} }
// If this module has submodules, we need to resolve the libraries for those. // If this module has submodules, we need to resolve the libraries for those.
// To avoid unnecessary recursive calls, base case is checked here. // To avoid unnecessary recursive calls, base case is checked here.
if(mdl.hasSubModules()){ if (mdl.hasSubModules()) {
const res = this._resolveModuleLibraries(sm) const res = this._resolveModuleLibraries(sm)
if(res.length > 0){ if (res.length > 0) {
libs = libs.concat(res) libs = libs.concat(res)
} }
} }

View File

@ -85,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) {
loggerLanding.log('Launching game..') loggerLanding.log('Lancement du jeu..')
const mcVersion = DistroManager.getDistribution().getServer(ConfigManager.getSelectedServer()).getMinecraftVersion() const mcVersion = DistroManager.getDistribution().getServer(ConfigManager.getSelectedServer()).getMinecraftVersion()
const jExe = ConfigManager.getJavaExecutable() const jExe = ConfigManager.getJavaExecutable()
if (jExe == null) { if (jExe == null) {
@ -98,7 +98,7 @@ document.getElementById('launch_button').addEventListener('click', function(e) {
const jg = new JavaGuard(mcVersion) const jg = new JavaGuard(mcVersion)
jg._validateJavaBinary(jExe).then((v) => { jg._validateJavaBinary(jExe).then((v) => {
loggerLanding.log('Java version meta', v) loggerLanding.log('Version de la donnée de meta de Java', v)
if (v.valid) { if (v.valid) {
dlAsync() dlAsync()
} else { } else {
@ -124,7 +124,7 @@ document.getElementById('avatarOverlay').onclick = (e) => {
// Bind selected account // Bind selected account
function updateSelectedAccount(authUser) { function updateSelectedAccount(authUser) {
let username = 'No Account Selected' let username = 'Aucun compte selectionné'
if (authUser != null) { if (authUser != null) {
if (authUser.displayName != null) { if (authUser.displayName != null) {
username = authUser.displayName username = authUser.displayName
@ -144,7 +144,7 @@ function updateSelectedServer(serv) {
} }
ConfigManager.setSelectedServer(serv != null ? serv.getID() : null) ConfigManager.setSelectedServer(serv != null ? serv.getID() : null)
ConfigManager.save() ConfigManager.save()
server_selection_button.innerHTML = '\u2022 ' + (serv != null ? serv.getName() : 'No Server Selected') server_selection_button.innerHTML = '\u2022 ' + (serv != null ? serv.getName() : 'Aucun serveur selecionné')
if (getCurrentView() === VIEWS.settings) { if (getCurrentView() === VIEWS.settings) {
animateModsTabRefresh() animateModsTabRefresh()
} }
@ -159,7 +159,7 @@ server_selection_button.onclick = (e) => {
// Update Mojang Status Color // Update Mojang Status Color
const refreshMojangStatuses = async function() { const refreshMojangStatuses = async function() {
loggerLanding.log('Refreshing Mojang Statuses..') loggerLanding.log('Rafraichissement des status de Mojang..')
let status = 'grey' let status = 'grey'
let tooltipEssentialHTML = '' let tooltipEssentialHTML = ''
@ -212,7 +212,7 @@ const refreshMojangStatuses = async function() {
} }
} catch (err) { } catch (err) {
loggerLanding.warn('Unable to refresh Mojang service status.') loggerLanding.warn('Impossible d\'actualiser l\'état du service Mojang. ')
loggerLanding.debug(err) loggerLanding.debug(err)
} }
@ -222,7 +222,7 @@ const refreshMojangStatuses = async function() {
} }
const refreshServerStatus = async function(fade = false) { const refreshServerStatus = async function(fade = false) {
loggerLanding.log('Refreshing Server Status') loggerLanding.log('Actualisation de l\'état du serveur')
const serv = DistroManager.getDistribution().getServer(ConfigManager.getSelectedServer()) const serv = DistroManager.getDistribution().getServer(ConfigManager.getSelectedServer())
let pLabel = 'SERVER' let pLabel = 'SERVER'
@ -237,7 +237,7 @@ const refreshServerStatus = async function(fade = false) {
} }
} catch (err) { } catch (err) {
loggerLanding.warn('Unable to refresh server status, assuming offline.') loggerLanding.warn('Impossible d\'actualiser l\'état du serveur, en supposant qu\'il est hors ligne.')
loggerLanding.debug(err) loggerLanding.debug(err)
} }
if (fade) { if (fade) {
@ -270,7 +270,7 @@ function showLaunchFailure(title, desc) {
setOverlayContent( setOverlayContent(
title, title,
desc, desc,
'Okay' 'Ok'
) )
setOverlayHandler(null) setOverlayHandler(null)
toggleOverlay(true) toggleOverlay(true)
@ -470,7 +470,7 @@ function asyncSystemScan(mcVersion, launchAfter = true) {
}) })
// Begin system Java scan. // Begin system Java scan.
setLaunchDetails('Checking system info..') setLaunchDetails('Vérification des informations système..')
sysAEx.send({ task: 'execute', function: 'validateJava', argsArr: [ConfigManager.getDataDirectory()] }) sysAEx.send({ task: 'execute', function: 'validateJava', argsArr: [ConfigManager.getDataDirectory()] })
} }
@ -650,8 +650,8 @@ function dlAsync(login = true) {
if (m.result.forgeData == null || m.result.versionData == null) { if (m.result.forgeData == null || m.result.versionData == null) {
loggerLaunchSuite.error('Error during validation:', m.result) loggerLaunchSuite.error('Error during validation:', m.result)
loggerLaunchSuite.error('Error during launch', m.result.error) loggerLaunchSuite.error('Erreur lors du lancement', m.result.error)
showLaunchFailure('Error During Launch', 'Please check the console (CTRL + Shift + i) for more details.') showLaunchFailure('Erreur lors du lancement', 'Veuillez vérifier la console (CTRL + Shift + i) pour plus de détails.')
allGood = false allGood = false
} }
@ -661,17 +661,17 @@ function dlAsync(login = true) {
if (login && allGood) { if (login && allGood) {
const authUser = ConfigManager.getSelectedAccount() const authUser = ConfigManager.getSelectedAccount()
loggerLaunchSuite.log(`Sending selected account (${authUser.displayName}) to ProcessBuilder.`) loggerLaunchSuite.log(`Envoi du compte sélectionné (${authUser.displayName}) à ProcessBuilder.`)
let pb = new ProcessBuilder(serv, versionData, forgeData, authUser, remote.app.getVersion()) let pb = new ProcessBuilder(serv, versionData, forgeData, authUser, remote.app.getVersion())
setLaunchDetails('Launching game..') setLaunchDetails('Lancement du jeu..')
// const SERVER_JOINED_REGEX = /\[.+\]: \[CHAT\] [a-zA-Z0-9_]{1,16} joined the game/ // const SERVER_JOINED_REGEX = /\[.+\]: \[CHAT\] [a-zA-Z0-9_]{1,16} joined the game/
const SERVER_JOINED_REGEX = new RegExp(`\\[.+\\]: \\[CHAT\\] ${authUser.displayName} joined the game`) const SERVER_JOINED_REGEX = new RegExp(`\\[.+\\]: \\[CHAT\\] ${authUser.displayName} rejoint le jeu`)
const onLoadComplete = () => { const onLoadComplete = () => {
toggleLaunchArea(false) toggleLaunchArea(false)
if (hasRPC) { if (hasRPC) {
DiscordWrapper.updateDetails('Loading game..') DiscordWrapper.updateDetails('Jeu en cours de chargement..')
} }
proc.stdout.on('data', gameStateChange) proc.stdout.on('data', gameStateChange)
proc.stdout.removeListener('data', tempListener) proc.stdout.removeListener('data', tempListener)
@ -879,7 +879,7 @@ let newsLoadingListener = null
*/ */
function setNewsLoading(val) { function setNewsLoading(val) {
if (val) { if (val) {
const nLStr = 'Checking for News' const nLStr = 'Vérification des actualités'
let dotStr = '..' let dotStr = '..'
nELoadSpan.innerHTML = nLStr + dotStr nELoadSpan.innerHTML = nLStr + dotStr
newsLoadingListener = setInterval(() => { newsLoadingListener = setInterval(() => {

View File

@ -2,24 +2,25 @@
* Script for login.ejs * Script for login.ejs
*/ */
// Validation Regexes. // Validation Regexes.
const validUsername = /^[a-zA-Z0-9_]{1,16}$/ const validUsername = /^[a-zA-Z0-9_]{1,16}$/
const basicEmail = /^\S+@\S+\.\S+$/ const basicEmail = /^\S+@\S+\.\S+$/
//const validEmail = /^(([^<>()\[\]\.,;:\s@\"]+(\.[^<>()\[\]\.,;:\s@\"]+)*)|(\".+\"))@(([^<>()[\]\.,;:\s@\"]+\.)+[^<>()[\]\.,;:\s@\"]{2,})$/i //const validEmail = /^(([^<>()\[\]\.,;:\s@\"]+(\.[^<>()\[\]\.,;:\s@\"]+)*)|(\".+\"))@(([^<>()[\]\.,;:\s@\"]+\.)+[^<>()[\]\.,;:\s@\"]{2,})$/i
// Login Elements // Login Elements
const loginCancelContainer = document.getElementById('loginCancelContainer') const loginCancelContainer = document.getElementById('loginCancelContainer')
const loginCancelButton = document.getElementById('loginCancelButton') const loginCancelButton = document.getElementById('loginCancelButton')
const loginEmailError = document.getElementById('loginEmailError') const loginEmailError = document.getElementById('loginEmailError')
const loginUsername = document.getElementById('loginUsername') const loginUsername = document.getElementById('loginUsername')
const loginPasswordError = document.getElementById('loginPasswordError') const loginPasswordError = document.getElementById('loginPasswordError')
const loginPassword = document.getElementById('loginPassword') const loginPassword = document.getElementById('loginPassword')
const checkmarkContainer = document.getElementById('checkmarkContainer') const checkmarkContainer = document.getElementById('checkmarkContainer')
const loginRememberOption = document.getElementById('loginRememberOption') const loginRememberOption = document.getElementById('loginRememberOption')
const loginButton = document.getElementById('loginButton') const loginButton = document.getElementById('loginButton')
const loginForm = document.getElementById('loginForm') 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') const loggerLogin = LoggerUtil('%c[Login]', 'color: #000668; font-weight: bold')
@ -30,7 +31,7 @@ const loggerLogin = LoggerUtil('%c[Login]', 'color: #000668; font-weight: bold')
* @param {HTMLElement} element The element on which to display the error. * @param {HTMLElement} element The element on which to display the error.
* @param {string} value The error text. * @param {string} value The error text.
*/ */
function showError(element, value){ function showError(element, value) {
element.innerHTML = value element.innerHTML = value
element.style.opacity = 1 element.style.opacity = 1
} }
@ -40,8 +41,8 @@ function showError(element, value){
* *
* @param {HTMLElement} element The element to shake. * @param {HTMLElement} element The element to shake.
*/ */
function shakeError(element){ function shakeError(element) {
if(element.style.opacity == 1){ if (element.style.opacity == 1) {
element.classList.remove('shake') element.classList.remove('shake')
void element.offsetWidth void element.offsetWidth
element.classList.add('shake') element.classList.add('shake')
@ -53,16 +54,16 @@ function shakeError(element){
* *
* @param {string} value The email value. * @param {string} value The email value.
*/ */
function validateEmail(value){ function validateEmail(value) {
if(value){ if (value) {
if(!basicEmail.test(value) && !validUsername.test(value)){ if (!basicEmail.test(value) && !validUsername.test(value)) {
showError(loginEmailError, Lang.queryJS('login.error.invalidValue')) showError(loginEmailError, Lang.queryJS('login.error.invalidValue'))
loginDisabled(true) loginDisabled(true)
lu = false lu = false
} else { } else {
loginEmailError.style.opacity = 0 loginEmailError.style.opacity = 0
lu = true lu = true
if(lp){ if (lp) {
loginDisabled(false) loginDisabled(false)
} }
} }
@ -78,11 +79,11 @@ function validateEmail(value){
* *
* @param {string} value The password value. * @param {string} value The password value.
*/ */
function validatePassword(value){ function validatePassword(value) {
if(value){ if (value) {
loginPasswordError.style.opacity = 0 loginPasswordError.style.opacity = 0
lp = true lp = true
if(lu){ if (lu) {
loginDisabled(false) loginDisabled(false)
} }
} else { } else {
@ -115,8 +116,8 @@ loginPassword.addEventListener('input', (e) => {
* *
* @param {boolean} v True to enable, false to disable. * @param {boolean} v True to enable, false to disable.
*/ */
function loginDisabled(v){ function loginDisabled(v) {
if(loginButton.disabled !== v){ if (loginButton.disabled !== v) {
loginButton.disabled = v loginButton.disabled = v
} }
} }
@ -126,8 +127,8 @@ function loginDisabled(v){
* *
* @param {boolean} v True to enable, false to disable. * @param {boolean} v True to enable, false to disable.
*/ */
function loginLoading(v){ function loginLoading(v) {
if(v){ if (v) {
loginButton.setAttribute('loading', v) loginButton.setAttribute('loading', v)
loginButton.innerHTML = loginButton.innerHTML.replace(Lang.queryJS('login.login'), Lang.queryJS('login.loggingIn')) loginButton.innerHTML = loginButton.innerHTML.replace(Lang.queryJS('login.login'), Lang.queryJS('login.loggingIn'))
} else { } else {
@ -141,12 +142,12 @@ function loginLoading(v){
* *
* @param {boolean} v True to enable, false to disable. * @param {boolean} v True to enable, false to disable.
*/ */
function formDisabled(v){ function formDisabled(v) {
loginDisabled(v) loginDisabled(v)
loginCancelButton.disabled = v loginCancelButton.disabled = v
loginUsername.disabled = v loginUsername.disabled = v
loginPassword.disabled = v loginPassword.disabled = v
if(v){ if (v) {
checkmarkContainer.setAttribute('disabled', v) checkmarkContainer.setAttribute('disabled', v)
} else { } else {
checkmarkContainer.removeAttribute('disabled') checkmarkContainer.removeAttribute('disabled')
@ -161,24 +162,24 @@ function formDisabled(v){
* @param {Error | {cause: string, error: string, errorMessage: string}} err A Node.js * @param {Error | {cause: string, error: string, errorMessage: string}} err A Node.js
* error or Mojang error response. * error or Mojang error response.
*/ */
function resolveError(err){ function resolveError(err) {
// Mojang Response => err.cause | err.error | err.errorMessage // Mojang Response => err.cause | err.error | err.errorMessage
// Node error => err.code | err.message // Node error => err.code | err.message
if(err.cause != null && err.cause === 'UserMigratedException') { if (err.cause != null && err.cause === 'UserMigratedException') {
return { return {
title: Lang.queryJS('login.error.userMigrated.title'), title: Lang.queryJS('login.error.userMigrated.title'),
desc: Lang.queryJS('login.error.userMigrated.desc') desc: Lang.queryJS('login.error.userMigrated.desc')
} }
} else { } else {
if(err.error != null){ if (err.error != null) {
if(err.error === 'ForbiddenOperationException'){ if (err.error === 'ForbiddenOperationException') {
if(err.errorMessage != null){ if (err.errorMessage != null) {
if(err.errorMessage === 'Invalid credentials. Invalid username or password.'){ if (err.errorMessage === 'invalidCredentials') {
return { return {
title: Lang.queryJS('login.error.invalidCredentials.title'), title: Lang.queryJS('login.error.invalidCredentials.title'),
desc: Lang.queryJS('login.error.invalidCredentials.desc') desc: Lang.queryJS('login.error.invalidCredentials.desc')
} }
} else if(err.errorMessage === 'Invalid credentials.'){ } else if (err.errorMessage === 'invalidCredentials') {
return { return {
title: Lang.queryJS('login.error.rateLimit.title'), title: Lang.queryJS('login.error.rateLimit.title'),
desc: Lang.queryJS('login.error.rateLimit.desc') desc: Lang.queryJS('login.error.rateLimit.desc')
@ -188,14 +189,14 @@ function resolveError(err){
} }
} else { } else {
// Request errors (from Node). // Request errors (from Node).
if(err.code != null){ if (err.code != null) {
if(err.code === 'ENOENT'){ if (err.code === 'ENOENT') {
// No Internet. // No Internet.
return { return {
title: Lang.queryJS('login.error.noInternet.title'), title: Lang.queryJS('login.error.noInternet.title'),
desc: Lang.queryJS('login.error.noInternet.desc') desc: Lang.queryJS('login.error.noInternet.desc')
} }
} else if(err.code === 'ENOTFOUND'){ } else if (err.code === 'ENOTFOUND') {
// Could not reach server. // Could not reach server.
return { return {
title: Lang.queryJS('login.error.authDown.title'), title: Lang.queryJS('login.error.authDown.title'),
@ -205,8 +206,8 @@ function resolveError(err){
} }
} }
} }
if(err.message != null){ if (err.message != null) {
if(err.message === 'NotPaidAccount'){ if (err.message === 'NotPaidAccount') {
return { return {
title: Lang.queryJS('login.error.notPaid.title'), title: Lang.queryJS('login.error.notPaid.title'),
desc: Lang.queryJS('login.error.notPaid.desc') desc: Lang.queryJS('login.error.notPaid.desc')
@ -231,8 +232,8 @@ let loginViewOnSuccess = VIEWS.landing
let loginViewOnCancel = VIEWS.settings let loginViewOnCancel = VIEWS.settings
let loginViewCancelHandler let loginViewCancelHandler
function loginCancelEnabled(val){ function loginCancelEnabled(val) {
if(val){ if (val) {
$(loginCancelContainer).show() $(loginCancelContainer).show()
} else { } else {
$(loginCancelContainer).hide() $(loginCancelContainer).hide()
@ -244,7 +245,7 @@ loginCancelButton.onclick = (e) => {
loginUsername.value = '' loginUsername.value = ''
loginPassword.value = '' loginPassword.value = ''
loginCancelEnabled(false) loginCancelEnabled(false)
if(loginViewCancelHandler != null){ if (loginViewCancelHandler != null) {
loginViewCancelHandler() loginViewCancelHandler()
loginViewCancelHandler = null loginViewCancelHandler = null
} }
@ -270,7 +271,7 @@ loginButton.addEventListener('click', () => {
setTimeout(() => { setTimeout(() => {
switchView(VIEWS.login, loginViewOnSuccess, 500, 500, () => { switchView(VIEWS.login, loginViewOnSuccess, 500, 500, () => {
// Temporary workaround // Temporary workaround
if(loginViewOnSuccess === VIEWS.settings){ if (loginViewOnSuccess === VIEWS.settings) {
prepareSettings() prepareSettings()
} }
loginViewOnSuccess = VIEWS.landing // Reset this for good measure. loginViewOnSuccess = VIEWS.landing // Reset this for good measure.
@ -294,7 +295,7 @@ loginButton.addEventListener('click', () => {
toggleOverlay(false) toggleOverlay(false)
}) })
toggleOverlay(true) toggleOverlay(true)
loggerLogin.log('Error while logging in.', err) loggerLogin.log('Erreur lors de la connexion.', err)
}) })
}) })

View File

@ -3,12 +3,12 @@
* Loaded after core UI functions are initialized in uicore.js. * Loaded after core UI functions are initialized in uicore.js.
*/ */
// Requirements // Requirements
const path = require('path') const path = require('path')
const AuthManager = require('./assets/js/authmanager') const AuthManager = require('./assets/js/authmanager')
const ConfigManager = require('./assets/js/configmanager') const ConfigManager = require('./assets/js/configmanager')
const DistroManager = require('./assets/js/distromanager') const DistroManager = require('./assets/js/distromanager')
const Lang = require('./assets/js/langloader') const Lang = require('./assets/js/langloader')
let rscShouldLoad = false let rscShouldLoad = false
let fatalStartupError = false let fatalStartupError = false
@ -36,7 +36,7 @@ let currentView
* @param {*} onNextFade Optional. Callback function to execute when the next view * @param {*} onNextFade Optional. Callback function to execute when the next view
* fades in. * fades in.
*/ */
function switchView(current, next, currentFadeTime = 500, nextFadeTime = 500, onCurrentFade = () => {}, onNextFade = () => {}){ function switchView(current, next, currentFadeTime = 500, nextFadeTime = 500, onCurrentFade = () => {}, onNextFade = () => {}) {
currentView = next currentView = next
$(`${current}`).fadeOut(currentFadeTime, () => { $(`${current}`).fadeOut(currentFadeTime, () => {
onCurrentFade() onCurrentFade()
@ -51,14 +51,14 @@ function switchView(current, next, currentFadeTime = 500, nextFadeTime = 500, on
* *
* @returns {string} The currently shown view container. * @returns {string} The currently shown view container.
*/ */
function getCurrentView(){ function getCurrentView() {
return currentView return currentView
} }
function showMainUI(data){ function showMainUI(data) {
if(!isDev){ if (!isDev) {
loggerAutoUpdater.log('Initializing..') loggerAutoUpdater.log('Initialisation..')
ipcRenderer.send('autoUpdateAction', 'initAutoUpdater', ConfigManager.getAllowPrerelease()) ipcRenderer.send('autoUpdateAction', 'initAutoUpdater', ConfigManager.getAllowPrerelease())
} }
@ -66,52 +66,52 @@ function showMainUI(data){
updateSelectedServer(data.getServer(ConfigManager.getSelectedServer())) updateSelectedServer(data.getServer(ConfigManager.getSelectedServer()))
refreshServerStatus() refreshServerStatus()
setTimeout(() => { setTimeout(() => {
document.getElementById('frameBar').style.backgroundColor = 'rgba(0, 0, 0, 0.5)' document.getElementById('frameBar').style.backgroundColor = 'rgba(0, 0, 0, 0.5)'
document.body.style.backgroundImage = `url('assets/images/backgrounds/${document.body.getAttribute('bkid')}.jpg')` document.body.style.backgroundImage = `url('assets/images/backgrounds/${document.body.getAttribute('bkid')}.jpg')`
$('#main').show() $('#main').show()
const isLoggedIn = Object.keys(ConfigManager.getAuthAccounts()).length > 0 const isLoggedIn = Object.keys(ConfigManager.getAuthAccounts()).length > 0
// 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() validateSelectedAccount()
}
if(ConfigManager.isFirstLaunch()){
currentView = VIEWS.welcome
$(VIEWS.welcome).fadeIn(1000)
} else {
if(isLoggedIn){
currentView = VIEWS.landing
$(VIEWS.landing).fadeIn(1000)
} else {
currentView = VIEWS.login
$(VIEWS.login).fadeIn(1000)
} }
}
setTimeout(() => { if (ConfigManager.isFirstLaunch()) {
$('#loadingContainer').fadeOut(500, () => { currentView = VIEWS.welcome
$('#loadSpinnerImage').removeClass('rotating') $(VIEWS.welcome).fadeIn(1000)
}) } else {
}, 250) if (isLoggedIn) {
currentView = VIEWS.landing
}, 750) $(VIEWS.landing).fadeIn(1000)
// Disable tabbing to the news container. } else {
currentView = VIEWS.login
$(VIEWS.login).fadeIn(1000)
}
}
setTimeout(() => {
$('#loadingContainer').fadeOut(500, () => {
$('#loadSpinnerImage').removeClass('rotating')
})
}, 250)
}, 750)
// Disable tabbing to the news container.
initNews().then(() => { initNews().then(() => {
$('#newsContainer *').attr('tabindex', '-1') $('#newsContainer *').attr('tabindex', '-1')
}) })
} }
function showFatalStartupError(){ function showFatalStartupError() {
setTimeout(() => { setTimeout(() => {
$('#loadingContainer').fadeOut(250, () => { $('#loadingContainer').fadeOut(250, () => {
document.getElementById('overlayContainer').style.background = 'none' document.getElementById('overlayContainer').style.background = 'none'
setOverlayContent( setOverlayContent(
'Fatal Error: Unable to Load Distribution Index', 'Erreur fatale: impossible de charger l\'index de distribution',
'A connection could not be established to our servers to download the distribution index. No local copies were available to load. <br><br>The distribution index is an essential file which provides the latest server information. The launcher is unable to start without it. Ensure you are connected to the internet and relaunch the application.', 'Une connexion n\'a pas pu être établie avec nos serveurs pour télécharger l\'index de distribution. Aucune copie locale n\'était disponible pour le chargement. <br> <br> L\'index de distribution est un fichier essentiel qui fournit les dernières informations sur le serveur. Le lanceur ne peut pas démarrer sans lui. Assurez-vous que vous êtes connecté à Internet et relancez l\'application.',
'Close' 'Fermer'
) )
setOverlayHandler(() => { setOverlayHandler(() => {
const window = remote.getCurrentWindow() const window = remote.getCurrentWindow()
@ -127,7 +127,7 @@ function showFatalStartupError(){
* *
* @param {Object} data The distro index object. * @param {Object} data The distro index object.
*/ */
function onDistroRefresh(data){ function onDistroRefresh(data) {
updateSelectedServer(data.getServer(ConfigManager.getSelectedServer())) updateSelectedServer(data.getServer(ConfigManager.getSelectedServer()))
refreshServerStatus() refreshServerStatus()
initNews() initNews()
@ -139,38 +139,38 @@ function onDistroRefresh(data){
* *
* @param {Object} data The distro index object. * @param {Object} data The distro index object.
*/ */
function syncModConfigurations(data){ function syncModConfigurations(data) {
const syncedCfgs = [] const syncedCfgs = []
for(let serv of data.getServers()){ for (let serv of data.getServers()) {
const id = serv.getID() const id = serv.getID()
const mdls = serv.getModules() const mdls = serv.getModules()
const cfg = ConfigManager.getModConfiguration(id) const cfg = ConfigManager.getModConfiguration(id)
if(cfg != null){ if (cfg != null) {
const modsOld = cfg.mods const modsOld = cfg.mods
const mods = {} const mods = {}
for(let mdl of mdls){ for (let mdl of mdls) {
const type = mdl.getType() const type = mdl.getType()
if(type === DistroManager.Types.ForgeMod || type === DistroManager.Types.LiteMod || type === DistroManager.Types.LiteLoader){ if (type === DistroManager.Types.ForgeMod || type === DistroManager.Types.LiteMod || type === DistroManager.Types.LiteLoader) {
if(!mdl.getRequired().isRequired()){ if (!mdl.getRequired().isRequired()) {
const mdlID = mdl.getVersionlessID() const mdlID = mdl.getVersionlessID()
if(modsOld[mdlID] == null){ if (modsOld[mdlID] == null) {
mods[mdlID] = scanOptionalSubModules(mdl.getSubModules(), mdl) mods[mdlID] = scanOptionalSubModules(mdl.getSubModules(), mdl)
} else { } else {
mods[mdlID] = mergeModConfiguration(modsOld[mdlID], scanOptionalSubModules(mdl.getSubModules(), mdl), false) mods[mdlID] = mergeModConfiguration(modsOld[mdlID], scanOptionalSubModules(mdl.getSubModules(), mdl), false)
} }
} else { } else {
if(mdl.hasSubModules()){ if (mdl.hasSubModules()) {
const mdlID = mdl.getVersionlessID() const mdlID = mdl.getVersionlessID()
const v = scanOptionalSubModules(mdl.getSubModules(), mdl) const v = scanOptionalSubModules(mdl.getSubModules(), mdl)
if(typeof v === 'object'){ if (typeof v === 'object') {
if(modsOld[mdlID] == null){ if (modsOld[mdlID] == null) {
mods[mdlID] = v mods[mdlID] = v
} else { } else {
mods[mdlID] = mergeModConfiguration(modsOld[mdlID], v, true) mods[mdlID] = mergeModConfiguration(modsOld[mdlID], v, true)
@ -190,15 +190,15 @@ function syncModConfigurations(data){
const mods = {} const mods = {}
for(let mdl of mdls){ for (let mdl of mdls) {
const type = mdl.getType() const type = mdl.getType()
if(type === DistroManager.Types.ForgeMod || type === DistroManager.Types.LiteMod || type === DistroManager.Types.LiteLoader){ if (type === DistroManager.Types.ForgeMod || type === DistroManager.Types.LiteMod || type === DistroManager.Types.LiteLoader) {
if(!mdl.getRequired().isRequired()){ if (!mdl.getRequired().isRequired()) {
mods[mdl.getVersionlessID()] = scanOptionalSubModules(mdl.getSubModules(), mdl) mods[mdl.getVersionlessID()] = scanOptionalSubModules(mdl.getSubModules(), mdl)
} else { } else {
if(mdl.hasSubModules()){ if (mdl.hasSubModules()) {
const v = scanOptionalSubModules(mdl.getSubModules(), mdl) const v = scanOptionalSubModules(mdl.getSubModules(), mdl)
if(typeof v === 'object'){ if (typeof v === 'object') {
mods[mdl.getVersionlessID()] = v mods[mdl.getVersionlessID()] = v
} }
} }
@ -225,21 +225,21 @@ function syncModConfigurations(data){
* *
* @returns {boolean | Object} The resolved mod configuration. * @returns {boolean | Object} The resolved mod configuration.
*/ */
function scanOptionalSubModules(mdls, origin){ function scanOptionalSubModules(mdls, origin) {
if(mdls != null){ if (mdls != null) {
const mods = {} const mods = {}
for(let mdl of mdls){ for (let mdl of mdls) {
const type = mdl.getType() const type = mdl.getType()
// Optional types. // Optional types.
if(type === DistroManager.Types.ForgeMod || type === DistroManager.Types.LiteMod || type === DistroManager.Types.LiteLoader){ if (type === DistroManager.Types.ForgeMod || type === DistroManager.Types.LiteMod || type === DistroManager.Types.LiteLoader) {
// It is optional. // It is optional.
if(!mdl.getRequired().isRequired()){ if (!mdl.getRequired().isRequired()) {
mods[mdl.getVersionlessID()] = scanOptionalSubModules(mdl.getSubModules(), mdl) mods[mdl.getVersionlessID()] = scanOptionalSubModules(mdl.getSubModules(), mdl)
} else { } else {
if(mdl.hasSubModules()){ if (mdl.hasSubModules()) {
const v = scanOptionalSubModules(mdl.getSubModules(), mdl) const v = scanOptionalSubModules(mdl.getSubModules(), mdl)
if(typeof v === 'object'){ if (typeof v === 'object') {
mods[mdl.getVersionlessID()] = v mods[mdl.getVersionlessID()] = v
} }
} }
@ -247,11 +247,11 @@ function scanOptionalSubModules(mdls, origin){
} }
} }
if(Object.keys(mods).length > 0){ if (Object.keys(mods).length > 0) {
const ret = { const ret = {
mods mods
} }
if(!origin.getRequired().isRequired()){ if (!origin.getRequired().isRequired()) {
ret.value = origin.getRequired().isDefault() ret.value = origin.getRequired().isDefault()
} }
return ret return ret
@ -269,27 +269,27 @@ function scanOptionalSubModules(mdls, origin){
* *
* @returns {boolean | Object} The merged configuration. * @returns {boolean | Object} The merged configuration.
*/ */
function mergeModConfiguration(o, n, nReq = false){ function mergeModConfiguration(o, n, nReq = false) {
if(typeof o === 'boolean'){ if (typeof o === 'boolean') {
if(typeof n === 'boolean') return o if (typeof n === 'boolean') return o
else if(typeof n === 'object'){ else if (typeof n === 'object') {
if(!nReq){ if (!nReq) {
n.value = o n.value = o
} }
return n return n
} }
} else if(typeof o === 'object'){ } else if (typeof o === 'object') {
if(typeof n === 'boolean') return typeof o.value !== 'undefined' ? o.value : true if (typeof n === 'boolean') return typeof o.value !== 'undefined' ? o.value : true
else if(typeof n === 'object'){ else if (typeof n === 'object') {
if(!nReq){ if (!nReq) {
n.value = typeof o.value !== 'undefined' ? o.value : true n.value = typeof o.value !== 'undefined' ? o.value : true
} }
const newMods = Object.keys(n.mods) const newMods = Object.keys(n.mods)
for(let i=0; i<newMods.length; i++){ for (let i = 0; i < newMods.length; i++) {
const mod = newMods[i] const mod = newMods[i]
if(o.mods[mod] != null){ if (o.mods[mod] != null) {
n.mods[mod] = mergeModConfiguration(o.mods[mod], n.mods[mod]) n.mods[mod] = mergeModConfiguration(o.mods[mod], n.mods[mod])
} }
} }
@ -302,8 +302,8 @@ function mergeModConfiguration(o, n, nReq = false){
return n return n
} }
function refreshDistributionIndex(remote, onSuccess, onError){ function refreshDistributionIndex(remote, onSuccess, onError) {
if(remote){ if (remote) {
DistroManager.pullRemote() DistroManager.pullRemote()
.then(onSuccess) .then(onSuccess)
.catch(onError) .catch(onError)
@ -314,26 +314,26 @@ function refreshDistributionIndex(remote, onSuccess, onError){
} }
} }
async function validateSelectedAccount(){ async function validateSelectedAccount() {
const selectedAcc = ConfigManager.getSelectedAccount() const selectedAcc = ConfigManager.getSelectedAccount()
if(selectedAcc != null){ if (selectedAcc != null) {
const val = await AuthManager.validateSelected() const val = await AuthManager.validateSelected()
if(!val){ if (!val) {
ConfigManager.removeAuthAccount(selectedAcc.uuid) ConfigManager.removeAuthAccount(selectedAcc.uuid)
ConfigManager.save() ConfigManager.save()
const accLen = Object.keys(ConfigManager.getAuthAccounts()).length const accLen = Object.keys(ConfigManager.getAuthAccounts()).length
setOverlayContent( setOverlayContent(
'Failed to Refresh Login', 'Échec de l\'actualisation de la connexion',
`We were unable to refresh the login for <strong>${selectedAcc.displayName}</strong>. Please ${accLen > 0 ? 'select another account or ' : ''} login again.`, `Nous n'avons pas pu actualiser la connexion pour <strong>${selectedAcc.displayName}</strong>. Merci ${accLen > 0 ? 'sélectionnez un autre compte ou ' : ''} reconnectez-vous.`,
'Login', 'Connection',
'Select Another Account' 'Sélectionnez un autre compte'
) )
setOverlayHandler(() => { setOverlayHandler(() => {
document.getElementById('loginUsername').value = selectedAcc.username document.getElementById('loginUsername').value = selectedAcc.username
validateEmail(selectedAcc.username) validateEmail(selectedAcc.username)
loginViewOnSuccess = getCurrentView() loginViewOnSuccess = getCurrentView()
loginViewOnCancel = getCurrentView() loginViewOnCancel = getCurrentView()
if(accLen > 0){ if (accLen > 0) {
loginViewCancelHandler = () => { loginViewCancelHandler = () => {
ConfigManager.addAuthAccount(selectedAcc.uuid, selectedAcc.accessToken, selectedAcc.username, selectedAcc.displayName) ConfigManager.addAuthAccount(selectedAcc.uuid, selectedAcc.accessToken, selectedAcc.username, selectedAcc.displayName)
ConfigManager.save() ConfigManager.save()
@ -345,7 +345,7 @@ async function validateSelectedAccount(){
switchView(getCurrentView(), VIEWS.login) switchView(getCurrentView(), VIEWS.login)
}) })
setDismissHandler(() => { setDismissHandler(() => {
if(accLen > 1){ if (accLen > 1) {
prepareAccountSelectionList() prepareAccountSelectionList()
$('#overlayContent').fadeOut(250, () => { $('#overlayContent').fadeOut(250, () => {
bindOverlayKeys(true, 'accountSelectContent', true) bindOverlayKeys(true, 'accountSelectContent', true)
@ -354,7 +354,7 @@ async function validateSelectedAccount(){
} else { } else {
const accountsObj = ConfigManager.getAuthAccounts() const accountsObj = ConfigManager.getAuthAccounts()
const accounts = Array.from(Object.keys(accountsObj), v => accountsObj[v]) const accounts = Array.from(Object.keys(accountsObj), v => accountsObj[v])
// This function validates the account switch. // This function validates the account switch.
setSelectedAccount(accounts[0].uuid) setSelectedAccount(accounts[0].uuid)
toggleOverlay(false) toggleOverlay(false)
} }
@ -374,7 +374,7 @@ async function validateSelectedAccount(){
* *
* @param {string} uuid The UUID of the account. * @param {string} uuid The UUID of the account.
*/ */
function setSelectedAccount(uuid){ function setSelectedAccount(uuid) {
const authAcc = ConfigManager.setSelectedAccount(uuid) const authAcc = ConfigManager.setSelectedAccount(uuid)
ConfigManager.save() ConfigManager.save()
updateSelectedAccount(authAcc) updateSelectedAccount(authAcc)
@ -382,38 +382,38 @@ function setSelectedAccount(uuid){
} }
// Synchronous Listener // Synchronous Listener
document.addEventListener('readystatechange', function(){ document.addEventListener('readystatechange', function() {
if (document.readyState === 'interactive' || document.readyState === 'complete'){ if (document.readyState === 'interactive' || document.readyState === 'complete') {
if(rscShouldLoad){ if (rscShouldLoad) {
rscShouldLoad = false rscShouldLoad = false
if(!fatalStartupError){ if (!fatalStartupError) {
const data = DistroManager.getDistribution() const data = DistroManager.getDistribution()
showMainUI(data) showMainUI(data)
} else { } else {
showFatalStartupError() showFatalStartupError()
} }
} }
} }
}, false) }, false)
// Actions that must be performed after the distribution index is downloaded. // Actions that must be performed after the distribution index is downloaded.
ipcRenderer.on('distributionIndexDone', (event, res) => { ipcRenderer.on('distributionIndexDone', (event, res) => {
if(res) { if (res) {
const data = DistroManager.getDistribution() const data = DistroManager.getDistribution()
syncModConfigurations(data) syncModConfigurations(data)
if(document.readyState === 'interactive' || document.readyState === 'complete'){ if (document.readyState === 'interactive' || document.readyState === 'complete') {
showMainUI(data) showMainUI(data)
} else { } else {
rscShouldLoad = true rscShouldLoad = true
} }
} else { } else {
fatalStartupError = true fatalStartupError = true
if(document.readyState === 'interactive' || document.readyState === 'complete'){ if (document.readyState === 'interactive' || document.readyState === 'complete') {
showFatalStartupError() showFatalStartupError()
} else { } else {
rscShouldLoad = true rscShouldLoad = true
} }
} }
}) })