Added Content-Security-Policy to ensure that external scripts cannot be loaded.
Moved inline scripts to their own files. Moved all front-end scripts to /assets/js/scripts.
This commit is contained in:
588
app/assets/js/scripts/actionbinder.js
Normal file
588
app/assets/js/scripts/actionbinder.js
Normal file
@@ -0,0 +1,588 @@
|
||||
const cp = require('child_process')
|
||||
const path = require('path')
|
||||
const {AssetGuard} = require(path.join(__dirname, 'assets', 'js', 'assetguard.js'))
|
||||
const ProcessBuilder = require(path.join(__dirname, 'assets', 'js', 'processbuilder.js'))
|
||||
const ConfigManager = require(path.join(__dirname, 'assets', 'js', 'configmanager.js'))
|
||||
const DiscordWrapper = require(path.join(__dirname, 'assets', 'js', 'discordwrapper.js'))
|
||||
const Mojang = require(path.join(__dirname, 'assets', 'js', 'mojang.js'))
|
||||
const AuthManager = require(path.join(__dirname, 'assets', 'js', 'authmanager.js'))
|
||||
const ServerStatus = require(path.join(__dirname, 'assets', 'js', 'serverstatus.js'))
|
||||
const {URL} = require('url')
|
||||
|
||||
let mojangStatusListener
|
||||
let serverStatusListener
|
||||
|
||||
// Launch Elements
|
||||
let launch_content, launch_details, launch_progress, launch_progress_label, launch_details_text
|
||||
|
||||
// Synchronous Listener
|
||||
document.addEventListener('readystatechange', function(){
|
||||
|
||||
if (document.readyState === 'complete'){
|
||||
if(ConfigManager.isFirstLaunch()){
|
||||
$('#welcomeContainer').fadeIn(500)
|
||||
} else {
|
||||
$('#landingContainer').fadeIn(500)
|
||||
}
|
||||
}
|
||||
|
||||
if (document.readyState === 'interactive'){
|
||||
|
||||
// Save a reference to the launch elements.
|
||||
launch_content = document.getElementById('launch_content')
|
||||
launch_details = document.getElementById('launch_details')
|
||||
launch_progress = document.getElementById('launch_progress')
|
||||
launch_progress_label = document.getElementById('launch_progress_label')
|
||||
launch_details_text = document.getElementById('launch_details_text')
|
||||
|
||||
// Bind launch button
|
||||
document.getElementById('launch_button').addEventListener('click', function(e){
|
||||
console.log('Launching game..')
|
||||
const jExe = ConfigManager.getJavaExecutable()
|
||||
if(jExe == null){
|
||||
asyncSystemScan()
|
||||
} else {
|
||||
|
||||
setLaunchDetails('Please wait..')
|
||||
toggleLaunchArea(true)
|
||||
setLaunchPercentage(0, 100)
|
||||
|
||||
AssetGuard._validateJavaBinary(jExe).then((v) => {
|
||||
if(v){
|
||||
dlAsync()
|
||||
} else {
|
||||
asyncSystemScan()
|
||||
}
|
||||
})
|
||||
}
|
||||
})
|
||||
|
||||
// TODO convert this to dropdown menu.
|
||||
// Bind selected server
|
||||
document.getElementById('server_selection').innerHTML = '\u2022 ' + AssetGuard.getServerById(ConfigManager.getGameDirectory(), ConfigManager.getSelectedServer()).name
|
||||
|
||||
|
||||
// Update Mojang Status Color
|
||||
const refreshMojangStatuses = async function(){
|
||||
console.log('Refreshing Mojang Statuses..')
|
||||
let status = 'grey'
|
||||
try {
|
||||
const statuses = await Mojang.status()
|
||||
greenCount = 0
|
||||
for(let i=0; i<statuses.length; i++){
|
||||
if(statuses[i].status === 'yellow' && status !== 'red'){
|
||||
status = 'yellow'
|
||||
continue
|
||||
} else if(statuses[i].status === 'red'){
|
||||
status = 'red'
|
||||
break
|
||||
}
|
||||
++greenCount
|
||||
}
|
||||
if(greenCount == statuses.length){
|
||||
status = 'green'
|
||||
}
|
||||
} catch (err) {
|
||||
console.warn('Unable to refresh Mojang service status.')
|
||||
console.debug(err)
|
||||
}
|
||||
document.getElementById('mojang_status_icon').style.color = Mojang.statusToHex(status)
|
||||
}
|
||||
|
||||
const refreshServerStatus = async function(){
|
||||
console.log('Refreshing Server Status')
|
||||
const serv = AssetGuard.resolveSelectedServer(ConfigManager.getGameDirectory())
|
||||
|
||||
let pLabel = 'SERVER'
|
||||
let pVal = 'OFFLINE'
|
||||
|
||||
try {
|
||||
const serverURL = new URL('my://' + serv.server_ip)
|
||||
const servStat = await ServerStatus.getStatus(serverURL.hostname, serverURL.port)
|
||||
if(servStat.online){
|
||||
pLabel = 'PLAYERS'
|
||||
pVal = servStat.onlinePlayers + '/' + servStat.maxPlayers
|
||||
}
|
||||
|
||||
} catch (err) {
|
||||
console.warn('Unable to refresh server status, assuming offline.')
|
||||
console.debug(err)
|
||||
}
|
||||
document.getElementById('landingPlayerLabel').innerHTML = pLabel
|
||||
document.getElementById('player_count').innerHTML = pVal
|
||||
}
|
||||
|
||||
refreshMojangStatuses()
|
||||
refreshServerStatus()
|
||||
|
||||
// Set refresh rate to once every 5 minutes.
|
||||
mojangStatusListener = setInterval(refreshMojangStatuses, 300000)
|
||||
serverStatusListener = setInterval(refreshServerStatus, 300000)
|
||||
|
||||
}
|
||||
}, false)
|
||||
|
||||
/* Overlay Wrapper Functions */
|
||||
|
||||
/**
|
||||
* Toggle the visibility of the overlay.
|
||||
*
|
||||
* @param {boolean} toggleState True to display, false to hide.
|
||||
* @param {boolean} dismissable Optional. True to show the dismiss option, otherwise false.
|
||||
* @param {string} content Optional. The content div to be shown.
|
||||
*/
|
||||
function toggleOverlay(toggleState, dismissable = false, content = 'overlayContent'){
|
||||
if(toggleState == null){
|
||||
toggleState = !document.getElementById('main').hasAttribute('overlay')
|
||||
}
|
||||
if(typeof dismissable === 'string'){
|
||||
content = dismissable
|
||||
}
|
||||
if(toggleState){
|
||||
document.getElementById('main').setAttribute('overlay', true)
|
||||
$('#' + content).parent().children().hide()
|
||||
$('#' + content).show()
|
||||
if(dismissable){
|
||||
$('#overlayDismiss').show()
|
||||
} else {
|
||||
$('#overlayDismiss').hide()
|
||||
}
|
||||
$('#overlayContainer').fadeIn(250)
|
||||
} else {
|
||||
document.getElementById('main').removeAttribute('overlay')
|
||||
$('#overlayContainer').fadeOut(250, () => {
|
||||
$('#' + content).parent().children().hide()
|
||||
$('#' + content).show()
|
||||
if(dismissable){
|
||||
$('#overlayDismiss').show()
|
||||
} else {
|
||||
$('#overlayDismiss').hide()
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the content of the overlay.
|
||||
*
|
||||
* @param {string} title Overlay title text.
|
||||
* @param {string} description Overlay description text.
|
||||
* @param {string} acknowledge Acknowledge button text.
|
||||
* @param {string} dismiss Dismiss button text.
|
||||
*/
|
||||
function setOverlayContent(title, description, acknowledge, dismiss = 'Dismiss'){
|
||||
document.getElementById('overlayTitle').innerHTML = title
|
||||
document.getElementById('overlayDesc').innerHTML = description
|
||||
document.getElementById('overlayAcknowledge').innerHTML = acknowledge
|
||||
document.getElementById('overlayDismiss').innerHTML = dismiss
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the onclick handler of the overlay acknowledge button.
|
||||
* If the handler is null, a default handler will be added.
|
||||
*
|
||||
* @param {function} handler
|
||||
*/
|
||||
function setOverlayHandler(handler){
|
||||
if(handler == null){
|
||||
document.getElementById('overlayAcknowledge').onclick = () => {
|
||||
toggleOverlay(false)
|
||||
}
|
||||
} else {
|
||||
document.getElementById('overlayAcknowledge').onclick = handler
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the onclick handler of the overlay dismiss button.
|
||||
* If the handler is null, a default handler will be added.
|
||||
*
|
||||
* @param {function} handler
|
||||
*/
|
||||
function setDismissHandler(handler){
|
||||
if(handler == null){
|
||||
document.getElementById('overlayDismiss').onclick = () => {
|
||||
toggleOverlay(false)
|
||||
}
|
||||
} else {
|
||||
document.getElementById('overlayDismiss').onclick = handler
|
||||
}
|
||||
}
|
||||
|
||||
/* Launch Progress Wrapper Functions */
|
||||
|
||||
/**
|
||||
* Show/hide the loading area.
|
||||
*
|
||||
* @param {boolean} loading True if the loading area should be shown, otherwise false.
|
||||
*/
|
||||
function toggleLaunchArea(loading){
|
||||
if(loading){
|
||||
launch_details.style.display = 'flex'
|
||||
launch_content.style.display = 'none'
|
||||
} else {
|
||||
launch_details.style.display = 'none'
|
||||
launch_content.style.display = 'inline-flex'
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the details text of the loading area.
|
||||
*
|
||||
* @param {string} details The new text for the loading details.
|
||||
*/
|
||||
function setLaunchDetails(details){
|
||||
launch_details_text.innerHTML = details
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the value of the loading progress bar and display that value.
|
||||
*
|
||||
* @param {number} value The progress value.
|
||||
* @param {number} max The total size.
|
||||
* @param {number|string} percent Optional. The percentage to display on the progress label.
|
||||
*/
|
||||
function setLaunchPercentage(value, max, percent = ((value/max)*100)){
|
||||
launch_progress.setAttribute('max', max)
|
||||
launch_progress.setAttribute('value', value)
|
||||
launch_progress_label.innerHTML = percent + '%'
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the value of the OS progress bar and display that on the UI.
|
||||
*
|
||||
* @param {number} value The progress value.
|
||||
* @param {number} max The total download size.
|
||||
* @param {number|string} percent Optional. The percentage to display on the progress label.
|
||||
*/
|
||||
function setDownloadPercentage(value, max, percent = ((value/max)*100)){
|
||||
remote.getCurrentWindow().setProgressBar(value/max)
|
||||
setLaunchPercentage(value, max, percent)
|
||||
}
|
||||
|
||||
/* System (Java) Scan */
|
||||
|
||||
let sysAEx
|
||||
let scanAt
|
||||
|
||||
function asyncSystemScan(launchAfter = true){
|
||||
|
||||
setLaunchDetails('Please wait..')
|
||||
toggleLaunchArea(true)
|
||||
setLaunchPercentage(0, 100)
|
||||
|
||||
// Fork a process to run validations.
|
||||
sysAEx = cp.fork(path.join(__dirname, 'assets', 'js', 'assetexec.js'), [
|
||||
ConfigManager.getGameDirectory(),
|
||||
ConfigManager.getJavaExecutable()
|
||||
])
|
||||
|
||||
sysAEx.on('message', (m) => {
|
||||
if(m.content === 'validateJava'){
|
||||
|
||||
if(m.result == null){
|
||||
// If the result is null, no valid Java installation was found.
|
||||
// Show this information to the user.
|
||||
setOverlayContent(
|
||||
'No Compatible<br>Java Installation Found',
|
||||
'In order to join WesterosCraft, you need a 64-bit installation of Java 8. Would you like us to install a copy? By installing, you accept <a href="http://www.oracle.com/technetwork/java/javase/terms/license/index.html">Oracle\'s license agreement</a>.',
|
||||
'Install Java',
|
||||
'Install Manually'
|
||||
)
|
||||
setOverlayHandler(() => {
|
||||
setLaunchDetails('Preparing Java Download..')
|
||||
sysAEx.send({task: 0, content: '_enqueueOracleJRE', argsArr: [ConfigManager.getLauncherDirectory()]})
|
||||
toggleOverlay(false)
|
||||
})
|
||||
setDismissHandler(() => {
|
||||
$('#overlayContent').fadeOut(250, () => {
|
||||
//$('#overlayDismiss').toggle(false)
|
||||
setOverlayContent(
|
||||
'Don\'t Forget!<br>Java is Required',
|
||||
'A valid x64 installation of Java 8 is required to launch. Downloads can be found on <a href="http://www.oracle.com/technetwork/java/javase/downloads/jre8-downloads-2133155.html">Oracle\'s website</a>. Once installed, you will be able to connect to the server.<br><br>Please refer to our <a href="http://westeroscraft.wikia.com/wiki/Troubleshooting_Guide">Troubleshooting Guide</a> if you have any difficulty.',
|
||||
'I Understand',
|
||||
'Go Back'
|
||||
)
|
||||
setOverlayHandler(() => {
|
||||
toggleLaunchArea(false)
|
||||
toggleOverlay(false)
|
||||
})
|
||||
setDismissHandler(() => {
|
||||
toggleOverlay(false, true)
|
||||
asyncSystemScan()
|
||||
})
|
||||
$('#overlayContent').fadeIn(250)
|
||||
})
|
||||
})
|
||||
toggleOverlay(true, true)
|
||||
|
||||
// TODO Add option to not install Java x64.
|
||||
|
||||
} else {
|
||||
// Java installation found, use this to launch the game.
|
||||
ConfigManager.setJavaExecutable(m.result)
|
||||
ConfigManager.save()
|
||||
if(launchAfter){
|
||||
dlAsync()
|
||||
}
|
||||
sysAEx.disconnect()
|
||||
}
|
||||
|
||||
} else if(m.content === '_enqueueOracleJRE'){
|
||||
|
||||
if(m.result === true){
|
||||
|
||||
// Oracle JRE enqueued successfully, begin download.
|
||||
setLaunchDetails('Downloading Java..')
|
||||
sysAEx.send({task: 0, content: 'processDlQueues', argsArr: [[{id:'java', limit:1}]]})
|
||||
|
||||
} else {
|
||||
|
||||
// Oracle JRE enqueue failed. Probably due to a change in their website format.
|
||||
// User will have to follow the guide to install Java.
|
||||
setOverlayContent(
|
||||
'Unexpected Issue:<br>Java Download Failed',
|
||||
'Unfortunately we\'ve encountered an issue while attempting to install Java. You will need to manually install a copy. Please check out our <a href="http://westeroscraft.wikia.com/wiki/Troubleshooting_Guide">Troubleshooting Guide</a> for more details and instructions.',
|
||||
'I Understand'
|
||||
)
|
||||
setOverlayHandler(() => {
|
||||
toggleOverlay(false)
|
||||
toggleLaunchArea(false)
|
||||
})
|
||||
toggleOverlay(true)
|
||||
sysAEx.disconnect()
|
||||
|
||||
}
|
||||
|
||||
} else if(m.content === 'dl'){
|
||||
|
||||
if(m.task === 0){
|
||||
// Downloading..
|
||||
setDownloadPercentage(m.value, m.total, m.percent)
|
||||
} else if(m.task === 1){
|
||||
// Download will be at 100%, remove the loading from the OS progress bar.
|
||||
remote.getCurrentWindow().setProgressBar(-1)
|
||||
|
||||
// Wait for extration to complete.
|
||||
setLaunchDetails('Extracting..')
|
||||
|
||||
} else if(m.task === 2){
|
||||
|
||||
// Extraction completed successfully.
|
||||
ConfigManager.setJavaExecutable(m.jPath)
|
||||
ConfigManager.save()
|
||||
|
||||
setLaunchDetails('Java Installed!')
|
||||
|
||||
if(launchAfter){
|
||||
dlAsync()
|
||||
}
|
||||
|
||||
sysAEx.disconnect()
|
||||
} else {
|
||||
console.error('Unknown download data type.', m)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
// Begin system Java scan.
|
||||
setLaunchDetails('Checking system info..')
|
||||
sysAEx.send({task: 0, content: 'validateJava', argsArr: [ConfigManager.getLauncherDirectory()]})
|
||||
|
||||
}
|
||||
|
||||
// Keep reference to Minecraft Process
|
||||
let proc
|
||||
// Is DiscordRPC enabled
|
||||
let hasRPC = false
|
||||
// Joined server regex
|
||||
const servJoined = /[[0-2][0-9]:[0-6][0-9]:[0-6][0-9]\] \[Client thread\/INFO\]: \[CHAT\] [a-zA-Z0-9_]{1,16} joined the game/g
|
||||
const gameJoined = /\[[0-2][0-9]:[0-6][0-9]:[0-6][0-9]\] \[Client thread\/WARN\]: Skipping bad option: lastServer:/g
|
||||
const gameJoined2 = /\[[0-2][0-9]:[0-6][0-9]:[0-6][0-9]\] \[Client thread\/INFO\]: Created: \d+x\d+ textures-atlas/g
|
||||
|
||||
let aEx
|
||||
let serv
|
||||
let versionData
|
||||
let forgeData
|
||||
|
||||
function dlAsync(login = true){
|
||||
|
||||
// Login parameter is temporary for debug purposes. Allows testing the validation/downloads without
|
||||
// launching the game.
|
||||
|
||||
if(login) {
|
||||
if(ConfigManager.getSelectedAccount() == null){
|
||||
console.error('login first.')
|
||||
//in devtools AuthManager.addAccount(username, pass)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
setLaunchDetails('Please wait..')
|
||||
toggleLaunchArea(true)
|
||||
setLaunchPercentage(0, 100)
|
||||
|
||||
// Start AssetExec to run validations and downloads in a forked process.
|
||||
aEx = cp.fork(path.join(__dirname, 'assets', 'js', 'assetexec.js'), [
|
||||
ConfigManager.getGameDirectory(),
|
||||
ConfigManager.getJavaExecutable()
|
||||
])
|
||||
|
||||
// Establish communications between the AssetExec and current process.
|
||||
aEx.on('message', (m) => {
|
||||
if(m.content === 'validateDistribution'){
|
||||
|
||||
setLaunchPercentage(20, 100)
|
||||
serv = m.result
|
||||
console.log('Forge Validation Complete.')
|
||||
|
||||
// Begin version load.
|
||||
setLaunchDetails('Loading version information..')
|
||||
aEx.send({task: 0, content: 'loadVersionData', argsArr: [serv.mc_version]})
|
||||
|
||||
} else if(m.content === 'loadVersionData'){
|
||||
|
||||
setLaunchPercentage(40, 100)
|
||||
versionData = m.result
|
||||
console.log('Version data loaded.')
|
||||
|
||||
// Begin asset validation.
|
||||
setLaunchDetails('Validating asset integrity..')
|
||||
aEx.send({task: 0, content: 'validateAssets', argsArr: [versionData]})
|
||||
|
||||
} else if(m.content === 'validateAssets'){
|
||||
|
||||
// Asset validation can *potentially* take longer, so let's track progress.
|
||||
if(m.task === 0){
|
||||
const perc = (m.value/m.total)*20
|
||||
setLaunchPercentage(40+perc, 100, parseInt(40+perc))
|
||||
} else {
|
||||
setLaunchPercentage(60, 100)
|
||||
console.log('Asset Validation Complete')
|
||||
|
||||
// Begin library validation.
|
||||
setLaunchDetails('Validating library integrity..')
|
||||
aEx.send({task: 0, content: 'validateLibraries', argsArr: [versionData]})
|
||||
}
|
||||
|
||||
} else if(m.content === 'validateLibraries'){
|
||||
|
||||
setLaunchPercentage(80, 100)
|
||||
console.log('Library validation complete.')
|
||||
|
||||
// Begin miscellaneous validation.
|
||||
setLaunchDetails('Validating miscellaneous file integrity..')
|
||||
aEx.send({task: 0, content: 'validateMiscellaneous', argsArr: [versionData]})
|
||||
|
||||
} else if(m.content === 'validateMiscellaneous'){
|
||||
|
||||
setLaunchPercentage(100, 100)
|
||||
console.log('File validation complete.')
|
||||
|
||||
// Download queued files.
|
||||
setLaunchDetails('Downloading files..')
|
||||
aEx.send({task: 0, content: 'processDlQueues'})
|
||||
|
||||
} else if(m.content === 'dl'){
|
||||
|
||||
if(m.task === 0){
|
||||
|
||||
setDownloadPercentage(m.value, m.total, m.percent)
|
||||
|
||||
} else if(m.task === 1){
|
||||
|
||||
// Download will be at 100%, remove the loading from the OS progress bar.
|
||||
remote.getCurrentWindow().setProgressBar(-1)
|
||||
|
||||
setLaunchDetails('Preparing to launch..')
|
||||
aEx.send({task: 0, content: 'loadForgeData', argsArr: [serv.id]})
|
||||
|
||||
} else {
|
||||
|
||||
console.error('Unknown download data type.', m)
|
||||
|
||||
}
|
||||
|
||||
} else if(m.content === 'loadForgeData'){
|
||||
|
||||
forgeData = m.result
|
||||
|
||||
if(login) {
|
||||
//if(!(await AuthManager.validateSelected())){
|
||||
//
|
||||
//}
|
||||
const authUser = ConfigManager.getSelectedAccount()
|
||||
console.log('authu', authUser)
|
||||
let pb = new ProcessBuilder(ConfigManager.getGameDirectory(), serv, versionData, forgeData, authUser)
|
||||
setLaunchDetails('Launching game..')
|
||||
try {
|
||||
// Build Minecraft process.
|
||||
proc = pb.build()
|
||||
setLaunchDetails('Done. Enjoy the server!')
|
||||
|
||||
// Attach a temporary listener to the client output.
|
||||
// Will wait for a certain bit of text meaning that
|
||||
// the client application has started, and we can hide
|
||||
// the progress bar stuff.
|
||||
const tempListener = function(data){
|
||||
if(data.indexOf('[Client thread/INFO]: -- System Details --') > -1){
|
||||
toggleLaunchArea(false)
|
||||
if(hasRPC){
|
||||
DiscordWrapper.updateDetails('Loading game..')
|
||||
}
|
||||
proc.stdout.removeListener('data', tempListener)
|
||||
}
|
||||
}
|
||||
|
||||
// Listener for Discord RPC.
|
||||
const gameStateChange = function(data){
|
||||
if(servJoined.test(data)){
|
||||
DiscordWrapper.updateDetails('Exploring the Realm!')
|
||||
} else if(gameJoined.test(data)){
|
||||
DiscordWrapper.updateDetails('Idling on Main Menu')
|
||||
}
|
||||
}
|
||||
|
||||
// Bind listeners to stdout.
|
||||
proc.stdout.on('data', tempListener)
|
||||
proc.stdout.on('data', gameStateChange)
|
||||
|
||||
// Init Discord Hook
|
||||
const distro = AssetGuard.retrieveDistributionDataSync(ConfigManager.getGameDirectory)
|
||||
if(distro.discord != null && serv.discord != null){
|
||||
DiscordWrapper.initRPC(distro.discord, serv.discord)
|
||||
hasRPC = true
|
||||
proc.on('close', (code, signal) => {
|
||||
console.log('Shutting down Discord Rich Presence..')
|
||||
DiscordWrapper.shutdownRPC()
|
||||
hasRPC = false
|
||||
proc = null
|
||||
})
|
||||
}
|
||||
|
||||
} catch(err) {
|
||||
|
||||
// Show that there was an error then hide the
|
||||
// progress area. Maybe switch this to an error
|
||||
// alert in the future. TODO
|
||||
setLaunchDetails('Error: See log for details..')
|
||||
console.log(err)
|
||||
setTimeout(function(){
|
||||
toggleLaunchArea(false)
|
||||
}, 5000)
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
// Disconnect from AssetExec
|
||||
aEx.disconnect()
|
||||
|
||||
}
|
||||
})
|
||||
|
||||
// Begin Validations
|
||||
|
||||
// Validate Forge files.
|
||||
setLaunchDetails('Loading server information..')
|
||||
aEx.send({task: 0, content: 'validateDistribution', argsArr: [ConfigManager.getSelectedServer()]})
|
||||
}
|
||||
212
app/assets/js/scripts/login.js
Normal file
212
app/assets/js/scripts/login.js
Normal file
@@ -0,0 +1,212 @@
|
||||
//const validEmail = /^(([^<>()\[\]\.,;:\s@\"]+(\.[^<>()\[\]\.,;:\s@\"]+)*)|(\".+\"))@(([^<>()[\]\.,;:\s@\"]+\.)+[^<>()[\]\.,;:\s@\"]{2,})$/i
|
||||
|
||||
// Validation Regexes.
|
||||
const validUsername = /^[a-zA-Z0-9_]{1,16}$/
|
||||
const basicEmail = /^\S+@\S+\.\S+$/
|
||||
|
||||
// DOM cache.
|
||||
const loginContainer = document.getElementById('loginContainer')
|
||||
const loginErrorTitle = document.getElementById('loginErrorTitle')
|
||||
const loginErrorDesc = document.getElementById('loginErrorDesc')
|
||||
const loginErrorAcknowledge = document.getElementById('loginErrorAcknowledge')
|
||||
|
||||
const loginEmailError = document.getElementById('loginEmailError')
|
||||
const loginUsername = document.getElementById('loginUsername')
|
||||
const loginPasswordError = document.getElementById('loginPasswordError')
|
||||
const loginPassword = document.getElementById('loginPassword')
|
||||
const checkmarkContainer = document.getElementById('checkmarkContainer')
|
||||
const loginRememberOption = document.getElementById('loginRememberOption')
|
||||
const loginButton = document.getElementById('loginButton')
|
||||
|
||||
// Control variables.
|
||||
let lu = false, lp = false
|
||||
|
||||
// Show error element.
|
||||
function showError(element, value){
|
||||
element.innerHTML = value
|
||||
element.style.opacity = 1
|
||||
}
|
||||
|
||||
// Shake error element.
|
||||
function shakeError(element){
|
||||
if(element.style.opacity == 1){
|
||||
element.classList.remove('shake')
|
||||
void element.offsetWidth
|
||||
element.classList.add('shake')
|
||||
}
|
||||
}
|
||||
|
||||
// Validate email field is neither empty nor invalid.
|
||||
function validateEmail(value){
|
||||
if(value){
|
||||
if(!basicEmail.test(value) && !validUsername.test(value)){
|
||||
showError(loginEmailError, '* Invalid Value')
|
||||
loginDisabled(true)
|
||||
lu = false
|
||||
} else {
|
||||
loginEmailError.style.opacity = 0
|
||||
lu = true
|
||||
if(lp){
|
||||
loginDisabled(false)
|
||||
}
|
||||
}
|
||||
} else {
|
||||
lu = false
|
||||
showError(loginEmailError, '* Required')
|
||||
loginDisabled(true)
|
||||
}
|
||||
}
|
||||
|
||||
// Validate password field is not empty.
|
||||
function validatePassword(value){
|
||||
if(value){
|
||||
loginPasswordError.style.opacity = 0
|
||||
lp = true
|
||||
if(lu){
|
||||
loginDisabled(false)
|
||||
}
|
||||
} else {
|
||||
lp = false
|
||||
showError(loginPasswordError, '* Required')
|
||||
loginDisabled(true)
|
||||
}
|
||||
}
|
||||
|
||||
// Emphasize errors with shake when focus is lost.
|
||||
loginUsername.addEventListener('focusout', (e) => {
|
||||
validateEmail(e.target.value)
|
||||
shakeError(loginEmailError)
|
||||
})
|
||||
loginPassword.addEventListener('focusout', (e) => {
|
||||
validatePassword(e.target.value)
|
||||
shakeError(loginPasswordError)
|
||||
})
|
||||
|
||||
// Validate input for each field.
|
||||
loginUsername.addEventListener('input', (e) => {
|
||||
validateEmail(e.target.value)
|
||||
})
|
||||
loginPassword.addEventListener('input', (e) => {
|
||||
validatePassword(e.target.value)
|
||||
})
|
||||
|
||||
// Enable or disable login button.
|
||||
function loginDisabled(v){
|
||||
if(loginButton.disabled !== v){
|
||||
loginButton.disabled = v
|
||||
}
|
||||
}
|
||||
|
||||
// Enable or disable loading elements.
|
||||
function loginLoading(v){
|
||||
if(v){
|
||||
loginButton.setAttribute('loading', v)
|
||||
loginButton.innerHTML = loginButton.innerHTML.replace('LOGIN', 'LOGGING IN')
|
||||
} else {
|
||||
loginButton.removeAttribute('loading')
|
||||
loginButton.innerHTML = loginButton.innerHTML.replace('LOGGING IN', 'LOGIN')
|
||||
}
|
||||
}
|
||||
|
||||
// Disable or enable login form.
|
||||
function formDisabled(v){
|
||||
loginDisabled(v)
|
||||
loginUsername.disabled = v
|
||||
loginPassword.disabled = v
|
||||
if(v){
|
||||
checkmarkContainer.setAttribute('disabled', v)
|
||||
} else {
|
||||
checkmarkContainer.removeAttribute('disabled')
|
||||
}
|
||||
loginRememberOption.disabled = v
|
||||
}
|
||||
|
||||
function resolveError(err){
|
||||
// Mojang Response => err.cause | err.error | err.errorMessage
|
||||
// Node error => err.code | err.message
|
||||
if(err.cause != null && err.cause === 'UserMigratedException') {
|
||||
return {
|
||||
title: 'Error During Login:<br>Invalid Credentials',
|
||||
desc: 'You\'ve attempted to login with a migrated account. Try again using the account email as the username.'
|
||||
}
|
||||
} else {
|
||||
if(err.error != null){
|
||||
if(err.error === 'ForbiddenOperationException'){
|
||||
if(err.errorMessage != null){
|
||||
if(err.errorMessage === 'Invalid credentials. Invalid username or password.'){
|
||||
return {
|
||||
title: 'Error During Login:<br>Invalid Credentials',
|
||||
desc: 'The email or password you\'ve entered is incorrect. Please try again.'
|
||||
}
|
||||
} else if(err.errorMessage === 'Invalid credentials.'){
|
||||
return {
|
||||
title: 'Error During Login:<br>Too Many Attempts',
|
||||
desc: 'There have been too many login attempts with this account recently. Please try again later.'
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// Request errors (from Node).
|
||||
if(err.code != null){
|
||||
if(err.code === 'ENOENT'){
|
||||
// No Internet.
|
||||
return {
|
||||
title: 'Error During Login:<br>No Internet Connection',
|
||||
desc: 'You must be connected to the internet in order to login. Please connect and try again.'
|
||||
}
|
||||
} else if(err.code === 'ENOTFOUND'){
|
||||
// Could not reach server.
|
||||
return {
|
||||
title: 'Error During Login:<br>Authentication Server Offline',
|
||||
desc: 'Mojang\'s authentication server is currently offline or unreachable. Please wait a bit and try again. You can check the status of the server on <a href="https://help.mojang.com/">Mojang\'s help portal</a>.'
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if(err.message != null){
|
||||
// Unknown error with request.
|
||||
return {
|
||||
title: 'Error During Login:<br>Unknown Error',
|
||||
desc: err.message
|
||||
}
|
||||
} else {
|
||||
// Unknown Mojang error.
|
||||
return {
|
||||
title: err.error,
|
||||
desc: err.errorMessage
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
loginButton.addEventListener('click', () => {
|
||||
// Disable form.
|
||||
formDisabled(true)
|
||||
|
||||
// Show loading stuff.
|
||||
loginLoading(true)
|
||||
|
||||
AuthManager.addAccount(loginUsername.value, loginPassword.value).then((value) => {
|
||||
loginButton.innerHTML = loginButton.innerHTML.replace('LOGGING IN', 'SUCCESS')
|
||||
$('.circle-loader').toggleClass('load-complete')
|
||||
$('.checkmark').toggle()
|
||||
//console.log(value)
|
||||
setTimeout(() => {
|
||||
$('#loginContainer').fadeOut(500, () => {
|
||||
$('#landingContainer').fadeIn(500)
|
||||
})
|
||||
}, 1000)
|
||||
}).catch((err) => {
|
||||
loginLoading(false)
|
||||
const errF = resolveError(err)
|
||||
setOverlayContent(errF.title, errF.desc, 'Try Again')
|
||||
setOverlayHandler(() => {
|
||||
formDisabled(false)
|
||||
toggleOverlay(false)
|
||||
})
|
||||
toggleOverlay(true)
|
||||
console.log(err)
|
||||
})
|
||||
|
||||
})
|
||||
92
app/assets/js/scripts/uicore.js
Normal file
92
app/assets/js/scripts/uicore.js
Normal file
@@ -0,0 +1,92 @@
|
||||
/**
|
||||
* Core UI functions are initialized in this file. This prevents
|
||||
* unexpected errors from breaking the core features. Specifically,
|
||||
* actions in this file should not require the usage of any internal
|
||||
* modules, excluding dependencies.
|
||||
*/
|
||||
const $ = require('jquery');
|
||||
const {remote, shell, webFrame} = require('electron')
|
||||
|
||||
// Disable zoom, needed for darwin.
|
||||
webFrame.setZoomLevel(0)
|
||||
webFrame.setVisualZoomLevelLimits(1, 1)
|
||||
webFrame.setLayoutZoomLevelLimits(0, 0)
|
||||
|
||||
/* jQuery Example
|
||||
$(function(){
|
||||
console.log('UICore Initialized');
|
||||
})*/
|
||||
|
||||
document.addEventListener('readystatechange', function () {
|
||||
if (document.readyState === 'interactive'){
|
||||
console.log('UICore Initializing..');
|
||||
|
||||
// Bind close button.
|
||||
Array.from(document.getElementsByClassName('fCb')).map((val) => {
|
||||
val.addEventListener('click', e => {
|
||||
const window = remote.getCurrentWindow()
|
||||
window.close()
|
||||
})
|
||||
})
|
||||
|
||||
// Bind restore down button.
|
||||
Array.from(document.getElementsByClassName('fRb')).map((val) => {
|
||||
val.addEventListener('click', e => {
|
||||
const window = remote.getCurrentWindow()
|
||||
if(window.isMaximized()){
|
||||
window.unmaximize()
|
||||
} else {
|
||||
window.maximize()
|
||||
}
|
||||
document.activeElement.blur()
|
||||
})
|
||||
})
|
||||
|
||||
// Bind minimize button.
|
||||
Array.from(document.getElementsByClassName('fMb')).map((val) => {
|
||||
val.addEventListener('click', e => {
|
||||
const window = remote.getCurrentWindow()
|
||||
window.minimize()
|
||||
document.activeElement.blur()
|
||||
})
|
||||
})
|
||||
|
||||
} else if(document.readyState === 'complete'){
|
||||
|
||||
//266.01
|
||||
//170.8
|
||||
//53.21
|
||||
// Bind progress bar length to length of bot wrapper
|
||||
//const targetWidth = document.getElementById("launch_content").getBoundingClientRect().width
|
||||
//const targetWidth2 = document.getElementById("server_selection").getBoundingClientRect().width
|
||||
//const targetWidth3 = document.getElementById("launch_button").getBoundingClientRect().width
|
||||
|
||||
document.getElementById("launch_details").style.maxWidth = 266.01
|
||||
document.getElementById("launch_progress").style.width = 170.8
|
||||
document.getElementById("launch_details_right").style.maxWidth = 170.8
|
||||
document.getElementById("launch_progress_label").style.width = 53.21
|
||||
|
||||
}
|
||||
|
||||
}, false)
|
||||
|
||||
/**
|
||||
* Open web links in the user's default browser.
|
||||
*/
|
||||
$(document).on('click', 'a[href^="http"]', function(event) {
|
||||
event.preventDefault();
|
||||
//console.log(os.homedir())
|
||||
shell.openExternal(this.href)
|
||||
})
|
||||
|
||||
/**
|
||||
* Opens DevTools window if you hold (ctrl + shift + i).
|
||||
* This will crash the program if you are using multiple
|
||||
* DevTools, for example the chrome debugger in VS Code.
|
||||
*/
|
||||
document.addEventListener('keydown', function (e) {
|
||||
if(e.keyCode == 73 && e.ctrlKey && e.shiftKey){
|
||||
let window = remote.getCurrentWindow()
|
||||
window.toggleDevTools()
|
||||
}
|
||||
})
|
||||
8
app/assets/js/scripts/welcome.js
Normal file
8
app/assets/js/scripts/welcome.js
Normal file
@@ -0,0 +1,8 @@
|
||||
// DOM cache.
|
||||
const welcomeButton = document.getElementById('welcomeButton')
|
||||
|
||||
welcomeButton.addEventListener('click', e => {
|
||||
$('#welcomeContainer').fadeOut(500, () => {
|
||||
$('#loginContainer').fadeIn(500)
|
||||
})
|
||||
})
|
||||
Reference in New Issue
Block a user