Compare commits

..

46 Commits

Author SHA1 Message Date
Daniel Scalzi
f139992e06
Dependency upgrade, replace moment with luxon. 2020-10-06 18:56:10 -04:00
Daniel Scalzi
df74b0e67c
Convert media button CSS from px to rem. 2020-09-14 00:51:06 -04:00
Daniel Scalzi
6a04ef0f62
Move landing media buttons to their own component.
The media buttons can either open a link or perform an action.
TODO: Convert CSS from px to rem.
2020-09-13 22:18:08 -04:00
Daniel Scalzi
e86992a7ee
Open anchor hrefs in the default browser. (#111) 2020-09-13 20:27:18 -04:00
Daniel Scalzi
9793c4072d
Convert server/account select overlay css from px to rem (#109). 2020-09-13 19:24:27 -04:00
Daniel Scalzi
043f85c0dc
Convert generic overlay css from px to rem. (#109) 2020-09-13 19:05:29 -04:00
Daniel Scalzi
0cbd39b79c
Move status refresh intervals to App component (resolves #107). 2020-09-13 18:43:01 -04:00
Daniel Scalzi
67e42ead78
Show player count on landing page.
The server status needs to be stored in the redux store as it needs to be determined before
mounting the Landing component.
2020-09-04 22:41:32 -04:00
Daniel Scalzi
cb68c34abe
Bind server select button and store selected server in redux store. 2020-08-31 22:58:43 -04:00
Daniel Scalzi
574b362d12
Server select overlay working. 2020-08-31 20:31:50 -04:00
Daniel Scalzi
dc00e6104b
Initial work on distro load logic.
Added new FATAL view to display information when a distro load fails. This replaces
the overlay behavior used on v1. The fatal view will eventually do an update check
and allow the user to update the app. This solves a potential issue of a user using
a very outdated launcher version, and the distro failing as a result.

Added new wrapper classes to store the distribution in the redux store.
2020-08-29 01:12:39 -04:00
Daniel Scalzi
dbc49f51dd
Make sure to return on rejection. 2020-08-28 17:39:29 -04:00
Daniel Scalzi
e76eb91ac9
Test improvements.
Clean mojang test directory.
Added test for server status.
Disable winston in test mode.
2020-08-27 21:55:24 -04:00
Daniel Scalzi
c7b95f3719
Clean up structure of Mojang API/Util files. 2020-08-27 21:27:56 -04:00
Daniel Scalzi
571b788e25
A better solution to read long data.
Assign a once listener to pick up the initial data including the packet type and length.
Assign a subsequent listener to read the remainder of the data.
2020-08-27 21:08:53 -04:00
Daniel Scalzi
27f95235f8
Working fix for socket read for large response. Going to try another fix. 2020-08-27 20:45:11 -04:00
Daniel Scalzi
3838729da7
Add API to get server status information. 2020-08-27 19:37:41 -04:00
Daniel Scalzi
feb9b98b2a
Add mojang statuses to landing component. 2020-08-24 21:26:24 -04:00
Daniel Scalzi
bc43d842e3
Pull out common got error handling for generic use. Initial distribution loading (no application state storage yet). 2020-08-24 20:18:08 -04:00
Daniel Scalzi
15fd2c842a
Fix tests with tsconfig-paths. 2020-07-15 23:54:35 -04:00
Daniel Scalzi
53d5599545
Get working on Electron 9, full dependency refresh. 2020-07-15 21:07:40 -04:00
Daniel Scalzi
10c88aa7d0
Dependency upgrade. 2020-07-15 20:35:06 -04:00
Daniel Scalzi
c670b7d88d
Initial work on overlay system.
The overlay display is driven by an array in the global redux store. Overlay
content is now queueabale, so alerts can be asynchronously dispatched without
interferring with existing displayed content.

The server/account select overlay components are yet to be completed. Some usability
features also need to be implemented, such as keybinds for the acknowledge/dismiss
buttons.
2020-06-12 20:58:07 -04:00
Daniel Scalzi
691cf937fc
Added landing view structure and styles.
The landing view will be broken up into subcomponents.
Updated dependencies.
2020-06-11 16:25:56 -04:00
Daniel Scalzi
33e454e529
Use rem on login view. 2020-05-27 16:54:52 -04:00
Daniel Scalzi
ab51b84bea
Use rem for loading spinner, fix frame bug when loader is scaled up. 2020-05-26 23:25:02 -04:00
Daniel Scalzi
d9394432d2
Add loading UI, add view transition animations.
Framework is in place to run initial load on app startup. These routines will be called
in Application's initLoad function. The loader will run for a min of 800ms to prevent it
from looking odd on the UI. This can be reduced/changed later if this turns out to not be
a concern.

Added an app reducer to redux. The loading state was initially going to be there. On further
inspection, it seemed better to have it as a state variable in the Application component. It
remains in the store for now as an example. The pattern is valid and will be used for other
proprties.

Added animations for view transitions. On v1, this was done with jquery. Here, we are using
react-transition-group. Got it working with a clever trick to store a workingView and use that
for rendering. When the currentView is changed by the redux store, the fade out transition will
start. Once the fade out completes, the workingView reference will be updated to the new view,
triggering the fade in.
2020-05-26 01:50:55 -04:00
Daniel Scalzi
18fbfe4289
Move backgrounds to static, get dynamic backgrounds to work.
TODO: Add loading spinner and make background load ease in.
2020-05-25 17:13:59 -04:00
Daniel Scalzi
7ef375db7a
Bring back eslint. 2020-05-24 19:11:34 -04:00
Daniel Scalzi
dc7386f19d
Remove some old code, apply fix from master.
Reference to the old code will be made from the master branch.
2020-05-24 15:50:23 -04:00
Daniel Scalzi
9a67087766
Move code to common.
Renderer will be only react/redux code.
Common code can be used in both main and renderer.
2020-05-24 15:44:16 -04:00
Daniel Scalzi
5944f70a2a
Add login behavior up to loading state.
The remaining functionality depends on implementing a new AuthManager and overlay system.
2020-05-23 03:31:26 -04:00
Daniel Scalzi
c718cc741a Add functionality to LoginField component.
State management and error detection/animation added.
TBD: Connect fields to parent component.
2020-05-23 02:03:20 -04:00
Daniel Scalzi
f1a7e39e13
Initial work on Login view, fixed some style issues.
So far, the basic structure of the Login view has been imported. The css
properties need to be converted to use rem. The component also needs to
be made functional and reactive.

Planning on using property callbacks for Child -> Parent communication.
2020-05-22 22:41:47 -04:00
Daniel Scalzi
a9d6f2021d
Use rem for sizing instead of px. Will enable scalability.
Applied rem changes to Welcome.css.
Updated dependencies.
2020-05-22 21:05:29 -04:00
Daniel Scalzi
af6066115c
Dependency Upgrade. 2020-05-11 19:03:28 -04:00
Daniel Scalzi
3fcfa492af
Initial redux setup. 2020-05-06 07:35:25 -04:00
Daniel Scalzi
28f78f719e
Updated dependencies, added Welcome component.
The CSS needs to be redone and made more modular. Measurements should not be done in px, and switched to em/rem.
Redux needs to be setup for state management.
2020-05-05 18:39:31 -04:00
Daniel Scalzi
c9147d86a8
Added Index Processor for Mojang Indices.
Also added test for the mojang processor.
TBD: Progress System for Validations.
TBD: Processor for Distribution.json.
2020-04-18 04:59:35 -04:00
Daniel Scalzi
8764c52fcc
Use Got instead of Axios.
The lack of maintainers on Axios is worrying. Got seems like a more solid option.
2020-04-17 23:50:18 -04:00
Daniel Scalzi
75a7e0f713
File structure refactor, move old files to old directory.
Removed legacy config path support in ConfigManager.
Moved model files to corresponding subdirectories, rather than being in
an uber model directory.
2020-04-13 22:51:32 -04:00
Daniel Scalzi
9097bafb5d
Added Axios + Logging & Testing Frameworks.
Rewrote mojang.ts to use axios. This included creating a more robust error handling
system and response payload structure. Also included unit tests.

Added axios (HTTP Library to replace request)
Added winston (Logging Framework)
Added mocha (Testing Framework)
Added chai (assertion library)
Added nock (mock server)
2020-04-13 22:21:48 -04:00
Daniel Scalzi
761a46060b
Add global styles, move fonts.
Need to figure out if the path trick to load fonts from css will work in prod.
May need to load fonts from tsx file and use __static.
2020-04-13 06:23:27 -04:00
Daniel Scalzi
3cde9ef75e
Simplify structure.
Now using electron-webpack.
Additional frameworks will be added down the line as this setup becomes
more comfortable.
2020-04-13 05:56:26 -04:00
Daniel Scalzi
b9536ed014
Initial work on react.
Far from done.
Far from working.
Requires rewrite of UI logic using react patterns.
2020-03-08 20:40:37 -04:00
Daniel Scalzi
9cb10b70af
Working on typescript conversion, not functional yet. 2020-01-26 01:12:48 -05:00
182 changed files with 24629 additions and 9908 deletions

View File

@ -1,66 +1,48 @@
{ {
"env": { "root": true,
"es2022": true, "parser": "@typescript-eslint/parser",
"node": true "plugins": [
}, "@typescript-eslint"
"extends": "eslint:recommended", ],
"extends": [
"eslint:recommended",
"plugin:@typescript-eslint/recommended",
"plugin:react/recommended"
],
"parserOptions": { "parserOptions": {
"ecmaVersion": 2022, "ecmaFeatures": {
"sourceType": "module" "jsx": true
}
}, },
"rules": { "rules": {
"indent": [ "semi": "off",
"error", "@typescript-eslint/semi": [
4,
{
"SwitchCase": 1
}
],
"linebreak-style": [
"error",
"windows"
],
"quotes": [
"error",
"single"
],
"semi": [
"error", "error",
"never" "never"
], ],
"no-var": [ "quotes": "off",
"error" "@typescript-eslint/quotes": [
"error",
"single"
], ],
"no-console": [ "indent": "off",
0 "@typescript-eslint/indent": [
"error",
4
], ],
"no-control-regex": [ "@typescript-eslint/member-delimiter-style": [
0
],
"no-unused-vars": [
"error", "error",
{ {
"vars": "all", "multiline": {
"args": "none", "delimiter": "none",
"ignoreRestSiblings": false, "requireLast": false
"argsIgnorePattern": "reject"
}
],
"no-async-promise-executor": [
0
]
}, },
"overrides": [ "singleline": {
{ "delimiter": "comma",
"files": [ "app/assets/js/scripts/*.js" ], "requireLast": false
"rules": { }
"no-unused-vars": [ }
0
], ],
"no-undef": [ "@typescript-eslint/no-non-null-assertion": "off"
0
]
} }
}
]
} }

66
.eslintrc.json.old Normal file
View File

@ -0,0 +1,66 @@
{
"env": {
"es2017": true,
"node": true
},
"extends": "eslint:recommended",
"parserOptions": {
"ecmaVersion": 2019,
"sourceType": "module"
},
"rules": {
"indent": [
"error",
4,
{
"SwitchCase": 1
}
],
"linebreak-style": [
"error",
"windows"
],
"quotes": [
"error",
"single"
],
"semi": [
"error",
"never"
],
"no-var": [
"error"
],
"no-console": [
0
],
"no-control-regex": [
0
],
"no-unused-vars": [
"error",
{
"vars": "all",
"args": "none",
"ignoreRestSiblings": false,
"argsIgnorePattern": "reject"
}
],
"no-async-promise-executor": [
0
]
},
"overrides": [
{
"files": [ "src/scripts/*.js" ],
"rules": {
"no-unused-vars": [
0
],
"no-undef": [
0
]
}
}
]
}

3
.github/FUNDING.yml vendored
View File

@ -1,3 +0,0 @@
github: dscalzi
patreon: dscalzi
custom: ['https://www.paypal.me/dscalzi']

View File

@ -1,38 +0,0 @@
name: Build
on: push
jobs:
release:
runs-on: ${{ matrix.os }}
permissions:
contents: write
strategy:
matrix:
os: [macos-latest, ubuntu-latest, windows-latest]
steps:
- name: Check out Git repository
uses: actions/checkout@v3
- name: Set up Node
uses: actions/setup-node@v3
with:
node-version: 18
- name: Set up Python
uses: actions/setup-python@v4
with:
python-version: 3.x
- name: Install Dependencies
run: npm ci
shell: bash
- name: Build
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: npm run dist
shell: bash

2
.gitignore vendored
View File

@ -4,3 +4,5 @@
/target/ /target/
/logs/ /logs/
/dist/ /dist/
/out/
/old/

2
.nvmrc
View File

@ -1 +1 @@
18 12

45
.travis.yml Normal file
View File

@ -0,0 +1,45 @@
matrix:
include:
- os: osx
osx_image: xcode11.3
language: node_js
node_js: "12"
env:
- ELECTRON_CACHE=$HOME/.cache/electron
- ELECTRON_BUILDER_CACHE=$HOME/.cache/electron-builder
- ELECTRON_BUILDER_ALLOW_UNRESOLVED_DEPENDENCIES=true
- CSC_IDENTITY_AUTO_DISCOVERY=false
- os: linux
services: docker
language: generic
node_js: "12"
env:
- ELECTRON_BUILDER_ALLOW_UNRESOLVED_DEPENDENCIES=true
cache:
directories:
- node_modules
- $HOME/.cache/electron
- $HOME/.cache/electron-builder
script:
- |
if [ "$TRAVIS_OS_NAME" == "linux" ]; then
ENVS=`env | grep -iE '(DEBUG|NODE_|ELECTRON_|YARN_|NPM_|CI|CIRCLE|TRAVIS|APPVEYOR_|CSC_|_TOKEN|_KEY|AWS_|STRIP|BUILD_)' | sed -n '/^[^\t]/s/=.*//p' | sed '/^$/d' | sed 's/^/-e /g' | tr '\n' ' '`
docker run $ENVS --rm \
-v ${PWD}:/project \
-v ~/.cache/electron:/root/.cache/electron \
-v ~/.cache/electron-builder:/root/.cache/electron-builder \
electronuserland/builder:wine \
/bin/bash -c "node -v && npm ci && npm run cilinux"
else
npm run cidarwin
fi
before_cache:
- rm -rf $HOME/.cache/electron-builder/wine
branches:
except:
- "/^v\\d+\\.\\d+\\.\\d+$/"

View File

@ -1,21 +0,0 @@
MIT License
Copyright (c) 2017-2022 Daniel D. Scalzi
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View File

@ -1,10 +1,10 @@
<p align="center"><img src="./app/assets/images/SealCircle.png" width="150px" height="150px" alt="aventium softworks"></p> <p align="center"><img src="./static/images/SealCircle.png" width="150px" height="150px" alt="aventium softworks"></p>
<h1 align="center">Helios Launcher</h1> <h1 align="center">Helios Launcher</h1>
<em><h5 align="center">(formerly Electron Launcher)</h5></em> <em><h5 align="center">(formerly Electron Launcher)</h5></em>
[<p align="center"><img src="https://img.shields.io/github/actions/workflow/status/dscalzi/HeliosLauncher/build.yml?branch=master&style=for-the-badge" alt="gh actions">](https://github.com/dscalzi/HeliosLauncher/actions) [<img src="https://img.shields.io/github/downloads/dscalzi/HeliosLauncher/total.svg?style=for-the-badge" alt="downloads">](https://github.com/dscalzi/HeliosLauncher/releases) <img src="https://forthebadge.com/images/badges/winter-is-coming.svg" height="28px" alt="winter-is-coming"></p> [<p align="center"><img src="https://img.shields.io/travis/dscalzi/HeliosLauncher.svg?style=for-the-badge" alt="travis">](https://travis-ci.org/dscalzi/HeliosLauncher) [<img src="https://img.shields.io/github/downloads/dscalzi/HeliosLauncher/total.svg?style=for-the-badge" alt="downloads">](https://github.com/dscalzi/HeliosLauncher/releases) <img src="https://forthebadge.com/images/badges/winter-is-coming.svg" height="28px" alt="stark"></p>
<p align="center">Join modded servers without worrying about installing Java, Forge, or other mods. We'll handle that for you.</p> <p align="center">Join modded servers without worrying about installing Java, Forge, or other mods. We'll handle that for you.</p>
@ -15,7 +15,6 @@
* 🔒 Full account management. * 🔒 Full account management.
* Add multiple accounts and easily switch between them. * Add multiple accounts and easily switch between them.
* Microsoft (OAuth 2.0) + Mojang (Yggdrasil) authentication fully supported.
* Credentials are never stored and transmitted directly to Mojang. * Credentials are never stored and transmitted directly to Mojang.
* 📂 Efficient asset management. * 📂 Efficient asset management.
* Receive client updates as soon as we release them. * Receive client updates as soon as we release them.
@ -54,10 +53,9 @@ If you download from the [Releases](https://github.com/dscalzi/HeliosLauncher/re
| Platform | File | | Platform | File |
| -------- | ---- | | -------- | ---- |
| Windows x64 | `Helios-Launcher-setup-VERSION.exe` | | Windows x64 | `helioslauncher-setup-VERSION.exe` |
| macOS x64 | `Helios-Launcher-setup-VERSION-x64.dmg` | | macOS | `helioslauncher-VERSION.dmg` |
| macOS arm64 | `Helios-Launcher-setup-VERSION-arm64.dmg` | | Linux x64 | `helioslauncher-VERSION-x86_64.AppImage` |
| Linux x64 | `Helios-Launcher-setup-VERSION.AppImage` |
## Console ## Console
@ -78,13 +76,11 @@ If you want to export the console output, simply right click anywhere on the con
## Development ## Development
This section details the setup of a basic developmentment environment.
### Getting Started ### Getting Started
**System Requirements** **System Requirements**
* [Node.js][nodejs] v18 * [Node.js][nodejs] v12
--- ---
@ -140,24 +136,28 @@ Paste the following into `.vscode/launch.json`
"name": "Debug Main Process", "name": "Debug Main Process",
"type": "node", "type": "node",
"request": "launch", "request": "launch",
"cwd": "${workspaceFolder}", "cwd": "${workspaceRoot}",
"program": "${workspaceFolder}/node_modules/electron/cli.js", "runtimeExecutable": "${workspaceRoot}/node_modules/.bin/electron",
"args" : ["."], "windows": {
"outputCapture": "std" "runtimeExecutable": "${workspaceRoot}/node_modules/.bin/electron.cmd"
},
"args": ["."],
"console": "integratedTerminal",
"protocol": "inspector"
}, },
{ {
"name": "Debug Renderer Process", "name": "Debug Renderer Process",
"type": "chrome", "type": "chrome",
"request": "launch", "request": "launch",
"runtimeExecutable": "${workspaceFolder}/node_modules/.bin/electron", "runtimeExecutable": "${workspaceRoot}/node_modules/.bin/electron",
"windows": { "windows": {
"runtimeExecutable": "${workspaceFolder}/node_modules/.bin/electron.cmd" "runtimeExecutable": "${workspaceRoot}/node_modules/.bin/electron.cmd"
}, },
"runtimeArgs": [ "runtimeArgs": [
"${workspaceFolder}/.", "${workspaceRoot}/.",
"--remote-debugging-port=9222" "--remote-debugging-port=9222"
], ],
"webRoot": "${workspaceFolder}" "webRoot": "${workspaceRoot}"
} }
] ]
} }
@ -177,19 +177,9 @@ Note that you **cannot** open the DevTools window while using this debug configu
--- ---
### Note on Third-Party Usage
Please give credit to the original author and provide a link to the original source. This is free software, please do at least this much.
For instructions on setting up Microsoft Authentication, see https://github.com/dscalzi/HeliosLauncher/blob/master/docs/MicrosoftAuth.md.
---
## Resources ## Resources
* [Wiki][wiki] * [Wiki][wiki]
* [Nebula (Create Distribution.json)][nebula]
* [v2 Rewrite Branch (Inactive)][v2branch]
The best way to contact the developers is on Discord. The best way to contact the developers is on Discord.
@ -207,5 +197,5 @@ The best way to contact the developers is on Discord.
[chromedebugger]: https://marketplace.visualstudio.com/items?itemName=msjsdiag.debugger-for-chrome 'Debugger for Chrome' [chromedebugger]: https://marketplace.visualstudio.com/items?itemName=msjsdiag.debugger-for-chrome 'Debugger for Chrome'
[discord]: https://discord.gg/zNWUXdt 'Discord' [discord]: https://discord.gg/zNWUXdt 'Discord'
[wiki]: https://github.com/dscalzi/HeliosLauncher/wiki 'wiki' [wiki]: https://github.com/dscalzi/HeliosLauncher/wiki 'wiki'
[nebula]: https://github.com/dscalzi/Nebula 'dscalzi/Nebula'
[v2branch]: https://github.com/dscalzi/HeliosLauncher/tree/ts-refactor 'v2 branch' © 2020 Daniel Scalzi All Rights Reserved

View File

@ -1,7 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 23 23">
<path fill="#f3f3f3" d="M0 0h23v23H0z" />
<path fill="#f35325" d="M1 1h10v10H1z" />
<path fill="#81bc06" d="M12 1h10v10H12z" />
<path fill="#05a6f0" d="M1 12h10v10H1z" />
<path fill="#ffba08" d="M12 12h10v10H12z" />
</svg>

Before

Width:  |  Height:  |  Size: 303 B

View File

@ -1,5 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" width="64" height="64" viewBox="0 0 9.677 9.667">
<path d="M-26.332-12.098h2.715c-1.357.18-2.574 1.23-2.715 2.633z" fill="#fff" />
<path d="M2.598.022h7.07L9.665 7c-.003 1.334-1.113 2.46-2.402 2.654H0V2.542C.134 1.2 1.3.195 2.598.022z" fill="#db2331" />
<path d="M1.54 2.844c.314-.76 1.31-.46 1.954-.528.785-.083 1.503.272 2.1.758l.164-.9c.327.345.587.756.964 1.052.28.254.655-.342.86-.013.42.864.408 1.86.54 2.795l-.788-.373C6.9 4.17 5.126 3.052 3.656 3.685c-1.294.592-1.156 2.65.06 3.255 1.354.703 2.953.51 4.405.292-.07.42-.34.87-.834.816l-4.95.002c-.5.055-.886-.413-.838-.89l.04-4.315z" fill="#fff" />
</svg>

Before

Width:  |  Height:  |  Size: 664 B

View File

@ -1,315 +0,0 @@
/**
* AuthManager
*
* This module aims to abstract login procedures. Results from Mojang's REST api
* are retrieved through our Mojang module. These results are processed and stored,
* if applicable, in the config using the ConfigManager. All login procedures should
* be made through this module.
*
* @module authmanager
*/
// Requirements
const ConfigManager = require('./configmanager')
const { LoggerUtil } = require('helios-core')
const { RestResponseStatus } = require('helios-core/common')
const { MojangRestAPI, mojangErrorDisplayable, MojangErrorCode } = require('helios-core/mojang')
const { MicrosoftAuth, microsoftErrorDisplayable, MicrosoftErrorCode } = require('helios-core/microsoft')
const { AZURE_CLIENT_ID } = require('./ipcconstants')
const log = LoggerUtil.getLogger('AuthManager')
// Functions
/**
* Add a Mojang account. This will authenticate the given credentials with Mojang's
* authserver. The resultant data will be stored as an auth account in the
* configuration database.
*
* @param {string} username The account username (email if migrated).
* @param {string} password The account password.
* @returns {Promise.<Object>} Promise which resolves the resolved authenticated account object.
*/
exports.addMojangAccount = async function(username, password) {
try {
const response = await MojangRestAPI.authenticate(username, password, ConfigManager.getClientToken())
console.log(response)
if(response.responseStatus === RestResponseStatus.SUCCESS) {
const session = response.data
if(session.selectedProfile != null){
const ret = ConfigManager.addMojangAuthAccount(session.selectedProfile.id, session.accessToken, username, session.selectedProfile.name)
if(ConfigManager.getClientToken() == null){
ConfigManager.setClientToken(session.clientToken)
}
ConfigManager.save()
return ret
} else {
return Promise.reject(mojangErrorDisplayable(MojangErrorCode.ERROR_NOT_PAID))
}
} else {
return Promise.reject(mojangErrorDisplayable(response.mojangErrorCode))
}
} catch (err){
log.error(err)
return Promise.reject(mojangErrorDisplayable(MojangErrorCode.UNKNOWN))
}
}
const AUTH_MODE = { FULL: 0, MS_REFRESH: 1, MC_REFRESH: 2 }
/**
* Perform the full MS Auth flow in a given mode.
*
* AUTH_MODE.FULL = Full authorization for a new account.
* AUTH_MODE.MS_REFRESH = Full refresh authorization.
* AUTH_MODE.MC_REFRESH = Refresh of the MC token, reusing the MS token.
*
* @param {string} entryCode FULL-AuthCode. MS_REFRESH=refreshToken, MC_REFRESH=accessToken
* @param {*} authMode The auth mode.
* @returns An object with all auth data. AccessToken object will be null when mode is MC_REFRESH.
*/
async function fullMicrosoftAuthFlow(entryCode, authMode) {
try {
let accessTokenRaw
let accessToken
if(authMode !== AUTH_MODE.MC_REFRESH) {
const accessTokenResponse = await MicrosoftAuth.getAccessToken(entryCode, authMode === AUTH_MODE.MS_REFRESH, AZURE_CLIENT_ID)
if(accessTokenResponse.responseStatus === RestResponseStatus.ERROR) {
return Promise.reject(microsoftErrorDisplayable(accessTokenResponse.microsoftErrorCode))
}
accessToken = accessTokenResponse.data
accessTokenRaw = accessToken.access_token
} else {
accessTokenRaw = entryCode
}
const xblResponse = await MicrosoftAuth.getXBLToken(accessTokenRaw)
if(xblResponse.responseStatus === RestResponseStatus.ERROR) {
return Promise.reject(microsoftErrorDisplayable(xblResponse.microsoftErrorCode))
}
const xstsResonse = await MicrosoftAuth.getXSTSToken(xblResponse.data)
if(xstsResonse.responseStatus === RestResponseStatus.ERROR) {
return Promise.reject(microsoftErrorDisplayable(xstsResonse.microsoftErrorCode))
}
const mcTokenResponse = await MicrosoftAuth.getMCAccessToken(xstsResonse.data)
if(mcTokenResponse.responseStatus === RestResponseStatus.ERROR) {
return Promise.reject(microsoftErrorDisplayable(mcTokenResponse.microsoftErrorCode))
}
const mcProfileResponse = await MicrosoftAuth.getMCProfile(mcTokenResponse.data.access_token)
if(mcProfileResponse.responseStatus === RestResponseStatus.ERROR) {
return Promise.reject(microsoftErrorDisplayable(mcProfileResponse.microsoftErrorCode))
}
return {
accessToken,
accessTokenRaw,
xbl: xblResponse.data,
xsts: xstsResonse.data,
mcToken: mcTokenResponse.data,
mcProfile: mcProfileResponse.data
}
} catch(err) {
log.error(err)
return Promise.reject(microsoftErrorDisplayable(MicrosoftErrorCode.UNKNOWN))
}
}
/**
* Calculate the expiry date. Advance the expiry time by 10 seconds
* to reduce the liklihood of working with an expired token.
*
* @param {number} nowMs Current time milliseconds.
* @param {number} epiresInS Expires in (seconds)
* @returns
*/
function calculateExpiryDate(nowMs, epiresInS) {
return nowMs + ((epiresInS-10)*1000)
}
/**
* Add a Microsoft account. This will pass the provided auth code to Mojang's OAuth2.0 flow.
* The resultant data will be stored as an auth account in the configuration database.
*
* @param {string} authCode The authCode obtained from microsoft.
* @returns {Promise.<Object>} Promise which resolves the resolved authenticated account object.
*/
exports.addMicrosoftAccount = async function(authCode) {
const fullAuth = await fullMicrosoftAuthFlow(authCode, AUTH_MODE.FULL)
// Advance expiry by 10 seconds to avoid close calls.
const now = new Date().getTime()
const ret = ConfigManager.addMicrosoftAuthAccount(
fullAuth.mcProfile.id,
fullAuth.mcToken.access_token,
fullAuth.mcProfile.name,
calculateExpiryDate(now, fullAuth.mcToken.expires_in),
fullAuth.accessToken.access_token,
fullAuth.accessToken.refresh_token,
calculateExpiryDate(now, fullAuth.accessToken.expires_in)
)
ConfigManager.save()
return ret
}
/**
* Remove a Mojang account. This will invalidate the access token associated
* with the account and then remove it from the database.
*
* @param {string} uuid The UUID of the account to be removed.
* @returns {Promise.<void>} Promise which resolves to void when the action is complete.
*/
exports.removeMojangAccount = async function(uuid){
try {
const authAcc = ConfigManager.getAuthAccount(uuid)
const response = await MojangRestAPI.invalidate(authAcc.accessToken, ConfigManager.getClientToken())
if(response.responseStatus === RestResponseStatus.SUCCESS) {
ConfigManager.removeAuthAccount(uuid)
ConfigManager.save()
return Promise.resolve()
} else {
log.error('Error while removing account', response.error)
return Promise.reject(response.error)
}
} catch (err){
log.error('Error while removing account', err)
return Promise.reject(err)
}
}
/**
* Remove a Microsoft account. It is expected that the caller will invoke the OAuth logout
* through the ipc renderer.
*
* @param {string} uuid The UUID of the account to be removed.
* @returns {Promise.<void>} Promise which resolves to void when the action is complete.
*/
exports.removeMicrosoftAccount = async function(uuid){
try {
ConfigManager.removeAuthAccount(uuid)
ConfigManager.save()
return Promise.resolve()
} catch (err){
log.error('Error while removing account', err)
return Promise.reject(err)
}
}
/**
* Validate the selected account with Mojang's authserver. If the account is not valid,
* we will attempt to refresh the access token and update that value. If that fails, a
* new login will be required.
*
* @returns {Promise.<boolean>} Promise which resolves to true if the access token is valid,
* otherwise false.
*/
async function validateSelectedMojangAccount(){
const current = ConfigManager.getSelectedAccount()
const response = await MojangRestAPI.validate(current.accessToken, ConfigManager.getClientToken())
if(response.responseStatus === RestResponseStatus.SUCCESS) {
const isValid = response.data
if(!isValid){
const refreshResponse = await MojangRestAPI.refresh(current.accessToken, ConfigManager.getClientToken())
if(refreshResponse.responseStatus === RestResponseStatus.SUCCESS) {
const session = refreshResponse.data
ConfigManager.updateMojangAuthAccount(current.uuid, session.accessToken)
ConfigManager.save()
} else {
log.error('Error while validating selected profile:', refreshResponse.error)
log.info('Account access token is invalid.')
return false
}
log.info('Account access token validated.')
return true
} else {
log.info('Account access token validated.')
return true
}
}
}
/**
* Validate the selected account with Microsoft's authserver. If the account is not valid,
* we will attempt to refresh the access token and update that value. If that fails, a
* new login will be required.
*
* @returns {Promise.<boolean>} Promise which resolves to true if the access token is valid,
* otherwise false.
*/
async function validateSelectedMicrosoftAccount(){
const current = ConfigManager.getSelectedAccount()
const now = new Date().getTime()
const mcExpiresAt = current.expiresAt
const mcExpired = now >= mcExpiresAt
if(!mcExpired) {
return true
}
// MC token expired. Check MS token.
const msExpiresAt = current.microsoft.expires_at
const msExpired = now >= msExpiresAt
if(msExpired) {
// MS expired, do full refresh.
try {
const res = await fullMicrosoftAuthFlow(current.microsoft.refresh_token, AUTH_MODE.MS_REFRESH)
ConfigManager.updateMicrosoftAuthAccount(
current.uuid,
res.mcToken.access_token,
res.accessToken.access_token,
res.accessToken.refresh_token,
calculateExpiryDate(now, res.accessToken.expires_in),
calculateExpiryDate(now, res.mcToken.expires_in)
)
ConfigManager.save()
return true
} catch(err) {
return false
}
} else {
// Only MC expired, use existing MS token.
try {
const res = await fullMicrosoftAuthFlow(current.microsoft.access_token, AUTH_MODE.MC_REFRESH)
ConfigManager.updateMicrosoftAuthAccount(
current.uuid,
res.mcToken.access_token,
current.microsoft.access_token,
current.microsoft.refresh_token,
current.microsoft.expires_at,
calculateExpiryDate(now, res.mcToken.expires_in)
)
ConfigManager.save()
return true
}
catch(err) {
return false
}
}
}
/**
* Validate the selected auth account.
*
* @returns {Promise.<boolean>} Promise which resolves to true if the access token is valid,
* otherwise false.
*/
exports.validateSelected = async function(){
const current = ConfigManager.getSelectedAccount()
if(current.type === 'microsoft') {
return await validateSelectedMicrosoftAccount()
} else {
return await validateSelectedMojangAccount()
}
}

View File

@ -1,793 +0,0 @@
const fs = require('fs-extra')
const { LoggerUtil } = require('helios-core')
const os = require('os')
const path = require('path')
const logger = LoggerUtil.getLogger('ConfigManager')
const sysRoot = process.env.APPDATA || (process.platform == 'darwin' ? process.env.HOME + '/Library/Application Support' : process.env.HOME)
const dataPath = path.join(sysRoot, '.helioslauncher')
const launcherDir = require('@electron/remote').app.getPath('userData')
/**
* Retrieve the absolute path of the launcher directory.
*
* @returns {string} The absolute path of the launcher directory.
*/
exports.getLauncherDirectory = function(){
return launcherDir
}
/**
* Get the launcher's data directory. This is where all files related
* to game launch are installed (common, instances, java, etc).
*
* @returns {string} The absolute path of the launcher's data directory.
*/
exports.getDataDirectory = function(def = false){
return !def ? config.settings.launcher.dataDirectory : DEFAULT_CONFIG.settings.launcher.dataDirectory
}
/**
* Set the new data directory.
*
* @param {string} dataDirectory The new data directory.
*/
exports.setDataDirectory = function(dataDirectory){
config.settings.launcher.dataDirectory = dataDirectory
}
const configPath = path.join(exports.getLauncherDirectory(), 'config.json')
const configPathLEGACY = path.join(dataPath, 'config.json')
const firstLaunch = !fs.existsSync(configPath) && !fs.existsSync(configPathLEGACY)
exports.getAbsoluteMinRAM = function(ram){
if(ram?.minimum != null) {
return ram.minimum/1024
} else {
// Legacy behavior
const mem = os.totalmem()
return mem >= (6*1073741824) ? 3 : 2
}
}
exports.getAbsoluteMaxRAM = function(ram){
const mem = os.totalmem()
const gT16 = mem-(16*1073741824)
return Math.floor((mem-(gT16 > 0 ? (Number.parseInt(gT16/8) + (16*1073741824)/4) : mem/4))/1073741824)
}
function resolveSelectedRAM(ram) {
if(ram?.recommended != null) {
return `${ram.recommended}M`
} else {
// Legacy behavior
const mem = os.totalmem()
return mem >= (8*1073741824) ? '4G' : (mem >= (6*1073741824) ? '3G' : '2G')
}
}
/**
* Three types of values:
* Static = Explicitly declared.
* Dynamic = Calculated by a private function.
* Resolved = Resolved externally, defaults to null.
*/
const DEFAULT_CONFIG = {
settings: {
game: {
resWidth: 1280,
resHeight: 720,
fullscreen: false,
autoConnect: true,
launchDetached: true
},
launcher: {
allowPrerelease: false,
dataDirectory: dataPath
}
},
newsCache: {
date: null,
content: null,
dismissed: false
},
clientToken: null,
selectedServer: null, // Resolved
selectedAccount: null,
authenticationDatabase: {},
modConfigurations: [],
javaConfig: {}
}
let config = null
// Persistance Utility Functions
/**
* Save the current configuration to a file.
*/
exports.save = function(){
fs.writeFileSync(configPath, JSON.stringify(config, null, 4), 'UTF-8')
}
/**
* Load the configuration into memory. If a configuration file exists,
* that will be read and saved. Otherwise, a default configuration will
* be generated. Note that "resolved" values default to null and will
* need to be externally assigned.
*/
exports.load = function(){
let doLoad = true
if(!fs.existsSync(configPath)){
// Create all parent directories.
fs.ensureDirSync(path.join(configPath, '..'))
if(fs.existsSync(configPathLEGACY)){
fs.moveSync(configPathLEGACY, configPath)
} else {
doLoad = false
config = DEFAULT_CONFIG
exports.save()
}
}
if(doLoad){
let doValidate = false
try {
config = JSON.parse(fs.readFileSync(configPath, 'UTF-8'))
doValidate = true
} catch (err){
logger.error(err)
logger.info('Configuration file contains malformed JSON or is corrupt.')
logger.info('Generating a new configuration file.')
fs.ensureDirSync(path.join(configPath, '..'))
config = DEFAULT_CONFIG
exports.save()
}
if(doValidate){
config = validateKeySet(DEFAULT_CONFIG, config)
exports.save()
}
}
logger.info('Successfully Loaded')
}
/**
* @returns {boolean} Whether or not the manager has been loaded.
*/
exports.isLoaded = function(){
return config != null
}
/**
* Validate that the destination object has at least every field
* present in the source object. Assign a default value otherwise.
*
* @param {Object} srcObj The source object to reference against.
* @param {Object} destObj The destination object.
* @returns {Object} A validated destination object.
*/
function validateKeySet(srcObj, destObj){
if(srcObj == null){
srcObj = {}
}
const validationBlacklist = ['authenticationDatabase', 'javaConfig']
const keys = Object.keys(srcObj)
for(let i=0; i<keys.length; i++){
if(typeof destObj[keys[i]] === 'undefined'){
destObj[keys[i]] = srcObj[keys[i]]
} else if(typeof srcObj[keys[i]] === 'object' && srcObj[keys[i]] != null && !(srcObj[keys[i]] instanceof Array) && validationBlacklist.indexOf(keys[i]) === -1){
destObj[keys[i]] = validateKeySet(srcObj[keys[i]], destObj[keys[i]])
}
}
return destObj
}
/**
* Check to see if this is the first time the user has launched the
* application. This is determined by the existance of the data path.
*
* @returns {boolean} True if this is the first launch, otherwise false.
*/
exports.isFirstLaunch = function(){
return firstLaunch
}
/**
* Returns the name of the folder in the OS temp directory which we
* will use to extract and store native dependencies for game launch.
*
* @returns {string} The name of the folder.
*/
exports.getTempNativeFolder = function(){
return 'WCNatives'
}
// System Settings (Unconfigurable on UI)
/**
* Retrieve the news cache to determine
* whether or not there is newer news.
*
* @returns {Object} The news cache object.
*/
exports.getNewsCache = function(){
return config.newsCache
}
/**
* Set the new news cache object.
*
* @param {Object} newsCache The new news cache object.
*/
exports.setNewsCache = function(newsCache){
config.newsCache = newsCache
}
/**
* Set whether or not the news has been dismissed (checked)
*
* @param {boolean} dismissed Whether or not the news has been dismissed (checked).
*/
exports.setNewsCacheDismissed = function(dismissed){
config.newsCache.dismissed = dismissed
}
/**
* Retrieve the common directory for shared
* game files (assets, libraries, etc).
*
* @returns {string} The launcher's common directory.
*/
exports.getCommonDirectory = function(){
return path.join(exports.getDataDirectory(), 'common')
}
/**
* Retrieve the instance directory for the per
* server game directories.
*
* @returns {string} The launcher's instance directory.
*/
exports.getInstanceDirectory = function(){
return path.join(exports.getDataDirectory(), 'instances')
}
/**
* Retrieve the launcher's Client Token.
* There is no default client token.
*
* @returns {string} The launcher's Client Token.
*/
exports.getClientToken = function(){
return config.clientToken
}
/**
* Set the launcher's Client Token.
*
* @param {string} clientToken The launcher's new Client Token.
*/
exports.setClientToken = function(clientToken){
config.clientToken = clientToken
}
/**
* Retrieve the ID of the selected serverpack.
*
* @param {boolean} def Optional. If true, the default value will be returned.
* @returns {string} The ID of the selected serverpack.
*/
exports.getSelectedServer = function(def = false){
return !def ? config.selectedServer : DEFAULT_CONFIG.clientToken
}
/**
* Set the ID of the selected serverpack.
*
* @param {string} serverID The ID of the new selected serverpack.
*/
exports.setSelectedServer = function(serverID){
config.selectedServer = serverID
}
/**
* Get an array of each account currently authenticated by the launcher.
*
* @returns {Array.<Object>} An array of each stored authenticated account.
*/
exports.getAuthAccounts = function(){
return config.authenticationDatabase
}
/**
* Returns the authenticated account with the given uuid. Value may
* be null.
*
* @param {string} uuid The uuid of the authenticated account.
* @returns {Object} The authenticated account with the given uuid.
*/
exports.getAuthAccount = function(uuid){
return config.authenticationDatabase[uuid]
}
/**
* Update the access token of an authenticated mojang account.
*
* @param {string} uuid The uuid of the authenticated account.
* @param {string} accessToken The new Access Token.
*
* @returns {Object} The authenticated account object created by this action.
*/
exports.updateMojangAuthAccount = function(uuid, accessToken){
config.authenticationDatabase[uuid].accessToken = accessToken
config.authenticationDatabase[uuid].type = 'mojang' // For gradual conversion.
return config.authenticationDatabase[uuid]
}
/**
* Adds an authenticated mojang account to the database to be stored.
*
* @param {string} uuid The uuid of the authenticated account.
* @param {string} accessToken The accessToken of the authenticated account.
* @param {string} username The username (usually email) of the authenticated account.
* @param {string} displayName The in game name of the authenticated account.
*
* @returns {Object} The authenticated account object created by this action.
*/
exports.addMojangAuthAccount = function(uuid, accessToken, username, displayName){
config.selectedAccount = uuid
config.authenticationDatabase[uuid] = {
type: 'mojang',
accessToken,
username: username.trim(),
uuid: uuid.trim(),
displayName: displayName.trim()
}
return config.authenticationDatabase[uuid]
}
/**
* Update the tokens of an authenticated microsoft account.
*
* @param {string} uuid The uuid of the authenticated account.
* @param {string} accessToken The new Access Token.
* @param {string} msAccessToken The new Microsoft Access Token
* @param {string} msRefreshToken The new Microsoft Refresh Token
* @param {date} msExpires The date when the microsoft access token expires
* @param {date} mcExpires The date when the mojang access token expires
*
* @returns {Object} The authenticated account object created by this action.
*/
exports.updateMicrosoftAuthAccount = function(uuid, accessToken, msAccessToken, msRefreshToken, msExpires, mcExpires) {
config.authenticationDatabase[uuid].accessToken = accessToken
config.authenticationDatabase[uuid].expiresAt = mcExpires
config.authenticationDatabase[uuid].microsoft.access_token = msAccessToken
config.authenticationDatabase[uuid].microsoft.refresh_token = msRefreshToken
config.authenticationDatabase[uuid].microsoft.expires_at = msExpires
return config.authenticationDatabase[uuid]
}
/**
* Adds an authenticated microsoft account to the database to be stored.
*
* @param {string} uuid The uuid of the authenticated account.
* @param {string} accessToken The accessToken of the authenticated account.
* @param {string} name The in game name of the authenticated account.
* @param {date} mcExpires The date when the mojang access token expires
* @param {string} msAccessToken The microsoft access token
* @param {string} msRefreshToken The microsoft refresh token
* @param {date} msExpires The date when the microsoft access token expires
*
* @returns {Object} The authenticated account object created by this action.
*/
exports.addMicrosoftAuthAccount = function(uuid, accessToken, name, mcExpires, msAccessToken, msRefreshToken, msExpires) {
config.selectedAccount = uuid
config.authenticationDatabase[uuid] = {
type: 'microsoft',
accessToken,
username: name.trim(),
uuid: uuid.trim(),
displayName: name.trim(),
expiresAt: mcExpires,
microsoft: {
access_token: msAccessToken,
refresh_token: msRefreshToken,
expires_at: msExpires
}
}
return config.authenticationDatabase[uuid]
}
/**
* Remove an authenticated account from the database. If the account
* was also the selected account, a new one will be selected. If there
* are no accounts, the selected account will be null.
*
* @param {string} uuid The uuid of the authenticated account.
*
* @returns {boolean} True if the account was removed, false if it never existed.
*/
exports.removeAuthAccount = function(uuid){
if(config.authenticationDatabase[uuid] != null){
delete config.authenticationDatabase[uuid]
if(config.selectedAccount === uuid){
const keys = Object.keys(config.authenticationDatabase)
if(keys.length > 0){
config.selectedAccount = keys[0]
} else {
config.selectedAccount = null
config.clientToken = null
}
}
return true
}
return false
}
/**
* Get the currently selected authenticated account.
*
* @returns {Object} The selected authenticated account.
*/
exports.getSelectedAccount = function(){
return config.authenticationDatabase[config.selectedAccount]
}
/**
* Set the selected authenticated account.
*
* @param {string} uuid The UUID of the account which is to be set
* as the selected account.
*
* @returns {Object} The selected authenticated account.
*/
exports.setSelectedAccount = function(uuid){
const authAcc = config.authenticationDatabase[uuid]
if(authAcc != null) {
config.selectedAccount = uuid
}
return authAcc
}
/**
* Get an array of each mod configuration currently stored.
*
* @returns {Array.<Object>} An array of each stored mod configuration.
*/
exports.getModConfigurations = function(){
return config.modConfigurations
}
/**
* Set the array of stored mod configurations.
*
* @param {Array.<Object>} configurations An array of mod configurations.
*/
exports.setModConfigurations = function(configurations){
config.modConfigurations = configurations
}
/**
* Get the mod configuration for a specific server.
*
* @param {string} serverid The id of the server.
* @returns {Object} The mod configuration for the given server.
*/
exports.getModConfiguration = function(serverid){
const cfgs = config.modConfigurations
for(let i=0; i<cfgs.length; i++){
if(cfgs[i].id === serverid){
return cfgs[i]
}
}
return null
}
/**
* Set the mod configuration for a specific server. This overrides any existing value.
*
* @param {string} serverid The id of the server for the given mod configuration.
* @param {Object} configuration The mod configuration for the given server.
*/
exports.setModConfiguration = function(serverid, configuration){
const cfgs = config.modConfigurations
for(let i=0; i<cfgs.length; i++){
if(cfgs[i].id === serverid){
cfgs[i] = configuration
return
}
}
cfgs.push(configuration)
}
// User Configurable Settings
// Java Settings
function defaultJavaConfig(effectiveJavaOptions, ram) {
if(effectiveJavaOptions.suggestedMajor > 8) {
return defaultJavaConfig17(ram)
} else {
return defaultJavaConfig8(ram)
}
}
function defaultJavaConfig8(ram) {
return {
minRAM: resolveSelectedRAM(ram),
maxRAM: resolveSelectedRAM(ram),
executable: null,
jvmOptions: [
'-XX:+UseConcMarkSweepGC',
'-XX:+CMSIncrementalMode',
'-XX:-UseAdaptiveSizePolicy',
'-Xmn128M'
],
}
}
function defaultJavaConfig17(ram) {
return {
minRAM: resolveSelectedRAM(ram),
maxRAM: resolveSelectedRAM(ram),
executable: null,
jvmOptions: [
'-XX:+UnlockExperimentalVMOptions',
'-XX:+UseG1GC',
'-XX:G1NewSizePercent=20',
'-XX:G1ReservePercent=20',
'-XX:MaxGCPauseMillis=50',
'-XX:G1HeapRegionSize=32M'
],
}
}
/**
* Ensure a java config property is set for the given server.
*
* @param {string} serverid The server id.
* @param {*} mcVersion The minecraft version of the server.
*/
exports.ensureJavaConfig = function(serverid, effectiveJavaOptions, ram) {
if(!Object.prototype.hasOwnProperty.call(config.javaConfig, serverid)) {
config.javaConfig[serverid] = defaultJavaConfig(effectiveJavaOptions, ram)
}
}
/**
* Retrieve the minimum amount of memory for JVM initialization. This value
* contains the units of memory. For example, '5G' = 5 GigaBytes, '1024M' =
* 1024 MegaBytes, etc.
*
* @param {string} serverid The server id.
* @returns {string} The minimum amount of memory for JVM initialization.
*/
exports.getMinRAM = function(serverid){
return config.javaConfig[serverid].minRAM
}
/**
* Set the minimum amount of memory for JVM initialization. This value should
* contain the units of memory. For example, '5G' = 5 GigaBytes, '1024M' =
* 1024 MegaBytes, etc.
*
* @param {string} serverid The server id.
* @param {string} minRAM The new minimum amount of memory for JVM initialization.
*/
exports.setMinRAM = function(serverid, minRAM){
config.javaConfig[serverid].minRAM = minRAM
}
/**
* Retrieve the maximum amount of memory for JVM initialization. This value
* contains the units of memory. For example, '5G' = 5 GigaBytes, '1024M' =
* 1024 MegaBytes, etc.
*
* @param {string} serverid The server id.
* @returns {string} The maximum amount of memory for JVM initialization.
*/
exports.getMaxRAM = function(serverid){
return config.javaConfig[serverid].maxRAM
}
/**
* Set the maximum amount of memory for JVM initialization. This value should
* contain the units of memory. For example, '5G' = 5 GigaBytes, '1024M' =
* 1024 MegaBytes, etc.
*
* @param {string} serverid The server id.
* @param {string} maxRAM The new maximum amount of memory for JVM initialization.
*/
exports.setMaxRAM = function(serverid, maxRAM){
config.javaConfig[serverid].maxRAM = maxRAM
}
/**
* Retrieve the path of the Java Executable.
*
* This is a resolved configuration value and defaults to null until externally assigned.
*
* @param {string} serverid The server id.
* @returns {string} The path of the Java Executable.
*/
exports.getJavaExecutable = function(serverid){
return config.javaConfig[serverid].executable
}
/**
* Set the path of the Java Executable.
*
* @param {string} serverid The server id.
* @param {string} executable The new path of the Java Executable.
*/
exports.setJavaExecutable = function(serverid, executable){
config.javaConfig[serverid].executable = executable
}
/**
* Retrieve the additional arguments for JVM initialization. Required arguments,
* such as memory allocation, will be dynamically resolved and will not be included
* in this value.
*
* @param {string} serverid The server id.
* @returns {Array.<string>} An array of the additional arguments for JVM initialization.
*/
exports.getJVMOptions = function(serverid){
return config.javaConfig[serverid].jvmOptions
}
/**
* Set the additional arguments for JVM initialization. Required arguments,
* such as memory allocation, will be dynamically resolved and should not be
* included in this value.
*
* @param {string} serverid The server id.
* @param {Array.<string>} jvmOptions An array of the new additional arguments for JVM
* initialization.
*/
exports.setJVMOptions = function(serverid, jvmOptions){
config.javaConfig[serverid].jvmOptions = jvmOptions
}
// Game Settings
/**
* Retrieve the width of the game window.
*
* @param {boolean} def Optional. If true, the default value will be returned.
* @returns {number} The width of the game window.
*/
exports.getGameWidth = function(def = false){
return !def ? config.settings.game.resWidth : DEFAULT_CONFIG.settings.game.resWidth
}
/**
* Set the width of the game window.
*
* @param {number} resWidth The new width of the game window.
*/
exports.setGameWidth = function(resWidth){
config.settings.game.resWidth = Number.parseInt(resWidth)
}
/**
* Validate a potential new width value.
*
* @param {number} resWidth The width value to validate.
* @returns {boolean} Whether or not the value is valid.
*/
exports.validateGameWidth = function(resWidth){
const nVal = Number.parseInt(resWidth)
return Number.isInteger(nVal) && nVal >= 0
}
/**
* Retrieve the height of the game window.
*
* @param {boolean} def Optional. If true, the default value will be returned.
* @returns {number} The height of the game window.
*/
exports.getGameHeight = function(def = false){
return !def ? config.settings.game.resHeight : DEFAULT_CONFIG.settings.game.resHeight
}
/**
* Set the height of the game window.
*
* @param {number} resHeight The new height of the game window.
*/
exports.setGameHeight = function(resHeight){
config.settings.game.resHeight = Number.parseInt(resHeight)
}
/**
* Validate a potential new height value.
*
* @param {number} resHeight The height value to validate.
* @returns {boolean} Whether or not the value is valid.
*/
exports.validateGameHeight = function(resHeight){
const nVal = Number.parseInt(resHeight)
return Number.isInteger(nVal) && nVal >= 0
}
/**
* Check if the game should be launched in fullscreen mode.
*
* @param {boolean} def Optional. If true, the default value will be returned.
* @returns {boolean} Whether or not the game is set to launch in fullscreen mode.
*/
exports.getFullscreen = function(def = false){
return !def ? config.settings.game.fullscreen : DEFAULT_CONFIG.settings.game.fullscreen
}
/**
* Change the status of if the game should be launched in fullscreen mode.
*
* @param {boolean} fullscreen Whether or not the game should launch in fullscreen mode.
*/
exports.setFullscreen = function(fullscreen){
config.settings.game.fullscreen = fullscreen
}
/**
* Check if the game should auto connect to servers.
*
* @param {boolean} def Optional. If true, the default value will be returned.
* @returns {boolean} Whether or not the game should auto connect to servers.
*/
exports.getAutoConnect = function(def = false){
return !def ? config.settings.game.autoConnect : DEFAULT_CONFIG.settings.game.autoConnect
}
/**
* Change the status of whether or not the game should auto connect to servers.
*
* @param {boolean} autoConnect Whether or not the game should auto connect to servers.
*/
exports.setAutoConnect = function(autoConnect){
config.settings.game.autoConnect = autoConnect
}
/**
* Check if the game should launch as a detached process.
*
* @param {boolean} def Optional. If true, the default value will be returned.
* @returns {boolean} Whether or not the game will launch as a detached process.
*/
exports.getLaunchDetached = function(def = false){
return !def ? config.settings.game.launchDetached : DEFAULT_CONFIG.settings.game.launchDetached
}
/**
* Change the status of whether or not the game should launch as a detached process.
*
* @param {boolean} launchDetached Whether or not the game should launch as a detached process.
*/
exports.setLaunchDetached = function(launchDetached){
config.settings.game.launchDetached = launchDetached
}
// Launcher Settings
/**
* Check if the launcher should download prerelease versions.
*
* @param {boolean} def Optional. If true, the default value will be returned.
* @returns {boolean} Whether or not the launcher should download prerelease versions.
*/
exports.getAllowPrerelease = function(def = false){
return !def ? config.settings.launcher.allowPrerelease : DEFAULT_CONFIG.settings.launcher.allowPrerelease
}
/**
* Change the status of Whether or not the launcher should download prerelease versions.
*
* @param {boolean} launchDetached Whether or not the launcher should download prerelease versions.
*/
exports.setAllowPrerelease = function(allowPrerelease){
config.settings.launcher.allowPrerelease = allowPrerelease
}

View File

@ -1,52 +0,0 @@
// Work in progress
const { LoggerUtil } = require('helios-core')
const logger = LoggerUtil.getLogger('DiscordWrapper')
const { Client } = require('discord-rpc-patch')
const Lang = require('./langloader')
let client
let activity
exports.initRPC = function(genSettings, servSettings, initialDetails = Lang.queryJS('discord.waiting')){
client = new Client({ transport: 'ipc' })
activity = {
details: initialDetails,
state: Lang.queryJS('discord.state', {shortId: servSettings.shortId}),
largeImageKey: servSettings.largeImageKey,
largeImageText: servSettings.largeImageText,
smallImageKey: genSettings.smallImageKey,
smallImageText: genSettings.smallImageText,
startTimestamp: new Date().getTime(),
instance: false
}
client.on('ready', () => {
logger.info('Discord RPC Connected')
client.setActivity(activity)
})
client.login({clientId: genSettings.clientId}).catch(error => {
if(error.message.includes('ENOENT')) {
logger.info('Unable to initialize Discord Rich Presence, no client detected.')
} else {
logger.info('Unable to initialize Discord Rich Presence: ' + error.message, error)
}
})
}
exports.updateDetails = function(details){
activity.details = details
client.setActivity(activity)
}
exports.shutdownRPC = function(){
if(!client) return
client.clearActivity()
client.destroy()
client = null
activity = null
}

View File

@ -1,17 +0,0 @@
const { DistributionAPI } = require('helios-core/common')
const ConfigManager = require('./configmanager')
// Old WesterosCraft url.
// exports.REMOTE_DISTRO_URL = 'http://mc.westeroscraft.com/WesterosCraftLauncher/distribution.json'
exports.REMOTE_DISTRO_URL = 'https://helios-files.geekcorner.eu.org/distribution.json'
const api = new DistributionAPI(
ConfigManager.getLauncherDirectory(),
null, // Injected forcefully by the preloader.
null, // Injected forcefully by the preloader.
exports.REMOTE_DISTRO_URL,
false
)
exports.DistroAPI = api

View File

@ -1,238 +0,0 @@
const fs = require('fs-extra')
const path = require('path')
const { ipcRenderer, shell } = require('electron')
const { SHELL_OPCODE } = require('./ipcconstants')
// Group #1: File Name (without .disabled, if any)
// Group #2: File Extension (jar, zip, or litemod)
// Group #3: If it is disabled (if string 'disabled' is present)
const MOD_REGEX = /^(.+(jar|zip|litemod))(?:\.(disabled))?$/
const DISABLED_EXT = '.disabled'
const SHADER_REGEX = /^(.+)\.zip$/
const SHADER_OPTION = /shaderPack=(.+)/
const SHADER_DIR = 'shaderpacks'
const SHADER_CONFIG = 'optionsshaders.txt'
/**
* Validate that the given directory exists. If not, it is
* created.
*
* @param {string} modsDir The path to the mods directory.
*/
exports.validateDir = function(dir) {
fs.ensureDirSync(dir)
}
/**
* Scan for drop-in mods in both the mods folder and version
* safe mods folder.
*
* @param {string} modsDir The path to the mods directory.
* @param {string} version The minecraft version of the server configuration.
*
* @returns {{fullName: string, name: string, ext: string, disabled: boolean}[]}
* An array of objects storing metadata about each discovered mod.
*/
exports.scanForDropinMods = function(modsDir, version) {
const modsDiscovered = []
if(fs.existsSync(modsDir)){
let modCandidates = fs.readdirSync(modsDir)
let verCandidates = []
const versionDir = path.join(modsDir, version)
if(fs.existsSync(versionDir)){
verCandidates = fs.readdirSync(versionDir)
}
for(let file of modCandidates){
const match = MOD_REGEX.exec(file)
if(match != null){
modsDiscovered.push({
fullName: match[0],
name: match[1],
ext: match[2],
disabled: match[3] != null
})
}
}
for(let file of verCandidates){
const match = MOD_REGEX.exec(file)
if(match != null){
modsDiscovered.push({
fullName: path.join(version, match[0]),
name: match[1],
ext: match[2],
disabled: match[3] != null
})
}
}
}
return modsDiscovered
}
/**
* Add dropin mods.
*
* @param {FileList} files The files to add.
* @param {string} modsDir The path to the mods directory.
*/
exports.addDropinMods = function(files, modsdir) {
exports.validateDir(modsdir)
for(let f of files) {
if(MOD_REGEX.exec(f.name) != null) {
fs.moveSync(f.path, path.join(modsdir, f.name))
}
}
}
/**
* Delete a drop-in mod from the file system.
*
* @param {string} modsDir The path to the mods directory.
* @param {string} fullName The fullName of the discovered mod to delete.
*
* @returns {Promise.<boolean>} True if the mod was deleted, otherwise false.
*/
exports.deleteDropinMod = async function(modsDir, fullName){
const res = await ipcRenderer.invoke(SHELL_OPCODE.TRASH_ITEM, path.join(modsDir, fullName))
if(!res.result) {
shell.beep()
console.error('Error deleting drop-in mod.', res.error)
return false
}
return true
}
/**
* Toggle a discovered mod on or off. This is achieved by either
* adding or disabling the .disabled extension to the local file.
*
* @param {string} modsDir The path to the mods directory.
* @param {string} fullName The fullName of the discovered mod to toggle.
* @param {boolean} enable Whether to toggle on or off the mod.
*
* @returns {Promise.<void>} A promise which resolves when the mod has
* been toggled. If an IO error occurs the promise will be rejected.
*/
exports.toggleDropinMod = function(modsDir, fullName, enable){
return new Promise((resolve, reject) => {
const oldPath = path.join(modsDir, fullName)
const newPath = path.join(modsDir, enable ? fullName.substring(0, fullName.indexOf(DISABLED_EXT)) : fullName + DISABLED_EXT)
fs.rename(oldPath, newPath, (err) => {
if(err){
reject(err)
} else {
resolve()
}
})
})
}
/**
* Check if a drop-in mod is enabled.
*
* @param {string} fullName The fullName of the discovered mod to toggle.
* @returns {boolean} True if the mod is enabled, otherwise false.
*/
exports.isDropinModEnabled = function(fullName){
return !fullName.endsWith(DISABLED_EXT)
}
/**
* Scan for shaderpacks inside the shaderpacks folder.
*
* @param {string} instanceDir The path to the server instance directory.
*
* @returns {{fullName: string, name: string}[]}
* An array of objects storing metadata about each discovered shaderpack.
*/
exports.scanForShaderpacks = function(instanceDir){
const shaderDir = path.join(instanceDir, SHADER_DIR)
const packsDiscovered = [{
fullName: 'OFF',
name: 'Off (Default)'
}]
if(fs.existsSync(shaderDir)){
let modCandidates = fs.readdirSync(shaderDir)
for(let file of modCandidates){
const match = SHADER_REGEX.exec(file)
if(match != null){
packsDiscovered.push({
fullName: match[0],
name: match[1]
})
}
}
}
return packsDiscovered
}
/**
* Read the optionsshaders.txt file to locate the current
* enabled pack. If the file does not exist, OFF is returned.
*
* @param {string} instanceDir The path to the server instance directory.
*
* @returns {string} The file name of the enabled shaderpack.
*/
exports.getEnabledShaderpack = function(instanceDir){
exports.validateDir(instanceDir)
const optionsShaders = path.join(instanceDir, SHADER_CONFIG)
if(fs.existsSync(optionsShaders)){
const buf = fs.readFileSync(optionsShaders, {encoding: 'utf-8'})
const match = SHADER_OPTION.exec(buf)
if(match != null){
return match[1]
} else {
console.warn('WARNING: Shaderpack regex failed.')
}
}
return 'OFF'
}
/**
* Set the enabled shaderpack.
*
* @param {string} instanceDir The path to the server instance directory.
* @param {string} pack the file name of the shaderpack.
*/
exports.setEnabledShaderpack = function(instanceDir, pack){
exports.validateDir(instanceDir)
const optionsShaders = path.join(instanceDir, SHADER_CONFIG)
let buf
if(fs.existsSync(optionsShaders)){
buf = fs.readFileSync(optionsShaders, {encoding: 'utf-8'})
buf = buf.replace(SHADER_OPTION, `shaderPack=${pack}`)
} else {
buf = `shaderPack=${pack}`
}
fs.writeFileSync(optionsShaders, buf, {encoding: 'utf-8'})
}
/**
* Add shaderpacks.
*
* @param {FileList} files The files to add.
* @param {string} instanceDir The path to the server instance directory.
*/
exports.addShaderpacks = function(files, instanceDir) {
const p = path.join(instanceDir, SHADER_DIR)
exports.validateDir(p)
for(let f of files) {
if(SHADER_REGEX.exec(f.name) != null) {
fs.moveSync(f.path, path.join(p, f.name))
}
}
}

View File

@ -1,28 +0,0 @@
// NOTE FOR THIRD-PARTY
// REPLACE THIS CLIENT ID WITH YOUR APPLICATION ID.
// SEE https://github.com/dscalzi/HeliosLauncher/blob/master/docs/MicrosoftAuth.md
exports.AZURE_CLIENT_ID = '1ce6e35a-126f-48fd-97fb-54d143ac6d45'
// SEE NOTE ABOVE.
// Opcodes
exports.MSFT_OPCODE = {
OPEN_LOGIN: 'MSFT_AUTH_OPEN_LOGIN',
OPEN_LOGOUT: 'MSFT_AUTH_OPEN_LOGOUT',
REPLY_LOGIN: 'MSFT_AUTH_REPLY_LOGIN',
REPLY_LOGOUT: 'MSFT_AUTH_REPLY_LOGOUT'
}
// Reply types for REPLY opcode.
exports.MSFT_REPLY_TYPE = {
SUCCESS: 'MSFT_AUTH_REPLY_SUCCESS',
ERROR: 'MSFT_AUTH_REPLY_ERROR'
}
// Error types for ERROR reply.
exports.MSFT_ERROR = {
ALREADY_OPEN: 'MSFT_AUTH_ERR_ALREADY_OPEN',
NOT_FINISHED: 'MSFT_AUTH_ERR_NOT_FINISHED'
}
exports.SHELL_OPCODE = {
TRASH_ITEM: 'TRASH_ITEM'
}

View File

@ -1,5 +0,0 @@
'use strict'
const getFromEnv = parseInt(process.env.ELECTRON_IS_DEV, 10) === 1
const isEnvSet = 'ELECTRON_IS_DEV' in process.env
module.exports = isEnvSet ? getFromEnv : (process.defaultApp || /node_modules[\\/]electron[\\/]/.test(process.execPath))

View File

@ -1,43 +0,0 @@
const fs = require('fs-extra')
const path = require('path')
const toml = require('toml')
const merge = require('lodash.merge')
let lang
exports.loadLanguage = function(id){
lang = merge(lang || {}, toml.parse(fs.readFileSync(path.join(__dirname, '..', 'lang', `${id}.toml`))) || {})
}
exports.query = function(id, placeHolders){
let query = id.split('.')
let res = lang
for(let q of query){
res = res[q]
}
let text = res === lang ? '' : res
if (placeHolders) {
Object.entries(placeHolders).forEach(([key, value]) => {
text = text.replace(`{${key}}`, value)
})
}
return text
}
exports.queryJS = function(id, placeHolders){
return exports.query(`js.${id}`, placeHolders)
}
exports.queryEJS = function(id, placeHolders){
return exports.query(`ejs.${id}`, placeHolders)
}
exports.setupLanguage = function(){
// Load Language Files
exports.loadLanguage('en_US')
// Uncomment this when translations are ready
//exports.loadLanguage('xx_XX')
// Load Custom Language File for Launcher Customizer
exports.loadLanguage('_custom')
}

View File

@ -1,67 +0,0 @@
const {ipcRenderer} = require('electron')
const fs = require('fs-extra')
const os = require('os')
const path = require('path')
const ConfigManager = require('./configmanager')
const { DistroAPI } = require('./distromanager')
const LangLoader = require('./langloader')
const { LoggerUtil } = require('helios-core')
// eslint-disable-next-line no-unused-vars
const { HeliosDistribution } = require('helios-core/common')
const logger = LoggerUtil.getLogger('Preloader')
logger.info('Loading..')
// Load ConfigManager
ConfigManager.load()
// Yuck!
// TODO Fix this
DistroAPI['commonDir'] = ConfigManager.getCommonDirectory()
DistroAPI['instanceDir'] = ConfigManager.getInstanceDirectory()
// Load Strings
LangLoader.setupLanguage()
/**
*
* @param {HeliosDistribution} data
*/
function onDistroLoad(data){
if(data != null){
// Resolve the selected server if its value has yet to be set.
if(ConfigManager.getSelectedServer() == null || data.getServerById(ConfigManager.getSelectedServer()) == null){
logger.info('Determining default selected server..')
ConfigManager.setSelectedServer(data.getMainServer().rawServer.id)
ConfigManager.save()
}
}
ipcRenderer.send('distributionIndexDone', data != null)
}
// Ensure Distribution is downloaded and cached.
DistroAPI.getDistribution()
.then(heliosDistro => {
logger.info('Loaded distribution index.')
onDistroLoad(heliosDistro)
})
.catch(err => {
logger.info('Failed to load an older version of the distribution index.')
logger.info('Application cannot run.')
logger.error(err)
onDistroLoad(null)
})
// Clean up temp dir incase previous launches ended unexpectedly.
fs.remove(path.join(os.tmpdir(), ConfigManager.getTempNativeFolder()), (err) => {
if(err){
logger.warn('Error while cleaning natives directory', err)
} else {
logger.info('Cleaned natives directory.')
}
})

View File

@ -1,894 +0,0 @@
const AdmZip = require('adm-zip')
const child_process = require('child_process')
const crypto = require('crypto')
const fs = require('fs-extra')
const { LoggerUtil } = require('helios-core')
const { getMojangOS, isLibraryCompatible, mcVersionAtLeast } = require('helios-core/common')
const { Type } = require('helios-distribution-types')
const os = require('os')
const path = require('path')
const ConfigManager = require('./configmanager')
const logger = LoggerUtil.getLogger('ProcessBuilder')
/**
* Only forge and fabric are top level mod loaders.
*
* Forge 1.13+ launch logic is similar to fabrics, for now using usingFabricLoader flag to
* change minor details when needed.
*
* Rewrite of this module may be needed in the future.
*/
class ProcessBuilder {
constructor(distroServer, vanillaManifest, modManifest, authUser, launcherVersion){
this.gameDir = path.join(ConfigManager.getInstanceDirectory(), distroServer.rawServer.id)
this.commonDir = ConfigManager.getCommonDirectory()
this.server = distroServer
this.vanillaManifest = vanillaManifest
this.modManifest = modManifest
this.authUser = authUser
this.launcherVersion = launcherVersion
this.forgeModListFile = path.join(this.gameDir, 'forgeMods.list') // 1.13+
this.fmlDir = path.join(this.gameDir, 'forgeModList.json')
this.llDir = path.join(this.gameDir, 'liteloaderModList.json')
this.libPath = path.join(this.commonDir, 'libraries')
this.usingLiteLoader = false
this.usingFabricLoader = false
this.llPath = null
}
/**
* Convienence method to run the functions typically used to build a process.
*/
build(){
fs.ensureDirSync(this.gameDir)
const tempNativePath = path.join(os.tmpdir(), ConfigManager.getTempNativeFolder(), crypto.pseudoRandomBytes(16).toString('hex'))
process.throwDeprecation = true
this.setupLiteLoader()
logger.info('Using liteloader:', this.usingLiteLoader)
this.usingFabricLoader = this.server.modules.some(mdl => mdl.rawModule.type === Type.Fabric)
logger.info('Using fabric loader:', this.usingFabricLoader)
const modObj = this.resolveModConfiguration(ConfigManager.getModConfiguration(this.server.rawServer.id).mods, this.server.modules)
// Mod list below 1.13
// Fabric only supports 1.14+
if(!mcVersionAtLeast('1.13', this.server.rawServer.minecraftVersion)){
this.constructJSONModList('forge', modObj.fMods, true)
if(this.usingLiteLoader){
this.constructJSONModList('liteloader', modObj.lMods, true)
}
}
const uberModArr = modObj.fMods.concat(modObj.lMods)
let args = this.constructJVMArguments(uberModArr, tempNativePath)
if(mcVersionAtLeast('1.13', this.server.rawServer.minecraftVersion)){
//args = args.concat(this.constructModArguments(modObj.fMods))
args = args.concat(this.constructModList(modObj.fMods))
}
logger.info('Launch Arguments:', args)
const child = child_process.spawn(ConfigManager.getJavaExecutable(this.server.rawServer.id), args, {
cwd: this.gameDir,
detached: ConfigManager.getLaunchDetached()
})
if(ConfigManager.getLaunchDetached()){
child.unref()
}
child.stdout.setEncoding('utf8')
child.stderr.setEncoding('utf8')
child.stdout.on('data', (data) => {
data.trim().split('\n').forEach(x => console.log(`\x1b[32m[Minecraft]\x1b[0m ${x}`))
})
child.stderr.on('data', (data) => {
data.trim().split('\n').forEach(x => console.log(`\x1b[31m[Minecraft]\x1b[0m ${x}`))
})
child.on('close', (code, signal) => {
logger.info('Exited with code', code)
fs.remove(tempNativePath, (err) => {
if(err){
logger.warn('Error while deleting temp dir', err)
} else {
logger.info('Temp dir deleted successfully.')
}
})
})
return child
}
/**
* Get the platform specific classpath separator. On windows, this is a semicolon.
* On Unix, this is a colon.
*
* @returns {string} The classpath separator for the current operating system.
*/
static getClasspathSeparator() {
return process.platform === 'win32' ? ';' : ':'
}
/**
* Determine if an optional mod is enabled from its configuration value. If the
* configuration value is null, the required object will be used to
* determine if it is enabled.
*
* A mod is enabled if:
* * The configuration is not null and one of the following:
* * The configuration is a boolean and true.
* * The configuration is an object and its 'value' property is true.
* * The configuration is null and one of the following:
* * The required object is null.
* * The required object's 'def' property is null or true.
*
* @param {Object | boolean} modCfg The mod configuration object.
* @param {Object} required Optional. The required object from the mod's distro declaration.
* @returns {boolean} True if the mod is enabled, false otherwise.
*/
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.def : true
}
/**
* Function which performs a preliminary scan of the top level
* mods. If liteloader is present here, we setup the special liteloader
* launch options. Note that liteloader is only allowed as a top level
* mod. It must not be declared as a submodule.
*/
setupLiteLoader(){
for(let ll of this.server.modules){
if(ll.rawModule.type === Type.LiteLoader){
if(!ll.getRequired().value){
const modCfg = ConfigManager.getModConfiguration(this.server.rawServer.id).mods
if(ProcessBuilder.isModEnabled(modCfg[ll.getVersionlessMavenIdentifier()], ll.getRequired())){
if(fs.existsSync(ll.getPath())){
this.usingLiteLoader = true
this.llPath = ll.getPath()
}
}
} else {
if(fs.existsSync(ll.getPath())){
this.usingLiteLoader = true
this.llPath = ll.getPath()
}
}
}
}
}
/**
* Resolve an array of all enabled mods. These mods will be constructed into
* a mod list format and enabled at launch.
*
* @param {Object} modCfg The mod configuration object.
* @param {Array.<Object>} mdls An array of modules to parse.
* @returns {{fMods: Array.<Object>, lMods: Array.<Object>}} An object which contains
* a list of enabled forge mods and litemods.
*/
resolveModConfiguration(modCfg, mdls){
let fMods = []
let lMods = []
for(let mdl of mdls){
const type = mdl.rawModule.type
if(type === Type.ForgeMod || type === Type.LiteMod || type === Type.LiteLoader || type === Type.FabricMod){
const o = !mdl.getRequired().value
const e = ProcessBuilder.isModEnabled(modCfg[mdl.getVersionlessMavenIdentifier()], mdl.getRequired())
if(!o || (o && e)){
if(mdl.subModules.length > 0){
const v = this.resolveModConfiguration(modCfg[mdl.getVersionlessMavenIdentifier()].mods, mdl.subModules)
fMods = fMods.concat(v.fMods)
lMods = lMods.concat(v.lMods)
if(type === Type.LiteLoader){
continue
}
}
if(type === Type.ForgeMod || type === Type.FabricMod){
fMods.push(mdl)
} else {
lMods.push(mdl)
}
}
}
}
return {
fMods,
lMods
}
}
_lteMinorVersion(version) {
return Number(this.modManifest.id.split('-')[0].split('.')[1]) <= Number(version)
}
/**
* Test to see if this version of forge requires the absolute: prefix
* on the modListFile repository field.
*/
_requiresAbsolute(){
try {
if(this._lteMinorVersion(9)) {
return false
}
const ver = this.modManifest.id.split('-')[2]
const pts = ver.split('.')
const min = [14, 23, 3, 2655]
for(let i=0; i<pts.length; i++){
const parsed = Number.parseInt(pts[i])
if(parsed < min[i]){
return false
} else if(parsed > min[i]){
return true
}
}
} catch (err) {
// We know old forge versions follow this format.
// Error must be caused by newer version.
}
// Equal or errored
return true
}
/**
* Construct a mod list json object.
*
* @param {'forge' | 'liteloader'} type The mod list type to construct.
* @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.
*/
constructJSONModList(type, mods, save = false){
const modList = {
repositoryRoot: ((type === 'forge' && this._requiresAbsolute()) ? 'absolute:' : '') + path.join(this.commonDir, 'modstore')
}
const ids = []
if(type === 'forge'){
for(let mod of mods){
ids.push(mod.getExtensionlessMavenIdentifier())
}
} else {
for(let mod of mods){
ids.push(mod.getMavenIdentifier())
}
}
modList.modRef = ids
if(save){
const json = JSON.stringify(modList, null, 4)
fs.writeFileSync(type === 'forge' ? this.fmlDir : this.llDir, json, 'UTF-8')
}
return modList
}
// /**
// * Construct the mod argument list for forge 1.13
// *
// * @param {Array.<Object>} mods An array of mods to add to the mod list.
// */
// constructModArguments(mods){
// const argStr = mods.map(mod => {
// return mod.getExtensionlessMavenIdentifier()
// }).join(',')
// if(argStr){
// return [
// '--fml.mavenRoots',
// path.join('..', '..', 'common', 'modstore'),
// '--fml.mods',
// argStr
// ]
// } else {
// return []
// }
// }
/**
* Construct the mod argument list for forge 1.13 and Fabric
*
* @param {Array.<Object>} mods An array of mods to add to the mod list.
*/
constructModList(mods) {
const writeBuffer = mods.map(mod => {
return this.usingFabricLoader ? mod.getPath() : mod.getExtensionlessMavenIdentifier()
}).join('\n')
if(writeBuffer) {
fs.writeFileSync(this.forgeModListFile, writeBuffer, 'UTF-8')
return this.usingFabricLoader ? [
'--fabric.addMods',
`@${this.forgeModListFile}`
] : [
'--fml.mavenRoots',
path.join('..', '..', 'common', 'modstore'),
'--fml.modLists',
this.forgeModListFile
]
} else {
return []
}
}
_processAutoConnectArg(args){
if(ConfigManager.getAutoConnect() && this.server.rawServer.autoconnect){
if(mcVersionAtLeast('1.20', this.server.rawServer.minecraftVersion)){
args.push('--quickPlayMultiplayer')
args.push(`${this.server.hostname}:${this.server.port}`)
} else {
args.push('--server')
args.push(this.server.hostname)
args.push('--port')
args.push(this.server.port)
}
}
}
/**
* Construct the argument array that will be passed to the JVM process.
*
* @param {Array.<Object>} mods An array of enabled mods which will be launched with this process.
* @param {string} tempNativePath The path to store the native libraries.
* @returns {Array.<string>} An array containing the full JVM arguments for this process.
*/
constructJVMArguments(mods, tempNativePath){
if(mcVersionAtLeast('1.13', this.server.rawServer.minecraftVersion)){
return this._constructJVMArguments113(mods, tempNativePath)
} else {
return this._constructJVMArguments112(mods, tempNativePath)
}
}
/**
* Construct the argument array that will be passed to the JVM process.
* This function is for 1.12 and below.
*
* @param {Array.<Object>} mods An array of enabled mods which will be launched with this process.
* @param {string} tempNativePath The path to store the native libraries.
* @returns {Array.<string>} An array containing the full JVM arguments for this process.
*/
_constructJVMArguments112(mods, tempNativePath){
let args = []
// Classpath Argument
args.push('-cp')
args.push(this.classpathArg(mods, tempNativePath).join(ProcessBuilder.getClasspathSeparator()))
// Java Arguments
if(process.platform === 'darwin'){
args.push('-Xdock:name=HeliosLauncher')
args.push('-Xdock:icon=' + path.join(__dirname, '..', 'images', 'minecraft.icns'))
}
args.push('-Xmx' + ConfigManager.getMaxRAM(this.server.rawServer.id))
args.push('-Xms' + ConfigManager.getMinRAM(this.server.rawServer.id))
args = args.concat(ConfigManager.getJVMOptions(this.server.rawServer.id))
args.push('-Djava.library.path=' + tempNativePath)
// Main Java Class
args.push(this.modManifest.mainClass)
// Forge Arguments
args = args.concat(this._resolveForgeArgs())
return args
}
/**
* Construct the argument array that will be passed to the JVM process.
* This function is for 1.13+
*
* Note: Required Libs https://github.com/MinecraftForge/MinecraftForge/blob/af98088d04186452cb364280340124dfd4766a5c/src/fmllauncher/java/net/minecraftforge/fml/loading/LibraryFinder.java#L82
*
* @param {Array.<Object>} mods An array of enabled mods which will be launched with this process.
* @param {string} tempNativePath The path to store the native libraries.
* @returns {Array.<string>} An array containing the full JVM arguments for this process.
*/
_constructJVMArguments113(mods, tempNativePath){
const argDiscovery = /\${*(.*)}/
// JVM Arguments First
let args = this.vanillaManifest.arguments.jvm
// Debug securejarhandler
// args.push('-Dbsl.debug=true')
if(this.modManifest.arguments.jvm != null) {
for(const argStr of this.modManifest.arguments.jvm) {
args.push(argStr
.replaceAll('${library_directory}', this.libPath)
.replaceAll('${classpath_separator}', ProcessBuilder.getClasspathSeparator())
.replaceAll('${version_name}', this.modManifest.id)
)
}
}
//args.push('-Dlog4j.configurationFile=D:\\WesterosCraft\\game\\common\\assets\\log_configs\\client-1.12.xml')
// Java Arguments
if(process.platform === 'darwin'){
args.push('-Xdock:name=HeliosLauncher')
args.push('-Xdock:icon=' + path.join(__dirname, '..', 'images', 'minecraft.icns'))
}
args.push('-Xmx' + ConfigManager.getMaxRAM(this.server.rawServer.id))
args.push('-Xms' + ConfigManager.getMinRAM(this.server.rawServer.id))
args = args.concat(ConfigManager.getJVMOptions(this.server.rawServer.id))
// Main Java Class
args.push(this.modManifest.mainClass)
// Vanilla Arguments
args = args.concat(this.vanillaManifest.arguments.game)
for(let i=0; i<args.length; i++){
if(typeof args[i] === 'object' && args[i].rules != null){
let checksum = 0
for(let rule of args[i].rules){
if(rule.os != null){
if(rule.os.name === getMojangOS()
&& (rule.os.version == null || new RegExp(rule.os.version).test(os.release))){
if(rule.action === 'allow'){
checksum++
}
} else {
if(rule.action === 'disallow'){
checksum++
}
}
} else if(rule.features != null){
// We don't have many 'features' in the index at the moment.
// This should be fine for a while.
if(rule.features.has_custom_resolution != null && rule.features.has_custom_resolution === true){
if(ConfigManager.getFullscreen()){
args[i].value = [
'--fullscreen',
'true'
]
}
checksum++
}
}
}
// TODO splice not push
if(checksum === args[i].rules.length){
if(typeof args[i].value === 'string'){
args[i] = args[i].value
} else if(typeof args[i].value === 'object'){
//args = args.concat(args[i].value)
args.splice(i, 1, ...args[i].value)
}
// Decrement i to reprocess the resolved value
i--
} else {
args[i] = null
}
} else if(typeof args[i] === 'string'){
if(argDiscovery.test(args[i])){
const identifier = args[i].match(argDiscovery)[1]
let val = null
switch(identifier){
case 'auth_player_name':
val = this.authUser.displayName.trim()
break
case 'version_name':
//val = vanillaManifest.id
val = this.server.rawServer.id
break
case 'game_directory':
val = this.gameDir
break
case 'assets_root':
val = path.join(this.commonDir, 'assets')
break
case 'assets_index_name':
val = this.vanillaManifest.assets
break
case 'auth_uuid':
val = this.authUser.uuid.trim()
break
case 'auth_access_token':
val = this.authUser.accessToken
break
case 'user_type':
val = this.authUser.type === 'microsoft' ? 'msa' : 'mojang'
break
case 'version_type':
val = this.vanillaManifest.type
break
case 'resolution_width':
val = ConfigManager.getGameWidth()
break
case 'resolution_height':
val = ConfigManager.getGameHeight()
break
case 'natives_directory':
val = args[i].replace(argDiscovery, tempNativePath)
break
case 'launcher_name':
val = args[i].replace(argDiscovery, 'Helios-Launcher')
break
case 'launcher_version':
val = args[i].replace(argDiscovery, this.launcherVersion)
break
case 'classpath':
val = this.classpathArg(mods, tempNativePath).join(ProcessBuilder.getClasspathSeparator())
break
}
if(val != null){
args[i] = val
}
}
}
}
// Autoconnect
this._processAutoConnectArg(args)
// Forge Specific Arguments
args = args.concat(this.modManifest.arguments.game)
// Filter null values
args = args.filter(arg => {
return arg != null
})
return args
}
/**
* Resolve the arguments required by forge.
*
* @returns {Array.<string>} An array containing the arguments required by forge.
*/
_resolveForgeArgs(){
const mcArgs = this.modManifest.minecraftArguments.split(' ')
const argDiscovery = /\${*(.*)}/
// Replace the declared variables with their proper values.
for(let i=0; i<mcArgs.length; ++i){
if(argDiscovery.test(mcArgs[i])){
const identifier = mcArgs[i].match(argDiscovery)[1]
let val = null
switch(identifier){
case 'auth_player_name':
val = this.authUser.displayName.trim()
break
case 'version_name':
//val = vanillaManifest.id
val = this.server.rawServer.id
break
case 'game_directory':
val = this.gameDir
break
case 'assets_root':
val = path.join(this.commonDir, 'assets')
break
case 'assets_index_name':
val = this.vanillaManifest.assets
break
case 'auth_uuid':
val = this.authUser.uuid.trim()
break
case 'auth_access_token':
val = this.authUser.accessToken
break
case 'user_type':
val = this.authUser.type === 'microsoft' ? 'msa' : 'mojang'
break
case 'user_properties': // 1.8.9 and below.
val = '{}'
break
case 'version_type':
val = this.vanillaManifest.type
break
}
if(val != null){
mcArgs[i] = val
}
}
}
// Autoconnect to the selected server.
this._processAutoConnectArg(mcArgs)
// Prepare game resolution
if(ConfigManager.getFullscreen()){
mcArgs.push('--fullscreen')
mcArgs.push(true)
} else {
mcArgs.push('--width')
mcArgs.push(ConfigManager.getGameWidth())
mcArgs.push('--height')
mcArgs.push(ConfigManager.getGameHeight())
}
// Mod List File Argument
mcArgs.push('--modListFile')
if(this._lteMinorVersion(9)) {
mcArgs.push(path.basename(this.fmlDir))
} else {
mcArgs.push('absolute:' + this.fmlDir)
}
// LiteLoader
if(this.usingLiteLoader){
mcArgs.push('--modRepo')
mcArgs.push(this.llDir)
// Set first arg to liteloader tweak class
mcArgs.unshift('com.mumfrey.liteloader.launch.LiteLoaderTweaker')
mcArgs.unshift('--tweakClass')
}
return mcArgs
}
/**
* Ensure that the classpath entries all point to jar files.
*
* @param {Array.<String>} list Array of classpath entries.
*/
_processClassPathList(list) {
const ext = '.jar'
const extLen = ext.length
for(let i=0; i<list.length; i++) {
const extIndex = list[i].indexOf(ext)
if(extIndex > -1 && extIndex !== list[i].length - extLen) {
list[i] = list[i].substring(0, extIndex + extLen)
}
}
}
/**
* Resolve the full classpath argument list for this process. This method will resolve all Mojang-declared
* libraries as well as the libraries declared by the server. Since mods are permitted to declare libraries,
* this method requires all enabled mods as an input
*
* @param {Array.<Object>} mods An array of enabled mods which will be launched with this process.
* @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.
*/
classpathArg(mods, tempNativePath){
let cpArgs = []
if(!mcVersionAtLeast('1.17', this.server.rawServer.minecraftVersion) || this.usingFabricLoader) {
// Add the version.jar to the classpath.
// Must not be added to the classpath for Forge 1.17+.
const version = this.vanillaManifest.id
cpArgs.push(path.join(this.commonDir, 'versions', version, version + '.jar'))
}
if(this.usingLiteLoader){
cpArgs.push(this.llPath)
}
// Resolve the Mojang declared libraries.
const mojangLibs = this._resolveMojangLibraries(tempNativePath)
// Resolve the server declared libraries.
const servLibs = this._resolveServerLibraries(mods)
// Merge libraries, server libs with the same
// maven identifier will override the mojang ones.
// Ex. 1.7.10 forge overrides mojang's guava with newer version.
const finalLibs = {...mojangLibs, ...servLibs}
cpArgs = cpArgs.concat(Object.values(finalLibs))
this._processClassPathList(cpArgs)
return cpArgs
}
/**
* Resolve the libraries defined by Mojang's version data. This method will also extract
* native libraries and point to the correct location for its classpath.
*
* TODO - clean up function
*
* @param {string} tempNativePath The path to store the native libraries.
* @returns {{[id: string]: string}} An object containing the paths of each library mojang declares.
*/
_resolveMojangLibraries(tempNativePath){
const nativesRegex = /.+:natives-([^-]+)(?:-(.+))?/
const libs = {}
const libArr = this.vanillaManifest.libraries
fs.ensureDirSync(tempNativePath)
for(let i=0; i<libArr.length; i++){
const lib = libArr[i]
if(isLibraryCompatible(lib.rules, lib.natives)){
// Pre-1.19 has a natives object.
if(lib.natives != null) {
// Extract the native library.
const exclusionArr = lib.extract != null ? lib.extract.exclude : ['META-INF/']
const artifact = lib.downloads.classifiers[lib.natives[getMojangOS()].replace('${arch}', process.arch.replace('x', ''))]
// Location of native zip.
const to = path.join(this.libPath, artifact.path)
let zip = new AdmZip(to)
let zipEntries = zip.getEntries()
// Unzip the native zip.
for(let i=0; i<zipEntries.length; i++){
const fileName = zipEntries[i].entryName
let shouldExclude = false
// Exclude noted files.
exclusionArr.forEach(function(exclusion){
if(fileName.indexOf(exclusion) > -1){
shouldExclude = true
}
})
// Extract the file.
if(!shouldExclude){
fs.writeFile(path.join(tempNativePath, fileName), zipEntries[i].getData(), (err) => {
if(err){
logger.error('Error while extracting native library:', err)
}
})
}
}
}
// 1.19+ logic
else if(lib.name.includes('natives-')) {
const regexTest = nativesRegex.exec(lib.name)
// const os = regexTest[1]
const arch = regexTest[2] ?? 'x64'
if(arch != process.arch) {
continue
}
// Extract the native library.
const exclusionArr = lib.extract != null ? lib.extract.exclude : ['META-INF/', '.git', '.sha1']
const artifact = lib.downloads.artifact
// Location of native zip.
const to = path.join(this.libPath, artifact.path)
let zip = new AdmZip(to)
let zipEntries = zip.getEntries()
// Unzip the native zip.
for(let i=0; i<zipEntries.length; i++){
if(zipEntries[i].isDirectory) {
continue
}
const fileName = zipEntries[i].entryName
let shouldExclude = false
// Exclude noted files.
exclusionArr.forEach(function(exclusion){
if(fileName.indexOf(exclusion) > -1){
shouldExclude = true
}
})
const extractName = fileName.includes('/') ? fileName.substring(fileName.lastIndexOf('/')) : fileName
// Extract the file.
if(!shouldExclude){
fs.writeFile(path.join(tempNativePath, extractName), zipEntries[i].getData(), (err) => {
if(err){
logger.error('Error while extracting native library:', err)
}
})
}
}
}
// No natives
else {
const dlInfo = lib.downloads
const artifact = dlInfo.artifact
const to = path.join(this.libPath, artifact.path)
const versionIndependentId = lib.name.substring(0, lib.name.lastIndexOf(':'))
libs[versionIndependentId] = to
}
}
}
return libs
}
/**
* Resolve the libraries declared by this server in order to add them to the classpath.
* This method will also check each enabled mod for libraries, as mods are permitted to
* declare libraries.
*
* @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.
*/
_resolveServerLibraries(mods){
const mdls = this.server.modules
let libs = {}
// Locate Forge/Fabric/Libraries
for(let mdl of mdls){
const type = mdl.rawModule.type
if(type === Type.ForgeHosted || type === Type.Fabric || type === Type.Library){
libs[mdl.getVersionlessMavenIdentifier()] = mdl.getPath()
if(mdl.subModules.length > 0){
const res = this._resolveModuleLibraries(mdl)
if(res.length > 0){
libs = {...libs, ...res}
}
}
}
}
//Check for any libraries in our mod list.
for(let i=0; i<mods.length; i++){
if(mods.sub_modules != null){
const res = this._resolveModuleLibraries(mods[i])
if(res.length > 0){
libs = {...libs, ...res}
}
}
}
return libs
}
/**
* Recursively resolve the path of each library required by this module.
*
* @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.
*/
_resolveModuleLibraries(mdl){
if(!mdl.subModules.length > 0){
return []
}
let libs = []
for(let sm of mdl.subModules){
if(sm.rawModule.type === Type.Library){
if(sm.rawModule.classpath ?? true) {
libs.push(sm.getPath())
}
}
// If this module has submodules, we need to resolve the libraries for those.
// To avoid unnecessary recursive calls, base case is checked here.
if(mdl.subModules.length > 0){
const res = this._resolveModuleLibraries(sm)
if(res.length > 0){
libs = libs.concat(res)
}
}
}
return libs
}
}
module.exports = ProcessBuilder

File diff suppressed because it is too large Load Diff

View File

@ -1,50 +0,0 @@
const loginOptionsCancelContainer = document.getElementById('loginOptionCancelContainer')
const loginOptionMicrosoft = document.getElementById('loginOptionMicrosoft')
const loginOptionMojang = document.getElementById('loginOptionMojang')
const loginOptionsCancelButton = document.getElementById('loginOptionCancelButton')
let loginOptionsCancellable = false
let loginOptionsViewOnLoginSuccess
let loginOptionsViewOnLoginCancel
let loginOptionsViewOnCancel
let loginOptionsViewCancelHandler
function loginOptionsCancelEnabled(val){
if(val){
$(loginOptionsCancelContainer).show()
} else {
$(loginOptionsCancelContainer).hide()
}
}
loginOptionMicrosoft.onclick = (e) => {
switchView(getCurrentView(), VIEWS.waiting, 500, 500, () => {
ipcRenderer.send(
MSFT_OPCODE.OPEN_LOGIN,
loginOptionsViewOnLoginSuccess,
loginOptionsViewOnLoginCancel
)
})
}
loginOptionMojang.onclick = (e) => {
switchView(getCurrentView(), VIEWS.login, 500, 500, () => {
loginViewOnSuccess = loginOptionsViewOnLoginSuccess
loginViewOnCancel = loginOptionsViewOnLoginCancel
loginCancelEnabled(true)
})
}
loginOptionsCancelButton.onclick = (e) => {
switchView(getCurrentView(), loginOptionsViewOnCancel, 500, 500, () => {
// Clear login values (Mojang login)
// No cleanup needed for Microsoft.
loginUsername.value = ''
loginPassword.value = ''
if(loginOptionsViewCancelHandler != null){
loginOptionsViewCancelHandler()
loginOptionsViewCancelHandler = null
}
})
}

View File

@ -1,9 +0,0 @@
/**
* Script for welcome.ejs
*/
document.getElementById('welcomeButton').addEventListener('click', e => {
loginOptionsCancelEnabled(false) // False by default, be explicit.
loginOptionsViewOnLoginSuccess = VIEWS.landing
loginOptionsViewOnLoginCancel = VIEWS.loginOptions
switchView(VIEWS.welcome, VIEWS.loginOptions)
})

View File

@ -1,65 +0,0 @@
const net = require('net')
/**
* Retrieves the status of a minecraft server.
*
* @param {string} address The server address.
* @param {number} port Optional. The port of the server. Defaults to 25565.
* @returns {Promise.<Object>} A promise which resolves to an object containing
* status information.
*/
exports.getStatus = function(address, port = 25565){
if(port == null || port == ''){
port = 25565
}
if(typeof port === 'string'){
port = parseInt(port)
}
return new Promise((resolve, reject) => {
const socket = net.connect(port, address, () => {
let buff = Buffer.from([0xFE, 0x01])
socket.write(buff)
})
socket.setTimeout(2500, () => {
socket.end()
reject({
code: 'ETIMEDOUT',
errno: 'ETIMEDOUT',
address,
port
})
})
socket.on('data', (data) => {
if(data != null && data != ''){
let server_info = data.toString().split('\x00\x00\x00')
const NUM_FIELDS = 6
if(server_info != null && server_info.length >= NUM_FIELDS){
resolve({
online: true,
version: server_info[2].replace(/\u0000/g, ''),
motd: server_info[3].replace(/\u0000/g, ''),
onlinePlayers: server_info[4].replace(/\u0000/g, ''),
maxPlayers: server_info[5].replace(/\u0000/g,'')
})
} else {
resolve({
online: false
})
}
}
socket.end()
})
socket.on('error', (err) => {
socket.destroy()
reject(err)
// ENOTFOUND = Unable to resolve.
// ECONNREFUSED = Unable to connect to port.
})
})
}

View File

@ -1,20 +0,0 @@
# Custom Language File for Launcher Customizer
[ejs.app]
title = "Helios Launcher"
[ejs.landing]
mediaGitHubURL = "https://github.com/dscalzi/HeliosLauncher"
mediaTwitterURL = "#"
mediaInstagramURL = "#"
mediaYouTubeURL = "#"
mediaDiscordURL = "https://discord.gg/zNWUXdt"
[ejs.settings]
sourceGithubLink = "https://github.com/dscalZi/HeliosLauncher"
supportLink = "https://github.com/dscalZi/HeliosLauncher/issues"
[ejs.welcome]
welcomeHeader = "WELCOME TO WESTEROSCRAFT"
welcomeDescription = "Our mission is to recreate the universe imagined by author George RR Martin in his fantasy series, A Song of Ice and Fire. Through the collaborative effort of thousands of community members, we have sought to create Westeros as accurately and precisely as possible within Minecraft. The world we are creating is yours to explore. Journey from Dorne to Castle Black, and if you arent afraid, beyond the Wall itself, but best not delay. As the words of House Stark ominously warn: Winter is Coming."
welcomeDescCTA = "You are just a few clicks away from Westeros."

View File

@ -1,297 +0,0 @@
[ejs.landing]
updateAvailableTooltip = "Update Available"
usernamePlaceholder = "Username"
usernameEditButton = "Edit"
settingsTooltip = "Settings"
serverStatus = "SERVER"
serverStatusPlaceholder = "OFFLINE"
mojangStatus = "MOJANG STATUS"
mojangStatusTooltipTitle = "Services"
mojangStatusNETitle = "Non&nbsp;Essential"
newsButton = "NEWS"
launchButton = "PLAY"
launchButtonPlaceholder = "&#8226; No Server Selected"
launchDetails = "Please wait.."
newsNavigationStatus = "{currentPage} of {totalPages}"
newsErrorLoadSpan = "Checking for News.."
newsErrorFailedSpan = "Failed to Load News"
newsErrorRetryButton = "Try Again"
newsErrorNoneSpan = "No News"
[ejs.login]
loginCancelText = "Cancel"
loginSubheader = "MINECRAFT LOGIN"
loginEmailError = "* Invalid Value"
loginEmailPlaceholder = "EMAIL OR USERNAME"
loginPasswordError = "* Required"
loginPasswordPlaceholder = "PASSWORD"
loginForgotPasswordLink = "https://minecraft.net/password/forgot/"
loginForgotPasswordText = "forgot password?"
loginRememberMeText = "remember me?"
loginButtonText = "LOGIN"
loginNeedAccountLink = "https://minecraft.net/store/minecraft-java-edition/"
loginNeedAccountText = "Need an Account?"
loginPasswordDisclaimer1 = "Your password is sent directly to mojang and never stored."
loginPasswordDisclaimer2 = "{appName} is not affiliated with Mojang AB."
[ejs.loginOptions]
loginOptionsTitle = "Login Options"
loginWithMicrosoft = "Login with Microsoft"
loginWithMojang = "Login with Mojang"
cancelButton = "Cancel"
[ejs.overlay]
serverSelectHeader = "Available Servers"
serverSelectConfirm = "Select"
serverSelectCancel = "Cancel"
accountSelectHeader = "Select an Account"
accountSelectConfirm = "Select"
accountSelectCancel = "Cancel"
[ejs.settings]
navHeaderText = "Settings"
navAccount = "Account"
navMinecraft = "Minecraft"
navMods = "Mods"
navJava = "Java"
navLauncher = "Launcher"
navAbout = "About"
navUpdates = "Updates"
navDone = "Done"
tabAccountHeaderText = "Account Settings"
tabAccountHeaderDesc = "Add new accounts or manage existing ones."
microsoftAccount = "Microsoft"
addMicrosoftAccount = "+ Add Microsoft Account"
mojangAccount = "Mojang"
addMojangAccount = "+ Add Mojang Account"
minecraftTabHeaderText = "Minecraft Settings"
minecraftTabHeaderDesc = "Options related to game launch."
gameResolutionTitle = "Game Resolution"
launchFullscreenTitle = "Launch in fullscreen."
autoConnectTitle = "Automatically connect to the server on launch."
launchDetachedTitle = "Launch game process detached from launcher."
launchDetachedDesc = "If the game is not detached, closing the launcher will also close the game."
tabModsHeaderText = "Mod Settings"
tabModsHeaderDesc = "Enable or disable mods."
switchServerButton = "Switch"
requiredMods = "Required Mods"
optionalMods = "Optional Mods"
dropinMods = "Drop-in Mods"
addMods = "Add Mods"
dropinRefreshNote = "(F5 to Refresh)"
shaderpacks = "Shaderpacks"
shaderpackDesc = "Enable or disable shaders. Please note, shaders will only run smoothly on powerful setups. You may add custom packs here."
selectShaderpack = "Select Shaderpack"
tabJavaHeaderText = "Java Settings"
tabJavaHeaderDesc = "Manage the Java configuration (advanced)."
memoryTitle = "Memory"
maxRAM = "Maximum RAM"
minRAM = "Minimum RAM"
memoryDesc = "The recommended minimum RAM is 3 gigabytes. Setting the minimum and maximum values to the same value may reduce lag."
memoryTotalTitle = "Total"
memoryAvailableTitle = "Available"
javaExecutableTitle = "Java Executable"
javaExecSelDialogTitle = "Select Java Executable"
javaExecSelButtonText = "Choose File"
javaExecDesc = "The Java executable is validated before game launch."
javaPathDesc = "The path should end with <strong>{pathSuffix}</strong>."
jvmOptsTitle = "Additional JVM Options"
jvmOptsDesc = "Options to be provided to the JVM at runtime. <em>-Xms</em> and <em>-Xmx</em> should not be included."
launcherTabHeaderText = "Launcher Settings"
launcherTabHeaderDesc = "Options related to the launcher itself."
allowPrereleaseTitle = "Allow Pre-Release Updates."
allowPrereleaseDesc = "Pre-Releases include new features which may have not been fully tested or integrated.<br>This will always be true if you are using a pre-release version."
dataDirectoryTitle = "Data Directory"
selectDataDirectory = "Select Data Directory"
chooseFolder = "Choose Folder"
dataDirectoryDesc = "All game files and local Java installations will be stored in the data directory.<br>Screenshots and world saves are stored in the instance folder for the corresponding server configuration."
aboutTabHeaderText = "About"
aboutTabHeaderDesc = "View information and release notes for the current version."
aboutTitle = "{appName}"
stableRelease = "Stable Release"
versionText = "Version "
sourceGithub = "Source (GitHub)"
support = "Support"
devToolsConsole = "DevTools Console"
releaseNotes = "Release Notes"
changelog = "Changelog"
noReleaseNotes = "No Release Notes"
viewReleaseNotes = "View Release Notes on GitHub"
launcherUpdatesHeaderText = "Launcher Updates"
launcherUpdatesHeaderDesc = "Download, install, and review updates for the launcher."
checkForUpdates = "Check for Updates"
whatsNew = "What's New"
updateReleaseNotes = "Update Release Notes"
[ejs.waiting]
waitingText = "Waiting for Microsoft.."
[ejs.welcome]
continueButton = "CONTINUE"
[js.discord]
waiting = "Waiting for Client.."
state = "Server: {shortId}"
[js.index]
microsoftLoginTitle = "Microsoft Login"
microsoftLogoutTitle = "Microsoft Logout"
[js.login]
login = "LOGIN"
loggingIn = "LOGGING IN"
success = "SUCCESS"
tryAgain = "Try Again"
[js.login.error]
invalidValue = "* Invalid Value"
requiredValue = "* Required"
[js.login.error.unknown]
title = "Unknown Error During Login"
desc = "An unknown error has occurred. Please see the console for details."
[js.landing.launch]
pleaseWait = "Please wait.."
failureTitle = "Error During Launch"
failureText = "See console (CTRL + Shift + i) for more details."
okay = "Okay"
[js.landing.selectedAccount]
noAccountSelected = "No Account Selected"
[js.landing.selectedServer]
noSelection = "No Server Selected"
loading = "Loading.."
[js.landing.serverStatus]
server = "SERVER"
offline = "OFFLINE"
players = "PLAYERS"
[js.landing.systemScan]
checking = "Checking system info.."
noCompatibleJava = "No Compatible<br>Java Installation Found"
installJavaMessage = "In order to launch Minecraft, you need a 64-bit installation of Java {major}. Would you like us to install a copy?"
installJava = "Install Java"
installJavaManually = "Install Manually"
javaDownloadPrepare = "Preparing Java Download.."
javaDownloadFailureTitle = "Error During Java Download"
javaDownloadFailureText = "See console (CTRL + Shift + i) for more details."
javaRequired = "Java is Required<br>to Launch"
javaRequiredMessage = 'A valid x64 installation of Java {major} is required to launch.<br><br>Please refer to our <a href="https://github.com/dscalzi/HeliosLauncher/wiki/Java-Management#manually-installing-a-valid-version-of-java">Java Management Guide</a> for instructions on how to manually install Java.'
javaRequiredDismiss = "I Understand"
javaRequiredCancel = "Go Back"
[js.landing.downloadJava]
findJdkFailure = "Failed to find OpenJDK distribution."
javaDownloadCorruptedError = "Downloaded JDK has a bad hash, the file may be corrupted."
extractingJava = "Extracting Java"
javaInstalled = "Java Installed!"
[js.landing.dlAsync]
loadingServerInfo = "Loading server information.."
fatalError = "Fatal Error"
unableToLoadDistributionIndex = "Could not load a copy of the distribution index. See the console (CTRL + Shift + i) for more details."
pleaseWait = "Please wait.."
errorDuringLaunchTitle = "Error During Launch"
seeConsoleForDetails = "See console (CTRL + Shift + i) for more details."
validatingFileIntegrity = "Validating file integrity.."
errorDuringFileVerificationTitle = "Error During File Verification"
downloadingFiles = "Downloading files.."
errorDuringFileDownloadTitle = "Error During File Download"
preparingToLaunch = "Preparing to launch.."
launchingGame = "Launching game.."
launchWrapperNotDownloaded = "The main file, LaunchWrapper, failed to download properly. As a result, the game cannot launch.<br><br>To fix this issue, temporarily turn off your antivirus software and launch the game again.<br><br>If you have time, please <a href=\"https://github.com/dscalzi/HeliosLauncher/issues\">submit an issue</a> and let us know what antivirus software you use. We'll contact them and try to straighten things out."
doneEnjoyServer = "Done. Enjoy the server!"
checkConsoleForDetails = "Please check the console (CTRL + Shift + i) for more details."
[js.landing.news]
checking = "Checking for News"
[js.landing.discord]
loading = "Loading game.."
joining = "Sailing to Westeros!"
joined = "Exploring the Realm!"
[js.overlay]
dismiss = "Dismiss"
[js.settings.fileSelectors]
executables = "Executables"
allFiles = "All Files"
[js.settings.mstfLogin]
errorTitle = "Something Went Wrong"
errorMessage = "Microsoft authentication failed. Please try again."
okButton = "OK"
[js.settings.mstfLogout]
errorTitle = "Something Went Wrong"
errorMessage = "Microsoft logout failed. Please try again."
okButton = "OK"
[js.settings.authAccountSelect]
selectButton = "Select Account"
selectedButton = "Selected Account &#10004;"
[js.settings.authAccountLogout]
lastAccountWarningTitle = "Warning<br>This is Your Last Account"
lastAccountWarningMessage = "In order to use the launcher you must be logged into at least one account. You will need to login again after.<br><br>Are you sure you want to log out?"
confirmButton = "I'm Sure"
cancelButton = "Cancel"
[js.settings.authAccountPopulate]
username = "Username"
uuid = "UUID"
selectAccount = "Select Account"
selectedAccount = "Selected Account ✓"
logout = "Log Out"
[js.settings.dropinMods]
removeButton = "Remove"
deleteFailedTitle = "Failed to Delete<br>Drop-in Mod {fullName}"
deleteFailedMessage = "Make sure the file is not in use and try again."
failedToggleTitle = "Failed to Toggle<br>One or More Drop-in Mods"
okButton = "Okay"
[js.settings.serverListing]
mainServer = "Main Server"
[js.settings.java]
selectedJava = "Selected: Java {version} ({vendor})"
invalidSelection = "Invalid Selection"
requiresJava = "Requires Java {major} x64."
availableOptions = "Available Options for Java {major} (HotSpot VM)"
[js.settings.about]
preReleaseTitle = "Pre-release"
stableReleaseTitle = "Stable Release"
releaseNotesFailed = "Failed to load release notes."
[js.settings.updates]
newReleaseTitle = "New Release Available"
newPreReleaseTitle = "New Pre-release Available"
downloadingButton = "Downloading.."
downloadButton = 'Download from GitHub<span style="font-size: 10px;color: gray;text-shadow: none !important;">Close the launcher and run the dmg to update.</span>'
latestVersionTitle = "You Are Running the Latest Version"
checkForUpdatesButton = "Check for Updates"
checkingForUpdatesButton = "Checking for Updates.."
[js.uibinder.startup]
fatalErrorTitle = "Fatal Error: Unable to Load Distribution Index"
fatalErrorMessage = "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."
closeButton = "Close"
[js.uibinder.validateAccount]
failedMessageTitle = "Failed to Refresh Login"
failedMessage = "We were unable to refresh the login for <strong>{account}</strong>. Please select another account or login again."
failedMessageSelectAnotherAccount = "We were unable to refresh the login for <strong>{account}</strong>. Please login again."
loginButton = "Login"
selectAnotherAccountButton = "Select Another Account"
[js.uicore.autoUpdate]
checkingForUpdateButton = "Checking for Updates..."
installNowButton = "Install Now"
checkForUpdatesButton = "Check for Updates"

View File

@ -1,34 +0,0 @@
<div id="loginOptionsContainer" style="display: none;">
<div id="loginOptionsContent">
<div class="loginOptionsMainContent">
<h2><%- lang('loginOptions.loginOptionsTitle') %></h2>
<div class="loginOptionActions">
<div class="loginOptionButtonContainer">
<button id="loginOptionMicrosoft" class="loginOptionButton">
<svg xmlns="http://www.w3.org/2000/svg" width="22" height="22" viewBox="0 0 23 23">
<path fill="#f35325" d="M1 1h10v10H1z" />
<path fill="#81bc06" d="M12 1h10v10H12z" />
<path fill="#05a6f0" d="M1 12h10v10H1z" />
<path fill="#ffba08" d="M12 12h10v10H12z" />
</svg>
<span><%- lang('loginOptions.loginWithMicrosoft') %></span>
</button>
</div>
<div class="loginOptionButtonContainer">
<button id="loginOptionMojang" class="loginOptionButton">
<svg xmlns="http://www.w3.org/2000/svg" width="22" height="22" viewBox="0 0 9.677 9.667">
<path d="M-26.332-12.098h2.715c-1.357.18-2.574 1.23-2.715 2.633z" fill="#fff" />
<path d="M2.598.022h7.07L9.665 7c-.003 1.334-1.113 2.46-2.402 2.654H0V2.542C.134 1.2 1.3.195 2.598.022z" fill="#db2331" />
<path d="M1.54 2.844c.314-.76 1.31-.46 1.954-.528.785-.083 1.503.272 2.1.758l.164-.9c.327.345.587.756.964 1.052.28.254.655-.342.86-.013.42.864.408 1.86.54 2.795l-.788-.373C6.9 4.17 5.126 3.052 3.656 3.685c-1.294.592-1.156 2.65.06 3.255 1.354.703 2.953.51 4.405.292-.07.42-.34.87-.834.816l-4.95.002c-.5.055-.886-.413-.838-.89l.04-4.315z" fill="#fff" />
</svg>
<span><%- lang('loginOptions.loginWithMojang') %></span>
</button>
</div>
</div>
<div id="loginOptionCancelContainer" style="display: none;">
<button id="loginOptionCancelButton"><%- lang('loginOptions.cancelButton') %></button>
</div>
</div>
</div>
<script src="./assets/js/scripts/loginOptions.js"></script>
</div>

View File

@ -1,8 +0,0 @@
<div id="waitingContainer" style="display: none;">
<div id="waitingContent">
<div class="waitingSpinner"></div>
<div id="waitingTextContainer">
<h2><%- lang('waiting.waitingText') %></h2>
</div>
</div>
</div>

View File

@ -1,25 +0,0 @@
<div id="welcomeContainer" style="display: none;">
<!--<div class="cloudDiv">
<div class="cloudTop"></div>
<div class="cloudBottom"></div>
</div>-->
<div id="welcomeContent">
<img id="welcomeImageSeal" src="assets/images/SealCircle.png"/>
<span id="welcomeHeader"><%- lang('welcome.welcomeHeader') %></span>
<span id="welcomeDescription"><%- lang('welcome.welcomeDescription') %></span>
<br>
<span id="welcomeDescCTA"><%- lang('welcome.welcomeDescCTA') %></span>
<button id="welcomeButton">
<div id="welcomeButtonContent">
<%- lang('welcome.continueButton') %>
<svg id="welcomeSVG" viewBox="0 0 24.87 13.97">
<defs>
<style>.arrowLine{fill:none;stroke:#FFF;stroke-width:2px;transition: 0.25s ease;}</style>
</defs>
<polyline class="arrowLine" points="0.71 13.26 12.56 1.41 24.16 13.02"/>
</svg>
</div>
</button>
</div>
<script src="./assets/js/scripts/welcome.js"></script>
</div>

View File

@ -1,5 +1,5 @@
/* Github Code Highlighting. */ /* Github Code Highlighting. */
@import "../../../node_modules/github-syntax-dark/lib/github-dark.css"; @import "../../node_modules/github-syntax-dark/lib/github-dark.css";
/******************************************************************************* /*******************************************************************************
* * * *
@ -222,7 +222,6 @@ body, button {
align-items: center; align-items: center;
height: 100%; height: 100%;
width: 100%; width: 100%;
background: rgba(0, 0, 0, 0.50);
} }
#welcomeContent { #welcomeContent {
@ -873,175 +872,6 @@ body, button {
} }
*/ */
/*******************************************************************************
* *
* Waiting View (waiting.ejs) *
* *
******************************************************************************/
#waitingContainer {
position: relative;
display: flex;
justify-content: center;
align-items: center;
height: 100%;
width: 100%;
transition: filter 0.25s ease;
background: rgba(0, 0, 0, 0.50);
}
#waitingContent {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
width: 50%;
top: -10%;
position: relative;
}
.waitingSpinner:before {
transform: rotateX(60deg) rotateY(45deg) rotateZ(45deg);
animation: 750ms rotateBefore infinite linear reverse;
}
.waitingSpinner:after {
transform: rotateX(240deg) rotateY(45deg) rotateZ(45deg);
animation: 750ms rotateAfter infinite linear;
}
.waitingSpinner:before,
.waitingSpinner:after {
box-sizing: border-box;
content: '';
display: block;
position: fixed;
top: calc(50% - 5em);
/* left: 50%; */
margin-top: -5em;
margin-left: -5em;
width: 10em;
height: 10em;
transform-style: preserve-3d;
transform-origin: 50%;
transform: rotateY(50%);
perspective-origin: 50% 50%;
perspective: 340px;
background-size: 10em 10em;
background-image: url(data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiIHN0YW5kYWxvbmU9Im5vIj8+Cjxzdmcgd2lkdGg9IjI2NnB4IiBoZWlnaHQ9IjI5N3B4IiB2aWV3Qm94PSIwIDAgMjY2IDI5NyIgdmVyc2lvbj0iMS4xIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHhtbG5zOnhsaW5rPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5L3hsaW5rIiB4bWxuczpza2V0Y2g9Imh0dHA6Ly93d3cuYm9oZW1pYW5jb2RpbmcuY29tL3NrZXRjaC9ucyI+CiAgICA8dGl0bGU+c3Bpbm5lcjwvdGl0bGU+CiAgICA8ZGVzY3JpcHRpb24+Q3JlYXRlZCB3aXRoIFNrZXRjaCAoaHR0cDovL3d3dy5ib2hlbWlhbmNvZGluZy5jb20vc2tldGNoKTwvZGVzY3JpcHRpb24+CiAgICA8ZGVmcz48L2RlZnM+CiAgICA8ZyBpZD0iUGFnZS0xIiBzdHJva2U9Im5vbmUiIHN0cm9rZS13aWR0aD0iMSIgZmlsbD0ibm9uZSIgZmlsbC1ydWxlPSJldmVub2RkIiBza2V0Y2g6dHlwZT0iTVNQYWdlIj4KICAgICAgICA8cGF0aCBkPSJNMTcxLjUwNzgxMywzLjI1MDAwMDM4IEMyMjYuMjA4MTgzLDEyLjg1NzcxMTEgMjk3LjExMjcyMiw3MS40OTEyODIzIDI1MC44OTU1OTksMTA4LjQxMDE1NSBDMjE2LjU4MjAyNCwxMzUuODIwMzEgMTg2LjUyODQwNSw5Ny4wNjI0OTY0IDE1Ni44MDA3NzQsODUuNzczNDM0NiBDMTI3LjA3MzE0Myw3NC40ODQzNzIxIDc2Ljg4ODQ2MzIsODQuMjE2MTQ2MiA2MC4xMjg5MDY1LDEwOC40MTAxNTMgQy0xNS45ODA0Njg1LDIxOC4yODEyNDcgMTQ1LjI3NzM0NCwyOTYuNjY3OTY4IDE0NS4yNzczNDQsMjk2LjY2Nzk2OCBDMTQ1LjI3NzM0NCwyOTYuNjY3OTY4IC0yNS40NDkyMTg3LDI1Ny4yNDIxOTggMy4zOTg0Mzc1LDEwOC40MTAxNTUgQzE2LjMwNzA2NjEsNDEuODExNDE3NCA4NC43Mjc1ODI5LC0xMS45OTIyOTg1IDE3MS41MDc4MTMsMy4yNTAwMDAzOCBaIiBpZD0iUGF0aC0xIiBmaWxsPSIjZmZmZmZmIiBza2V0Y2g6dHlwZT0iTVNTaGFwZUdyb3VwIj48L3BhdGg+CiAgICA8L2c+Cjwvc3ZnPg==);
}
#waitingTextContainer {
position: fixed;
top: 50%;
}
@keyframes rotateBefore {
from {
transform: rotateX(60deg) rotateY(45deg) rotateZ(0deg);
}
to {
transform: rotateX(60deg) rotateY(45deg) rotateZ(-360deg);
}
}
@keyframes rotateAfter {
from {
transform: rotateX(240deg) rotateY(45deg) rotateZ(0deg);
}
to {
transform: rotateX(240deg) rotateY(45deg) rotateZ(360deg);
}
}
/*******************************************************************************
* *
* Login Options View (loginOptions.ejs) *
* *
******************************************************************************/
#loginOptionsContainer {
position: relative;
display: flex;
justify-content: center;
align-items: center;
height: 100%;
width: 100%;
transition: filter 0.25s ease;
background: rgba(0, 0, 0, 0.50);
}
#loginOptionsContent {
border-radius: 3px;
position: relative;
top: -5%;
}
.loginOptionsMainContent {
display: flex;
flex-direction: column;
align-items: center;
}
.loginOptionActions {
display: flex;
flex-direction: column;
row-gap: 10px;
}
.loginOptionButtonContainer {
width: 16em;
}
.loginOptionButton {
background: rgba(0, 0, 0, 0.25);
border: 1px solid rgba(126, 126, 126, 0.57);
border-radius: 3px;
height: 50px;
width: 100%;
text-align: left;
padding: 0px 25px;
cursor: pointer;
outline: none;
transition: 0.25s ease;
display: flex;
align-items: center;
column-gap: 5px;
}
.loginOptionButton:hover,
.loginOptionButton:focus {
background: rgba(54, 54, 54, 0.25);
text-shadow: 0px 0px 20px white;
}
#loginOptionCancelContainer {
position: absolute;
bottom: -100px;
}
#loginOptionCancelButton {
background: none;
border: none;
padding: 2px 0px;
font-size: 16px;
font-weight: bold;
color: lightgrey;
cursor: pointer;
outline: none;
transition: 0.25s ease;
}
#loginOptionCancelButton:hover,
#loginOptionCancelButton:focus {
text-shadow: 0px 0px 20px lightgrey;
}
#loginOptionCancelButton:active {
text-shadow: 0px 0px 20px rgba(211, 211, 211, 0.75);
color: rgba(211, 211, 211, 0.75);
}
#loginOptionCancelButton:disabled {
color: rgba(211, 211, 211, 0.75);
pointer-events: none;
}
/******************************************************************************* /*******************************************************************************
* * * *
* Settings View (sttings.ejs) * * Settings View (sttings.ejs) *
@ -1228,59 +1058,6 @@ body, button {
font-size: 12px; font-size: 12px;
} }
/* Selected server content container */
.settingsSelServContainer {
background: rgba(0, 0, 0, 0.25);
width: 75%;
border-radius: 3px;
display: flex;
justify-content: space-between;
margin: 15px 0px;
}
/* Div which will be populated with the selected server's information. */
.settingsSelServContent {
display: flex;
align-items: center;
justify-content: flex-start;
padding: 5px 0px;
}
/* Wrapper container for the switch server button. */
.settingsSwitchServerContainer {
display: flex;
align-items: center;
padding: 15px;
}
/* Button to switch server configurations on the mods tab. */
.settingsSwitchServerButton {
opacity: 0;
border: 1px solid rgb(255, 255, 255);
color: rgb(255, 255, 255);
background: none;
font-size: 12px;
border-radius: 3px;
font-family: 'Avenir Medium';
transition: 0.25s ease;
cursor: pointer;
outline: none;
}
.settingsSwitchServerButton:hover,
.settingsSwitchServerButton:focus {
box-shadow: 0px 0px 20px rgb(255, 255, 255);
background: rgba(255, 255, 255, 0.25);
}
.settingsSwitchServerButton:active {
box-shadow: 0px 0px 20px rgb(187, 187, 187);
background: rgba(187, 187, 187, 0.25);
border: 1px solid rgb(187, 187, 187);
color: rgb(187, 187, 187);
}
.settingsSelServContainer:hover .settingsSwitchServerButton {
opacity: 1;
}
/* Remove spin button from number inputs. */ /* Remove spin button from number inputs. */
#settingsContainer input[type=number]::-webkit-inner-spin-button { #settingsContainer input[type=number]::-webkit-inner-spin-button {
-webkit-appearance: none; -webkit-appearance: none;
@ -1456,26 +1233,34 @@ input:checked + .toggleSwitchSlider:before {
height: 30px; height: 30px;
} }
/* File selection button. */ /* File input for file selection. */
.settingsFileSelButton { .settingsFileSelSel {
border: 0px; width: 0px;
height: 0px;
opacity: 0;
}
.settingsFileSelSel::-webkit-file-upload-button {
display: none;
}
/* Wrapper label to add a custom style to the file input. */
.settingsFileSelLabel {
border-left: 0px;
border-radius: 0px 3px 3px 0px; border-radius: 0px 3px 3px 0px;
font-size: 12px; font-size: 12px;
padding: 0px 5px; padding: 0px 5px;
cursor: pointer; cursor: pointer;
display: flex;
align-items: center;
background: rgba(126, 126, 126, 0.57); background: rgba(126, 126, 126, 0.57);
transition: 0.25s ease; transition: 0.25s ease;
white-space: nowrap; white-space: nowrap;
outline: none;
} }
.settingsFileSelButton:hover, .settingsFileSelLabel:hover,
.settingsFileSelButton:focus { .settingsFileSelLabel:focus,
.settingsFileSelSel:focus ~ #settingsJavaExecLabel {
text-shadow: 0px 0px 20px white; text-shadow: 0px 0px 20px white;
} }
.settingsFileSelButton:active {
text-shadow: 0px 0px 20px rgba(255, 255, 255, 0.75);
color: rgba(255, 255, 255, 0.75);
}
/* Description for the file selector. */ /* Description for the file selector. */
.settingsFileSelDesc { .settingsFileSelDesc {
@ -1492,65 +1277,45 @@ input:checked + .toggleSwitchSlider:before {
* Settings View (Account Tab) * Settings View (Account Tab)
* * */ * * */
.settingsAuthAccountTypeContainer { /* Add account button styles. */
display: flex; #settingsAddAccount {
background: rgba(0, 0, 0, 0.25);
border: 1px solid rgba(126, 126, 126, 0.57);
border-radius: 3px;
height: 50px;
width: 75%; width: 75%;
flex-direction: column;
}
.settingsAuthAccountTypeHeader {
display: flex;
align-items: center;
width: 100%;
justify-content: space-between;
padding: 10px 0px;
border-bottom: 1px solid #ffffff85;
margin-bottom: 30px;
}
.settingsAuthAccountTypeHeaderLeft {
display: flex;
column-gap: 5px;
}
/* Settings add account button styles. */
.settingsAddAuthAccount {
background: none;
border: none;
text-align: left; text-align: left;
padding: 2px 0px; padding: 0px 50px;
color: white;
cursor: pointer; cursor: pointer;
outline: none; outline: none;
transition: 0.25s ease; transition: 0.25s ease;
} }
.settingsAddAuthAccount:hover, #settingsAddAccount:hover,
.settingsAddAuthAccount:focus { #settingsAddAccount:focus {
text-shadow: 0px 0px 20px white, 0px 0px 20px white, 0px 0px 20px white; background: rgba(54, 54, 54, 0.25);
text-shadow: 0px 0px 20px white;
} }
.settingsAddAuthAccount:active {
text-shadow: 0px 0px 20px rgba(255, 255, 255, 0.75), 0px 0px 20px rgba(255, 255, 255, 0.75), 0px 0px 20px rgba(255, 255, 255, 0.75); /* Settings auth accounts header. */
color: rgba(255, 255, 255, 0.75); #settingsCurrentAccountsHeader {
} margin: 20px 0px;
.settingsAddAuthAccount:disabled {
color: rgba(255, 255, 255, 0.75);
pointer-events: none;
} }
/* Auth account list container styles. */ /* Auth account list container styles. */
.settingsCurrentAccounts { #settingsCurrentAccounts {
margin-bottom: 5%; margin-bottom: 5%;
} }
.settingsCurrentAccounts > .settingsAuthAccount:not(:last-child) { #settingsCurrentAccounts > .settingsAuthAccount:not(:last-child) {
margin-bottom: 10px; margin-bottom: 10px;
} }
.settingsCurrentAccounts > .settingsAuthAccount:not(:first-child) { #settingsCurrentAccounts > .settingsAuthAccount:not(:first-child) {
margin-top: 10px; margin-top: 10px;
} }
/* Auth account shared styles. */ /* Auth account shared styles. */
.settingsAuthAccount { .settingsAuthAccount {
display: flex; display: flex;
width: 75%;
background: rgba(0, 0, 0, 0.25); background: rgba(0, 0, 0, 0.25);
border-radius: 3px; border-radius: 3px;
border: 1px solid rgba(126, 126, 126, 0.57); border: 1px solid rgba(126, 126, 126, 0.57);
@ -1691,6 +1456,59 @@ input:checked + .toggleSwitchSlider:before {
* Settings View (Mods Tab) * Settings View (Mods Tab)
* * */ * * */
/* Selected server content container */
#settingsSelServContainer {
background: rgba(0, 0, 0, 0.25);
width: 75%;
border-radius: 3px;
display: flex;
justify-content: space-between;
margin: 15px 0px;
}
/* Div which will be populated with the selected server's information. */
#settingsSelServContent {
display: flex;
align-items: center;
justify-content: flex-start;
padding: 5px 0px;
}
/* Wrapper container for the switch server button. */
#settingsSwitchServerContainer {
display: flex;
align-items: center;
padding: 15px;
}
/* Button to switch server configurations on the mods tab. */
#settingsSwitchServerButton {
opacity: 0;
border: 1px solid rgb(255, 255, 255);
color: rgb(255, 255, 255);
background: none;
font-size: 12px;
border-radius: 3px;
font-family: 'Avenir Medium';
transition: 0.25s ease;
cursor: pointer;
outline: none;
}
#settingsSwitchServerButton:hover,
#settingsSwitchServerButton:focus {
box-shadow: 0px 0px 20px rgb(255, 255, 255);
background: rgba(255, 255, 255, 0.25);
}
#settingsSwitchServerButton:active {
box-shadow: 0px 0px 20px rgb(187, 187, 187);
background: rgba(187, 187, 187, 0.25);
border: 1px solid rgb(187, 187, 187);
color: rgb(187, 187, 187);
}
#settingsSelServContainer:hover #settingsSwitchServerButton {
opacity: 1;
}
/* Main content container for the mod elements. */ /* Main content container for the mod elements. */
#settingsModsContainer { #settingsModsContainer {
width: 75%; width: 75%;
@ -3772,7 +3590,6 @@ input:checked + .toggleSwitchSlider:before {
font-size: 10px; font-size: 10px;
line-height: 10px; line-height: 10px;
font-weight: bold; font-weight: bold;
text-align: left;
} }
/* Content container for the server listing's information. */ /* Content container for the server listing's information. */

View File

Before

Width:  |  Height:  |  Size: 298 B

After

Width:  |  Height:  |  Size: 298 B

View File

Before

Width:  |  Height:  |  Size: 1.2 KiB

After

Width:  |  Height:  |  Size: 1.2 KiB

View File

Before

Width:  |  Height:  |  Size: 1.8 KiB

After

Width:  |  Height:  |  Size: 1.8 KiB

View File

Before

Width:  |  Height:  |  Size: 875 B

After

Width:  |  Height:  |  Size: 875 B

View File

Before

Width:  |  Height:  |  Size: 756 B

After

Width:  |  Height:  |  Size: 756 B

View File

Before

Width:  |  Height:  |  Size: 959 B

After

Width:  |  Height:  |  Size: 959 B

View File

Before

Width:  |  Height:  |  Size: 602 B

After

Width:  |  Height:  |  Size: 602 B

View File

Before

Width:  |  Height:  |  Size: 1.3 KiB

After

Width:  |  Height:  |  Size: 1.3 KiB

View File

Before

Width:  |  Height:  |  Size: 809 B

After

Width:  |  Height:  |  Size: 809 B

View File

Before

Width:  |  Height:  |  Size: 932 B

After

Width:  |  Height:  |  Size: 932 B

View File

Before

Width:  |  Height:  |  Size: 822 B

After

Width:  |  Height:  |  Size: 822 B

View File

Before

Width:  |  Height:  |  Size: 1018 B

After

Width:  |  Height:  |  Size: 1018 B

View File

Before

Width:  |  Height:  |  Size: 907 B

After

Width:  |  Height:  |  Size: 907 B

View File

Before

Width:  |  Height:  |  Size: 700 B

After

Width:  |  Height:  |  Size: 700 B

View File

Before

Width:  |  Height:  |  Size: 9.8 KiB

After

Width:  |  Height:  |  Size: 9.8 KiB

View File

Before

Width:  |  Height:  |  Size: 654 B

After

Width:  |  Height:  |  Size: 654 B

49
assets/lang/en_US.json Normal file
View File

@ -0,0 +1,49 @@
{
"html": {
"avatarOverlay": "Edit"
},
"js": {
"login": {
"error": {
"invalidValue": "* Invalid Value",
"requiredValue": "* Required",
"userMigrated": {
"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."
},
"invalidCredentials": {
"title": "Error During Login:<br>Invalid Credentials",
"desc": "The email or password you've entered is incorrect. Please try again."
},
"rateLimit": {
"title": "Error During Login:<br>Too Many Attempts",
"desc": "There have been too many login attempts with this account recently. Please try again later."
},
"noInternet": {
"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."
},
"authDown": {
"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>."
},
"notPaid": {
"title": "Error During Login:<br>Game Not Purchased",
"desc": "The account you are trying to login with has not purchased a copy of Minecraft.<br>You may purchase a copy on <a href=\"https://minecraft.net/\">Minecraft.net</a>"
},
"unknown": {
"title": "Error During Login:<br>Unknown Error"
}
},
"login": "LOGIN",
"loggingIn": "LOGGING IN",
"success": "SUCCESS",
"tryAgain": "Try Again"
},
"landing": {
"launch": {
"pleaseWait": "Please wait.."
}
}
}
}

1134
assets/scripts/landing.js Normal file

File diff suppressed because it is too large Load Diff

View File

@ -21,6 +21,8 @@ const loginForm = document.getElementById('loginForm')
// Control variables. // Control variables.
let lu = false, lp = false let lu = false, lp = false
const loggerLogin = new LoggerUtil('%c[Login]', 'color: #000668; font-weight: bold')
/** /**
* Show a login error. * Show a login error.
@ -152,6 +154,79 @@ function formDisabled(v){
loginRememberOption.disabled = v loginRememberOption.disabled = v
} }
/**
* Parses an error and returns a user-friendly title and description
* for our error overlay.
*
* @param {Error | {cause: string, error: string, errorMessage: string}} err A Node.js
* error or Mojang error response.
*/
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: Lang.queryJS('login.error.userMigrated.title'),
desc: Lang.queryJS('login.error.userMigrated.desc')
}
} else {
if(err.error != null){
if(err.error === 'ForbiddenOperationException'){
if(err.errorMessage != null){
if(err.errorMessage === 'Invalid credentials. Invalid username or password.'){
return {
title: Lang.queryJS('login.error.invalidCredentials.title'),
desc: Lang.queryJS('login.error.invalidCredentials.desc')
}
} else if(err.errorMessage === 'Invalid credentials.'){
return {
title: Lang.queryJS('login.error.rateLimit.title'),
desc: Lang.queryJS('login.error.rateLimit.desc')
}
}
}
}
} else {
// Request errors (from Node).
if(err.code != null){
if(err.code === 'ENOENT'){
// No Internet.
return {
title: Lang.queryJS('login.error.noInternet.title'),
desc: Lang.queryJS('login.error.noInternet.desc')
}
} else if(err.code === 'ENOTFOUND'){
// Could not reach server.
return {
title: Lang.queryJS('login.error.authDown.title'),
desc: Lang.queryJS('login.error.authDown.desc')
}
}
}
}
}
if(err.message != null){
if(err.message === 'NotPaidAccount'){
return {
title: Lang.queryJS('login.error.notPaid.title'),
desc: Lang.queryJS('login.error.notPaid.desc')
}
} else {
// Unknown error with request.
return {
title: Lang.queryJS('login.error.unknown.title'),
desc: err.message
}
}
} else {
// Unknown Mojang error.
return {
title: err.error,
desc: err.errorMessage
}
}
}
let loginViewOnSuccess = VIEWS.landing let loginViewOnSuccess = VIEWS.landing
let loginViewOnCancel = VIEWS.settings let loginViewOnCancel = VIEWS.settings
let loginViewCancelHandler let loginViewCancelHandler
@ -187,16 +262,16 @@ loginButton.addEventListener('click', () => {
// Show loading stuff. // Show loading stuff.
loginLoading(true) loginLoading(true)
AuthManager.addMojangAccount(loginUsername.value, loginPassword.value).then((value) => { AuthManager.addAccount(loginUsername.value, loginPassword.value).then((value) => {
updateSelectedAccount(value) updateSelectedAccount(value)
loginButton.innerHTML = loginButton.innerHTML.replace(Lang.queryJS('login.loggingIn'), Lang.queryJS('login.success')) loginButton.innerHTML = loginButton.innerHTML.replace(Lang.queryJS('login.loggingIn'), Lang.queryJS('login.success'))
$('.circle-loader').toggleClass('load-complete') $('.circle-loader').toggleClass('load-complete')
$('.checkmark').toggle() $('.checkmark').toggle()
setTimeout(() => { setTimeout(() => {
switchView(VIEWS.login, loginViewOnSuccess, 500, 500, async () => { switchView(VIEWS.login, loginViewOnSuccess, 500, 500, () => {
// Temporary workaround // Temporary workaround
if(loginViewOnSuccess === VIEWS.settings){ if(loginViewOnSuccess === VIEWS.settings){
await prepareSettings() prepareSettings()
} }
loginViewOnSuccess = VIEWS.landing // Reset this for good measure. loginViewOnSuccess = VIEWS.landing // Reset this for good measure.
loginCancelEnabled(false) // Reset this for good measure. loginCancelEnabled(false) // Reset this for good measure.
@ -210,25 +285,16 @@ loginButton.addEventListener('click', () => {
formDisabled(false) formDisabled(false)
}) })
}, 1000) }, 1000)
}).catch((displayableError) => { }).catch((err) => {
loginLoading(false) loginLoading(false)
const errF = resolveError(err)
let actualDisplayableError setOverlayContent(errF.title, errF.desc, Lang.queryJS('login.tryAgain'))
if(isDisplayableError(displayableError)) {
msftLoginLogger.error('Error while logging in.', displayableError)
actualDisplayableError = displayableError
} else {
// Uh oh.
msftLoginLogger.error('Unhandled error during login.', displayableError)
actualDisplayableError = Lang.queryJS('login.error.unknown')
}
setOverlayContent(actualDisplayableError.title, actualDisplayableError.desc, Lang.queryJS('login.tryAgain'))
setOverlayHandler(() => { setOverlayHandler(() => {
formDisabled(false) formDisabled(false)
toggleOverlay(false) toggleOverlay(false)
}) })
toggleOverlay(true) toggleOverlay(true)
loggerLogin.log('Error while logging in.', err)
}) })
}) })

View File

@ -117,8 +117,8 @@ function toggleOverlay(toggleState, dismissable = false, content = 'overlayConte
} }
} }
async function toggleServerSelection(toggleState){ function toggleServerSelection(toggleState){
await prepareServerSelectionList() prepareServerSelectionList()
toggleOverlay(toggleState, true, 'serverSelectContent') toggleOverlay(toggleState, true, 'serverSelectContent')
} }
@ -130,7 +130,7 @@ async function toggleServerSelection(toggleState){
* @param {string} acknowledge Acknowledge button text. * @param {string} acknowledge Acknowledge button text.
* @param {string} dismiss Dismiss button text. * @param {string} dismiss Dismiss button text.
*/ */
function setOverlayContent(title, description, acknowledge, dismiss = Lang.queryJS('overlay.dismiss')){ function setOverlayContent(title, description, acknowledge, dismiss = 'Dismiss'){
document.getElementById('overlayTitle').innerHTML = title document.getElementById('overlayTitle').innerHTML = title
document.getElementById('overlayDesc').innerHTML = description document.getElementById('overlayDesc').innerHTML = description
document.getElementById('overlayAcknowledge').innerHTML = acknowledge document.getElementById('overlayAcknowledge').innerHTML = acknowledge
@ -171,11 +171,11 @@ function setDismissHandler(handler){
/* Server Select View */ /* Server Select View */
document.getElementById('serverSelectConfirm').addEventListener('click', async () => { document.getElementById('serverSelectConfirm').addEventListener('click', () => {
const listings = document.getElementsByClassName('serverListing') const listings = document.getElementsByClassName('serverListing')
for(let i=0; i<listings.length; i++){ for(let i=0; i<listings.length; i++){
if(listings[i].hasAttribute('selected')){ if(listings[i].hasAttribute('selected')){
const serv = (await DistroAPI.getDistribution()).getServerById(listings[i].getAttribute('servid')) const serv = DistroManager.getDistribution().getServer(listings[i].getAttribute('servid'))
updateSelectedServer(serv) updateSelectedServer(serv)
refreshServerStatus(true) refreshServerStatus(true)
toggleOverlay(false) toggleOverlay(false)
@ -184,22 +184,19 @@ document.getElementById('serverSelectConfirm').addEventListener('click', async (
} }
// None are selected? Not possible right? Meh, handle it. // None are selected? Not possible right? Meh, handle it.
if(listings.length > 0){ if(listings.length > 0){
const serv = (await DistroAPI.getDistribution()).getServerById(listings[i].getAttribute('servid')) const serv = DistroManager.getDistribution().getServer(listings[i].getAttribute('servid'))
updateSelectedServer(serv) updateSelectedServer(serv)
toggleOverlay(false) toggleOverlay(false)
} }
}) })
document.getElementById('accountSelectConfirm').addEventListener('click', async () => { document.getElementById('accountSelectConfirm').addEventListener('click', () => {
const listings = document.getElementsByClassName('accountListing') const listings = document.getElementsByClassName('accountListing')
for(let i=0; i<listings.length; i++){ for(let i=0; i<listings.length; i++){
if(listings[i].hasAttribute('selected')){ if(listings[i].hasAttribute('selected')){
const authAcc = ConfigManager.setSelectedAccount(listings[i].getAttribute('uuid')) const authAcc = ConfigManager.setSelectedAccount(listings[i].getAttribute('uuid'))
ConfigManager.save() ConfigManager.save()
updateSelectedAccount(authAcc) updateSelectedAccount(authAcc)
if(getCurrentView() === VIEWS.settings) {
await prepareSettings()
}
toggleOverlay(false) toggleOverlay(false)
validateSelectedAccount() validateSelectedAccount()
return return
@ -210,9 +207,6 @@ document.getElementById('accountSelectConfirm').addEventListener('click', async
const authAcc = ConfigManager.setSelectedAccount(listings[0].getAttribute('uuid')) const authAcc = ConfigManager.setSelectedAccount(listings[0].getAttribute('uuid'))
ConfigManager.save() ConfigManager.save()
updateSelectedAccount(authAcc) updateSelectedAccount(authAcc)
if(getCurrentView() === VIEWS.settings) {
await prepareSettings()
}
toggleOverlay(false) toggleOverlay(false)
validateSelectedAccount() validateSelectedAccount()
} }
@ -267,21 +261,21 @@ function setAccountListingHandlers(){
}) })
} }
async function populateServerListings(){ function populateServerListings(){
const distro = await DistroAPI.getDistribution() const distro = DistroManager.getDistribution()
const giaSel = ConfigManager.getSelectedServer() const giaSel = ConfigManager.getSelectedServer()
const servers = distro.servers const servers = distro.getServers()
let htmlString = '' let htmlString = ''
for(const serv of servers){ for(const serv of servers){
htmlString += `<button class="serverListing" servid="${serv.rawServer.id}" ${serv.rawServer.id === giaSel ? 'selected' : ''}> htmlString += `<button class="serverListing" servid="${serv.getID()}" ${serv.getID() === giaSel ? 'selected' : ''}>
<img class="serverListingImg" src="${serv.rawServer.icon}"/> <img class="serverListingImg" src="${serv.getIcon()}"/>
<div class="serverListingDetails"> <div class="serverListingDetails">
<span class="serverListingName">${serv.rawServer.name}</span> <span class="serverListingName">${serv.getName()}</span>
<span class="serverListingDescription">${serv.rawServer.description}</span> <span class="serverListingDescription">${serv.getDescription()}</span>
<div class="serverListingInfo"> <div class="serverListingInfo">
<div class="serverListingVersion">${serv.rawServer.minecraftVersion}</div> <div class="serverListingVersion">${serv.getMinecraftVersion()}</div>
<div class="serverListingRevision">${serv.rawServer.version}</div> <div class="serverListingRevision">${serv.getVersion()}</div>
${serv.rawServer.mainServer ? `<div class="serverListingStarWrapper"> ${serv.isMainServer() ? `<div class="serverListingStarWrapper">
<svg id="Layer_1" viewBox="0 0 107.45 104.74" width="20px" height="20px"> <svg id="Layer_1" viewBox="0 0 107.45 104.74" width="20px" height="20px">
<defs> <defs>
<style>.cls-1{fill:#fff;}.cls-2{fill:none;stroke:#fff;stroke-miterlimit:10;}</style> <style>.cls-1{fill:#fff;}.cls-2{fill:none;stroke:#fff;stroke-miterlimit:10;}</style>
@ -289,7 +283,7 @@ async function populateServerListings(){
<path class="cls-1" d="M100.93,65.54C89,62,68.18,55.65,63.54,52.13c2.7-5.23,18.8-19.2,28-27.55C81.36,31.74,63.74,43.87,58.09,45.3c-2.41-5.37-3.61-26.52-4.37-39-.77,12.46-2,33.64-4.36,39-5.7-1.46-23.3-13.57-33.49-20.72,9.26,8.37,25.39,22.36,28,27.55C39.21,55.68,18.47,62,6.52,65.55c12.32-2,33.63-6.06,39.34-4.9-.16,5.87-8.41,26.16-13.11,37.69,6.1-10.89,16.52-30.16,21-33.9,4.5,3.79,14.93,23.09,21,34C70,86.84,61.73,66.48,61.59,60.65,67.36,59.49,88.64,63.52,100.93,65.54Z"/> <path class="cls-1" d="M100.93,65.54C89,62,68.18,55.65,63.54,52.13c2.7-5.23,18.8-19.2,28-27.55C81.36,31.74,63.74,43.87,58.09,45.3c-2.41-5.37-3.61-26.52-4.37-39-.77,12.46-2,33.64-4.36,39-5.7-1.46-23.3-13.57-33.49-20.72,9.26,8.37,25.39,22.36,28,27.55C39.21,55.68,18.47,62,6.52,65.55c12.32-2,33.63-6.06,39.34-4.9-.16,5.87-8.41,26.16-13.11,37.69,6.1-10.89,16.52-30.16,21-33.9,4.5,3.79,14.93,23.09,21,34C70,86.84,61.73,66.48,61.59,60.65,67.36,59.49,88.64,63.52,100.93,65.54Z"/>
<circle class="cls-2" cx="53.73" cy="53.9" r="38"/> <circle class="cls-2" cx="53.73" cy="53.9" r="38"/>
</svg> </svg>
<span class="serverListingStarTooltip">${Lang.queryJS('settings.serverListing.mainServer')}</span> <span class="serverListingStarTooltip">Main Server</span>
</div>` : ''} </div>` : ''}
</div> </div>
</div> </div>
@ -305,7 +299,7 @@ function populateAccountListings(){
let htmlString = '' let htmlString = ''
for(let i=0; i<accounts.length; i++){ for(let i=0; i<accounts.length; i++){
htmlString += `<button class="accountListing" uuid="${accounts[i].uuid}" ${i===0 ? 'selected' : ''}> htmlString += `<button class="accountListing" uuid="${accounts[i].uuid}" ${i===0 ? 'selected' : ''}>
<img src="https://mc-heads.net/head/${accounts[i].uuid}/40"> <img src="https://crafatar.com/renders/head/${accounts[i].uuid}?scale=2&default=MHF_Steve&overlay">
<div class="accountListingName">${accounts[i].displayName}</div> <div class="accountListingName">${accounts[i].displayName}</div>
</button>` </button>`
} }
@ -313,8 +307,8 @@ function populateAccountListings(){
} }
async function prepareServerSelectionList(){ function prepareServerSelectionList(){
await populateServerListings() populateServerListings()
setServerListingHandlers() setServerListingHandlers()
} }

View File

@ -2,8 +2,8 @@
const os = require('os') const os = require('os')
const semver = require('semver') const semver = require('semver')
const DropinModUtil = require('./assets/js/dropinmodutil') const { JavaGuard } = require('./../assetguard')
const { MSFT_OPCODE, MSFT_REPLY_TYPE, MSFT_ERROR } = require('./assets/js/ipcconstants') const DropinModUtil = require('./../dropinmodutil')
const settingsState = { const settingsState = {
invalid: new Set() invalid: new Set()
@ -42,34 +42,15 @@ bindSettingsSelect()
function bindFileSelectors(){ function bindFileSelectors(){
for(let ele of document.getElementsByClassName('settingsFileSelButton')){ for(let ele of document.getElementsByClassName('settingsFileSelSel')){
if(ele.id === 'settingsJavaExecSel'){
ele.onclick = async e => { ele.onchange = (e) => {
const isJavaExecSel = ele.id === 'settingsJavaExecSel' ele.previousElementSibling.value = ele.files[0].path
const directoryDialog = ele.hasAttribute('dialogDirectory') && ele.getAttribute('dialogDirectory') == 'true' populateJavaExecDetails(ele.previousElementSibling.value)
const properties = directoryDialog ? ['openDirectory', 'createDirectory'] : ['openFile']
const options = {
properties
}
if(ele.hasAttribute('dialogTitle')) {
options.title = ele.getAttribute('dialogTitle')
}
if(isJavaExecSel && process.platform === 'win32') {
options.filters = [
{ name: Lang.queryJS('settings.fileSelectors.executables'), extensions: ['exe'] },
{ name: Lang.queryJS('settings.fileSelectors.allFiles'), extensions: ['*'] }
]
}
const res = await remote.dialog.showOpenDialog(remote.getCurrentWindow(), options)
if(!res.canceled) {
ele.previousElementSibling.value = res.filePaths[0]
if(isJavaExecSel) {
await populateJavaExecDetails(ele.previousElementSibling.value)
} }
} else {
ele.onchange = (e) => {
ele.previousElementSibling.value = ele.files[0].path
} }
} }
} }
@ -85,7 +66,7 @@ bindFileSelectors()
/** /**
* Bind value validators to the settings UI elements. These will * Bind value validators to the settings UI elements. These will
* validate against the criteria defined in the ConfigManager (if * validate against the criteria defined in the ConfigManager (if
* any). If the value is invalid, the UI will reflect this and saving * and). If the value is invalid, the UI will reflect this and saving
* will be disabled until the value is corrected. This is an automated * will be disabled until the value is corrected. This is an automated
* process. More complex UI may need to be bound separately. * process. More complex UI may need to be bound separately.
*/ */
@ -122,54 +103,48 @@ function initSettingsValidators(){
/** /**
* Load configuration values onto the UI. This is an automated process. * Load configuration values onto the UI. This is an automated process.
*/ */
async function initSettingsValues(){ function initSettingsValues(){
const sEls = document.getElementById('settingsContainer').querySelectorAll('[cValue]') const sEls = document.getElementById('settingsContainer').querySelectorAll('[cValue]')
Array.from(sEls).map((v, index, arr) => {
for(const v of sEls) {
const cVal = v.getAttribute('cValue') const cVal = v.getAttribute('cValue')
const serverDependent = v.hasAttribute('serverDependent') // Means the first argument is the server id.
const gFn = ConfigManager['get' + cVal] const gFn = ConfigManager['get' + cVal]
const gFnOpts = []
if(serverDependent) {
gFnOpts.push(ConfigManager.getSelectedServer())
}
if(typeof gFn === 'function'){ if(typeof gFn === 'function'){
if(v.tagName === 'INPUT'){ if(v.tagName === 'INPUT'){
if(v.type === 'number' || v.type === 'text'){ if(v.type === 'number' || v.type === 'text'){
// Special Conditions // Special Conditions
if(cVal === 'JavaExecutable'){ if(cVal === 'JavaExecutable'){
v.value = gFn.apply(null, gFnOpts) populateJavaExecDetails(v.value)
await populateJavaExecDetails(v.value) v.value = gFn()
} else if (cVal === 'DataDirectory'){ } else if (cVal === 'DataDirectory'){
v.value = gFn.apply(null, gFnOpts) v.value = gFn()
} else if(cVal === 'JVMOptions'){ } else if(cVal === 'JVMOptions'){
v.value = gFn.apply(null, gFnOpts).join(' ') v.value = gFn().join(' ')
} else { } else {
v.value = gFn.apply(null, gFnOpts) v.value = gFn()
} }
} else if(v.type === 'checkbox'){ } else if(v.type === 'checkbox'){
v.checked = gFn.apply(null, gFnOpts) v.checked = gFn()
} }
} else if(v.tagName === 'DIV'){ } else if(v.tagName === 'DIV'){
if(v.classList.contains('rangeSlider')){ if(v.classList.contains('rangeSlider')){
// Special Conditions // Special Conditions
if(cVal === 'MinRAM' || cVal === 'MaxRAM'){ if(cVal === 'MinRAM' || cVal === 'MaxRAM'){
let val = gFn.apply(null, gFnOpts) let val = gFn()
if(val.endsWith('M')){ if(val.endsWith('M')){
val = Number(val.substring(0, val.length-1))/1024 val = Number(val.substring(0, val.length-1))/1000
} else { } else {
val = Number.parseFloat(val) val = Number.parseFloat(val)
} }
v.setAttribute('value', val) v.setAttribute('value', val)
} else { } else {
v.setAttribute('value', Number.parseFloat(gFn.apply(null, gFnOpts))) v.setAttribute('value', Number.parseFloat(gFn()))
}
} }
} }
} }
} }
})
} }
/** /**
@ -179,31 +154,18 @@ function saveSettingsValues(){
const sEls = document.getElementById('settingsContainer').querySelectorAll('[cValue]') const sEls = document.getElementById('settingsContainer').querySelectorAll('[cValue]')
Array.from(sEls).map((v, index, arr) => { Array.from(sEls).map((v, index, arr) => {
const cVal = v.getAttribute('cValue') const cVal = v.getAttribute('cValue')
const serverDependent = v.hasAttribute('serverDependent') // Means the first argument is the server id.
const sFn = ConfigManager['set' + cVal] const sFn = ConfigManager['set' + cVal]
const sFnOpts = []
if(serverDependent) {
sFnOpts.push(ConfigManager.getSelectedServer())
}
if(typeof sFn === 'function'){ if(typeof sFn === 'function'){
if(v.tagName === 'INPUT'){ if(v.tagName === 'INPUT'){
if(v.type === 'number' || v.type === 'text'){ if(v.type === 'number' || v.type === 'text'){
// Special Conditions // Special Conditions
if(cVal === 'JVMOptions'){ if(cVal === 'JVMOptions'){
if(!v.value.trim()) { sFn(v.value.split(' '))
sFnOpts.push([])
sFn.apply(null, sFnOpts)
} else { } else {
sFnOpts.push(v.value.trim().split(/\s+/)) sFn(v.value)
sFn.apply(null, sFnOpts)
}
} else {
sFnOpts.push(v.value)
sFn.apply(null, sFnOpts)
} }
} else if(v.type === 'checkbox'){ } else if(v.type === 'checkbox'){
sFnOpts.push(v.checked) sFn(v.checked)
sFn.apply(null, sFnOpts)
// Special Conditions // Special Conditions
if(cVal === 'AllowPrerelease'){ if(cVal === 'AllowPrerelease'){
changeAllowPrerelease(v.checked) changeAllowPrerelease(v.checked)
@ -215,16 +177,14 @@ function saveSettingsValues(){
if(cVal === 'MinRAM' || cVal === 'MaxRAM'){ if(cVal === 'MinRAM' || cVal === 'MaxRAM'){
let val = Number(v.getAttribute('value')) let val = Number(v.getAttribute('value'))
if(val%1 > 0){ if(val%1 > 0){
val = val*1024 + 'M' val = val*1000 + 'M'
} else { } else {
val = val + 'G' val = val + 'G'
} }
sFnOpts.push(val) sFn(val)
sFn.apply(null, sFnOpts)
} else { } else {
sFnOpts.push(v.getAttribute('value')) sFn(v.getAttribute('value'))
sFn.apply(null, sFnOpts)
} }
} }
} }
@ -321,17 +281,13 @@ function settingsSaveDisabled(v){
settingsNavDone.disabled = v settingsNavDone.disabled = v
} }
function fullSettingsSave() { /* Closes the settings view and saves all data. */
settingsNavDone.onclick = () => {
saveSettingsValues() saveSettingsValues()
saveModConfiguration() saveModConfiguration()
ConfigManager.save() ConfigManager.save()
saveDropinModConfiguration() saveDropinModConfiguration()
saveShaderpackSettings() saveShaderpackSettings()
}
/* Closes the settings view and saves all data. */
settingsNavDone.onclick = () => {
fullSettingsSave()
switchView(getCurrentView(), VIEWS.landing) switchView(getCurrentView(), VIEWS.landing)
} }
@ -339,11 +295,8 @@ settingsNavDone.onclick = () => {
* Account Management Tab * Account Management Tab
*/ */
const msftLoginLogger = LoggerUtil.getLogger('Microsoft Login') // Bind the add account button.
const msftLogoutLogger = LoggerUtil.getLogger('Microsoft Logout') document.getElementById('settingsAddAccount').onclick = (e) => {
// Bind the add mojang account button.
document.getElementById('settingsAddMojangAccount').onclick = (e) => {
switchView(getCurrentView(), VIEWS.login, 500, 500, () => { switchView(getCurrentView(), VIEWS.login, 500, 500, () => {
loginViewOnCancel = VIEWS.settings loginViewOnCancel = VIEWS.settings
loginViewOnSuccess = VIEWS.settings loginViewOnSuccess = VIEWS.settings
@ -351,99 +304,6 @@ document.getElementById('settingsAddMojangAccount').onclick = (e) => {
}) })
} }
// Bind the add microsoft account button.
document.getElementById('settingsAddMicrosoftAccount').onclick = (e) => {
switchView(getCurrentView(), VIEWS.waiting, 500, 500, () => {
ipcRenderer.send(MSFT_OPCODE.OPEN_LOGIN, VIEWS.settings, VIEWS.settings)
})
}
// Bind reply for Microsoft Login.
ipcRenderer.on(MSFT_OPCODE.REPLY_LOGIN, (_, ...arguments_) => {
if (arguments_[0] === MSFT_REPLY_TYPE.ERROR) {
const viewOnClose = arguments_[2]
console.log(arguments_)
switchView(getCurrentView(), viewOnClose, 500, 500, () => {
if(arguments_[1] === MSFT_ERROR.NOT_FINISHED) {
// User cancelled.
msftLoginLogger.info('Login cancelled by user.')
return
}
// Unexpected error.
setOverlayContent(
Lang.queryJS('settings.msftLogin.errorTitle'),
Lang.queryJS('settings.msftLogin.errorMessage'),
Lang.queryJS('settings.msftLogin.okButton')
)
setOverlayHandler(() => {
toggleOverlay(false)
})
toggleOverlay(true)
})
} else if(arguments_[0] === MSFT_REPLY_TYPE.SUCCESS) {
const queryMap = arguments_[1]
const viewOnClose = arguments_[2]
// Error from request to Microsoft.
if (Object.prototype.hasOwnProperty.call(queryMap, 'error')) {
switchView(getCurrentView(), viewOnClose, 500, 500, () => {
// TODO Dont know what these errors are. Just show them I guess.
// This is probably if you messed up the app registration with Azure.
let error = queryMap.error // Error might be 'access_denied' ?
let errorDesc = queryMap.error_description
console.log('Error getting authCode, is Azure application registered correctly?')
console.log(error)
console.log(errorDesc)
console.log('Full query map: ', queryMap)
setOverlayContent(
error,
errorDesc,
Lang.queryJS('settings.msftLogin.okButton')
)
setOverlayHandler(() => {
toggleOverlay(false)
})
toggleOverlay(true)
})
} else {
msftLoginLogger.info('Acquired authCode, proceeding with authentication.')
const authCode = queryMap.code
AuthManager.addMicrosoftAccount(authCode).then(value => {
updateSelectedAccount(value)
switchView(getCurrentView(), viewOnClose, 500, 500, async () => {
await prepareSettings()
})
})
.catch((displayableError) => {
let actualDisplayableError
if(isDisplayableError(displayableError)) {
msftLoginLogger.error('Error while logging in.', displayableError)
actualDisplayableError = displayableError
} else {
// Uh oh.
msftLoginLogger.error('Unhandled error during login.', displayableError)
actualDisplayableError = Lang.queryJS('login.error.unknown')
}
switchView(getCurrentView(), viewOnClose, 500, 500, () => {
setOverlayContent(actualDisplayableError.title, actualDisplayableError.desc, Lang.queryJS('login.tryAgain'))
setOverlayHandler(() => {
toggleOverlay(false)
})
toggleOverlay(true)
})
})
}
}
})
/** /**
* Bind functionality for the account selection buttons. If another account * Bind functionality for the account selection buttons. If another account
* is selected, the UI of the previously selected account will be updated. * is selected, the UI of the previously selected account will be updated.
@ -458,11 +318,11 @@ function bindAuthAccountSelect(){
for(let i=0; i<selectBtns.length; i++){ for(let i=0; i<selectBtns.length; i++){
if(selectBtns[i].hasAttribute('selected')){ if(selectBtns[i].hasAttribute('selected')){
selectBtns[i].removeAttribute('selected') selectBtns[i].removeAttribute('selected')
selectBtns[i].innerHTML = Lang.queryJS('settings.authAccountSelect.selectButton') selectBtns[i].innerHTML = 'Select Account'
} }
} }
val.setAttribute('selected', '') val.setAttribute('selected', '')
val.innerHTML = Lang.queryJS('settings.authAccountSelect.selectedButton') val.innerHTML = 'Selected Account &#10004;'
setSelectedAccount(val.closest('.settingsAuthAccount').getAttribute('uuid')) setSelectedAccount(val.closest('.settingsAuthAccount').getAttribute('uuid'))
} }
}) })
@ -480,14 +340,15 @@ function bindAuthAccountLogOut(){
if(Object.keys(ConfigManager.getAuthAccounts()).length === 1){ if(Object.keys(ConfigManager.getAuthAccounts()).length === 1){
isLastAccount = true isLastAccount = true
setOverlayContent( setOverlayContent(
Lang.queryJS('settings.authAccountLogout.lastAccountWarningTitle'), 'Warning<br>This is Your Last Account',
Lang.queryJS('settings.authAccountLogout.lastAccountWarningMessage'), 'In order to use the launcher you must be logged into at least one account. You will need to login again after.<br><br>Are you sure you want to log out?',
Lang.queryJS('settings.authAccountLogout.confirmButton'), 'I\'m Sure',
Lang.queryJS('settings.authAccountLogout.cancelButton') 'Cancel'
) )
setOverlayHandler(() => { setOverlayHandler(() => {
processLogOut(val, isLastAccount) processLogOut(val, isLastAccount)
toggleOverlay(false) toggleOverlay(false)
switchView(getCurrentView(), VIEWS.login)
}) })
setDismissHandler(() => { setDismissHandler(() => {
toggleOverlay(false) toggleOverlay(false)
@ -501,7 +362,6 @@ function bindAuthAccountLogOut(){
}) })
} }
let msAccDomElementCache
/** /**
* Process a log out. * Process a log out.
* *
@ -512,91 +372,19 @@ function processLogOut(val, isLastAccount){
const parent = val.closest('.settingsAuthAccount') const parent = val.closest('.settingsAuthAccount')
const uuid = parent.getAttribute('uuid') const uuid = parent.getAttribute('uuid')
const prevSelAcc = ConfigManager.getSelectedAccount() const prevSelAcc = ConfigManager.getSelectedAccount()
const targetAcc = ConfigManager.getAuthAccount(uuid) AuthManager.removeAccount(uuid).then(() => {
if(targetAcc.type === 'microsoft') {
msAccDomElementCache = parent
switchView(getCurrentView(), VIEWS.waiting, 500, 500, () => {
ipcRenderer.send(MSFT_OPCODE.OPEN_LOGOUT, uuid, isLastAccount)
})
} else {
AuthManager.removeMojangAccount(uuid).then(() => {
if(!isLastAccount && uuid === prevSelAcc.uuid){ if(!isLastAccount && uuid === prevSelAcc.uuid){
const selAcc = ConfigManager.getSelectedAccount() const selAcc = ConfigManager.getSelectedAccount()
refreshAuthAccountSelected(selAcc.uuid) refreshAuthAccountSelected(selAcc.uuid)
updateSelectedAccount(selAcc) updateSelectedAccount(selAcc)
validateSelectedAccount() validateSelectedAccount()
} }
if(isLastAccount) {
loginOptionsCancelEnabled(false)
loginOptionsViewOnLoginSuccess = VIEWS.settings
loginOptionsViewOnLoginCancel = VIEWS.loginOptions
switchView(getCurrentView(), VIEWS.loginOptions)
}
}) })
$(parent).fadeOut(250, () => { $(parent).fadeOut(250, () => {
parent.remove() parent.remove()
}) })
}
} }
// Bind reply for Microsoft Logout.
ipcRenderer.on(MSFT_OPCODE.REPLY_LOGOUT, (_, ...arguments_) => {
if (arguments_[0] === MSFT_REPLY_TYPE.ERROR) {
switchView(getCurrentView(), VIEWS.settings, 500, 500, () => {
if(arguments_.length > 1 && arguments_[1] === MSFT_ERROR.NOT_FINISHED) {
// User cancelled.
msftLogoutLogger.info('Logout cancelled by user.')
return
}
// Unexpected error.
setOverlayContent(
Lang.queryJS('settings.msftLogout.errorTitle'),
Lang.queryJS('settings.msftLogout.errorMessage'),
Lang.queryJS('settings.msftLogout.okButton')
)
setOverlayHandler(() => {
toggleOverlay(false)
})
toggleOverlay(true)
})
} else if(arguments_[0] === MSFT_REPLY_TYPE.SUCCESS) {
const uuid = arguments_[1]
const isLastAccount = arguments_[2]
const prevSelAcc = ConfigManager.getSelectedAccount()
msftLogoutLogger.info('Logout Successful. uuid:', uuid)
AuthManager.removeMicrosoftAccount(uuid)
.then(() => {
if(!isLastAccount && uuid === prevSelAcc.uuid){
const selAcc = ConfigManager.getSelectedAccount()
refreshAuthAccountSelected(selAcc.uuid)
updateSelectedAccount(selAcc)
validateSelectedAccount()
}
if(isLastAccount) {
loginOptionsCancelEnabled(false)
loginOptionsViewOnLoginSuccess = VIEWS.settings
loginOptionsViewOnLoginCancel = VIEWS.loginOptions
switchView(getCurrentView(), VIEWS.loginOptions)
}
if(msAccDomElementCache) {
msAccDomElementCache.remove()
msAccDomElementCache = null
}
})
.finally(() => {
if(!isLastAccount) {
switchView(getCurrentView(), VIEWS.settings, 500, 500)
}
})
}
})
/** /**
* Refreshes the status of the selected account on the auth account * Refreshes the status of the selected account on the auth account
* elements. * elements.
@ -608,18 +396,17 @@ function refreshAuthAccountSelected(uuid){
const selBtn = val.getElementsByClassName('settingsAuthAccountSelect')[0] const selBtn = val.getElementsByClassName('settingsAuthAccountSelect')[0]
if(uuid === val.getAttribute('uuid')){ if(uuid === val.getAttribute('uuid')){
selBtn.setAttribute('selected', '') selBtn.setAttribute('selected', '')
selBtn.innerHTML = Lang.queryJS('settings.authAccountSelect.selectedButton') selBtn.innerHTML = 'Selected Account &#10004;'
} else { } else {
if(selBtn.hasAttribute('selected')){ if(selBtn.hasAttribute('selected')){
selBtn.removeAttribute('selected') selBtn.removeAttribute('selected')
} }
selBtn.innerHTML = Lang.queryJS('settings.authAccountSelect.selectButton') selBtn.innerHTML = 'Select Account'
} }
}) })
} }
const settingsCurrentMicrosoftAccounts = document.getElementById('settingsCurrentMicrosoftAccounts') const settingsCurrentAccounts = document.getElementById('settingsCurrentAccounts')
const settingsCurrentMojangAccounts = document.getElementById('settingsCurrentMojangAccounts')
/** /**
* Add auth account elements for each one stored in the authentication database. * Add auth account elements for each one stored in the authentication database.
@ -632,46 +419,36 @@ function populateAuthAccounts(){
} }
const selectedUUID = ConfigManager.getSelectedAccount().uuid const selectedUUID = ConfigManager.getSelectedAccount().uuid
let microsoftAuthAccountStr = '' let authAccountStr = ''
let mojangAuthAccountStr = ''
authKeys.forEach((val) => { authKeys.map((val) => {
const acc = authAccounts[val] const acc = authAccounts[val]
authAccountStr += `<div class="settingsAuthAccount" uuid="${acc.uuid}">
const accHtml = `<div class="settingsAuthAccount" uuid="${acc.uuid}">
<div class="settingsAuthAccountLeft"> <div class="settingsAuthAccountLeft">
<img class="settingsAuthAccountImage" alt="${acc.displayName}" src="https://mc-heads.net/body/${acc.uuid}/60"> <img class="settingsAuthAccountImage" alt="${acc.displayName}" src="https://crafatar.com/renders/body/${acc.uuid}?scale=3&default=MHF_Steve&overlay">
</div> </div>
<div class="settingsAuthAccountRight"> <div class="settingsAuthAccountRight">
<div class="settingsAuthAccountDetails"> <div class="settingsAuthAccountDetails">
<div class="settingsAuthAccountDetailPane"> <div class="settingsAuthAccountDetailPane">
<div class="settingsAuthAccountDetailTitle">${Lang.queryJS('settings.authAccountPopulate.username')}</div> <div class="settingsAuthAccountDetailTitle">Username</div>
<div class="settingsAuthAccountDetailValue">${acc.displayName}</div> <div class="settingsAuthAccountDetailValue">${acc.displayName}</div>
</div> </div>
<div class="settingsAuthAccountDetailPane"> <div class="settingsAuthAccountDetailPane">
<div class="settingsAuthAccountDetailTitle">${Lang.queryJS('settings.authAccountPopulate.uuid')}</div> <div class="settingsAuthAccountDetailTitle">UUID</div>
<div class="settingsAuthAccountDetailValue">${acc.uuid}</div> <div class="settingsAuthAccountDetailValue">${acc.uuid}</div>
</div> </div>
</div> </div>
<div class="settingsAuthAccountActions"> <div class="settingsAuthAccountActions">
<button class="settingsAuthAccountSelect" ${selectedUUID === acc.uuid ? 'selected>' + Lang.queryJS('settings.authAccountPopulate.selectedAccount') : '>' + Lang.queryJS('settings.authAccountPopulate.selectAccount')}</button> <button class="settingsAuthAccountSelect" ${selectedUUID === acc.uuid ? 'selected>Selected Account &#10004;' : '>Select Account'}</button>
<div class="settingsAuthAccountWrapper"> <div class="settingsAuthAccountWrapper">
<button class="settingsAuthAccountLogOut">${Lang.queryJS('settings.authAccountPopulate.logout')}</button> <button class="settingsAuthAccountLogOut">Log Out</button>
</div> </div>
</div> </div>
</div> </div>
</div>` </div>`
if(acc.type === 'microsoft') {
microsoftAuthAccountStr += accHtml
} else {
mojangAuthAccountStr += accHtml
}
}) })
settingsCurrentMicrosoftAccounts.innerHTML = microsoftAuthAccountStr settingsCurrentAccounts.innerHTML = authAccountStr
settingsCurrentMojangAccounts.innerHTML = mojangAuthAccountStr
} }
/** /**
@ -710,13 +487,13 @@ const settingsModsContainer = document.getElementById('settingsModsContainer')
/** /**
* Resolve and update the mods on the UI. * Resolve and update the mods on the UI.
*/ */
async function resolveModsForUI(){ function resolveModsForUI(){
const serv = ConfigManager.getSelectedServer() const serv = ConfigManager.getSelectedServer()
const distro = await DistroAPI.getDistribution() const distro = DistroManager.getDistribution()
const servConf = ConfigManager.getModConfiguration(serv) const servConf = ConfigManager.getModConfiguration(serv)
const modStr = parseModulesForUI(distro.getServerById(serv).modules, false, servConf.mods) const modStr = parseModulesForUI(distro.getServer(serv).getModules(), false, servConf.mods)
document.getElementById('settingsReqModsContent').innerHTML = modStr.reqMods document.getElementById('settingsReqModsContent').innerHTML = modStr.reqMods
document.getElementById('settingsOptModsContent').innerHTML = modStr.optMods document.getElementById('settingsOptModsContent').innerHTML = modStr.optMods
@ -736,17 +513,17 @@ function parseModulesForUI(mdls, submodules, servConf){
for(const mdl of mdls){ for(const mdl of mdls){
if(mdl.rawModule.type === Type.ForgeMod || mdl.rawModule.type === Type.LiteMod || mdl.rawModule.type === Type.LiteLoader || mdl.rawModule.type === Type.FabricMod){ if(mdl.getType() === DistroManager.Types.ForgeMod || mdl.getType() === DistroManager.Types.LiteMod || mdl.getType() === DistroManager.Types.LiteLoader){
if(mdl.getRequired().value){ if(mdl.getRequired().isRequired()){
reqMods += `<div id="${mdl.getVersionlessMavenIdentifier()}" class="settingsBaseMod settings${submodules ? 'Sub' : ''}Mod" enabled> reqMods += `<div id="${mdl.getVersionlessID()}" class="settingsBaseMod settings${submodules ? 'Sub' : ''}Mod" enabled>
<div class="settingsModContent"> <div class="settingsModContent">
<div class="settingsModMainWrapper"> <div class="settingsModMainWrapper">
<div class="settingsModStatus"></div> <div class="settingsModStatus"></div>
<div class="settingsModDetails"> <div class="settingsModDetails">
<span class="settingsModName">${mdl.rawModule.name}</span> <span class="settingsModName">${mdl.getName()}</span>
<span class="settingsModVersion">v${mdl.mavenComponents.version}</span> <span class="settingsModVersion">v${mdl.getVersion()}</span>
</div> </div>
</div> </div>
<label class="toggleSwitch" reqmod> <label class="toggleSwitch" reqmod>
@ -754,32 +531,32 @@ function parseModulesForUI(mdls, submodules, servConf){
<span class="toggleSwitchSlider"></span> <span class="toggleSwitchSlider"></span>
</label> </label>
</div> </div>
${mdl.subModules.length > 0 ? `<div class="settingsSubModContainer"> ${mdl.hasSubModules() ? `<div class="settingsSubModContainer">
${Object.values(parseModulesForUI(mdl.subModules, true, servConf[mdl.getVersionlessMavenIdentifier()])).join('')} ${Object.values(parseModulesForUI(mdl.getSubModules(), true, servConf[mdl.getVersionlessID()])).join('')}
</div>` : ''} </div>` : ''}
</div>` </div>`
} else { } else {
const conf = servConf[mdl.getVersionlessMavenIdentifier()] const conf = servConf[mdl.getVersionlessID()]
const val = typeof conf === 'object' ? conf.value : conf const val = typeof conf === 'object' ? conf.value : conf
optMods += `<div id="${mdl.getVersionlessMavenIdentifier()}" class="settingsBaseMod settings${submodules ? 'Sub' : ''}Mod" ${val ? 'enabled' : ''}> optMods += `<div id="${mdl.getVersionlessID()}" class="settingsBaseMod settings${submodules ? 'Sub' : ''}Mod" ${val ? 'enabled' : ''}>
<div class="settingsModContent"> <div class="settingsModContent">
<div class="settingsModMainWrapper"> <div class="settingsModMainWrapper">
<div class="settingsModStatus"></div> <div class="settingsModStatus"></div>
<div class="settingsModDetails"> <div class="settingsModDetails">
<span class="settingsModName">${mdl.rawModule.name}</span> <span class="settingsModName">${mdl.getName()}</span>
<span class="settingsModVersion">v${mdl.mavenComponents.version}</span> <span class="settingsModVersion">v${mdl.getVersion()}</span>
</div> </div>
</div> </div>
<label class="toggleSwitch"> <label class="toggleSwitch">
<input type="checkbox" formod="${mdl.getVersionlessMavenIdentifier()}" ${val ? 'checked' : ''}> <input type="checkbox" formod="${mdl.getVersionlessID()}" ${val ? 'checked' : ''}>
<span class="toggleSwitchSlider"></span> <span class="toggleSwitchSlider"></span>
</label> </label>
</div> </div>
${mdl.subModules.length > 0 ? `<div class="settingsSubModContainer"> ${mdl.hasSubModules() ? `<div class="settingsSubModContainer">
${Object.values(parseModulesForUI(mdl.subModules, true, conf.mods)).join('')} ${Object.values(parseModulesForUI(mdl.getSubModules(), true, conf.mods)).join('')}
</div>` : ''} </div>` : ''}
</div>` </div>`
@ -855,10 +632,10 @@ let CACHE_DROPIN_MODS
* Resolve any located drop-in mods for this server and * Resolve any located drop-in mods for this server and
* populate the results onto the UI. * populate the results onto the UI.
*/ */
async function resolveDropinModsForUI(){ function resolveDropinModsForUI(){
const serv = (await DistroAPI.getDistribution()).getServerById(ConfigManager.getSelectedServer()) const serv = DistroManager.getDistribution().getServer(ConfigManager.getSelectedServer())
CACHE_SETTINGS_MODS_DIR = path.join(ConfigManager.getInstanceDirectory(), serv.rawServer.id, 'mods') CACHE_SETTINGS_MODS_DIR = path.join(ConfigManager.getInstanceDirectory(), serv.getID(), 'mods')
CACHE_DROPIN_MODS = DropinModUtil.scanForDropinMods(CACHE_SETTINGS_MODS_DIR, serv.rawServer.minecraftVersion) CACHE_DROPIN_MODS = DropinModUtil.scanForDropinMods(CACHE_SETTINGS_MODS_DIR, serv.getMinecraftVersion())
let dropinMods = '' let dropinMods = ''
@ -870,7 +647,7 @@ async function resolveDropinModsForUI(){
<div class="settingsModDetails"> <div class="settingsModDetails">
<span class="settingsModName">${dropin.name}</span> <span class="settingsModName">${dropin.name}</span>
<div class="settingsDropinRemoveWrapper"> <div class="settingsDropinRemoveWrapper">
<button class="settingsDropinRemoveButton" remmod="${dropin.fullName}">${Lang.queryJS('settings.dropinMods.removeButton')}</button> <button class="settingsDropinRemoveButton" remmod="${dropin.fullName}">Remove</button>
</div> </div>
</div> </div>
</div> </div>
@ -891,16 +668,16 @@ async function resolveDropinModsForUI(){
function bindDropinModsRemoveButton(){ function bindDropinModsRemoveButton(){
const sEls = settingsModsContainer.querySelectorAll('[remmod]') const sEls = settingsModsContainer.querySelectorAll('[remmod]')
Array.from(sEls).map((v, index, arr) => { Array.from(sEls).map((v, index, arr) => {
v.onclick = async () => { v.onclick = () => {
const fullName = v.getAttribute('remmod') const fullName = v.getAttribute('remmod')
const res = await DropinModUtil.deleteDropinMod(CACHE_SETTINGS_MODS_DIR, fullName) const res = DropinModUtil.deleteDropinMod(CACHE_SETTINGS_MODS_DIR, fullName)
if(res){ if(res){
document.getElementById(fullName).remove() document.getElementById(fullName).remove()
} else { } else {
setOverlayContent( setOverlayContent(
Lang.queryJS('settings.dropinMods.deleteFailedTitle', { fullName }), `Failed to Delete<br>Drop-in Mod ${fullName}`,
Lang.queryJS('settings.dropinMods.deleteFailedMessage'), 'Make sure the file is not in use and try again.',
Lang.queryJS('settings.dropinMods.okButton') 'Okay'
) )
setOverlayHandler(null) setOverlayHandler(null)
toggleOverlay(true) toggleOverlay(true)
@ -931,12 +708,12 @@ function bindDropinModFileSystemButton(){
fsBtn.removeAttribute('drag') fsBtn.removeAttribute('drag')
} }
fsBtn.ondrop = async e => { fsBtn.ondrop = e => {
fsBtn.removeAttribute('drag') fsBtn.removeAttribute('drag')
e.preventDefault() e.preventDefault()
DropinModUtil.addDropinMods(e.dataTransfer.files, CACHE_SETTINGS_MODS_DIR) DropinModUtil.addDropinMods(e.dataTransfer.files, CACHE_SETTINGS_MODS_DIR)
await reloadDropinMods() reloadDropinMods()
} }
} }
@ -953,9 +730,9 @@ function saveDropinModConfiguration(){
DropinModUtil.toggleDropinMod(CACHE_SETTINGS_MODS_DIR, dropin.fullName, dropinUIEnabled).catch(err => { DropinModUtil.toggleDropinMod(CACHE_SETTINGS_MODS_DIR, dropin.fullName, dropinUIEnabled).catch(err => {
if(!isOverlayVisible()){ if(!isOverlayVisible()){
setOverlayContent( setOverlayContent(
Lang.queryJS('settings.dropinMods.failedToggleTitle'), 'Failed to Toggle<br>One or More Drop-in Mods',
err.message, err.message,
Lang.queryJS('settings.dropinMods.okButton') 'Okay'
) )
setOverlayHandler(null) setOverlayHandler(null)
toggleOverlay(true) toggleOverlay(true)
@ -968,18 +745,18 @@ function saveDropinModConfiguration(){
// Refresh the drop-in mods when F5 is pressed. // Refresh the drop-in mods when F5 is pressed.
// Only active on the mods tab. // Only active on the mods tab.
document.addEventListener('keydown', async (e) => { document.addEventListener('keydown', (e) => {
if(getCurrentView() === VIEWS.settings && selectedSettingsTab === 'settingsTabMods'){ if(getCurrentView() === VIEWS.settings && selectedSettingsTab === 'settingsTabMods'){
if(e.key === 'F5'){ if(e.key === 'F5'){
await reloadDropinMods() reloadDropinMods()
saveShaderpackSettings() saveShaderpackSettings()
await resolveShaderpacksForUI() resolveShaderpacksForUI()
} }
} }
}) })
async function reloadDropinMods(){ function reloadDropinMods(){
await resolveDropinModsForUI() resolveDropinModsForUI()
bindDropinModsRemoveButton() bindDropinModsRemoveButton()
bindDropinModFileSystemButton() bindDropinModFileSystemButton()
bindModsToggleSwitch() bindModsToggleSwitch()
@ -994,9 +771,9 @@ let CACHE_SELECTED_SHADERPACK
/** /**
* Load shaderpack information. * Load shaderpack information.
*/ */
async function resolveShaderpacksForUI(){ function resolveShaderpacksForUI(){
const serv = (await DistroAPI.getDistribution()).getServerById(ConfigManager.getSelectedServer()) const serv = DistroManager.getDistribution().getServer(ConfigManager.getSelectedServer())
CACHE_SETTINGS_INSTANCE_DIR = path.join(ConfigManager.getInstanceDirectory(), serv.rawServer.id) CACHE_SETTINGS_INSTANCE_DIR = path.join(ConfigManager.getInstanceDirectory(), serv.getID())
CACHE_SHADERPACKS = DropinModUtil.scanForShaderpacks(CACHE_SETTINGS_INSTANCE_DIR) CACHE_SHADERPACKS = DropinModUtil.scanForShaderpacks(CACHE_SETTINGS_INSTANCE_DIR)
CACHE_SELECTED_SHADERPACK = DropinModUtil.getEnabledShaderpack(CACHE_SETTINGS_INSTANCE_DIR) CACHE_SELECTED_SHADERPACK = DropinModUtil.getEnabledShaderpack(CACHE_SETTINGS_INSTANCE_DIR)
@ -1055,13 +832,13 @@ function bindShaderpackButton() {
spBtn.removeAttribute('drag') spBtn.removeAttribute('drag')
} }
spBtn.ondrop = async e => { spBtn.ondrop = e => {
spBtn.removeAttribute('drag') spBtn.removeAttribute('drag')
e.preventDefault() e.preventDefault()
DropinModUtil.addShaderpacks(e.dataTransfer.files, CACHE_SETTINGS_INSTANCE_DIR) DropinModUtil.addShaderpacks(e.dataTransfer.files, CACHE_SETTINGS_INSTANCE_DIR)
saveShaderpackSettings() saveShaderpackSettings()
await resolveShaderpacksForUI() resolveShaderpacksForUI()
} }
} }
@ -1070,19 +847,18 @@ function bindShaderpackButton() {
/** /**
* Load the currently selected server information onto the mods tab. * Load the currently selected server information onto the mods tab.
*/ */
async function loadSelectedServerOnModsTab(){ function loadSelectedServerOnModsTab(){
const serv = (await DistroAPI.getDistribution()).getServerById(ConfigManager.getSelectedServer()) const serv = DistroManager.getDistribution().getServer(ConfigManager.getSelectedServer())
for(const el of document.getElementsByClassName('settingsSelServContent')) { document.getElementById('settingsSelServContent').innerHTML = `
el.innerHTML = ` <img class="serverListingImg" src="${serv.getIcon()}"/>
<img class="serverListingImg" src="${serv.rawServer.icon}"/>
<div class="serverListingDetails"> <div class="serverListingDetails">
<span class="serverListingName">${serv.rawServer.name}</span> <span class="serverListingName">${serv.getName()}</span>
<span class="serverListingDescription">${serv.rawServer.description}</span> <span class="serverListingDescription">${serv.getDescription()}</span>
<div class="serverListingInfo"> <div class="serverListingInfo">
<div class="serverListingVersion">${serv.rawServer.minecraftVersion}</div> <div class="serverListingVersion">${serv.getMinecraftVersion()}</div>
<div class="serverListingRevision">${serv.rawServer.version}</div> <div class="serverListingRevision">${serv.getVersion()}</div>
${serv.rawServer.mainServer ? `<div class="serverListingStarWrapper"> ${serv.isMainServer() ? `<div class="serverListingStarWrapper">
<svg id="Layer_1" viewBox="0 0 107.45 104.74" width="20px" height="20px"> <svg id="Layer_1" viewBox="0 0 107.45 104.74" width="20px" height="20px">
<defs> <defs>
<style>.cls-1{fill:#fff;}.cls-2{fill:none;stroke:#fff;stroke-miterlimit:10;}</style> <style>.cls-1{fill:#fff;}.cls-2{fill:none;stroke:#fff;stroke-miterlimit:10;}</style>
@ -1090,20 +866,17 @@ async function loadSelectedServerOnModsTab(){
<path class="cls-1" d="M100.93,65.54C89,62,68.18,55.65,63.54,52.13c2.7-5.23,18.8-19.2,28-27.55C81.36,31.74,63.74,43.87,58.09,45.3c-2.41-5.37-3.61-26.52-4.37-39-.77,12.46-2,33.64-4.36,39-5.7-1.46-23.3-13.57-33.49-20.72,9.26,8.37,25.39,22.36,28,27.55C39.21,55.68,18.47,62,6.52,65.55c12.32-2,33.63-6.06,39.34-4.9-.16,5.87-8.41,26.16-13.11,37.69,6.1-10.89,16.52-30.16,21-33.9,4.5,3.79,14.93,23.09,21,34C70,86.84,61.73,66.48,61.59,60.65,67.36,59.49,88.64,63.52,100.93,65.54Z"/> <path class="cls-1" d="M100.93,65.54C89,62,68.18,55.65,63.54,52.13c2.7-5.23,18.8-19.2,28-27.55C81.36,31.74,63.74,43.87,58.09,45.3c-2.41-5.37-3.61-26.52-4.37-39-.77,12.46-2,33.64-4.36,39-5.7-1.46-23.3-13.57-33.49-20.72,9.26,8.37,25.39,22.36,28,27.55C39.21,55.68,18.47,62,6.52,65.55c12.32-2,33.63-6.06,39.34-4.9-.16,5.87-8.41,26.16-13.11,37.69,6.1-10.89,16.52-30.16,21-33.9,4.5,3.79,14.93,23.09,21,34C70,86.84,61.73,66.48,61.59,60.65,67.36,59.49,88.64,63.52,100.93,65.54Z"/>
<circle class="cls-2" cx="53.73" cy="53.9" r="38"/> <circle class="cls-2" cx="53.73" cy="53.9" r="38"/>
</svg> </svg>
<span class="serverListingStarTooltip">${Lang.queryJS('settings.serverListing.mainServer')}</span> <span class="serverListingStarTooltip">Main Server</span>
</div>` : ''} </div>` : ''}
</div> </div>
</div> </div>
` `
}
} }
// Bind functionality to the server switch button. // Bind functionality to the server switch button.
Array.from(document.getElementsByClassName('settingsSwitchServerButton')).forEach(el => { document.getElementById('settingsSwitchServerButton').addEventListener('click', (e) => {
el.addEventListener('click', async e => {
e.target.blur() e.target.blur()
await toggleServerSelection(true) toggleServerSelection(true)
})
}) })
/** /**
@ -1116,28 +889,28 @@ function saveAllModConfigurations(){
} }
/** /**
* Function to refresh the current tab whenever the selected * Function to refresh the mods tab whenever the selected
* server is changed. * server is changed.
*/ */
function animateSettingsTabRefresh(){ function animateModsTabRefresh(){
$(`#${selectedSettingsTab}`).fadeOut(500, async () => { $('#settingsTabMods').fadeOut(500, () => {
await prepareSettings() prepareModsTab()
$(`#${selectedSettingsTab}`).fadeIn(500) $('#settingsTabMods').fadeIn(500)
}) })
} }
/** /**
* Prepare the Mods tab for display. * Prepare the Mods tab for display.
*/ */
async function prepareModsTab(first){ function prepareModsTab(first){
await resolveModsForUI() resolveModsForUI()
await resolveDropinModsForUI() resolveDropinModsForUI()
await resolveShaderpacksForUI() resolveShaderpacksForUI()
bindDropinModsRemoveButton() bindDropinModsRemoveButton()
bindDropinModFileSystemButton() bindDropinModFileSystemButton()
bindShaderpackButton() bindShaderpackButton()
bindModsToggleSwitch() bindModsToggleSwitch()
await loadSelectedServerOnModsTab() loadSelectedServerOnModsTab()
} }
/** /**
@ -1152,8 +925,16 @@ const settingsMinRAMLabel = document.getElementById('settingsMinRAMLabel')
const settingsMemoryTotal = document.getElementById('settingsMemoryTotal') const settingsMemoryTotal = document.getElementById('settingsMemoryTotal')
const settingsMemoryAvail = document.getElementById('settingsMemoryAvail') const settingsMemoryAvail = document.getElementById('settingsMemoryAvail')
const settingsJavaExecDetails = document.getElementById('settingsJavaExecDetails') const settingsJavaExecDetails = document.getElementById('settingsJavaExecDetails')
const settingsJavaReqDesc = document.getElementById('settingsJavaReqDesc')
const settingsJvmOptsLink = document.getElementById('settingsJvmOptsLink') // Store maximum memory values.
const SETTINGS_MAX_MEMORY = ConfigManager.getAbsoluteMaxRAM()
const SETTINGS_MIN_MEMORY = ConfigManager.getAbsoluteMinRAM()
// Set the max and min values for the ranged sliders.
settingsMaxRAMRange.setAttribute('max', SETTINGS_MAX_MEMORY)
settingsMaxRAMRange.setAttribute('min', SETTINGS_MIN_MEMORY)
settingsMinRAMRange.setAttribute('max', SETTINGS_MAX_MEMORY)
settingsMinRAMRange.setAttribute('min', SETTINGS_MIN_MEMORY )
// Bind on change event for min memory container. // Bind on change event for min memory container.
settingsMinRAMRange.onchange = (e) => { settingsMinRAMRange.onchange = (e) => {
@ -1165,7 +946,7 @@ settingsMinRAMRange.onchange = (e) => {
// Get reference to range bar. // Get reference to range bar.
const bar = e.target.getElementsByClassName('rangeSliderBar')[0] const bar = e.target.getElementsByClassName('rangeSliderBar')[0]
// Calculate effective total memory. // Calculate effective total memory.
const max = os.totalmem()/1073741824 const max = (os.totalmem()-1000000000)/1000000000
// Change range bar color based on the selected value. // Change range bar color based on the selected value.
if(sMinV >= max/2){ if(sMinV >= max/2){
@ -1197,7 +978,7 @@ settingsMaxRAMRange.onchange = (e) => {
// Get reference to range bar. // Get reference to range bar.
const bar = e.target.getElementsByClassName('rangeSliderBar')[0] const bar = e.target.getElementsByClassName('rangeSliderBar')[0]
// Calculate effective total memory. // Calculate effective total memory.
const max = os.totalmem()/1073741824 const max = (os.totalmem()-1000000000)/1000000000
// Change range bar color based on the selected value. // Change range bar color based on the selected value.
if(sMaxV >= max/2){ if(sMaxV >= max/2){
@ -1325,8 +1106,8 @@ function updateRangedSlider(element, value, notch){
* Display the total and available RAM. * Display the total and available RAM.
*/ */
function populateMemoryStatus(){ function populateMemoryStatus(){
settingsMemoryTotal.innerHTML = Number((os.totalmem()-1073741824)/1073741824).toFixed(1) + 'G' settingsMemoryTotal.innerHTML = Number((os.totalmem()-1000000000)/1000000000).toFixed(1) + 'G'
settingsMemoryAvail.innerHTML = Number(os.freemem()/1073741824).toFixed(1) + 'G' settingsMemoryAvail.innerHTML = Number(os.freemem()/1000000000).toFixed(1) + 'G'
} }
/** /**
@ -1335,61 +1116,27 @@ function populateMemoryStatus(){
* *
* @param {string} execPath The executable path to populate against. * @param {string} execPath The executable path to populate against.
*/ */
async function populateJavaExecDetails(execPath){ function populateJavaExecDetails(execPath){
const server = (await DistroAPI.getDistribution()).getServerById(ConfigManager.getSelectedServer()) const jg = new JavaGuard(DistroManager.getDistribution().getServer(ConfigManager.getSelectedServer()).getMinecraftVersion())
jg._validateJavaBinary(execPath).then(v => {
const details = await validateSelectedJvm(ensureJavaDirIsRoot(execPath), server.effectiveJavaOptions.supported) if(v.valid){
if(v.version.major < 9) {
if(details != null) { settingsJavaExecDetails.innerHTML = `Selected: Java ${v.version.major} Update ${v.version.update} (x${v.arch})`
settingsJavaExecDetails.innerHTML = Lang.queryJS('settings.java.selectedJava', { version: details.semverStr, vendor: details.vendor })
} else { } else {
settingsJavaExecDetails.innerHTML = Lang.queryJS('settings.java.invalidSelection') settingsJavaExecDetails.innerHTML = `Selected: Java ${v.version.major}.${v.version.minor}.${v.version.revision} (x${v.arch})`
} }
} } else {
settingsJavaExecDetails.innerHTML = 'Invalid Selection'
function populateJavaReqDesc(server) {
settingsJavaReqDesc.innerHTML = Lang.queryJS('settings.java.requiresJava', { major: server.effectiveJavaOptions.suggestedMajor })
}
function populateJvmOptsLink(server) {
const major = server.effectiveJavaOptions.suggestedMajor
settingsJvmOptsLink.innerHTML = Lang.queryJS('settings.java.availableOptions', { major: major })
if(major >= 12) {
settingsJvmOptsLink.href = `https://docs.oracle.com/en/java/javase/${major}/docs/specs/man/java.html#extra-options-for-java`
} }
else if(major >= 11) { })
settingsJvmOptsLink.href = 'https://docs.oracle.com/en/java/javase/11/tools/java.html#GUID-3B1CE181-CD30-4178-9602-230B800D4FAE'
}
else if(major >= 9) {
settingsJvmOptsLink.href = `https://docs.oracle.com/javase/${major}/tools/java.htm`
}
else {
settingsJvmOptsLink.href = `https://docs.oracle.com/javase/${major}/docs/technotes/tools/${process.platform === 'win32' ? 'windows' : 'unix'}/java.html`
}
}
function bindMinMaxRam(server) {
// Store maximum memory values.
const SETTINGS_MAX_MEMORY = ConfigManager.getAbsoluteMaxRAM(server.rawServer.javaOptions?.ram)
const SETTINGS_MIN_MEMORY = ConfigManager.getAbsoluteMinRAM(server.rawServer.javaOptions?.ram)
// Set the max and min values for the ranged sliders.
settingsMaxRAMRange.setAttribute('max', SETTINGS_MAX_MEMORY)
settingsMaxRAMRange.setAttribute('min', SETTINGS_MIN_MEMORY)
settingsMinRAMRange.setAttribute('max', SETTINGS_MAX_MEMORY)
settingsMinRAMRange.setAttribute('min', SETTINGS_MIN_MEMORY)
} }
/** /**
* Prepare the Java tab for display. * Prepare the Java tab for display.
*/ */
async function prepareJavaTab(){ function prepareJavaTab(){
const server = (await DistroAPI.getDistribution()).getServerById(ConfigManager.getSelectedServer()) bindRangeSlider()
bindMinMaxRam(server)
bindRangeSlider(server)
populateMemoryStatus() populateMemoryStatus()
populateJavaReqDesc(server)
populateJvmOptsLink(server)
} }
/** /**
@ -1430,11 +1177,11 @@ function isPrerelease(version){
function populateVersionInformation(version, valueElement, titleElement, checkElement){ function populateVersionInformation(version, valueElement, titleElement, checkElement){
valueElement.innerHTML = version valueElement.innerHTML = version
if(isPrerelease(version)){ if(isPrerelease(version)){
titleElement.innerHTML = Lang.queryJS('settings.about.preReleaseTitle') titleElement.innerHTML = 'Pre-release'
titleElement.style.color = '#ff886d' titleElement.style.color = '#ff886d'
checkElement.style.background = '#ff886d' checkElement.style.background = '#ff886d'
} else { } else {
titleElement.innerHTML = Lang.queryJS('settings.about.stableReleaseTitle') titleElement.innerHTML = 'Stable Release'
titleElement.style.color = null titleElement.style.color = null
checkElement.style.background = null checkElement.style.background = null
} }
@ -1473,7 +1220,7 @@ function populateReleaseNotes(){
}, },
timeout: 2500 timeout: 2500
}).catch(err => { }).catch(err => {
settingsAboutChangelogText.innerHTML = Lang.queryJS('settings.about.releaseNotesFailed') settingsAboutChangelogText.innerHTML = 'Failed to load release notes.'
}) })
} }
@ -1521,27 +1268,27 @@ function settingsUpdateButtonStatus(text, disabled = false, handler = null){
*/ */
function populateSettingsUpdateInformation(data){ function populateSettingsUpdateInformation(data){
if(data != null){ if(data != null){
settingsUpdateTitle.innerHTML = isPrerelease(data.version) ? Lang.queryJS('settings.updates.newPreReleaseTitle') : Lang.queryJS('settings.updates.newReleaseTitle') settingsUpdateTitle.innerHTML = `New ${isPrerelease(data.version) ? 'Pre-release' : 'Release'} Available`
settingsUpdateChangelogCont.style.display = null settingsUpdateChangelogCont.style.display = null
settingsUpdateChangelogTitle.innerHTML = data.releaseName settingsUpdateChangelogTitle.innerHTML = data.releaseName
settingsUpdateChangelogText.innerHTML = data.releaseNotes settingsUpdateChangelogText.innerHTML = data.releaseNotes
populateVersionInformation(data.version, settingsUpdateVersionValue, settingsUpdateVersionTitle, settingsUpdateVersionCheck) populateVersionInformation(data.version, settingsUpdateVersionValue, settingsUpdateVersionTitle, settingsUpdateVersionCheck)
if(process.platform === 'darwin'){ if(process.platform === 'darwin'){
settingsUpdateButtonStatus(Lang.queryJS('settings.updates.downloadButton'), false, () => { settingsUpdateButtonStatus('Download from GitHub<span style="font-size: 10px;color: gray;text-shadow: none !important;">Close the launcher and run the dmg to update.</span>', false, () => {
shell.openExternal(data.darwindownload) shell.openExternal(data.darwindownload)
}) })
} else { } else {
settingsUpdateButtonStatus(Lang.queryJS('settings.updates.downloadingButton'), true) settingsUpdateButtonStatus('Downloading..', true)
} }
} else { } else {
settingsUpdateTitle.innerHTML = Lang.queryJS('settings.updates.latestVersionTitle') settingsUpdateTitle.innerHTML = 'You Are Running the Latest Version'
settingsUpdateChangelogCont.style.display = 'none' settingsUpdateChangelogCont.style.display = 'none'
populateVersionInformation(remote.app.getVersion(), settingsUpdateVersionValue, settingsUpdateVersionTitle, settingsUpdateVersionCheck) populateVersionInformation(remote.app.getVersion(), settingsUpdateVersionValue, settingsUpdateVersionTitle, settingsUpdateVersionCheck)
settingsUpdateButtonStatus(Lang.queryJS('settings.updates.checkForUpdatesButton'), false, () => { settingsUpdateButtonStatus('Check for Updates', false, () => {
if(!isDev){ if(!isDev){
ipcRenderer.send('autoUpdateAction', 'checkForUpdate') ipcRenderer.send('autoUpdateAction', 'checkForUpdate')
settingsUpdateButtonStatus(Lang.queryJS('settings.updates.checkingForUpdatesButton'), true) settingsUpdateButtonStatus('Checking for Updates..', true)
} }
}) })
} }
@ -1565,17 +1312,17 @@ function prepareUpdateTab(data = null){
* *
* @param {boolean} first Whether or not it is the first load. * @param {boolean} first Whether or not it is the first load.
*/ */
async function prepareSettings(first = false) { function prepareSettings(first = false) {
if(first){ if(first){
setupSettingsTabs() setupSettingsTabs()
initSettingsValidators() initSettingsValidators()
prepareUpdateTab() prepareUpdateTab()
} else { } else {
await prepareModsTab() prepareModsTab()
} }
await initSettingsValues() initSettingsValues()
prepareAccountsTab() prepareAccountsTab()
await prepareJavaTab() prepareJavaTab()
prepareAboutTab() prepareAboutTab()
} }

View File

@ -4,11 +4,11 @@
*/ */
// Requirements // Requirements
const path = require('path') const path = require('path')
const { Type } = require('helios-distribution-types')
const AuthManager = require('./assets/js/authmanager') const { AuthManager } = require('./../authmanager')
const ConfigManager = require('./assets/js/configmanager') const ConfigManager = require('./../configmanager')
const { DistroAPI } = require('./assets/js/distromanager') const DistroManager = require('./../distromanager')
const Lang = require('./../langloader')
let rscShouldLoad = false let rscShouldLoad = false
let fatalStartupError = false let fatalStartupError = false
@ -16,11 +16,9 @@ let fatalStartupError = false
// Mapping of each view to their container IDs. // Mapping of each view to their container IDs.
const VIEWS = { const VIEWS = {
landing: '#landingContainer', landing: '#landingContainer',
loginOptions: '#loginOptionsContainer',
login: '#loginContainer', login: '#loginContainer',
settings: '#settingsContainer', settings: '#settingsContainer',
welcome: '#welcomeContainer', welcome: '#welcomeContainer'
waiting: '#waitingContainer'
} }
// The currently shown view container. // The currently shown view container.
@ -40,10 +38,10 @@ let currentView
*/ */
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, async () => { $(`${current}`).fadeOut(currentFadeTime, () => {
await onCurrentFade() onCurrentFade()
$(`${next}`).fadeIn(nextFadeTime, async () => { $(`${next}`).fadeIn(nextFadeTime, () => {
await onNextFade() onNextFade()
}) })
}) })
} }
@ -57,15 +55,15 @@ function getCurrentView(){
return currentView return currentView
} }
async function showMainUI(data){ function showMainUI(data){
if(!isDev){ if(!isDev){
loggerAutoUpdater.info('Initializing..') loggerAutoUpdater.log('Initializing..')
ipcRenderer.send('autoUpdateAction', 'initAutoUpdater', ConfigManager.getAllowPrerelease()) ipcRenderer.send('autoUpdateAction', 'initAutoUpdater', ConfigManager.getAllowPrerelease())
} }
await prepareSettings(true) prepareSettings(true)
updateSelectedServer(data.getServerById(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)'
@ -88,11 +86,8 @@ async function showMainUI(data){
currentView = VIEWS.landing currentView = VIEWS.landing
$(VIEWS.landing).fadeIn(1000) $(VIEWS.landing).fadeIn(1000)
} else { } else {
loginOptionsCancelEnabled(false) currentView = VIEWS.login
loginOptionsViewOnLoginSuccess = VIEWS.landing $(VIEWS.login).fadeIn(1000)
loginOptionsViewOnLoginCancel = VIEWS.loginOptions
currentView = VIEWS.loginOptions
$(VIEWS.loginOptions).fadeIn(1000)
} }
} }
@ -114,9 +109,9 @@ function showFatalStartupError(){
$('#loadingContainer').fadeOut(250, () => { $('#loadingContainer').fadeOut(250, () => {
document.getElementById('overlayContainer').style.background = 'none' document.getElementById('overlayContainer').style.background = 'none'
setOverlayContent( setOverlayContent(
Lang.queryJS('uibinder.startup.fatalErrorTitle'), 'Fatal Error: Unable to Load Distribution Index',
Lang.queryJS('uibinder.startup.fatalErrorMessage'), '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.',
Lang.queryJS('uibinder.startup.closeButton') 'Close'
) )
setOverlayHandler(() => { setOverlayHandler(() => {
const window = remote.getCurrentWindow() const window = remote.getCurrentWindow()
@ -133,11 +128,10 @@ function showFatalStartupError(){
* @param {Object} data The distro index object. * @param {Object} data The distro index object.
*/ */
function onDistroRefresh(data){ function onDistroRefresh(data){
updateSelectedServer(data.getServerById(ConfigManager.getSelectedServer())) updateSelectedServer(data.getServer(ConfigManager.getSelectedServer()))
refreshServerStatus() refreshServerStatus()
initNews() initNews()
syncModConfigurations(data) syncModConfigurations(data)
ensureJavaSettings(data)
} }
/** /**
@ -149,10 +143,10 @@ function syncModConfigurations(data){
const syncedCfgs = [] const syncedCfgs = []
for(let serv of data.servers){ for(let serv of data.getServers()){
const id = serv.rawServer.id const id = serv.getID()
const mdls = serv.modules const mdls = serv.getModules()
const cfg = ConfigManager.getModConfiguration(id) const cfg = ConfigManager.getModConfiguration(id)
if(cfg != null){ if(cfg != null){
@ -161,20 +155,20 @@ function syncModConfigurations(data){
const mods = {} const mods = {}
for(let mdl of mdls){ for(let mdl of mdls){
const type = mdl.rawModule.type const type = mdl.getType()
if(type === Type.ForgeMod || type === Type.LiteMod || type === Type.LiteLoader || type === Type.FabricMod){ if(type === DistroManager.Types.ForgeMod || type === DistroManager.Types.LiteMod || type === DistroManager.Types.LiteLoader){
if(!mdl.getRequired().value){ if(!mdl.getRequired().isRequired()){
const mdlID = mdl.getVersionlessMavenIdentifier() const mdlID = mdl.getVersionlessID()
if(modsOld[mdlID] == null){ if(modsOld[mdlID] == null){
mods[mdlID] = scanOptionalSubModules(mdl.subModules, mdl) mods[mdlID] = scanOptionalSubModules(mdl.getSubModules(), mdl)
} else { } else {
mods[mdlID] = mergeModConfiguration(modsOld[mdlID], scanOptionalSubModules(mdl.subModules, mdl), false) mods[mdlID] = mergeModConfiguration(modsOld[mdlID], scanOptionalSubModules(mdl.getSubModules(), mdl), false)
} }
} else { } else {
if(mdl.subModules.length > 0){ if(mdl.hasSubModules()){
const mdlID = mdl.getVersionlessMavenIdentifier() const mdlID = mdl.getVersionlessID()
const v = scanOptionalSubModules(mdl.subModules, 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
@ -197,15 +191,15 @@ function syncModConfigurations(data){
const mods = {} const mods = {}
for(let mdl of mdls){ for(let mdl of mdls){
const type = mdl.rawModule.type const type = mdl.getType()
if(type === Type.ForgeMod || type === Type.LiteMod || type === Type.LiteLoader || type === Type.FabricMod){ if(type === DistroManager.Types.ForgeMod || type === DistroManager.Types.LiteMod || type === DistroManager.Types.LiteLoader){
if(!mdl.getRequired().value){ if(!mdl.getRequired().isRequired()){
mods[mdl.getVersionlessMavenIdentifier()] = scanOptionalSubModules(mdl.subModules, mdl) mods[mdl.getVersionlessID()] = scanOptionalSubModules(mdl.getSubModules(), mdl)
} else { } else {
if(mdl.subModules.length > 0){ if(mdl.hasSubModules()){
const v = scanOptionalSubModules(mdl.subModules, mdl) const v = scanOptionalSubModules(mdl.getSubModules(), mdl)
if(typeof v === 'object'){ if(typeof v === 'object'){
mods[mdl.getVersionlessMavenIdentifier()] = v mods[mdl.getVersionlessID()] = v
} }
} }
} }
@ -224,21 +218,6 @@ function syncModConfigurations(data){
ConfigManager.save() ConfigManager.save()
} }
/**
* Ensure java configurations are present for the available servers.
*
* @param {Object} data The distro index object.
*/
function ensureJavaSettings(data) {
// Nothing too fancy for now.
for(const serv of data.servers){
ConfigManager.ensureJavaConfig(serv.rawServer.id, serv.effectiveJavaOptions, serv.rawServer.javaOptions?.ram)
}
ConfigManager.save()
}
/** /**
* Recursively scan for optional sub modules. If none are found, * Recursively scan for optional sub modules. If none are found,
* this function returns a boolean. If optional sub modules do exist, * this function returns a boolean. If optional sub modules do exist,
@ -251,17 +230,17 @@ function scanOptionalSubModules(mdls, origin){
const mods = {} const mods = {}
for(let mdl of mdls){ for(let mdl of mdls){
const type = mdl.rawModule.type const type = mdl.getType()
// Optional types. // Optional types.
if(type === Type.ForgeMod || type === Type.LiteMod || type === Type.LiteLoader || type === Type.FabricMod){ if(type === DistroManager.Types.ForgeMod || type === DistroManager.Types.LiteMod || type === DistroManager.Types.LiteLoader){
// It is optional. // It is optional.
if(!mdl.getRequired().value){ if(!mdl.getRequired().isRequired()){
mods[mdl.getVersionlessMavenIdentifier()] = scanOptionalSubModules(mdl.subModules, mdl) mods[mdl.getVersionlessID()] = scanOptionalSubModules(mdl.getSubModules(), mdl)
} else { } else {
if(mdl.hasSubModules()){ if(mdl.hasSubModules()){
const v = scanOptionalSubModules(mdl.subModules, mdl) const v = scanOptionalSubModules(mdl.getSubModules(), mdl)
if(typeof v === 'object'){ if(typeof v === 'object'){
mods[mdl.getVersionlessMavenIdentifier()] = v mods[mdl.getVersionlessID()] = v
} }
} }
} }
@ -272,13 +251,13 @@ function scanOptionalSubModules(mdls, origin){
const ret = { const ret = {
mods mods
} }
if(!origin.getRequired().value){ if(!origin.getRequired().isRequired()){
ret.value = origin.getRequired().def ret.value = origin.getRequired().isDefault()
} }
return ret return ret
} }
} }
return origin.getRequired().def return origin.getRequired().isDefault()
} }
/** /**
@ -323,6 +302,18 @@ function mergeModConfiguration(o, n, nReq = false){
return n return n
} }
function refreshDistributionIndex(remote, onSuccess, onError){
if(remote){
DistroManager.pullRemote()
.then(onSuccess)
.catch(onError)
} else {
DistroManager.pullLocal()
.then(onSuccess)
.catch(onError)
}
}
async function validateSelectedAccount(){ async function validateSelectedAccount(){
const selectedAcc = ConfigManager.getSelectedAccount() const selectedAcc = ConfigManager.getSelectedAccount()
if(selectedAcc != null){ if(selectedAcc != null){
@ -332,54 +323,26 @@ async function validateSelectedAccount(){
ConfigManager.save() ConfigManager.save()
const accLen = Object.keys(ConfigManager.getAuthAccounts()).length const accLen = Object.keys(ConfigManager.getAuthAccounts()).length
setOverlayContent( setOverlayContent(
Lang.queryJS('uibinder.validateAccount.failedMessageTitle'), 'Failed to Refresh Login',
accLen > 0 `We were unable to refresh the login for <strong>${selectedAcc.displayName}</strong>. Please ${accLen > 0 ? 'select another account or ' : ''} login again.`,
? Lang.queryJS('uibinder.validateAccount.failedMessage', { 'account': selectedAcc.displayName }) 'Login',
: Lang.queryJS('uibinder.validateAccount.failedMessageSelectAnotherAccount', { 'account': selectedAcc.displayName }), 'Select Another Account'
Lang.queryJS('uibinder.validateAccount.loginButton'),
Lang.queryJS('uibinder.validateAccount.selectAnotherAccountButton')
) )
setOverlayHandler(() => { setOverlayHandler(() => {
const isMicrosoft = selectedAcc.type === 'microsoft'
if(isMicrosoft) {
// Empty for now
} else {
// Mojang
// For convenience, pre-populate the username of the account.
document.getElementById('loginUsername').value = selectedAcc.username document.getElementById('loginUsername').value = selectedAcc.username
validateEmail(selectedAcc.username) validateEmail(selectedAcc.username)
} loginViewOnSuccess = getCurrentView()
loginViewOnCancel = getCurrentView()
loginOptionsViewOnLoginSuccess = getCurrentView() if(accLen > 0){
loginOptionsViewOnLoginCancel = VIEWS.loginOptions loginViewCancelHandler = () => {
ConfigManager.addAuthAccount(selectedAcc.uuid, selectedAcc.accessToken, selectedAcc.username, selectedAcc.displayName)
if(accLen > 0) {
loginOptionsViewOnCancel = getCurrentView()
loginOptionsViewCancelHandler = () => {
if(isMicrosoft) {
ConfigManager.addMicrosoftAuthAccount(
selectedAcc.uuid,
selectedAcc.accessToken,
selectedAcc.username,
selectedAcc.expiresAt,
selectedAcc.microsoft.access_token,
selectedAcc.microsoft.refresh_token,
selectedAcc.microsoft.expires_at
)
} else {
ConfigManager.addMojangAuthAccount(selectedAcc.uuid, selectedAcc.accessToken, selectedAcc.username, selectedAcc.displayName)
}
ConfigManager.save() ConfigManager.save()
validateSelectedAccount() validateSelectedAccount()
} }
loginOptionsCancelEnabled(true) loginCancelEnabled(true)
} else {
loginOptionsCancelEnabled(false)
} }
toggleOverlay(false) toggleOverlay(false)
switchView(getCurrentView(), VIEWS.loginOptions) switchView(getCurrentView(), VIEWS.login)
}) })
setDismissHandler(() => { setDismissHandler(() => {
if(accLen > 1){ if(accLen > 1){
@ -419,14 +382,14 @@ function setSelectedAccount(uuid){
} }
// Synchronous Listener // Synchronous Listener
document.addEventListener('readystatechange', async () => { 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 = await DistroAPI.getDistribution() const data = DistroManager.getDistribution()
await showMainUI(data) showMainUI(data)
} else { } else {
showFatalStartupError() showFatalStartupError()
} }
@ -436,13 +399,12 @@ document.addEventListener('readystatechange', async () => {
}, 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', async (event, res) => { ipcRenderer.on('distributionIndexDone', (event, res) => {
if(res) { if(res) {
const data = await DistroAPI.getDistribution() const data = DistroManager.getDistribution()
syncModConfigurations(data) syncModConfigurations(data)
ensureJavaSettings(data)
if(document.readyState === 'interactive' || document.readyState === 'complete'){ if(document.readyState === 'interactive' || document.readyState === 'complete'){
await showMainUI(data) showMainUI(data)
} else { } else {
rscShouldLoad = true rscShouldLoad = true
} }
@ -455,12 +417,3 @@ ipcRenderer.on('distributionIndexDone', async (event, res) => {
} }
} }
}) })
// Util for development
async function devModeToggle() {
DistroAPI.toggleDevMode(true)
const data = await DistroAPI.refreshDistributionOrFallback()
ensureJavaSettings(data)
updateSelectedServer(data.servers[0])
syncModConfigurations(data)
}

View File

@ -1,19 +1,19 @@
// @ts-nocheck
import $ from 'jquery'
import { ipcRenderer, remote, shell, webFrame } from 'electron'
import { LoggerUtil } from '../loggerutil'
import isDev from '../isdev'
/** /**
* Core UI functions are initialized in this file. This prevents * Core UI functions are initialized in this file. This prevents
* unexpected errors from breaking the core features. Specifically, * unexpected errors from breaking the core features. Specifically,
* actions in this file should not require the usage of any internal * actions in this file should not require the usage of any internal
* modules, excluding dependencies. * modules, excluding dependencies.
*/ */
// Requirements
const $ = require('jquery')
const {ipcRenderer, shell, webFrame} = require('electron')
const remote = require('@electron/remote')
const isDev = require('./assets/js/isdev')
const { LoggerUtil } = require('helios-core')
const Lang = require('./assets/js/langloader')
const loggerUICore = LoggerUtil.getLogger('UICore') const loggerUICore = new LoggerUtil('%c[UICore]', 'color: #000668; font-weight: bold')
const loggerAutoUpdater = LoggerUtil.getLogger('AutoUpdater') const loggerAutoUpdater = new LoggerUtil('%c[AutoUpdater]', 'color: #000668; font-weight: bold')
const loggerAutoUpdaterSuccess = new LoggerUtil('%c[AutoUpdater]', 'color: #209b07; font-weight: bold')
// Log deprecation and process warnings. // Log deprecation and process warnings.
process.traceProcessWarnings = true process.traceProcessWarnings = true
@ -35,6 +35,7 @@ remote.getCurrentWebContents().on('devtools-opened', () => {
// Disable zoom, needed for darwin. // Disable zoom, needed for darwin.
webFrame.setZoomLevel(0) webFrame.setZoomLevel(0)
webFrame.setVisualZoomLevelLimits(1, 1) webFrame.setVisualZoomLevelLimits(1, 1)
webFrame.setLayoutZoomLevelLimits(0, 0)
// Initialize auto updates in production environments. // Initialize auto updates in production environments.
let updateCheckListener let updateCheckListener
@ -42,22 +43,22 @@ if(!isDev){
ipcRenderer.on('autoUpdateNotification', (event, arg, info) => { ipcRenderer.on('autoUpdateNotification', (event, arg, info) => {
switch(arg){ switch(arg){
case 'checking-for-update': case 'checking-for-update':
loggerAutoUpdater.info('Checking for update..') loggerAutoUpdater.log('Checking for update..')
settingsUpdateButtonStatus(Lang.queryJS('uicore.autoUpdate.checkingForUpdateButton'), true) settingsUpdateButtonStatus('Checking for Updates..', true)
break break
case 'update-available': case 'update-available':
loggerAutoUpdater.info('New update available', info.version) loggerAutoUpdaterSuccess.log('New update available', info.version)
if(process.platform === 'darwin'){ if(process.platform === 'darwin'){
info.darwindownload = `https://github.com/dscalzi/HeliosLauncher/releases/download/v${info.version}/Helios-Launcher-setup-${info.version}${process.arch === 'arm64' ? '-arm64' : '-x64'}.dmg` info.darwindownload = `https://github.com/dscalzi/HeliosLauncher/releases/download/v${info.version}/helioslauncher-setup-${info.version}.dmg`
showUpdateUI(info) showUpdateUI(info)
} }
populateSettingsUpdateInformation(info) populateSettingsUpdateInformation(info)
break break
case 'update-downloaded': case 'update-downloaded':
loggerAutoUpdater.info('Update ' + info.version + ' ready to be installed.') loggerAutoUpdaterSuccess.log('Update ' + info.version + ' ready to be installed.')
settingsUpdateButtonStatus(Lang.queryJS('uicore.autoUpdate.installNowButton'), false, () => { settingsUpdateButtonStatus('Install Now', false, () => {
if(!isDev){ if(!isDev){
ipcRenderer.send('autoUpdateAction', 'installUpdateNow') ipcRenderer.send('autoUpdateAction', 'installUpdateNow')
} }
@ -65,8 +66,8 @@ if(!isDev){
showUpdateUI(info) showUpdateUI(info)
break break
case 'update-not-available': case 'update-not-available':
loggerAutoUpdater.info('No new update found.') loggerAutoUpdater.log('No new update found.')
settingsUpdateButtonStatus(Lang.queryJS('uicore.autoUpdate.checkForUpdatesButton')) settingsUpdateButtonStatus('Check for Updates')
break break
case 'ready': case 'ready':
updateCheckListener = setInterval(() => { updateCheckListener = setInterval(() => {
@ -77,9 +78,9 @@ if(!isDev){
case 'realerror': case 'realerror':
if(info != null && info.code != null){ if(info != null && info.code != null){
if(info.code === 'ERR_UPDATER_INVALID_RELEASE_FEED'){ if(info.code === 'ERR_UPDATER_INVALID_RELEASE_FEED'){
loggerAutoUpdater.info('No suitable releases found.') loggerAutoUpdater.log('No suitable releases found.')
} else if(info.code === 'ERR_XML_MISSED_ELEMENT'){ } else if(info.code === 'ERR_XML_MISSED_ELEMENT'){
loggerAutoUpdater.info('No releases found.') loggerAutoUpdater.log('No releases found.')
} else { } else {
loggerAutoUpdater.error('Error during update check..', info) loggerAutoUpdater.error('Error during update check..', info)
loggerAutoUpdater.debug('Error Code:', info.code) loggerAutoUpdater.debug('Error Code:', info.code)
@ -87,7 +88,7 @@ if(!isDev){
} }
break break
default: default:
loggerAutoUpdater.info('Unknown argument', arg) loggerAutoUpdater.log('Unknown argument', arg)
break break
} }
}) })
@ -107,7 +108,7 @@ function changeAllowPrerelease(val){
function showUpdateUI(info){ function showUpdateUI(info){
//TODO Make this message a bit more informative `${info.version}` //TODO Make this message a bit more informative `${info.version}`
document.getElementById('image_seal_container').setAttribute('update', true) document.getElementById('image_seal_container').setAttribute('update', 'true')
document.getElementById('image_seal_container').onclick = () => { document.getElementById('image_seal_container').onclick = () => {
/*setOverlayContent('Update Available', 'A new update for the launcher is available. Would you like to install now?', 'Install', 'Later') /*setOverlayContent('Update Available', 'A new update for the launcher is available. Would you like to install now?', 'Install', 'Later')
setOverlayHandler(() => { setOverlayHandler(() => {
@ -130,14 +131,15 @@ function showUpdateUI(info){
/* jQuery Example /* jQuery Example
$(function(){ $(function(){
loggerUICore.info('UICore Initialized'); loggerUICore.log('UICore Initialized');
})*/ })*/
document.addEventListener('readystatechange', function () { document.addEventListener('readystatechange', function () {
if (document.readyState === 'interactive'){ if (document.readyState === 'interactive'){
loggerUICore.info('UICore Initializing..') loggerUICore.log('UICore Initializing..')
// Bind close button. // Bind close button.
// DONE
Array.from(document.getElementsByClassName('fCb')).map((val) => { Array.from(document.getElementsByClassName('fCb')).map((val) => {
val.addEventListener('click', e => { val.addEventListener('click', e => {
const window = remote.getCurrentWindow() const window = remote.getCurrentWindow()
@ -146,6 +148,7 @@ document.addEventListener('readystatechange', function () {
}) })
// Bind restore down button. // Bind restore down button.
// DONE
Array.from(document.getElementsByClassName('fRb')).map((val) => { Array.from(document.getElementsByClassName('fRb')).map((val) => {
val.addEventListener('click', e => { val.addEventListener('click', e => {
const window = remote.getCurrentWindow() const window = remote.getCurrentWindow()
@ -154,23 +157,24 @@ document.addEventListener('readystatechange', function () {
} else { } else {
window.maximize() window.maximize()
} }
document.activeElement.blur() (document.activeElement as HTMLElement).blur()
}) })
}) })
// Bind minimize button. // Bind minimize button.
// DONE
Array.from(document.getElementsByClassName('fMb')).map((val) => { Array.from(document.getElementsByClassName('fMb')).map((val) => {
val.addEventListener('click', e => { val.addEventListener('click', e => {
const window = remote.getCurrentWindow() const window = remote.getCurrentWindow()
window.minimize() window.minimize();
document.activeElement.blur() (document.activeElement as HTMLElement).blur()
}) })
}) })
// Remove focus from social media buttons once they're clicked. // Remove focus from social media buttons once they're clicked.
Array.from(document.getElementsByClassName('mediaURL')).map(val => { Array.from(document.getElementsByClassName('mediaURL')).map(val => {
val.addEventListener('click', e => { val.addEventListener('click', e => {
document.activeElement.blur() (document.activeElement as HTMLElement).blur()
}) })
}) })
@ -184,10 +188,10 @@ document.addEventListener('readystatechange', function () {
//const targetWidth2 = document.getElementById("server_selection").getBoundingClientRect().width //const targetWidth2 = document.getElementById("server_selection").getBoundingClientRect().width
//const targetWidth3 = document.getElementById("launch_button").getBoundingClientRect().width //const targetWidth3 = document.getElementById("launch_button").getBoundingClientRect().width
document.getElementById('launch_details').style.maxWidth = 266.01 document.getElementById('launch_details').style.maxWidth = '266.01'
document.getElementById('launch_progress').style.width = 170.8 document.getElementById('launch_progress').style.width = '170.8'
document.getElementById('launch_details_right').style.maxWidth = 170.8 document.getElementById('launch_details_right').style.maxWidth = '170.8'
document.getElementById('launch_progress_label').style.width = 53.21 document.getElementById('launch_progress_label').style.width = '53.21'
} }
@ -209,6 +213,6 @@ $(document).on('click', 'a[href^="http"]', function(event) {
document.addEventListener('keydown', function (e) { document.addEventListener('keydown', function (e) {
if((e.key === 'I' || e.key === 'i') && e.ctrlKey && e.shiftKey){ if((e.key === 'I' || e.key === 'i') && e.ctrlKey && e.shiftKey){
let window = remote.getCurrentWindow() let window = remote.getCurrentWindow()
window.toggleDevTools() window.webContents.toggleDevTools()
} }
}) })

View File

@ -0,0 +1,6 @@
/**
* Script for welcome.ejs
*/
document.getElementById('welcomeButton').addEventListener('click', e => {
switchView(VIEWS.welcome, VIEWS.login)
})

View File

@ -1,10 +1,10 @@
<html lang="en" xmlns="http://www.w3.org/1999/xhtml"> <html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head> <head>
<meta charset="utf-8" http-equiv="Content-Security-Policy" content="script-src 'self' 'sha256-In6B8teKZQll5heMl9bS7CESTbGvuAt3VVV86BUQBDk='"/> <meta charset="utf-8" http-equiv="Content-Security-Policy" content="script-src 'self' 'sha256-In6B8teKZQll5heMl9bS7CESTbGvuAt3VVV86BUQBDk='"/>
<title><%= lang('app.title') %></title> <title>Westeroscraft Launcher</title>
<script src="./assets/js/scripts/uicore.js"></script> <script src="../../out/scripts/uicore.js"></script>
<script src="./assets/js/scripts/uibinder.js"></script> <script src="../../out/scripts/uibinder.js"></script>
<link type="text/css" rel="stylesheet" href="./assets/css/launcher.css"> <link type="text/css" rel="stylesheet" href="../css/launcher.css">
<style> <style>
body { body {
/*background: url('assets/images/backgrounds/<%=bkid%>.jpg') no-repeat center center fixed;*/ /*background: url('assets/images/backgrounds/<%=bkid%>.jpg') no-repeat center center fixed;*/
@ -27,23 +27,27 @@
</style> </style>
</head> </head>
<body bkid="<%=bkid%>"> <body bkid="<%=bkid%>">
<%- include('frame') %> <% include frame.ejs %>
<div id="main"> <div id="main">
<%- include('welcome') %> <% include welcome.ejs %>
<%- include('login') %> <% include login.ejs %>
<%- include('waiting') %> <% include settings.ejs %>
<%- include('loginOptions') %> <% include landing.ejs %>
<%- include('settings') %>
<%- include('landing') %>
</div> </div>
<%- include('overlay') %> <% include overlay.ejs %>
<div id="loadingContainer"> <div id="loadingContainer">
<div id="loadingContent"> <div id="loadingContent">
<div id="loadSpinnerContainer"> <div id="loadSpinnerContainer">
<img id="loadCenterImage" src="assets/images/LoadingSeal.png"> <img id="loadCenterImage" src="../images/LoadingSeal.png">
<img id="loadSpinnerImage" class="rotating" src="assets/images/LoadingText.png"> <img id="loadSpinnerImage" class="rotating" src="../images/LoadingText.png">
</div> </div>
</div> </div>
</div> </div>
<script>
// Load language
for(let key of Object.keys(Lang.query('html'))){
document.getElementById(key).innerHTML = Lang.query(`html.${key}`)
}
</script>
</body> </body>
</html> </html>

View File

@ -13,7 +13,7 @@
<% } else{ %> <% } else{ %>
<div id="frameContentWin"> <div id="frameContentWin">
<div id="frameTitleDock"> <div id="frameTitleDock">
<span id="frameTitleText"><%= lang('app.title') %></span> <span id="frameTitleText">Helios Launcher</span>
</div> </div>
<div id="frameButtonDockWin"> <div id="frameButtonDockWin">
<button class="frameButton fMb" id="frameButton_minimize" tabIndex="-1"> <button class="frameButton fMb" id="frameButton_minimize" tabIndex="-1">

View File

@ -2,8 +2,8 @@
<div id="upper"> <div id="upper">
<div id="left"> <div id="left">
<div id="image_seal_container"> <div id="image_seal_container">
<img id="image_seal" src="assets/images/SealCircle.png"/> <img id="image_seal" src="../images/SealCircle.png"/>
<div id="updateAvailableTooltip"><%- lang('landing.updateAvailableTooltip') %></div> <div id="updateAvailableTooltip">Update Available</div>
</div> </div>
</div> </div>
<div id="content"> <div id="content">
@ -11,9 +11,9 @@
<div id="right"> <div id="right">
<div id="rightContainer"> <div id="rightContainer">
<div id="user_content"> <div id="user_content">
<span id="user_text"><%- lang('landing.usernamePlaceholder') %></span> <span id="user_text">Username</span>
<div id="avatarContainer"> <div id="avatarContainer">
<button id="avatarOverlay"><%- lang('landing.usernameEditButton') %></button> <button id="avatarOverlay">Edit</button>
</div> </div>
</div> </div>
<div id="mediaContent"> <div id="mediaContent">
@ -23,14 +23,14 @@
<svg id="settingsSVG" class="mediaSVG" viewBox="0 0 141.36 137.43"> <svg id="settingsSVG" class="mediaSVG" viewBox="0 0 141.36 137.43">
<path d="M70.70475616319865,83.36934004916053 a15.320781354859122,15.320781354859122 0 1 1 14.454501310561755,-15.296030496450625 A14.850515045097694,14.850515045097694 0 0 1 70.70475616319865,83.36934004916053 M123.25082856443602,55.425620905968366 h-12.375429204248078 A45.54157947163293,45.54157947163293 0 0 0 107.21227231573047,46.243052436416285 l8.613298726156664,-9.108315894326587 a9.727087354538993,9.727087354538993 0 0 0 0,-13.167456673319956 l-3.465120177189462,-3.6631270444574313 a8.489544434114185,8.489544434114185 0 0 0 -12.375429204248078,0 l-8.613298726156664,9.108315894326587 A40.442902639482725,40.442902639482725 0 0 0 81.99114759747292,25.427580514871032 V12.532383284044531 a9.108315894326587,9.108315894326587 0 0 0 -8.811305593424633,-9.306322761594556 h-4.950171681699231 a9.108315894326587,9.108315894326587 0 0 0 -8.811305593424633,9.306322761594556 v12.895197230826497 a40.17064319698927,40.17064319698927 0 0 0 -9.331073620003052,4.0591407789933704 l-8.613298726156664,-9.108315894326587 a8.489544434114185,8.489544434114185 0 0 0 -12.375429204248078,0 L25.58394128451018,23.967279868769744 a9.727087354538993,9.727087354538993 0 0 0 0,13.167456673319956 L34.19724001066683,46.243052436416285 a45.07131316187151,45.07131316187151 0 0 0 -3.6631270444574313,9.083565035918088 h-12.375429204248078 a9.083565035918088,9.083565035918088 0 0 0 -8.811305593424633,9.306322761594556 v5.197680265784193 a9.108315894326587,9.108315894326587 0 0 0 8.811305593424633,9.306322761594556 h11.979415469712139 a45.69008462208391,45.69008462208391 0 0 0 4.0591407789933704,10.642869115653347 l-8.613298726156664,9.108315894326587 a9.727087354538993,9.727087354538993 0 0 0 0,13.167456673319956 l3.465120177189462,3.6631270444574313 a8.489544434114185,8.489544434114185 0 0 0 12.375429204248078,0 l8.613298726156664,-9.108315894326587 a40.49240435629971,40.49240435629971 0 0 0 9.331073620003052,4.0591407789933704 v12.895197230826497 a9.083565035918088,9.083565035918088 0 0 0 8.811305593424633,9.306322761594556 h4.950171681699231 A9.083565035918088,9.083565035918088 0 0 0 81.99114759747292,123.68848839660077 V110.79329116577425 a40.78941465720167,40.78941465720167 0 0 0 9.331073620003052,-4.0591407789933704 l8.613298726156664,9.108315894326587 a8.489544434114185,8.489544434114185 0 0 0 12.375429204248078,0 l3.465120177189462,-3.6631270444574313 a9.727087354538993,9.727087354538993 0 0 0 0,-13.167456673319956 l-8.613298726156664,-9.108315894326587 a45.665333763675406,45.665333763675406 0 0 0 4.034389920584874,-10.642869115653347 h12.004166328120636 a9.108315894326587,9.108315894326587 0 0 0 8.811305593424633,-9.306322761594556 v-5.197680265784193 a9.083565035918088,9.083565035918088 0 0 0 -8.811305593424633,-9.306322761594556 " id="svg_3" class=""/> <path d="M70.70475616319865,83.36934004916053 a15.320781354859122,15.320781354859122 0 1 1 14.454501310561755,-15.296030496450625 A14.850515045097694,14.850515045097694 0 0 1 70.70475616319865,83.36934004916053 M123.25082856443602,55.425620905968366 h-12.375429204248078 A45.54157947163293,45.54157947163293 0 0 0 107.21227231573047,46.243052436416285 l8.613298726156664,-9.108315894326587 a9.727087354538993,9.727087354538993 0 0 0 0,-13.167456673319956 l-3.465120177189462,-3.6631270444574313 a8.489544434114185,8.489544434114185 0 0 0 -12.375429204248078,0 l-8.613298726156664,9.108315894326587 A40.442902639482725,40.442902639482725 0 0 0 81.99114759747292,25.427580514871032 V12.532383284044531 a9.108315894326587,9.108315894326587 0 0 0 -8.811305593424633,-9.306322761594556 h-4.950171681699231 a9.108315894326587,9.108315894326587 0 0 0 -8.811305593424633,9.306322761594556 v12.895197230826497 a40.17064319698927,40.17064319698927 0 0 0 -9.331073620003052,4.0591407789933704 l-8.613298726156664,-9.108315894326587 a8.489544434114185,8.489544434114185 0 0 0 -12.375429204248078,0 L25.58394128451018,23.967279868769744 a9.727087354538993,9.727087354538993 0 0 0 0,13.167456673319956 L34.19724001066683,46.243052436416285 a45.07131316187151,45.07131316187151 0 0 0 -3.6631270444574313,9.083565035918088 h-12.375429204248078 a9.083565035918088,9.083565035918088 0 0 0 -8.811305593424633,9.306322761594556 v5.197680265784193 a9.108315894326587,9.108315894326587 0 0 0 8.811305593424633,9.306322761594556 h11.979415469712139 a45.69008462208391,45.69008462208391 0 0 0 4.0591407789933704,10.642869115653347 l-8.613298726156664,9.108315894326587 a9.727087354538993,9.727087354538993 0 0 0 0,13.167456673319956 l3.465120177189462,3.6631270444574313 a8.489544434114185,8.489544434114185 0 0 0 12.375429204248078,0 l8.613298726156664,-9.108315894326587 a40.49240435629971,40.49240435629971 0 0 0 9.331073620003052,4.0591407789933704 v12.895197230826497 a9.083565035918088,9.083565035918088 0 0 0 8.811305593424633,9.306322761594556 h4.950171681699231 A9.083565035918088,9.083565035918088 0 0 0 81.99114759747292,123.68848839660077 V110.79329116577425 a40.78941465720167,40.78941465720167 0 0 0 9.331073620003052,-4.0591407789933704 l8.613298726156664,9.108315894326587 a8.489544434114185,8.489544434114185 0 0 0 12.375429204248078,0 l3.465120177189462,-3.6631270444574313 a9.727087354538993,9.727087354538993 0 0 0 0,-13.167456673319956 l-8.613298726156664,-9.108315894326587 a45.665333763675406,45.665333763675406 0 0 0 4.034389920584874,-10.642869115653347 h12.004166328120636 a9.108315894326587,9.108315894326587 0 0 0 8.811305593424633,-9.306322761594556 v-5.197680265784193 a9.083565035918088,9.083565035918088 0 0 0 -8.811305593424633,-9.306322761594556 " id="svg_3" class=""/>
</svg> </svg>
<div id="settingsTooltip"><%- lang('landing.settingsTooltip') %></div> <div id="settingsTooltip">Settings</div>
</button> </button>
</div> </div>
</div> </div>
<div class="mediaDivider"></div> <div class="mediaDivider"></div>
<div id="externalMedia"> <div id="externalMedia">
<div class="mediaContainer"> <div class="mediaContainer">
<a href="<%- lang('landing.mediaGitHubURL') %>" class="mediaURL" id="linkURL"> <a href="https://github.com/dscalZi/HeliosLauncher" class="mediaURL" id="linkURL">
<svg id="linkSVG" class="mediaSVG" viewBox="35.34 34.3575 70.68 68.71500"> <svg id="linkSVG" class="mediaSVG" viewBox="35.34 34.3575 70.68 68.71500">
<g> <g>
<path d="M75.37,65.51a3.85,3.85,0,0,0-1.73.42,8.22,8.22,0,0,1,.94,3.76A8.36,8.36,0,0,1,66.23,78H46.37a8.35,8.35,0,1,1,0-16.7h9.18a21.51,21.51,0,0,1,6.65-8.72H46.37a17.07,17.07,0,1,0,0,34.15H66.23A17,17,0,0,0,82.77,65.51Z"/> <path d="M75.37,65.51a3.85,3.85,0,0,0-1.73.42,8.22,8.22,0,0,1,.94,3.76A8.36,8.36,0,0,1,66.23,78H46.37a8.35,8.35,0,1,1,0-16.7h9.18a21.51,21.51,0,0,1,6.65-8.72H46.37a17.07,17.07,0,1,0,0,34.15H66.23A17,17,0,0,0,82.77,65.51Z"/>
@ -40,7 +40,7 @@
</a> </a>
</div> </div>
<div class="mediaContainer"> <div class="mediaContainer">
<a href="<%- lang('landing.mediaTwitterURL') %>" class="mediaURL" id="twitterURL"> <a href="#" class="mediaURL" id="twitterURL" disabled>
<svg id="twitterSVG" class="mediaSVG" viewBox="0 0 5000 4060" preserveAspectRatio="xMidYMid meet"> <svg id="twitterSVG" class="mediaSVG" viewBox="0 0 5000 4060" preserveAspectRatio="xMidYMid meet">
<g> <g>
<path d="M1210 4048 c-350 -30 -780 -175 -1124 -378 -56 -33 -86 -57 -86 -68 0 -16 7 -17 83 -9 114 12 349 1 493 -22 295 -49 620 -180 843 -341 l54 -38 -49 -7 c-367 -49 -660 -256 -821 -582 -30 -61 -53 -120 -51 -130 3 -16 12 -17 73 -13 97 7 199 5 270 -4 l60 -9 -65 -22 c-341 -117 -609 -419 -681 -769 -18 -88 -26 -226 -13 -239 4 -3 32 7 63 22 68 35 198 77 266 86 28 4 58 9 68 12 10 2 -22 -34 -72 -82 -240 -232 -353 -532 -321 -852 15 -149 79 -347 133 -418 16 -20 17 -19 49 20 377 455 913 795 1491 945 160 41 346 74 485 86 l82 7 -7 -59 c-5 -33 -7 -117 -6 -189 2 -163 31 -286 103 -430 141 -285 422 -504 708 -550 112 -19 333 -19 442 0 180 30 335 108 477 239 l58 54 95 -24 c143 -36 286 -89 427 -160 70 -35 131 -60 135 -56 19 19 -74 209 -151 312 -50 66 -161 178 -216 217 l-30 22 73 -14 c111 -21 257 -63 353 -101 99 -39 99 -39 99 -19 0 57 -237 326 -412 468 l-88 71 6 51 c4 28 1 130 -5 226 -30 440 -131 806 -333 1202 -380 745 -1036 1277 -1823 1477 -243 62 -430 81 -786 78 -134 0 -291 -5 -349 -10z"/> <path d="M1210 4048 c-350 -30 -780 -175 -1124 -378 -56 -33 -86 -57 -86 -68 0 -16 7 -17 83 -9 114 12 349 1 493 -22 295 -49 620 -180 843 -341 l54 -38 -49 -7 c-367 -49 -660 -256 -821 -582 -30 -61 -53 -120 -51 -130 3 -16 12 -17 73 -13 97 7 199 5 270 -4 l60 -9 -65 -22 c-341 -117 -609 -419 -681 -769 -18 -88 -26 -226 -13 -239 4 -3 32 7 63 22 68 35 198 77 266 86 28 4 58 9 68 12 10 2 -22 -34 -72 -82 -240 -232 -353 -532 -321 -852 15 -149 79 -347 133 -418 16 -20 17 -19 49 20 377 455 913 795 1491 945 160 41 346 74 485 86 l82 7 -7 -59 c-5 -33 -7 -117 -6 -189 2 -163 31 -286 103 -430 141 -285 422 -504 708 -550 112 -19 333 -19 442 0 180 30 335 108 477 239 l58 54 95 -24 c143 -36 286 -89 427 -160 70 -35 131 -60 135 -56 19 19 -74 209 -151 312 -50 66 -161 178 -216 217 l-30 22 73 -14 c111 -21 257 -63 353 -101 99 -39 99 -39 99 -19 0 57 -237 326 -412 468 l-88 71 6 51 c4 28 1 130 -5 226 -30 440 -131 806 -333 1202 -380 745 -1036 1277 -1823 1477 -243 62 -430 81 -786 78 -134 0 -291 -5 -349 -10z"/>
@ -49,7 +49,7 @@
</a> </a>
</div> </div>
<div class="mediaContainer"> <div class="mediaContainer">
<a href="<%- lang('landing.mediaInstagramURL') %>" class="mediaURL" id="instagramURL"> <a href="#" class="mediaURL" id="instagramURL" disabled>
<svg id="instagramSVG" class="mediaSVG" viewBox="0 0 5040 5040"> <svg id="instagramSVG" class="mediaSVG" viewBox="0 0 5040 5040">
<defs> <defs>
<radialGradient id="instaFill" cx="30%" cy="107%" r="150%"> <radialGradient id="instaFill" cx="30%" cy="107%" r="150%">
@ -69,7 +69,7 @@
</a> </a>
</div> </div>
<div class="mediaContainer"> <div class="mediaContainer">
<a href="<%- lang('landing.mediaYouTubeURL') %>" class="mediaURL" id="youtubeURL"> <a href="#" class="mediaURL" id="youtubeURL" disabled>
<svg id="youtubeSVG" class="mediaSVG" viewBox="35.34 34.3575 70.68 68.71500"> <svg id="youtubeSVG" class="mediaSVG" viewBox="35.34 34.3575 70.68 68.71500">
<g> <g>
<path d="M84.8,69.52,65.88,79.76V59.27Zm23.65.59c0-5.14-.79-17.63-3.94-20.57S99,45.86,73.37,45.86s-28,.73-31.14,3.68S38.29,65,38.29,70.11s.79,17.63,3.94,20.57,5.52,3.68,31.14,3.68,28-.74,31.14-3.68,3.94-15.42,3.94-20.57"/> <path d="M84.8,69.52,65.88,79.76V59.27Zm23.65.59c0-5.14-.79-17.63-3.94-20.57S99,45.86,73.37,45.86s-28,.73-31.14,3.68S38.29,65,38.29,70.11s.79,17.63,3.94,20.57,5.52,3.68,31.14,3.68,28-.74,31.14-3.68,3.94-15.42,3.94-20.57"/>
@ -78,7 +78,7 @@
</a> </a>
</div> </div>
<div class="mediaContainer"> <div class="mediaContainer">
<a href="<%- lang('landing.mediaDiscordURL') %>" class="mediaURL" id="discordURL"> <a href="https://discord.gg/zNWUXdt" class="mediaURL" id="discordURL">
<svg id="discordSVG" class="mediaSVG" viewBox="35.34 34.3575 70.68 68.71500"> <svg id="discordSVG" class="mediaSVG" viewBox="35.34 34.3575 70.68 68.71500">
<g> <g>
<path d="M81.23,78.48a6.14,6.14,0,1,1,6.14-6.14,6.14,6.14,0,0,1-6.14,6.14M60,78.48a6.14,6.14,0,1,1,6.14-6.14A6.14,6.14,0,0,1,60,78.48M104.41,73c-.92-7.7-8.24-22.9-8.24-22.9A43,43,0,0,0,88,45.59a17.88,17.88,0,0,0-8.38-1.27l-.13,1.06a23.52,23.52,0,0,1,5.8,1.95,87.59,87.59,0,0,1,8.17,4.87s-10.32-5.63-22.27-5.63a51.32,51.32,0,0,0-23.2,5.63,87.84,87.84,0,0,1,8.17-4.87,23.57,23.57,0,0,1,5.8-1.95l-.13-1.06a17.88,17.88,0,0,0-8.38,1.27,42.84,42.84,0,0,0-8.21,4.56S37.87,65.35,37,73s-.37,11.54-.37,11.54,4.22,5.68,9.9,7.14,7.7,1.47,7.7,1.47l3.75-4.68a21.22,21.22,0,0,1-4.65-2A24.47,24.47,0,0,1,47.93,82S61.16,88.4,70.68,88.4c10,0,22.75-6.44,22.75-6.44a24.56,24.56,0,0,1-5.35,4.56,21.22,21.22,0,0,1-4.65,2l3.75,4.68s2,0,7.7-1.47,9.89-7.14,9.89-7.14.55-3.85-.37-11.54"/> <path d="M81.23,78.48a6.14,6.14,0,1,1,6.14-6.14,6.14,6.14,0,0,1-6.14,6.14M60,78.48a6.14,6.14,0,1,1,6.14-6.14A6.14,6.14,0,0,1,60,78.48M104.41,73c-.92-7.7-8.24-22.9-8.24-22.9A43,43,0,0,0,88,45.59a17.88,17.88,0,0,0-8.38-1.27l-.13,1.06a23.52,23.52,0,0,1,5.8,1.95,87.59,87.59,0,0,1,8.17,4.87s-10.32-5.63-22.27-5.63a51.32,51.32,0,0,0-23.2,5.63,87.84,87.84,0,0,1,8.17-4.87,23.57,23.57,0,0,1,5.8-1.95l-.13-1.06a17.88,17.88,0,0,0-8.38,1.27,42.84,42.84,0,0,0-8.21,4.56S37.87,65.35,37,73s-.37,11.54-.37,11.54,4.22,5.68,9.9,7.14,7.7,1.47,7.7,1.47l3.75-4.68a21.22,21.22,0,0,1-4.65-2A24.47,24.47,0,0,1,47.93,82S61.16,88.4,70.68,88.4c10,0,22.75-6.44,22.75-6.44a24.56,24.56,0,0,1-5.35,4.56,21.22,21.22,0,0,1-4.65,2l3.75,4.68s2,0,7.7-1.47,9.89-7.14,9.89-7.14.55-3.85-.37-11.54"/>
@ -96,21 +96,21 @@
<div class="bot_wrapper"> <div class="bot_wrapper">
<div id="content"> <div id="content">
<div id="server_status_wrapper"> <div id="server_status_wrapper">
<span class="bot_label" id="landingPlayerLabel"><%- lang('landing.serverStatus') %></span> <span class="bot_label" id="landingPlayerLabel">SERVER</span>
<span id="player_count"><%- lang('landing.serverStatusPlaceholder') %></span> <span id="player_count">OFFLINE</span>
</div> </div>
<div class="bot_divider"></div> <div class="bot_divider"></div>
<div id="mojangStatusWrapper"> <div id="mojangStatusWrapper">
<span class="bot_label"><%- lang('landing.mojangStatus') %></span> <span class="bot_label">MOJANG STATUS</span>
<span id="mojang_status_icon">&#8226;</span> <span id="mojang_status_icon">&#8226;</span>
<div id="mojangStatusTooltip"> <div id="mojangStatusTooltip">
<div id="mojangStatusTooltipTitle"><%- lang('landing.mojangStatusTooltipTitle') %></div> <div id="mojangStatusTooltipTitle">Services</div>
<div id="mojangStatusEssentialContainer"> <div id="mojangStatusEssentialContainer">
<!-- Essential Mojang services are populated here. --> <!-- Essential Mojang services are populated here. -->
</div> </div>
<div id="mojangStatusNEContainer"> <div id="mojangStatusNEContainer">
<div class="mojangStatusNEBar"></div> <div class="mojangStatusNEBar"></div>
<div id="mojangStatusNETitle"><%- lang('landing.mojangStatusNETitle') %></div> <div id="mojangStatusNETitle">Non&nbsp;Essential</div>
<div class="mojangStatusNEBar"></div> <div class="mojangStatusNEBar"></div>
</div> </div>
<div id="mojangStatusNonEssentialContainer"> <div id="mojangStatusNonEssentialContainer">
@ -133,7 +133,7 @@
</defs> </defs>
<polyline class="arrowLine" points="0.71 13.26 12.56 1.41 24.16 13.02"/> <polyline class="arrowLine" points="0.71 13.26 12.56 1.41 24.16 13.02"/>
</svg> </svg>
&#10;<span id="newsButtonText"><%- lang('landing.newsButton') %></span> &#10;<span id="newsButtonText">NEWS</span>
</button> </button>
</div> </div>
</div> </div>
@ -141,9 +141,9 @@
<div id="right"> <div id="right">
<div class="bot_wrapper"> <div class="bot_wrapper">
<div id="launch_content"> <div id="launch_content">
<button id="launch_button"><%- lang('landing.launchButton') %></button> <button id="launch_button">PLAY</button>
<div class="bot_divider"></div> <div class="bot_divider"></div>
<button id="server_selection_button" class="bot_label"><%- lang('landing.launchButtonPlaceholder') %></button> <button id="server_selection_button" class="bot_label">&#8226; No Server Selected</button>
</div> </div>
<div id="launch_details"> <div id="launch_details">
<div id="launch_details_left"> <div id="launch_details_left">
@ -152,7 +152,7 @@
</div> </div>
<div id="launch_details_right"> <div id="launch_details_right">
<progress id="launch_progress" value="22" max="100"></progress> <progress id="launch_progress" value="22" max="100"></progress>
<span id="launch_details_text" class="bot_label"><%- lang('landing.launchDetails') %></span> <span id="launch_details_text" class="bot_label">Please wait..</span>
</div> </div>
</div> </div>
</div> </div>
@ -184,7 +184,7 @@
<polyline class="arrowLine" points="0.71 13.26 12.56 1.41 24.16 13.02"/> <polyline class="arrowLine" points="0.71 13.26 12.56 1.41 24.16 13.02"/>
</svg> </svg>
</button> </button>
<span id="newsNavigationStatus"><%- lang('landing.newsNavigationStatus', { currentPage: 1, totalPages: 1 }) %></span> <span id="newsNavigationStatus">1 of 1</span>
<button id="newsNavigateRight"> <button id="newsNavigateRight">
<svg id="newsNavigationRightSVG" viewBox="0 0 24.87 13.97"> <svg id="newsNavigationRightSVG" viewBox="0 0 24.87 13.97">
<defs> <defs>
@ -205,16 +205,16 @@
</div> </div>
<div id="newsErrorContainer"> <div id="newsErrorContainer">
<div id="newsErrorLoading"> <div id="newsErrorLoading">
<span id="nELoadSpan" class="newsErrorContent"><%- lang('landing.newsErrorLoadSpan') %></span> <span id="nELoadSpan" class="newsErrorContent">Checking for News..</span>
</div> </div>
<div id="newsErrorFailed" style="display: none;"> <div id="newsErrorFailed" style="display: none;">
<span id="nEFailedSpan" class="newsErrorContent"><%- lang('landing.newsErrorFailedSpan') %></span> <span id="nEFailedSpan" class="newsErrorContent">Failed to Load News</span>
<button id="newsErrorRetry"><%- lang('landing.newsErrorRetryButton') %></button> <button id="newsErrorRetry">Try Again</button>
</div> </div>
<div id="newsErrorNone" style="display: none;"> <div id="newsErrorNone" style="display: none;">
<span id="nENoneSpan" class="newsErrorContent"><%- lang('landing.newsErrorNoneSpan') %></span> <span id="nENoneSpan" class="newsErrorContent">No News</span>
</div> </div>
</div> </div>
</div> </div>
<script src="./assets/js/scripts/landing.js"></script> <script src="../../out/scripts/landing.js"></script>
</div> </div>

View File

@ -2,21 +2,21 @@
<div id="loginCancelContainer" style="display: none;"> <div id="loginCancelContainer" style="display: none;">
<button id="loginCancelButton"> <button id="loginCancelButton">
<div id="loginCancelIcon">X</div> <div id="loginCancelIcon">X</div>
<span id="loginCancelText"><%- lang('login.loginCancelText') %></span> <span id="loginCancelText">Cancel</span>
</button> </button>
</div> </div>
<div id="loginContent"> <div id="loginContent">
<form id="loginForm"> <form id="loginForm">
<img id="loginImageSeal" src="assets/images/SealCircle.png"/> <img id="loginImageSeal" src="../images/SealCircle.png"/>
<span id="loginSubheader"><%- lang('login.loginSubheader') %></span> <span id="loginSubheader">MINECRAFT LOGIN</span>
<div class="loginFieldContainer"> <div class="loginFieldContainer">
<svg id="profileSVG" class="loginSVG" viewBox="40 37 65.36 61.43"> <svg id="profileSVG" class="loginSVG" viewBox="40 37 65.36 61.43">
<g> <g>
<path d="M86.77,58.12A13.79,13.79,0,1,0,73,71.91,13.79,13.79,0,0,0,86.77,58.12M97,103.67a3.41,3.41,0,0,0,3.39-3.84,27.57,27.57,0,0,0-54.61,0,3.41,3.41,0,0,0,3.39,3.84Z"/> <path d="M86.77,58.12A13.79,13.79,0,1,0,73,71.91,13.79,13.79,0,0,0,86.77,58.12M97,103.67a3.41,3.41,0,0,0,3.39-3.84,27.57,27.57,0,0,0-54.61,0,3.41,3.41,0,0,0,3.39,3.84Z"/>
</g> </g>
</svg> </svg>
<span class="loginErrorSpan" id="loginEmailError"><%- lang('login.loginEmailError') %></span> <span class="loginErrorSpan" id="loginEmailError">* Invalid Value</span>
<input id="loginUsername" class="loginField" type="text" placeholder="<%- lang('login.loginEmailPlaceholder') %>"/> <input id="loginUsername" class="loginField" type="text" placeholder="EMAIL OR USERNAME"/>
</div> </div>
<div class="loginFieldContainer"> <div class="loginFieldContainer">
<svg id="lockSVG" class="loginSVG" viewBox="40 32 60.36 70.43"> <svg id="lockSVG" class="loginSVG" viewBox="40 32 60.36 70.43">
@ -24,22 +24,22 @@
<path d="M86.16,54a16.38,16.38,0,1,0-32,0H44V102.7H96V54Zm-25.9-3.39a9.89,9.89,0,1,1,19.77,0A9.78,9.78,0,0,1,79.39,54H60.89A9.78,9.78,0,0,1,60.26,50.59ZM70,96.2a6.5,6.5,0,0,1-6.5-6.5,6.39,6.39,0,0,1,3.1-5.4V67h6.5V84.11a6.42,6.42,0,0,1,3.39,5.6A6.5,6.5,0,0,1,70,96.2Z"/> <path d="M86.16,54a16.38,16.38,0,1,0-32,0H44V102.7H96V54Zm-25.9-3.39a9.89,9.89,0,1,1,19.77,0A9.78,9.78,0,0,1,79.39,54H60.89A9.78,9.78,0,0,1,60.26,50.59ZM70,96.2a6.5,6.5,0,0,1-6.5-6.5,6.39,6.39,0,0,1,3.1-5.4V67h6.5V84.11a6.42,6.42,0,0,1,3.39,5.6A6.5,6.5,0,0,1,70,96.2Z"/>
</g> </g>
</svg> </svg>
<span class="loginErrorSpan" id="loginPasswordError"><%- lang('login.loginPasswordError') %></span> <span class="loginErrorSpan" id="loginPasswordError">* Required</span>
<input id="loginPassword" class="loginField" type="password" placeholder="<%- lang('login.loginPasswordPlaceholder') %>"/> <input id="loginPassword" class="loginField" type="password" placeholder="PASSWORD"/>
</div> </div>
<div id="loginOptions"> <div id="loginOptions">
<span class="loginSpanDim"> <span class="loginSpanDim">
<a href="<%- lang('login.loginForgotPasswordLink') %>"><%- lang('login.loginForgotPasswordText') %></a> <a href="https://help.mojang.com/customer/en/portal/articles/329524-change-or-forgot-password">forgot password?</a>
</span> </span>
<label id="checkmarkContainer"> <label id="checkmarkContainer">
<input id="loginRememberOption" type="checkbox" checked> <input id="loginRememberOption" type="checkbox" checked>
<span id="loginRememberText" class="loginSpanDim"><%- lang('login.loginRememberMeText') %></span> <span id="loginRememberText" class="loginSpanDim">remember me?</span>
<span class="loginCheckmark"></span> <span class="loginCheckmark"></span>
</label> </label>
</div> </div>
<button id="loginButton" disabled> <button id="loginButton" disabled>
<div id="loginButtonContent"> <div id="loginButtonContent">
<%- lang('login.loginButtonText') %> LOGIN
<svg id="loginSVG" viewBox="0 0 24.87 13.97"> <svg id="loginSVG" viewBox="0 0 24.87 13.97">
<defs> <defs>
<style>.arrowLine{fill:none;stroke:#FFF;stroke-width:2px;transition: 0.25s ease;}</style> <style>.arrowLine{fill:none;stroke:#FFF;stroke-width:2px;transition: 0.25s ease;}</style>
@ -54,12 +54,12 @@
</button> </button>
<div id="loginDisclaimer"> <div id="loginDisclaimer">
<span class="loginSpanDim" id="loginRegisterSpan"> <span class="loginSpanDim" id="loginRegisterSpan">
<a href="<%- lang('login.loginNeedAccountLink') %>"><%- lang('login.loginNeedAccountText') %></a> <a href="https://minecraft.net/en-us/store/minecraft/">Need an Account?</a>
</span> </span>
<p class="loginDisclaimerText"><%- lang('login.loginPasswordDisclaimer1') %></p> <p class="loginDisclaimerText">Your password is sent directly to mojang and never stored.</p>
<p class="loginDisclaimerText"><%- lang('login.loginPasswordDisclaimer2', { appName: lang('app.title') }) %></p> <p class="loginDisclaimerText">Helios Launcher is not affiliated with Mojang AB.</p>
</div> </div>
</form> </form>
</div> </div>
<script src="./assets/js/scripts/login.js"></script> <script src="../../out/scripts/login.js"></script>
</div> </div>

View File

@ -1,29 +1,29 @@
<div id="overlayContainer" style="display: none;"> <div id="overlayContainer" style="display: none;">
<div id="serverSelectContent" style="display: none;"> <div id="serverSelectContent" style="display: none;">
<span id="serverSelectHeader"><%- lang('overlay.serverSelectHeader') %></span> <span id="serverSelectHeader">Available Servers</span>
<div id="serverSelectList"> <div id="serverSelectList">
<div id="serverSelectListScrollable"> <div id="serverSelectListScrollable">
<!-- Server listings populated here. --> <!-- Server listings populated here. -->
</div> </div>
</div> </div>
<div id="serverSelectActions"> <div id="serverSelectActions">
<button id="serverSelectConfirm" class="overlayKeybindEnter" type="submit"><%- lang('overlay.serverSelectConfirm') %></button> <button id="serverSelectConfirm" class="overlayKeybindEnter" type="submit">Select</button>
<div id="serverSelectCancelWrapper"> <div id="serverSelectCancelWrapper">
<button id="serverSelectCancel" class="overlayKeybindEsc"><%- lang('overlay.serverSelectCancel') %></button> <button id="serverSelectCancel" class="overlayKeybindEsc">Cancel</button>
</div> </div>
</div> </div>
</div> </div>
<div id="accountSelectContent" style="display: none;"> <div id="accountSelectContent" style="display: none;">
<span id="accountSelectHeader"><%- lang('overlay.accountSelectHeader') %></span> <span id="accountSelectHeader">Select an Account</span>
<div id="accountSelectList"> <div id="accountSelectList">
<div id="accountSelectListScrollable"> <div id="accountSelectListScrollable">
<!-- Accounts populated here. --> <!-- Accounts populated here. -->
</div> </div>
</div> </div>
<div id="accountSelectActions"> <div id="accountSelectActions">
<button id="accountSelectConfirm" class="overlayKeybindEnter" type="submit"><%- lang('overlay.accountSelectConfirm') %></button> <button id="accountSelectConfirm" class="overlayKeybindEnter" type="submit">Select</button>
<div id="accountSelectCancelWrapper"> <div id="accountSelectCancelWrapper">
<button id="accountSelectCancel" class="overlayKeybindEsc"><%- lang('overlay.accountSelectCancel') %></button> <button id="accountSelectCancel" class="overlayKeybindEsc">Cancel</button>
</div> </div>
</div> </div>
</div> </div>
@ -37,5 +37,5 @@
</div> </div>
</div> </div>
</div> </div>
<script src="./assets/js/scripts/overlay.js"></script> <script src="../../out/scripts/overlay.js"></script>
</div> </div>

View File

@ -2,21 +2,21 @@
<div id="settingsContainerLeft"> <div id="settingsContainerLeft">
<div id="settingsNavContainer"> <div id="settingsNavContainer">
<div id="settingsNavHeader"> <div id="settingsNavHeader">
<span id="settingsNavHeaderText"><%- lang('settings.navHeaderText') %></span> <span id="settingsNavHeaderText">Settings</span>
</div> </div>
<div id="settingsNavItemsContainer"> <div id="settingsNavItemsContainer">
<div id="settingsNavItemsContent"> <div id="settingsNavItemsContent">
<button class="settingsNavItem" rSc="settingsTabAccount" id="settingsNavAccount" selected><%- lang('settings.navAccount') %></button> <button class="settingsNavItem" rSc="settingsTabAccount" id="settingsNavAccount" selected>Account</button>
<button class="settingsNavItem" rSc="settingsTabMinecraft"><%- lang('settings.navMinecraft') %></button> <button class="settingsNavItem" rSc="settingsTabMinecraft">Minecraft</button>
<button class="settingsNavItem" rSc="settingsTabMods"><%- lang('settings.navMods') %></button> <button class="settingsNavItem" rSc="settingsTabMods">Mods</button>
<button class="settingsNavItem" rSc="settingsTabJava"><%- lang('settings.navJava') %></button> <button class="settingsNavItem" rSc="settingsTabJava">Java</button>
<button class="settingsNavItem" rSc="settingsTabLauncher"><%- lang('settings.navLauncher') %></button> <button class="settingsNavItem" rSc="settingsTabLauncher">Launcher</button>
<div class="settingsNavSpacer"></div> <div class="settingsNavSpacer"></div>
<button class="settingsNavItem" rSc="settingsTabAbout"><%- lang('settings.navAbout') %></button> <button class="settingsNavItem" rSc="settingsTabAbout">About</button>
<button class="settingsNavItem" rSc="settingsTabUpdate" id="settingsNavUpdate"><%- lang('settings.navUpdates') %></button> <button class="settingsNavItem" rSc="settingsTabUpdate" id="settingsNavUpdate">Updates</button>
<div id="settingsNavContentBottom"> <div id="settingsNavContentBottom">
<div class="settingsNavDivider"></div> <div class="settingsNavDivider"></div>
<button id="settingsNavDone"><%- lang('settings.navDone') %></button> <button id="settingsNavDone">Done</button>
</div> </div>
</div> </div>
</div> </div>
@ -25,57 +25,28 @@
<div id="settingsContainerRight"> <div id="settingsContainerRight">
<div id="settingsTabAccount" class="settingsTab"> <div id="settingsTabAccount" class="settingsTab">
<div class="settingsTabHeader"> <div class="settingsTabHeader">
<span class="settingsTabHeaderText"><%- lang('settings.tabAccountHeaderText') %></span> <span class="settingsTabHeaderText">Account Settings</span>
<span class="settingsTabHeaderDesc"><%- lang('settings.tabAccountHeaderDesc') %></span> <span class="settingsTabHeaderDesc">Add new accounts or manage existing ones.</span>
</div> </div>
<div class="settingsAuthAccountTypeContainer"> <div id="settingsAddAccountContainer">
<div class="settingsAuthAccountTypeHeader"> <button id="settingsAddAccount">
<div class="settingsAuthAccountTypeHeaderLeft"> <span id="settingsAddAccountText">&#43; Add Account</span>
<svg xmlns="http://www.w3.org/2000/svg" width="22" height="22" viewBox="0 0 23 23"> </button>
<path fill="#f35325" d="M1 1h10v10H1z" />
<path fill="#81bc06" d="M12 1h10v10H12z" />
<path fill="#05a6f0" d="M1 12h10v10H1z" />
<path fill="#ffba08" d="M12 12h10v10H12z" />
</svg>
<span><%- lang('settings.microsoftAccount') %></span>
</div> </div>
<div class="settingsAuthAccountTypeHeaderRight"> <div id="settingsCurrentAccountsHeader">
<button class="settingsAddAuthAccount" id="settingsAddMicrosoftAccount"><%- lang('settings.addMicrosoftAccount') %></button> <span class="settingsFieldTitle">Current Accounts</span>
</div>
</div>
<div class="settingsCurrentAccounts" id="settingsCurrentMicrosoftAccounts">
<!-- Microsoft auth accounts populated here. -->
</div>
</div>
<div class="settingsAuthAccountTypeContainer">
<div class="settingsAuthAccountTypeHeader">
<div class="settingsAuthAccountTypeHeaderLeft">
<svg xmlns="http://www.w3.org/2000/svg" width="22" height="22" viewBox="0 0 9.677 9.667">
<path d="M-26.332-12.098h2.715c-1.357.18-2.574 1.23-2.715 2.633z" fill="#fff" />
<path d="M2.598.022h7.07L9.665 7c-.003 1.334-1.113 2.46-2.402 2.654H0V2.542C.134 1.2 1.3.195 2.598.022z" fill="#db2331" />
<path d="M1.54 2.844c.314-.76 1.31-.46 1.954-.528.785-.083 1.503.272 2.1.758l.164-.9c.327.345.587.756.964 1.052.28.254.655-.342.86-.013.42.864.408 1.86.54 2.795l-.788-.373C6.9 4.17 5.126 3.052 3.656 3.685c-1.294.592-1.156 2.65.06 3.255 1.354.703 2.953.51 4.405.292-.07.42-.34.87-.834.816l-4.95.002c-.5.055-.886-.413-.838-.89l.04-4.315z" fill="#fff" />
</svg>
<span><%- lang('settings.mojangAccount') %></span>
</div>
<div class="settingsAuthAccountTypeHeaderRight">
<button class="settingsAddAuthAccount" id="settingsAddMojangAccount"><%- lang('settings.addMojangAccount') %></button>
</div>
</div>
<div class="settingsCurrentAccounts" id="settingsCurrentMojangAccounts">
<!-- Mojang auth accounts populated here. -->
</div> </div>
<div id="settingsCurrentAccounts">
<!-- Auth accounts populated here. -->
</div> </div>
</div> </div>
<div id="settingsTabMinecraft" class="settingsTab" style="display: none;"> <div id="settingsTabMinecraft" class="settingsTab" style="display: none;">
<div class="settingsTabHeader"> <div class="settingsTabHeader">
<span class="settingsTabHeaderText"><%- lang('settings.minecraftTabHeaderText') %></span> <span class="settingsTabHeaderText">Minecraft Settings</span>
<span class="settingsTabHeaderDesc"><%- lang('settings.minecraftTabHeaderDesc') %></span> <span class="settingsTabHeaderDesc">Options related to game launch.</span>
</div> </div>
<div id="settingsGameResolutionContainer"> <div id="settingsGameResolutionContainer">
<span class="settingsFieldTitle"><%- lang('settings.gameResolutionTitle') %></span> <span class="settingsFieldTitle">Game Resolution</span>
<div id="settingsGameResolutionContent"> <div id="settingsGameResolutionContent">
<input type="number" id="settingsGameWidth" min="0" cValue="GameWidth"> <input type="number" id="settingsGameWidth" min="0" cValue="GameWidth">
<div id="settingsGameResolutionCross">&#10006;</div> <div id="settingsGameResolutionCross">&#10006;</div>
@ -84,7 +55,7 @@
</div> </div>
<div class="settingsFieldContainer"> <div class="settingsFieldContainer">
<div class="settingsFieldLeft"> <div class="settingsFieldLeft">
<span class="settingsFieldTitle"><%- lang('settings.launchFullscreenTitle') %></span> <span class="settingsFieldTitle">Launch in fullscreen.</span>
</div> </div>
<div class="settingsFieldRight"> <div class="settingsFieldRight">
<label class="toggleSwitch"> <label class="toggleSwitch">
@ -95,7 +66,7 @@
</div> </div>
<div class="settingsFieldContainer"> <div class="settingsFieldContainer">
<div class="settingsFieldLeft"> <div class="settingsFieldLeft">
<span class="settingsFieldTitle"><%- lang('settings.autoConnectTitle') %></span> <span class="settingsFieldTitle">Automatically connect to the server on launch.</span>
</div> </div>
<div class="settingsFieldRight"> <div class="settingsFieldRight">
<label class="toggleSwitch"> <label class="toggleSwitch">
@ -106,8 +77,8 @@
</div> </div>
<div class="settingsFieldContainer"> <div class="settingsFieldContainer">
<div class="settingsFieldLeft"> <div class="settingsFieldLeft">
<span class="settingsFieldTitle"><%- lang('settings.launchDetachedTitle') %></span> <span class="settingsFieldTitle">Launch game process detached from launcher.</span>
<span class="settingsFieldDesc"><%- lang('settings.launchDetachedDesc') %></span> <span class="settingsFieldDesc">If the game is not detached, closing the launcher will also close the game.</span>
</div> </div>
<div class="settingsFieldRight"> <div class="settingsFieldRight">
<label class="toggleSwitch"> <label class="toggleSwitch">
@ -119,46 +90,46 @@
</div> </div>
<div id="settingsTabMods" class="settingsTab" style="display: none;"> <div id="settingsTabMods" class="settingsTab" style="display: none;">
<div class="settingsTabHeader"> <div class="settingsTabHeader">
<span class="settingsTabHeaderText"><%- lang('settings.tabModsHeaderText') %></span> <span class="settingsTabHeaderText">Mod Settings</span>
<span class="settingsTabHeaderDesc"><%- lang('settings.tabModsHeaderDesc') %></span> <span class="settingsTabHeaderDesc">Enable or disable mods.</span>
</div> </div>
<div class="settingsSelServContainer"> <div id="settingsSelServContainer">
<div class="settingsSelServContent"> <div id="settingsSelServContent">
</div> </div>
<div class="settingsSwitchServerContainer"> <div id="settingsSwitchServerContainer">
<div class="settingsSwitchServerContent"> <div id="settingsSwitchServerContent">
<button class="settingsSwitchServerButton"><%- lang('settings.switchServerButton') %></button> <button id="settingsSwitchServerButton">Switch</button>
</div> </div>
</div> </div>
</div> </div>
<div id="settingsModsContainer"> <div id="settingsModsContainer">
<div id="settingsReqModsContainer"> <div id="settingsReqModsContainer">
<div class="settingsModsHeader"><%- lang('settings.requiredMods') %></div> <div class="settingsModsHeader">Required Mods</div>
<div id="settingsReqModsContent"> <div id="settingsReqModsContent">
</div> </div>
</div> </div>
<div id="settingsOptModsContainer"> <div id="settingsOptModsContainer">
<div class="settingsModsHeader"><%- lang('settings.optionalMods') %></div> <div class="settingsModsHeader">Optional Mods</div>
<div id="settingsOptModsContent"> <div id="settingsOptModsContent">
</div> </div>
</div> </div>
<div id="settingsDropinModsContainer"> <div id="settingsDropinModsContainer">
<div class="settingsModsHeader"><%- lang('settings.dropinMods') %></div> <div class="settingsModsHeader">Drop-in Mods</div>
<button id="settingsDropinFileSystemButton"><%- lang('settings.addMods') %> <span id="settingsDropinRefreshNote"><%- lang('settings.dropinRefreshNote') %></span></button> <button id="settingsDropinFileSystemButton">+ Add Mods <span id="settingsDropinRefreshNote">(F5 to Refresh)</span></button>
<div id="settingsDropinModsContent"> <div id="settingsDropinModsContent">
</div> </div>
</div> </div>
<div id="settingsShadersContainer"> <div id="settingsShadersContainer">
<div class="settingsModsHeader"><%- lang('settings.shaderpacks') %></div> <div class="settingsModsHeader">Shaderpacks</div>
<div id="settingsShaderpackDesc"><%- lang('settings.shaderpackDesc') %></div> <div id="settingsShaderpackDesc">Enable or disable shaders. Please note, shaders will only run smoothly on powerful setups. You may add custom packs here.</div>
<div id="settingsShaderpackWrapper"> <div id="settingsShaderpackWrapper">
<button id="settingsShaderpackButton"> + </button> <button id="settingsShaderpackButton"> + </button>
<div class="settingsSelectContainer"> <div class="settingsSelectContainer">
<div class="settingsSelectSelected" id="settingsShadersSelected"><%- lang('settings.selectShaderpack') %></div> <div class="settingsSelectSelected" id="settingsShadersSelected">Select Shaderpack</div>
<div class="settingsSelectOptions" id="settingsShadersOptions" hidden> <div class="settingsSelectOptions" id="settingsShadersOptions" hidden>
</div> </div>
@ -169,27 +140,17 @@
</div> </div>
<div id="settingsTabJava" class="settingsTab" style="display: none;"> <div id="settingsTabJava" class="settingsTab" style="display: none;">
<div class="settingsTabHeader"> <div class="settingsTabHeader">
<span class="settingsTabHeaderText"><%- lang('settings.tabJavaHeaderText') %></span> <span class="settingsTabHeaderText">Java Settings</span>
<span class="settingsTabHeaderDesc"><%- lang('settings.tabJavaHeaderDesc') %></span> <span class="settingsTabHeaderDesc">Manage the Java configuration (advanced).</span>
</div>
<div class="settingsSelServContainer">
<div class="settingsSelServContent">
</div>
<div class="settingsSwitchServerContainer">
<div class="settingsSwitchServerContent">
<button class="settingsSwitchServerButton"><%- lang('settings.switchServerButton') %></button>
</div>
</div>
</div> </div>
<div id="settingsMemoryContainer"> <div id="settingsMemoryContainer">
<div id="settingsMemoryTitle"><%- lang('settings.memoryTitle') %></div> <div id="settingsMemoryTitle">Memory</div>
<div id="settingsMemoryContent"> <div id="settingsMemoryContent">
<div id="settingsMemoryContentLeft"> <div id="settingsMemoryContentLeft">
<div class="settingsMemoryContentItem"> <div class="settingsMemoryContentItem">
<span class="settingsMemoryHeader"><%- lang('settings.maxRAM') %></span> <span class="settingsMemoryHeader">Maximum RAM</span>
<div class="settingsMemoryActionContainer"> <div class="settingsMemoryActionContainer">
<div id="settingsMaxRAMRange" class="rangeSlider" cValue="MaxRAM" serverDependent min="3" max="8" value="3" step="0.5"> <div id="settingsMaxRAMRange" class="rangeSlider" cValue="MaxRAM" min="3" max="8" value="3" step="0.5">
<div class="rangeSliderBar"></div> <div class="rangeSliderBar"></div>
<div class="rangeSliderTrack"></div> <div class="rangeSliderTrack"></div>
</div> </div>
@ -197,25 +158,25 @@
</div> </div>
</div> </div>
<div class="settingsMemoryContentItem"> <div class="settingsMemoryContentItem">
<span class="settingsMemoryHeader"><%- lang('settings.minRAM') %></span> <span class="settingsMemoryHeader">Minimum RAM</span>
<div class="settingsMemoryActionContainer"> <div class="settingsMemoryActionContainer">
<div id="settingsMinRAMRange" class="rangeSlider" cValue="MinRAM" serverDependent min="3" max="8" value="3" step="0.5"> <div id="settingsMinRAMRange" class="rangeSlider" cValue="MinRAM" min="3" max="8" value="3" step="0.5">
<div class="rangeSliderBar"></div> <div class="rangeSliderBar"></div>
<div class="rangeSliderTrack"></div> <div class="rangeSliderTrack"></div>
</div> </div>
<span id="settingsMinRAMLabel" class="settingsMemoryLabel">3G</span> <span id="settingsMinRAMLabel" class="settingsMemoryLabel">3G</span>
</div> </div>
</div> </div>
<div id="settingsMemoryDesc"><%- lang('settings.memoryDesc') %></div> <div id="settingsMemoryDesc">The recommended minimum RAM is 3 gigabytes. Setting the minimum and maximum values to the same value may reduce lag.</div>
</div> </div>
<div id="settingsMemoryContentRight"> <div id="settingsMemoryContentRight">
<div id="settingsMemoryStatus"> <div id="settingsMemoryStatus">
<div class="settingsMemoryStatusContainer"> <div class="settingsMemoryStatusContainer">
<span class="settingsMemoryStatusTitle"><%- lang('settings.memoryTotalTitle') %></span> <span class="settingsMemoryStatusTitle">Total</span>
<span id="settingsMemoryTotal" class="settingsMemoryStatusValue">16G</span> <span id="settingsMemoryTotal" class="settingsMemoryStatusValue">16G</span>
</div> </div>
<div class="settingsMemoryStatusContainer"> <div class="settingsMemoryStatusContainer">
<span class="settingsMemoryStatusTitle"><%- lang('settings.memoryAvailableTitle') %></span> <span class="settingsMemoryStatusTitle">Available</span>
<span id="settingsMemoryAvail" class="settingsMemoryStatusValue">7.3G</span> <span id="settingsMemoryAvail" class="settingsMemoryStatusValue">7.3G</span>
</div> </div>
</div> </div>
@ -223,9 +184,9 @@
</div> </div>
</div> </div>
<div class="settingsFileSelContainer"> <div class="settingsFileSelContainer">
<div class="settingsFileSelTitle"><%- lang('settings.javaExecutableTitle') %></div> <div class="settingsFileSelTitle">Java Executable</div>
<div class="settingsFileSelContent"> <div class="settingsFileSelContent">
<div id="settingsJavaExecDetails"><!-- Invalid Selection --></div> <div id="settingsJavaExecDetails">Selected: Java 8 Update 172 (x64)</div>
<div class="settingsFileSelActions"> <div class="settingsFileSelActions">
<div class="settingsFileSelIcon"> <div class="settingsFileSelIcon">
<svg class="settingsFileSelSVG" x="0px" y="0px" viewBox="0 0 305.001 305.001"> <svg class="settingsFileSelSVG" x="0px" y="0px" viewBox="0 0 305.001 305.001">
@ -241,14 +202,15 @@
</g> </g>
</svg> </svg>
</div> </div>
<input class="settingsFileSelVal" id="settingsJavaExecVal" type="text" value="null" cValue="JavaExecutable" serverDependent disabled> <input class="settingsFileSelVal" id="settingsJavaExecVal" type="text" value="null" cValue="JavaExecutable" disabled>
<button class="settingsFileSelButton" id="settingsJavaExecSel" dialogTitle="<%- lang('settings.javaExecSelDialogTitle') %>" dialogDirectory="false"><%- lang('settings.javaExecSelButtonText') %></button> <input class="settingsFileSelSel" id="settingsJavaExecSel" type="file" <%= process.platform === 'win32' ? 'accept=.exe' : '' %>>
<label class="settingsFileSelLabel" for="settingsJavaExecSel">Choose File</label>
</div> </div>
</div> </div>
<div class="settingsFileSelDesc"><%- lang('settings.javaExecDesc') %> <strong id="settingsJavaReqDesc"><!-- Requires Java 8 x64. --></strong><br><%- lang('settings.javaPathDesc', {'pathSuffix': `bin${process.platform === 'win32' ? '\\javaw.exe' : '/java'}`}) %></div> <div class="settingsFileSelDesc">The Java executable is validated before game launch. <strong>Requires Java 8 x64.</strong><br>The path should end with <strong>bin<%= process.platform === 'win32' ? '\\javaw.exe' : '/java' %></strong>.</div>
</div> </div>
<div id="settingsJVMOptsContainer"> <div id="settingsJVMOptsContainer">
<div id="settingsJVMOptsTitle"><%- lang('settings.jvmOptsTitle') %></div> <div id="settingsJVMOptsTitle">Additional JVM Options</div>
<div id="settingsJVMOptsContent"> <div id="settingsJVMOptsContent">
<div class="settingsFileSelIcon"> <div class="settingsFileSelIcon">
<svg class="settingsFileSelSVG" x="0px" y="0px" viewBox="0 0 305.001 305.001"> <svg class="settingsFileSelSVG" x="0px" y="0px" viewBox="0 0 305.001 305.001">
@ -264,20 +226,20 @@
</g> </g>
</svg> </svg>
</div> </div>
<input id="settingsJVMOptsVal" cValue="JVMOptions" serverDependent type="text"> <input id="settingsJVMOptsVal" cValue="JVMOptions" type="text">
</div> </div>
<div id="settingsJVMOptsDesc"><%- lang('settings.jvmOptsDesc') %><br><a href="#" id="settingsJvmOptsLink"><!-- Available Options --></a></div> <div id="settingsJVMOptsDesc">Options to be provided to the JVM at runtime. <em>-Xms</em> and <em>-Xmx</em> should not be included.<br><a href="https://docs.oracle.com/javase/8/docs/technotes/tools/<%= process.platform === 'win32' ? 'windows' : 'unix' %>/java.html">Available Options for Java 8</a>.</div>
</div> </div>
</div> </div>
<div id="settingsTabLauncher" class="settingsTab" style="display: none;"> <div id="settingsTabLauncher" class="settingsTab" style="display: none;">
<div class="settingsTabHeader"> <div class="settingsTabHeader">
<span class="settingsTabHeaderText"><%- lang('settings.launcherTabHeaderText') %></span> <span class="settingsTabHeaderText">Launcher Settings</span>
<span class="settingsTabHeaderDesc"><%- lang('settings.launcherTabHeaderDesc') %></span> <span class="settingsTabHeaderDesc">Options related to the launcher itself.</span>
</div> </div>
<div class="settingsFieldContainer"> <div class="settingsFieldContainer">
<div class="settingsFieldLeft"> <div class="settingsFieldLeft">
<span class="settingsFieldTitle"><%- lang('settings.allowPrereleaseTitle') %></span> <span class="settingsFieldTitle">Allow Pre-Release Updates.</span>
<span class="settingsFieldDesc"><%- lang('settings.allowPrereleaseDesc') %></span> <span class="settingsFieldDesc">Pre-Releases include new features which may have not been fully tested or integrated.<br>This will always be true if you are using a pre-release version.</span>
</div> </div>
<div class="settingsFieldRight"> <div class="settingsFieldRight">
<label class="toggleSwitch"> <label class="toggleSwitch">
@ -288,7 +250,7 @@
</div> </div>
<div class="settingsFileSelContainer"> <div class="settingsFileSelContainer">
<div class="settingsFileSelContent"> <div class="settingsFileSelContent">
<div class="settingsFieldTitle" id="settingsDataDirTitle"><%- lang('settings.dataDirectoryTitle') %></div> <div class="settingsFieldTitle" id="settingsDataDirTitle">Data Directory</div>
<div class="settingsFileSelActions"> <div class="settingsFileSelActions">
<div class="settingsFileSelIcon"> <div class="settingsFileSelIcon">
<svg class="settingsFileSelSVG"> <svg class="settingsFileSelSVG">
@ -300,94 +262,95 @@
</svg> </svg>
</div> </div>
<input class="settingsFileSelVal" type="text" value="null" cValue="DataDirectory" disabled> <input class="settingsFileSelVal" type="text" value="null" cValue="DataDirectory" disabled>
<button class="settingsFileSelButton" dialogTitle="<%- lang('settings.selectDataDirectory') %>" dialogDirectory="true"><%- lang('settings.chooseFolder') %></button> <input class="settingsFileSelSel" id="settingsDataDirSel" type="file" webkitdirectory>
<label class="settingsFileSelLabel" for="settingsDataDirSel">Choose Folder</label>
</div> </div>
</div> </div>
<div class="settingsFileSelDesc"><%- lang('settings.dataDirectoryDesc') %></div> <div class="settingsFileSelDesc">All game files and local Java installations will be stored in the data directory.<br>Screenshots and world saves are stored in the instance folder for the corresponding server configuration.</div>
</div> </div>
</div> </div>
<div id="settingsTabAbout" class="settingsTab" style="display: none;"> <div id="settingsTabAbout" class="settingsTab" style="display: none;">
<div class="settingsTabHeader"> <div class="settingsTabHeader">
<span class="settingsTabHeaderText"><%- lang('settings.aboutTabHeaderText') %></span> <span class="settingsTabHeaderText">About</span>
<span class="settingsTabHeaderDesc"><%- lang('settings.aboutTabHeaderDesc') %></span> <span class="settingsTabHeaderDesc">View information and release notes for the current version.</span>
</div> </div>
<div id="settingsAboutCurrentContainer"> <div id="settingsAboutCurrentContainer">
<div id="settingsAboutCurrentContent"> <div id="settingsAboutCurrentContent">
<div id="settingsAboutCurrentHeadline"> <div id="settingsAboutCurrentHeadline">
<img id="settingsAboutLogo" src="./assets/images/SealCircle.png"> <img id="settingsAboutLogo" src="../images/SealCircle.png">
<span id="settingsAboutTitle"><%- lang('settings.aboutTitle', { appName: lang('app.title') }) %></span> <span id="settingsAboutTitle">Helios Launcher</span>
</div> </div>
<div id="settingsAboutCurrentVersion"> <div id="settingsAboutCurrentVersion">
<div id="settingsAboutCurrentVersionCheck">&#10003;</div> <div id="settingsAboutCurrentVersionCheck">&#10003;</div>
<div id="settingsAboutCurrentVersionDetails"> <div id="settingsAboutCurrentVersionDetails">
<span id="settingsAboutCurrentVersionTitle"><%- lang('settings.stableRelease') %></span> <span id="settingsAboutCurrentVersionTitle">Stable Release</span>
<div id="settingsAboutCurrentVersionLine"> <div id="settingsAboutCurrentVersionLine">
<span id="settingsAboutCurrentVersionText"><%- lang('settings.versionText') %></span> <span id="settingsAboutCurrentVersionText">Version </span>
<span id="settingsAboutCurrentVersionValue">0.0.1-alpha.18</span> <span id="settingsAboutCurrentVersionValue">0.0.1-alpha.12</span>
</div> </div>
</div> </div>
</div> </div>
</div> </div>
<div id="settingsAboutButtons"> <div id="settingsAboutButtons">
<a href="<%- lang('settings.sourceGithubLink') %>" id="settingsAboutSourceButton" class="settingsAboutButton"><%- lang('settings.sourceGithub') %></a> <a href="https://github.com/dscalZi/HeliosLauncher" id="settingsAboutSourceButton" class="settingsAboutButton">Source (GitHub)</a>
<!-- The following must be included in third-party usage. --> <!-- The following must be included in third-party usage. -->
<!-- <a href="https://github.com/dscalzi/HeliosLauncher" id="settingsAboutSourceButton" class="settingsAboutButton">Original Source</a> --> <!-- <a href="https://github.com/dscalzi/HeliosLauncher" id="settingsAboutSourceButton" class="settingsAboutButton">Original Source</a> -->
<a href="<%- lang('settings.supportLink') %>" id="settingsAboutSupportButton" class="settingsAboutButton"><%- lang('settings.support') %></a> <a href="https://github.com/dscalZi/HeliosLauncher/issues" id="settingsAboutSupportButton" class="settingsAboutButton">Support</a>
<a href="#" id="settingsAboutDevToolsButton" class="settingsAboutButton"><%- lang('settings.devToolsConsole') %></a> <a href="#" id="settingsAboutDevToolsButton" class="settingsAboutButton">DevTools Console</a>
</div> </div>
</div> </div>
<div class="settingsChangelogContainer"> <div class="settingsChangelogContainer">
<div class="settingsChangelogContent"> <div class="settingsChangelogContent">
<div class="settingsChangelogHeadline"> <div class="settingsChangelogHeadline">
<div class="settingsChangelogLabel"><%- lang('settings.releaseNotes') %></div> <div class="settingsChangelogLabel">Release Notes</div>
<div class="settingsChangelogTitle"><%- lang('settings.changelog') %></div> <div class="settingsChangelogTitle">Changelog</div>
</div> </div>
<div class="settingsChangelogText"> <div class="settingsChangelogText">
<%- lang('settings.noReleaseNotes') %> No Release Notes
</div> </div>
</div> </div>
<div class="settingsChangelogActions"> <div class="settingsChangelogActions">
<a class="settingsChangelogButton settingsAboutButton" href="#"><%- lang('settings.viewReleaseNotes') %></a> <a class="settingsChangelogButton settingsAboutButton" href="#">View Release Notes on GitHub</a>
</div> </div>
</div> </div>
</div> </div>
<div id="settingsTabUpdate" class="settingsTab" style="display: none;"> <div id="settingsTabUpdate" class="settingsTab" style="display: none;">
<div class="settingsTabHeader"> <div class="settingsTabHeader">
<span class="settingsTabHeaderText"><%- lang('settings.launcherUpdatesHeaderText') %></span> <span class="settingsTabHeaderText">Launcher Updates</span>
<span class="settingsTabHeaderDesc"><%- lang('settings.launcherUpdatesHeaderDesc') %></span> <span class="settingsTabHeaderDesc">Download, install, and review updates for the launcher.</span>
</div> </div>
<div id="settingsUpdateStatusContainer"> <div id="settingsUpdateStatusContainer">
<div id="settingsUpdateStatusContent"> <div id="settingsUpdateStatusContent">
<div id="settingsUpdateStatusHeadline"> <div id="settingsUpdateStatusHeadline">
<span id="settingsUpdateTitle"><!-- You Are Running the Latest Version --></span> <span id="settingsUpdateTitle">You Are Running the Latest Version</span>
</div> </div>
<div id="settingsUpdateVersion"> <div id="settingsUpdateVersion">
<div id="settingsUpdateVersionCheck">&#10003;</div> <div id="settingsUpdateVersionCheck">&#10003;</div>
<div id="settingsUpdateVersionDetails"> <div id="settingsUpdateVersionDetails">
<span id="settingsUpdateVersionTitle"><%- lang('settings.stableRelease') %></span> <span id="settingsUpdateVersionTitle">Stable Release</span>
<div id="settingsUpdateVersionLine"> <div id="settingsUpdateVersionLine">
<span id="settingsUpdateVersionText"><%- lang('settings.versionText') %> </span> <span id="settingsUpdateVersionText">Version </span>
<span id="settingsUpdateVersionValue">0.0.1-alpha.18</span> <span id="settingsUpdateVersionValue">0.0.1-alpha.18</span>
</div> </div>
</div> </div>
</div> </div>
<div id="settingsUpdateActionContainer"> <div id="settingsUpdateActionContainer">
<button id="settingsUpdateActionButton"><%- lang('settings.checkForUpdates') %></button> <button id="settingsUpdateActionButton">Check for Updates</button>
</div> </div>
</div> </div>
</div> </div>
<div class="settingsChangelogContainer"> <div class="settingsChangelogContainer">
<div class="settingsChangelogContent"> <div class="settingsChangelogContent">
<div class="settingsChangelogHeadline"> <div class="settingsChangelogHeadline">
<div class="settingsChangelogLabel"><%- lang('settings.whatsNew') %></div> <div class="settingsChangelogLabel">What's New</div>
<div class="settingsChangelogTitle"><%- lang('settings.updateReleaseNotes') %></div> <div class="settingsChangelogTitle">Update Release Notes</div>
</div> </div>
<div class="settingsChangelogText"> <div class="settingsChangelogText">
<%- lang('settings.noReleaseNotes') %> No Release Notes
</div> </div>
</div> </div>
</div> </div>
</div> </div>
</div> </div>
<script src="./assets/js/scripts/settings.js"></script> <script src="../../out/scripts/settings.js"></script>
</div> </div>

View File

@ -0,0 +1,25 @@
<div id="welcomeContainer" style="display: none;">
<!--<div class="cloudDiv">
<div class="cloudTop"></div>
<div class="cloudBottom"></div>
</div>-->
<div id="welcomeContent">
<img id="welcomeImageSeal" src="../images/SealCircle.png"/>
<span id="welcomeHeader">WELCOME TO WESTEROSCRAFT</span>
<span id="welcomeDescription">Our mission is to recreate the universe imagined by author George RR Martin in his fantasy series, A Song of Ice and Fire. Through the collaborative effort of thousands of community members, we have sought to create Westeros as accurately and precisely as possible within Minecraft. The world we are creating is yours to explore. Journey from Dorne to Castle Black, and if you arent afraid, beyond the Wall itself, but best not delay. As the words of House Stark ominously warn: Winter is Coming.</span>
<br>
<span id="welcomeDescCTA">You are just a few clicks away from Westeros.</span>
<button id="welcomeButton">
<div id="welcomeButtonContent">
CONTINUE
<svg id="welcomeSVG" viewBox="0 0 24.87 13.97">
<defs>
<style>.arrowLine{fill:none;stroke:#FFF;stroke-width:2px;transition: 0.25s ease;}</style>
</defs>
<polyline class="arrowLine" points="0.71 13.26 12.56 1.41 24.16 13.02"/>
</svg>
</div>
</button>
</div>
<script src="../../out/scripts/welcome.js"></script>
</div>

69
build.js Normal file
View File

@ -0,0 +1,69 @@
const builder = require('electron-builder')
const Platform = builder.Platform
function getCurrentPlatform(){
switch(process.platform){
case 'win32':
return Platform.WINDOWS
case 'darwin':
return Platform.MAC
case 'linux':
return Platform.linux
default:
console.error('Cannot resolve current platform!')
return undefined
}
}
builder.build({
targets: (process.argv[2] != null && Platform[process.argv[2]] != null ? Platform[process.argv[2]] : getCurrentPlatform()).createTarget(),
config: {
appId: 'helioslauncher',
productName: 'Helios Launcher',
artifactName: '${productName}-setup-${version}.${ext}',
copyright: 'Copyright © 2018-2020 Daniel Scalzi',
directories: {
buildResources: 'build',
output: 'dist'
},
win: {
target: [
{
target: 'nsis',
arch: 'x64'
}
]
},
nsis: {
oneClick: false,
perMachine: false,
allowElevation: true,
allowToChangeInstallationDirectory: true
},
mac: {
target: 'dmg',
category: 'public.app-category.games'
},
linux: {
target: 'AppImage',
maintainer: 'Daniel Scalzi',
vendor: 'Daniel Scalzi',
synopsis: 'Modded Minecraft Launcher',
description: 'Custom launcher which allows users to join modded servers. All mods, configurations, and updates are handled automatically.',
category: 'Game'
},
compression: 'maximum',
files: [
'!{dist,.gitignore,.vscode,docs,dev-app-update.yml,.travis.yml,.nvmrc,.eslintrc.json,build.js}'
],
extraResources: [
'libraries',
'static'
],
asar: true
}
}).then(() => {
console.log('Build complete!')
}).catch(err => {
console.error('Error during build!', err)
})

View File

@ -1,52 +0,0 @@
# Microsoft Authentication
Authenticating with Microsoft is fully supported by Helios Launcher.
## Acquiring an Azure Client ID
1. Navigate to https://portal.azure.com
2. In the search bar, search for **Azure Active Directory**.
3. In Azure Active Directory, go to **App Registrations** on the left pane (Under *Manage*).
4. Click **New Registration**.
- Set **Name** to be your launcher's name.
- Set **Supported account types** to *Accounts in any organizational directory (Any Azure AD directory - Multitenant) and personal Microsoft accounts (e.g. Skype, Xbox)*
- Leave **Redirect URI** blank.
- Register the application.
5. You should be on the application's management page. If not, Navigate back to **App Registrations**. Select the application you just registered.
6. Click **Authentication** on the left pane (Under *Manage*).
7. Click **Add Platform**.
- Select **Mobile and desktop applications**.
- Choose `https://login.microsoftonline.com/common/oauth2/nativeclient` as the **Redirect URI**.
- Select **Configure** to finish adding the platform.
8. Go to **Credentials & secrets**.
- Select **Client secrets**.
- Click **New client secret**.
- Set a description.
- Click **Add**.
- Don't copy the client secret, adding one is just a requirement from Microsoft.
8. Navigate back to **Overview**.
9. Copy **Application (client) ID**.
## Adding the Azure Client ID to Helios Launcher.
In `app/assets/js/ipcconstants.js` you'll find **`AZURE_CLIENT_ID`**. Set it to your application's id.
Note: Azure Client ID is NOT a secret value and **can** be stored in git. Reference: https://stackoverflow.com/questions/57306964/are-azure-active-directorys-tenantid-and-clientid-considered-secrets
Then relaunch your app, and login. You'll be greeted with an error message, because the app isn't whitelisted yet. Microsoft needs some activity on the app before whitelisting it. __Trying to log in before requesting whitelist is mandatory.__
## Requesting whitelisting from Microsoft
1. Ensure you have completed every step of this doc page.
2. Fill [this form](https://aka.ms/mce-reviewappid) with the required information. Remember this is a new appID for approval. You can find both the Client ID and the Tenant ID on the overview page in the Azure Portal.
3. Give Microsoft some time to review your app.
4. Once you have received Microsoft's approval, allow up to 24 hours for the changes to apply.
----
You can now authenticate with Microsoft through the launcher.
References:
- https://docs.microsoft.com/en-us/azure/active-directory/develop/quickstart-register-app
- https://help.minecraft.net/hc/en-us/articles/16254801392141

View File

@ -1,4 +1,8 @@
{ {
"__comment__": [
"This is an example only.",
"The file is hosted on the URL in DistroManager.js"
],
"version": "1.0.0", "version": "1.0.0",
"discord": { "discord": {
"clientId": "385581240906022916", "clientId": "385581240906022916",

View File

@ -1,9 +1,5 @@
# Distribution Index # Distribution Index
You can use [Nebula](https://github.com/dscalzi/Nebula) to automate the generation of a distribution index.
The most up to date and accurate descriptions of the distribution spec can be viewed in [helios-distribution-types](https://github.com/dscalzi/helios-distribution-types).
The distribution index is written in JSON. The general format of the index is as posted below. The distribution index is written in JSON. The general format of the index is as posted below.
```json ```json
@ -145,122 +141,12 @@ Only one server in the array should have the `mainServer` property enabled. This
Whether or not the server can be autoconnected to. If false, the server will not be autoconnected to even when the user has the autoconnect setting enabled. Whether or not the server can be autoconnected to. If false, the server will not be autoconnected to even when the user has the autoconnect setting enabled.
### `Server.javaOptions: JavaOptions`
**OPTIONAL**
Sever-specific Java options. If not provided, defaults are used by the client.
### `Server.modules: Module[]` ### `Server.modules: Module[]`
An array of module objects. An array of module objects.
--- ---
## JavaOptions Object
Server-specific Java options.
#### Example
```JSON
{
"supported": ">=17",
"suggestedMajor": 17,
"platformOptions": [
{
"platform": "darwin",
"architecture": "arm64",
"distribution": "CORRETTO"
}
],
"ram": {
"recommended": 3072,
"minimum": 2048
}
}
```
### `JavaOptions.platformOptions: JavaPlatformOptions[]`
**OPTIONAL**
Platform-specific java rules for this server configuration. Validation rules will be delegated to the client for any undefined properties. Java validation can be configured for specific platforms and architectures. The most specific ruleset will be applied.
Maxtrix Precedence (Highest - Lowest)
- Current platform, current architecture (ex. win32 x64).
- Current platform, any architecture (ex. win32).
- Java Options base properties.
- Client logic (default logic in the client).
Properties:
- `platformOptions.platform: string` - The platform that this validation matrix applies to.
- `platformOptions.architecture: string` - Optional. The architecture that this validation matrix applies to. If omitted, applies to all architectures.
- `platformOptions.distribution: string` - Optional. See `JavaOptions.distribution`.
- `platformOptions.supported: string` - Optional. See `JavaOptions.supported`.
- `platformOptions.suggestedMajor: number` - Optional. See `JavaOptions.suggestedMajor`.
### `JavaOptions.ram: object`
**OPTIONAL**
This allows you to require a minimum and recommended amount of RAM per server instance. The minimum is the smallest value the user can select in the settings slider. The recommended value will be the default value selected for that server. These values are specified in megabytes and must be an interval of 512. This allows configuration in intervals of half gigabytes. In the above example, the recommended ram value is 3 GB (3072 MB) and the minimum is 2 GB (2048 MB).
- `ram.recommended: number` - The recommended amount of RAM in megabytes. Must be an interval of 512.
- `ram.minimum: number` - The absolute minimum amount of RAM in megabytes. Must be an interval of 512.
### `JavaOptions.distribution: string`
**OPTIONAL**
Preferred JDK distribution to download if no applicable installation could be found. If omitted, the client will decide (decision may be platform-specific).
### `JavaOptions.supported: string`
**OPTIONAL**
A semver range of supported JDK versions.
Java version syntax is platform dependent.
JDK 8 and prior
```
1.{major}.{minor}_{patch}-b{build}
Ex. 1.8.0_152-b16
```
JDK 9+
```
{major}.{minor}.{patch}+{build}
Ex. 11.0.12+7
```
For processing, all versions will be translated into a semver compliant string. JDK 9+ is already semver. For versions 8 and below, `1.{major}.{minor}_{patch}-b{build}` will be translated to `{major}.{minor}.{patch}+{build}`.
If specified, you must also specify suggestedMajor.
If omitted, the client will decide based on the game version.
### `JavaOptions.suggestedMajor: number`
**OPTIONAL**
The suggested major Java version. The suggested major should comply with the version range specified by supported, if defined. This will be used in messages displayed to the end user, and to automatically fetch a Java version.
NOTE If supported is specified, suggestedMajor must be set. The launcher's default value may not comply with your custom major supported range.
Common use case:
- supported: '>=17.x'
- suggestedMajor: 17
More involved:
- supported: '>=16 <20'
- suggestedMajor: 17
Given a wider support range, it becomes necessary to specify which major version in the range is the suggested.
---
## Module Object ## Module Object
A module is a generic representation of a file required to run the minecraft client. A module is a generic representation of a file required to run the minecraft client.
@ -320,12 +206,6 @@ The name of the module. Used on the UI.
The type of the module. The type of the module.
### `Module.classpath: boolean`
**OPTIONAL**
If the module is of type `Library`, whether the library should be added to the classpath. Defaults to true.
### `Module.required: Required` ### `Module.required: Required`
**OPTIONAL** **OPTIONAL**
@ -360,12 +240,10 @@ The resolved/provided paths are appended to a base path depending on the module'
| Type | Path | | Type | Path |
| ---- | ---- | | ---- | ---- |
| `ForgeHosted` | ({`commonDirectory`}/libraries/{`path` OR resolved}) | | `ForgeHosted` | ({`commonDirectory`}/libraries/{`path` OR resolved}) |
| `Fabric` | ({`commonDirectory`}/libraries/{`path` OR resolved}) |
| `LiteLoader` | ({`commonDirectory`}/libraries/{`path` OR resolved}) | | `LiteLoader` | ({`commonDirectory`}/libraries/{`path` OR resolved}) |
| `Library` | ({`commonDirectory`}/libraries/{`path` OR resolved}) | | `Library` | ({`commonDirectory`}/libraries/{`path` OR resolved}) |
| `ForgeMod` | ({`commonDirectory`}/modstore/{`path` OR resolved}) | | `ForgeMod` | ({`commonDirectory`}/modstore/{`path` OR resolved}) |
| `LiteMod` | ({`commonDirectory`}/modstore/{`path` OR resolved}) | | `LiteMod` | ({`commonDirectory`}/modstore/{`path` OR resolved}) |
| `FabricMod` | ({`commonDirectory`}/mods/fabric/{`path` OR resolved}) |
| `File` | ({`instanceDirectory`}/{`Server.id`}/{`path` OR resolved}) | | `File` | ({`instanceDirectory`}/{`Server.id`}/{`path` OR resolved}) |
The `commonDirectory` and `instanceDirectory` values are stored in the launcher's config.json. The `commonDirectory` and `instanceDirectory` values are stored in the launcher's config.json.
@ -410,7 +288,7 @@ If the module is enabled by default. Has no effect unless `Required.value` is fa
### ForgeHosted ### ForgeHosted
The module type `ForgeHosted` represents forge itself. Currently, the launcher only supports modded servers, as vanilla servers can be connected to via the mojang launcher. The `Hosted` part is key, this means that the forge module must declare its required libraries as submodules. The module type `ForgeHosted` represents forge itself. Currently, the launcher only supports forge servers, as vanilla servers can be connected to via the mojang launcher. The `Hosted` part is key, this means that the forge module must declare its required libraries as submodules.
Ex. Ex.
@ -445,40 +323,6 @@ There were plans to add a `Forge` type, in which the required libraries would be
--- ---
### Fabric
The module type `Fabric` represents the fabric mod loader. Currently, the launcher only supports modded servers, as vanilla servers can be connected to via the mojang launcher.
Ex.
```json
{
"id": "net.fabricmc:fabric-loader:0.15.0",
"name": "Fabric (fabric-loader)",
"type": "Fabric",
"artifact": {
"size": 1196222,
"MD5": "a43d5a142246801343b6cedef1c102c4",
"url": "http://localhost:8080/repo/lib/net/fabricmc/fabric-loader/0.15.0/fabric-loader-0.15.0.jar"
},
"subModules": [
{
"id": "1.20.1-fabric-0.15.0",
"name": "Fabric (version.json)",
"type": "VersionManifest",
"artifact": {
"size": 2847,
"MD5": "69a2bd43452325ba1bc882fa0904e054",
"url": "http://localhost:8080/repo/versions/1.20.1-fabric-0.15.0/1.20.1-fabric-0.15.0.json"
}
}
}
```
Fabric works similarly to Forge 1.13+.
---
### LiteLoader ### LiteLoader
The module type `LiteLoader` represents liteloader. It is handled as a library and added to the classpath at runtime. Special launch conditions are executed when liteloader is present and enabled. This module can be optional and toggled similarly to `ForgeMod` and `Litemod` modules. The module type `LiteLoader` represents liteloader. It is handled as a library and added to the classpath at runtime. Special launch conditions are executed when liteloader is present and enabled. This module can be optional and toggled similarly to `ForgeMod` and `Litemod` modules.

View File

@ -1,51 +0,0 @@
appId: 'helioslauncher'
productName: 'Helios Launcher'
artifactName: '${productName}-setup-${version}.${ext}'
copyright: 'Copyright © 2018-2022 Daniel Scalzi'
asar: true
compression: 'maximum'
files:
- '!{dist,.gitignore,.vscode,docs,dev-app-update.yml,.nvmrc,.eslintrc.json}'
extraResources:
- 'libraries'
# Windows Configuration
win:
target:
- target: 'nsis'
arch: 'x64'
# Windows Installer Configuration
nsis:
oneClick: false
perMachine: false
allowElevation: true
allowToChangeInstallationDirectory: true
# macOS Configuration
mac:
target:
- target: 'dmg'
arch:
- 'x64'
- 'arm64'
artifactName: '${productName}-setup-${version}-${arch}.${ext}'
category: 'public.app-category.games'
# Linux Configuration
linux:
target: 'AppImage'
maintainer: 'Daniel Scalzi'
vendor: 'Daniel Scalzi'
synopsis: 'Modded Minecraft Launcher'
description: 'Custom launcher which allows users to join modded servers. All mods, configurations, and updates are handled automatically.'
category: 'Game'
directories:
buildResources: 'build'
output: 'dist'

361
index.js
View File

@ -1,361 +0,0 @@
const remoteMain = require('@electron/remote/main')
remoteMain.initialize()
// Requirements
const { app, BrowserWindow, ipcMain, Menu, shell } = require('electron')
const autoUpdater = require('electron-updater').autoUpdater
const ejse = require('ejs-electron')
const fs = require('fs')
const isDev = require('./app/assets/js/isdev')
const path = require('path')
const semver = require('semver')
const { pathToFileURL } = require('url')
const { AZURE_CLIENT_ID, MSFT_OPCODE, MSFT_REPLY_TYPE, MSFT_ERROR, SHELL_OPCODE } = require('./app/assets/js/ipcconstants')
const LangLoader = require('./app/assets/js/langloader')
// Setup Lang
LangLoader.setupLanguage()
// Setup auto updater.
function initAutoUpdater(event, data) {
if(data){
autoUpdater.allowPrerelease = true
} else {
// Defaults to true if application version contains prerelease components (e.g. 0.12.1-alpha.1)
// autoUpdater.allowPrerelease = true
}
if(isDev){
autoUpdater.autoInstallOnAppQuit = false
autoUpdater.updateConfigPath = path.join(__dirname, 'dev-app-update.yml')
}
if(process.platform === 'darwin'){
autoUpdater.autoDownload = false
}
autoUpdater.on('update-available', (info) => {
event.sender.send('autoUpdateNotification', 'update-available', info)
})
autoUpdater.on('update-downloaded', (info) => {
event.sender.send('autoUpdateNotification', 'update-downloaded', info)
})
autoUpdater.on('update-not-available', (info) => {
event.sender.send('autoUpdateNotification', 'update-not-available', info)
})
autoUpdater.on('checking-for-update', () => {
event.sender.send('autoUpdateNotification', 'checking-for-update')
})
autoUpdater.on('error', (err) => {
event.sender.send('autoUpdateNotification', 'realerror', err)
})
}
// Open channel to listen for update actions.
ipcMain.on('autoUpdateAction', (event, arg, data) => {
switch(arg){
case 'initAutoUpdater':
console.log('Initializing auto updater.')
initAutoUpdater(event, data)
event.sender.send('autoUpdateNotification', 'ready')
break
case 'checkForUpdate':
autoUpdater.checkForUpdates()
.catch(err => {
event.sender.send('autoUpdateNotification', 'realerror', err)
})
break
case 'allowPrereleaseChange':
if(!data){
const preRelComp = semver.prerelease(app.getVersion())
if(preRelComp != null && preRelComp.length > 0){
autoUpdater.allowPrerelease = true
} else {
autoUpdater.allowPrerelease = data
}
} else {
autoUpdater.allowPrerelease = data
}
break
case 'installUpdateNow':
autoUpdater.quitAndInstall()
break
default:
console.log('Unknown argument', arg)
break
}
})
// Redirect distribution index event from preloader to renderer.
ipcMain.on('distributionIndexDone', (event, res) => {
event.sender.send('distributionIndexDone', res)
})
// Handle trash item.
ipcMain.handle(SHELL_OPCODE.TRASH_ITEM, async (event, ...args) => {
try {
await shell.trashItem(args[0])
return {
result: true
}
} catch(error) {
return {
result: false,
error: error
}
}
})
// Disable hardware acceleration.
// https://electronjs.org/docs/tutorial/offscreen-rendering
app.disableHardwareAcceleration()
const REDIRECT_URI_PREFIX = 'https://login.microsoftonline.com/common/oauth2/nativeclient?'
// Microsoft Auth Login
let msftAuthWindow
let msftAuthSuccess
let msftAuthViewSuccess
let msftAuthViewOnClose
ipcMain.on(MSFT_OPCODE.OPEN_LOGIN, (ipcEvent, ...arguments_) => {
if (msftAuthWindow) {
ipcEvent.reply(MSFT_OPCODE.REPLY_LOGIN, MSFT_REPLY_TYPE.ERROR, MSFT_ERROR.ALREADY_OPEN, msftAuthViewOnClose)
return
}
msftAuthSuccess = false
msftAuthViewSuccess = arguments_[0]
msftAuthViewOnClose = arguments_[1]
msftAuthWindow = new BrowserWindow({
title: LangLoader.queryJS('index.microsoftLoginTitle'),
backgroundColor: '#222222',
width: 520,
height: 600,
frame: true,
icon: getPlatformIcon('SealCircle')
})
msftAuthWindow.on('closed', () => {
msftAuthWindow = undefined
})
msftAuthWindow.on('close', () => {
if(!msftAuthSuccess) {
ipcEvent.reply(MSFT_OPCODE.REPLY_LOGIN, MSFT_REPLY_TYPE.ERROR, MSFT_ERROR.NOT_FINISHED, msftAuthViewOnClose)
}
})
msftAuthWindow.webContents.on('did-navigate', (_, uri) => {
if (uri.startsWith(REDIRECT_URI_PREFIX)) {
let queries = uri.substring(REDIRECT_URI_PREFIX.length).split('#', 1).toString().split('&')
let queryMap = {}
queries.forEach(query => {
const [name, value] = query.split('=')
queryMap[name] = decodeURI(value)
})
ipcEvent.reply(MSFT_OPCODE.REPLY_LOGIN, MSFT_REPLY_TYPE.SUCCESS, queryMap, msftAuthViewSuccess)
msftAuthSuccess = true
msftAuthWindow.close()
msftAuthWindow = null
}
})
msftAuthWindow.removeMenu()
msftAuthWindow.loadURL(`https://login.microsoftonline.com/consumers/oauth2/v2.0/authorize?prompt=select_account&client_id=${AZURE_CLIENT_ID}&response_type=code&scope=XboxLive.signin%20offline_access&redirect_uri=https://login.microsoftonline.com/common/oauth2/nativeclient`)
})
// Microsoft Auth Logout
let msftLogoutWindow
let msftLogoutSuccess
let msftLogoutSuccessSent
ipcMain.on(MSFT_OPCODE.OPEN_LOGOUT, (ipcEvent, uuid, isLastAccount) => {
if (msftLogoutWindow) {
ipcEvent.reply(MSFT_OPCODE.REPLY_LOGOUT, MSFT_REPLY_TYPE.ERROR, MSFT_ERROR.ALREADY_OPEN)
return
}
msftLogoutSuccess = false
msftLogoutSuccessSent = false
msftLogoutWindow = new BrowserWindow({
title: LangLoader.queryJS('index.microsoftLogoutTitle'),
backgroundColor: '#222222',
width: 520,
height: 600,
frame: true,
icon: getPlatformIcon('SealCircle')
})
msftLogoutWindow.on('closed', () => {
msftLogoutWindow = undefined
})
msftLogoutWindow.on('close', () => {
if(!msftLogoutSuccess) {
ipcEvent.reply(MSFT_OPCODE.REPLY_LOGOUT, MSFT_REPLY_TYPE.ERROR, MSFT_ERROR.NOT_FINISHED)
} else if(!msftLogoutSuccessSent) {
msftLogoutSuccessSent = true
ipcEvent.reply(MSFT_OPCODE.REPLY_LOGOUT, MSFT_REPLY_TYPE.SUCCESS, uuid, isLastAccount)
}
})
msftLogoutWindow.webContents.on('did-navigate', (_, uri) => {
if(uri.startsWith('https://login.microsoftonline.com/common/oauth2/v2.0/logoutsession')) {
msftLogoutSuccess = true
setTimeout(() => {
if(!msftLogoutSuccessSent) {
msftLogoutSuccessSent = true
ipcEvent.reply(MSFT_OPCODE.REPLY_LOGOUT, MSFT_REPLY_TYPE.SUCCESS, uuid, isLastAccount)
}
if(msftLogoutWindow) {
msftLogoutWindow.close()
msftLogoutWindow = null
}
}, 5000)
}
})
msftLogoutWindow.removeMenu()
msftLogoutWindow.loadURL('https://login.microsoftonline.com/common/oauth2/v2.0/logout')
})
// Keep a global reference of the window object, if you don't, the window will
// be closed automatically when the JavaScript object is garbage collected.
let win
function createWindow() {
win = new BrowserWindow({
width: 980,
height: 552,
icon: getPlatformIcon('SealCircle'),
frame: false,
webPreferences: {
preload: path.join(__dirname, 'app', 'assets', 'js', 'preloader.js'),
nodeIntegration: true,
contextIsolation: false
},
backgroundColor: '#171614'
})
remoteMain.enable(win.webContents)
const data = {
bkid: Math.floor((Math.random() * fs.readdirSync(path.join(__dirname, 'app', 'assets', 'images', 'backgrounds')).length)),
lang: (str, placeHolders) => LangLoader.queryEJS(str, placeHolders)
}
Object.entries(data).forEach(([key, val]) => ejse.data(key, val))
win.loadURL(pathToFileURL(path.join(__dirname, 'app', 'app.ejs')).toString())
/*win.once('ready-to-show', () => {
win.show()
})*/
win.removeMenu()
win.resizable = true
win.on('closed', () => {
win = null
})
}
function createMenu() {
if(process.platform === 'darwin') {
// Extend default included application menu to continue support for quit keyboard shortcut
let applicationSubMenu = {
label: 'Application',
submenu: [{
label: 'About Application',
selector: 'orderFrontStandardAboutPanel:'
}, {
type: 'separator'
}, {
label: 'Quit',
accelerator: 'Command+Q',
click: () => {
app.quit()
}
}]
}
// New edit menu adds support for text-editing keyboard shortcuts
let editSubMenu = {
label: 'Edit',
submenu: [{
label: 'Undo',
accelerator: 'CmdOrCtrl+Z',
selector: 'undo:'
}, {
label: 'Redo',
accelerator: 'Shift+CmdOrCtrl+Z',
selector: 'redo:'
}, {
type: 'separator'
}, {
label: 'Cut',
accelerator: 'CmdOrCtrl+X',
selector: 'cut:'
}, {
label: 'Copy',
accelerator: 'CmdOrCtrl+C',
selector: 'copy:'
}, {
label: 'Paste',
accelerator: 'CmdOrCtrl+V',
selector: 'paste:'
}, {
label: 'Select All',
accelerator: 'CmdOrCtrl+A',
selector: 'selectAll:'
}]
}
// Bundle submenus into a single template and build a menu object with it
let menuTemplate = [applicationSubMenu, editSubMenu]
let menuObject = Menu.buildFromTemplate(menuTemplate)
// Assign it to the application
Menu.setApplicationMenu(menuObject)
}
}
function getPlatformIcon(filename){
let ext
switch(process.platform) {
case 'win32':
ext = 'ico'
break
case 'darwin':
case 'linux':
default:
ext = 'png'
break
}
return path.join(__dirname, 'app', 'assets', 'images', `${filename}.${ext}`)
}
app.on('ready', createWindow)
app.on('ready', createMenu)
app.on('window-all-closed', () => {
// On macOS it is common for applications and their menu bar
// to stay active until the user quits explicitly with Cmd + Q
if (process.platform !== 'darwin') {
app.quit()
}
})
app.on('activate', () => {
// On macOS it's common to re-create a window in the app when the
// dock icon is clicked and there are no other windows open.
if (win === null) {
createWindow()
}
})

Binary file not shown.

16326
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@ -1,6 +1,6 @@
{ {
"name": "helioslauncher", "name": "helioslauncher",
"version": "2.1.0", "version": "2.0.0-alpha.0",
"productName": "Helios Launcher", "productName": "Helios Launcher",
"description": "Modded Minecraft Launcher", "description": "Modded Minecraft Launcher",
"author": "Daniel Scalzi (https://github.com/dscalzi/)", "author": "Daniel Scalzi (https://github.com/dscalzi/)",
@ -10,39 +10,90 @@
"url": "https://github.com/dscalzi/HeliosLauncher/issues" "url": "https://github.com/dscalzi/HeliosLauncher/issues"
}, },
"private": true, "private": true,
"main": "index.js", "main": "./dist/main.js",
"scripts": { "scripts": {
"clean": "rimraf dist",
"tsc": "tsc",
"start": "electron .", "start": "electron .",
"dist": "electron-builder build", "cilinux": "node build.js WINDOWS && node build.js LINUX",
"dist:win": "npm run dist -- -w", "cidarwin": "node build.js MAC",
"dist:mac": "npm run dist -- -m", "dist:win": "npm run dist -- WINDOWS",
"dist:linux": "npm run dist -- -l", "dist:mac": "npm run dist -- MAC",
"lint": "eslint --config .eslintrc.json ." "dist:linux": "npm run dist -- LINUX",
"lint": "eslint --ext=jsx,js,tsx,ts src",
"dev": "electron-webpack dev",
"compile": "electron-webpack",
"test": "cross-env TS_NODE_PROJECT='./tsconfig.test.json' NODE_ENV=test mocha -r ts-node/register -r tsconfig-paths/register test/**/*.ts"
}, },
"engines": { "engines": {
"node": "18.x.x" "node": "12.x.x"
}, },
"dependencies": { "dependencies": {
"@electron/remote": "^2.1.0", "adm-zip": "^0.4.16",
"adm-zip": "^0.5.9", "async": "^3.2.0",
"discord-rpc-patch": "^4.0.1", "discord-rpc": "^3.1.4",
"ejs": "^3.1.9", "electron-updater": "^4.3.5",
"ejs-electron": "^2.1.1", "fs-extra": "^9.0.1",
"electron-updater": "^6.1.7",
"fs-extra": "^11.1.1",
"github-syntax-dark": "^0.5.0", "github-syntax-dark": "^0.5.0",
"got": "^11.8.5", "got": "^11.7.0",
"helios-core": "~2.1.0", "jquery": "^3.5.1",
"helios-distribution-types": "^1.3.0", "lodash": "^4.17.20",
"jquery": "^3.7.1", "luxon": "^1.25.0",
"lodash.merge": "^4.6.2", "request": "^2.88.2",
"semver": "^7.5.4", "semver": "^7.3.2",
"toml": "^3.0.0" "tar-fs": "^2.1.0",
"triple-beam": "^1.3.0",
"winreg": "^1.2.4",
"winston": "^3.3.3"
}, },
"devDependencies": { "devDependencies": {
"electron": "^27.1.3", "@babel/preset-react": "^7.10.4",
"electron-builder": "^24.9.1", "@types/adm-zip": "^0.4.33",
"eslint": "^8.55.0" "@types/async": "^3.2.3",
"@types/chai": "^4.2.13",
"@types/chai-as-promised": "^7.1.3",
"@types/discord-rpc": "^3.0.4",
"@types/electron-devtools-installer": "^2.2.0",
"@types/fs-extra": "^9.0.1",
"@types/jquery": "^3.5.2",
"@types/lodash": "^4.14.161",
"@types/luxon": "^1.25.0",
"@types/mocha": "^8.0.3",
"@types/node": "^12.12.64",
"@types/react": "^16.9.51",
"@types/react-dom": "^16.9.8",
"@types/react-redux": "^7.1.9",
"@types/react-transition-group": "^4.4.0",
"@types/request": "^2.48.5",
"@types/tar-fs": "^2.0.0",
"@types/triple-beam": "^1.3.2",
"@types/winreg": "^1.2.30",
"@typescript-eslint/eslint-plugin": "^4.4.0",
"@typescript-eslint/parser": "^4.4.0",
"chai": "^4.2.0",
"chai-as-promised": "^7.1.1",
"cross-env": "^7.0.2",
"electron": "^9.3.2",
"electron-builder": "^22.8.1",
"electron-devtools-installer": "^3.1.1",
"electron-webpack": "^2.8.2",
"electron-webpack-ts": "^4.0.1",
"eslint": "^7.10.0",
"eslint-plugin-react": "^7.21.3",
"helios-distribution-types": "1.0.0-rc.1",
"mocha": "^8.1.3",
"nock": "^13.0.4",
"react": "^16.13.0",
"react-dom": "^16.13.0",
"react-hot-loader": "^4.13.0",
"react-redux": "^7.2.1",
"react-transition-group": "^4.4.1",
"redux": "^4.0.5",
"rimraf": "^3.0.2",
"ts-node": "^9.0.0",
"tsconfig-paths": "^3.9.0",
"typescript": "^4.0.3",
"webpack": "^4.44.2"
}, },
"repository": { "repository": {
"type": "git", "type": "git",

View File

View File

@ -0,0 +1,7 @@
export interface Asset {
id: string
hash: string
size: number
url: string
path: string
}

View File

@ -0,0 +1,33 @@
export class AssetGuardError extends Error {
code?: string
stack!: string
error?: Partial<Error & {code?: string}>
constructor(message: string, error?: Partial<Error & {code?: string}>) {
super(message)
Error.captureStackTrace(this, this.constructor)
// Reference: https://github.com/sindresorhus/got/blob/master/source/core/index.ts#L340
if(error) {
this.error = error
this.code = error?.code
if (error.stack != null) {
const indexOfMessage = this.stack.indexOf(this.message) + this.message.length
const thisStackTrace = this.stack.slice(indexOfMessage).split('\n').reverse()
const errorStackTrace = error.stack.slice(error.stack.indexOf(error.message!) + error.message!.length).split('\n').reverse()
// Remove duplicated traces
while (errorStackTrace.length !== 0 && errorStackTrace[0] === thisStackTrace[0]) {
thisStackTrace.shift()
}
this.stack = `${this.stack.slice(0, indexOfMessage)}${thisStackTrace.reverse().join('\n')}${errorStackTrace.reverse().join('\n')}`
}
}
}
}

View File

@ -0,0 +1,12 @@
import { Asset } from './Asset'
export abstract class IndexProcessor {
constructor(
protected commonDir: string
) {}
abstract async init(): Promise<void>
abstract async validate(): Promise<{[category: string]: Asset[]}>
}

View File

@ -0,0 +1,54 @@
export interface LauncherJava {
sha1: string
url: string
version: string
}
export interface LauncherVersions {
launcher: {
commit: string
name: string
}
}
export interface LauncherJson {
java: {
lzma: {
sha1: string
url: string
}
sha1: string
}
linux: {
applink: string
downloadhash: string
versions: LauncherVersions
}
osx: {
'64': {
jdk: LauncherJava
jre: LauncherJava
}
apphash: string
applink: string
downloadhash: string
versions: LauncherVersions
}
windows: {
'32': {
jdk: LauncherJava
jre: LauncherJava
}
'64': {
jdk: LauncherJava
jre: LauncherJava
}
apphash: string
applink: string
downloadhash: string
rolloutPercent: number
versions: LauncherVersions
}
}

View File

@ -0,0 +1,103 @@
export interface Rule {
action: string
os?: {
name: string
version?: string
}
features?: {
[key: string]: boolean
}
}
export interface Natives {
linux?: string
osx?: string
windows?: string
}
export interface BaseArtifact {
sha1: string
size: number
url: string
}
export interface LibraryArtifact extends BaseArtifact {
path: string
}
export interface Library {
downloads: {
artifact: LibraryArtifact
classifiers?: {
javadoc?: LibraryArtifact
'natives-linux'?: LibraryArtifact
'natives-macos'?: LibraryArtifact
'natives-windows'?: LibraryArtifact
sources?: LibraryArtifact
}
}
extract?: {
exclude: string[]
}
name: string
natives?: Natives
rules?: Rule[]
}
export interface VersionJson {
arguments: {
game: string[]
jvm: {
rules: Rule[]
value: string[]
}[]
}
assetIndex: {
id: string
sha1: string
size: number
totalSize: number
url: string
}
assets: string
downloads: {
client: BaseArtifact
server: BaseArtifact
}
id: string
libraries: Library[]
logging: {
client: {
argument: string
file: {
id: string
sha1: string
size: number
url: string
}
type: string
}
}
mainClass: string
minimumLauncherVersion: number
releaseTime: string
time: string
type: string
}
export interface AssetIndex {
objects: {
[file: string]: {
hash: string
size: number
}
}
}

View File

@ -0,0 +1,15 @@
export interface MojangVersionManifest {
latest: {
release: string
snapshot: string
}
versions: {
id: string
type: string
url: string
time: string
releaseTime: string
}[]
}

View File

@ -0,0 +1,290 @@
import got from 'got'
import { dirname, join } from 'path'
import { ensureDir, pathExists, readFile, readJson, writeFile } from 'fs-extra'
import { Asset } from 'common/asset/model/engine/Asset'
import { AssetGuardError } from 'common/asset/model/engine/AssetGuardError'
import { IndexProcessor } from 'common/asset/model/engine/IndexProcessor'
import { MojangVersionManifest } from 'common/asset/model/mojang/VersionManifest'
import { handleGotError } from 'common/got/RestResponse'
import { AssetIndex, LibraryArtifact, VersionJson } from 'common/asset/model/mojang/VersionJson'
import { calculateHash, getLibraryDir, getVersionJarPath, getVersionJsonPath, validateLocalFile } from 'common/util/FileUtils'
import { getMojangOS, isLibraryCompatible } from 'common/util/MojangUtils'
import { LoggerUtil } from 'common/logging/loggerutil'
export class MojangIndexProcessor extends IndexProcessor {
public static readonly LAUNCHER_JSON_ENDPOINT = 'https://launchermeta.mojang.com/mc/launcher.json'
public static readonly VERSION_MANIFEST_ENDPOINT = 'https://launchermeta.mojang.com/mc/game/version_manifest.json'
public static readonly ASSET_RESOURCE_ENDPOINT = 'http://resources.download.minecraft.net'
private static readonly logger = LoggerUtil.getLogger('MojangIndexProcessor')
private versionJson!: VersionJson
private assetIndex!: AssetIndex
private client = got.extend({
responseType: 'json'
})
private assetPath: string
constructor(commonDir: string, protected version: string) {
super(commonDir)
this.assetPath = join(commonDir, 'assets')
}
/**
* Download https://launchermeta.mojang.com/mc/game/version_manifest.json
* Unable to download:
* Proceed, check versions directory for target version
* If version.json not present, fatal error.
* If version.json present, load and use.
* Able to download:
* Download, use in memory only.
* Locate target version entry.
* Extract hash
* Validate local exists and matches hash
* Condition fails: download
* Download fails: fatal error
* Download succeeds: Save to disk, continue
* Passes: load from file
*
* Version JSON in memory
* Extract assetIndex
* Check that local exists and hash matches
* if false, download
* download fails: fatal error
* if true: load from disk and use
*
* complete init when 3 files are validated and loaded.
*
*/
public async init(): Promise<void> {
const versionManifest = await this.loadVersionManifest()
this.versionJson = await this.loadVersionJson(this.version, versionManifest)
this.assetIndex = await this.loadAssetIndex(this.versionJson)
}
private async loadAssetIndex(versionJson: VersionJson): Promise<AssetIndex> {
const assetIndexPath = this.getAssetIndexPath(versionJson.assetIndex.id)
const assetIndex = await this.loadContentWithRemoteFallback<AssetIndex>(versionJson.assetIndex.url, assetIndexPath, { algo: 'sha1', value: versionJson.assetIndex.sha1 })
if(assetIndex == null) {
throw new AssetGuardError(`Failed to download ${versionJson.assetIndex.id} asset index.`)
}
return assetIndex
}
private async loadVersionJson(version: string, versionManifest: MojangVersionManifest | null): Promise<VersionJson> {
const versionJsonPath = getVersionJsonPath(this.commonDir, version)
if(versionManifest != null) {
const versionJsonUrl = this.getVersionJsonUrl(version, versionManifest)
if(versionJsonUrl == null) {
throw new AssetGuardError(`Invalid version: ${version}.`)
}
const hash = this.getVersionJsonHash(versionJsonUrl)
if(hash == null) {
throw new AssetGuardError('Format of Mojang\'s version manifest has changed. Unable to proceed.')
}
const versionJson = await this.loadContentWithRemoteFallback<VersionJson>(versionJsonUrl, versionJsonPath, { algo: 'sha1', value: hash })
if(versionJson == null) {
throw new AssetGuardError(`Failed to download ${version} json index.`)
}
return versionJson
} else {
// Attempt to find local index.
if(await pathExists(versionJsonPath)) {
return await readJson(versionJsonPath)
} else {
throw new AssetGuardError(`Unable to load version manifest and ${version} json index does not exist locally.`)
}
}
}
private async loadContentWithRemoteFallback<T>(url: string, path: string, hash?: {algo: string, value: string}): Promise<T | null> {
try {
if(await pathExists(path)) {
const buf = await readFile(path)
if(hash) {
const bufHash = calculateHash(buf, hash.algo)
if(bufHash === hash.value) {
return JSON.parse(buf.toString())
}
} else {
return JSON.parse(buf.toString())
}
}
} catch(error) {
throw new AssetGuardError(`Failure while loading ${path}.`, error)
}
try {
const res = await this.client.get<T>(url)
await ensureDir(dirname(path))
await writeFile(path, res.body)
return res.body
} catch(error) {
return handleGotError(url, error, MojangIndexProcessor.logger, () => null).data
}
}
private async loadVersionManifest(): Promise<MojangVersionManifest | null> {
try {
const res = await this.client.get<MojangVersionManifest>(MojangIndexProcessor.VERSION_MANIFEST_ENDPOINT)
return res.body
} catch(error) {
return handleGotError('Load Mojang Version Manifest', error, MojangIndexProcessor.logger, () => null).data
}
}
private getVersionJsonUrl(id: string, manifest: MojangVersionManifest): string | null {
for(const version of manifest.versions) {
if(version.id == id){
return version.url
}
}
return null
}
private getVersionJsonHash(url: string): string | null {
const regex = /^https:\/\/launchermeta.mojang.com\/v1\/packages\/(.+)\/.+.json$/
const match = regex.exec(url)
if(match != null && match[1]) {
return match[1]
} else {
return null
}
}
private getAssetIndexPath(id: string): string {
return join(this.assetPath, 'indexes', `${id}.json`)
}
// TODO progress tracker
// TODO type return object
public async validate(): Promise<{[category: string]: Asset[]}> {
const assets = await this.validateAssets(this.assetIndex)
const libraries = await this.validateLibraries(this.versionJson)
const client = await this.validateClient(this.versionJson)
const logConfig = await this.validateLogConfig(this.versionJson)
return {
assets,
libraries,
client,
misc: [
...logConfig
]
}
}
private async validateAssets(assetIndex: AssetIndex): Promise<Asset[]> {
const objectDir = join(this.assetPath, 'objects')
const notValid: Asset[] = []
for(const assetEntry of Object.entries(assetIndex.objects)) {
const hash = assetEntry[1].hash
const path = join(objectDir, hash.substring(0, 2), hash)
const url = `${MojangIndexProcessor.ASSET_RESOURCE_ENDPOINT}/${hash.substring(0, 2)}/${hash}`
if(!await validateLocalFile(path, 'sha1', hash)) {
notValid.push({
id: assetEntry[0],
hash,
size: assetEntry[1].size,
url,
path
})
}
}
return notValid
}
private async validateLibraries(versionJson: VersionJson): Promise<Asset[]> {
const libDir = getLibraryDir(this.commonDir)
const notValid: Asset[] = []
for(const libEntry of versionJson.libraries) {
if(isLibraryCompatible(libEntry.rules, libEntry.natives)) {
let artifact: LibraryArtifact
if(libEntry.natives == null) {
artifact = libEntry.downloads.artifact
} else {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
const classifier = libEntry.natives[getMojangOS()].replace('${arch}', process.arch.replace('x', ''))
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
artifact = libEntry.downloads.classifiers[classifier]
}
const path = join(libDir, artifact.path)
const hash = artifact.sha1
if(!await validateLocalFile(path, 'sha1', hash)) {
notValid.push({
id: libEntry.name,
hash,
size: artifact.size,
url: artifact.url,
path
})
}
}
}
return notValid
}
private async validateClient(versionJson: VersionJson): Promise<Asset[]> {
const version = versionJson.id
const versionJarPath = getVersionJarPath(this.commonDir, version)
const hash = versionJson.downloads.client.sha1
if(!await validateLocalFile(versionJarPath, 'sha1', hash)) {
return [{
id: `${version} client`,
hash,
size: versionJson.downloads.client.size,
url: versionJson.downloads.client.url,
path: versionJarPath
}]
}
return []
}
private async validateLogConfig(versionJson: VersionJson): Promise<Asset[]> {
const logFile = versionJson.logging.client.file
const path = join(this.assetPath, 'log_configs', logFile.id)
const hash = logFile.sha1
if(!await validateLocalFile(path, 'sha1', hash)) {
return [{
id: logFile.id,
hash,
size: logFile.size,
url: logFile.url,
path
}]
}
return []
}
}

View File

@ -0,0 +1,700 @@
import { join } from 'path'
import { pathExistsSync, writeFileSync, ensureDirSync, readFileSync } from 'fs-extra'
import { totalmem } from 'os'
import { SavedAccount } from './model/SavedAccount'
import { LauncherConfig } from './model/LauncherConfig'
import { ModConfig } from './model/ModConfig'
import { NewsCache } from './model/NewsCache'
import { LoggerUtil } from '../logging/loggerutil'
// TODO final review upon usage in implementation.
export class ConfigManager {
private static readonly logger = LoggerUtil.getLogger('ConfigManager')
private static readonly sysRoot = process.env.APPDATA || (process.platform == 'darwin' ? process.env.HOME + '/Library/Application Support' : process.env.HOME)
private static readonly dataPath = join(ConfigManager.sysRoot as string, '.helioslauncher')
// Forked processes do not have access to electron, so we have this workaround.
private static readonly launcherDir = process.env.CONFIG_DIRECT_PATH || require('electron').remote.app.getPath('userData')
/**
* Retrieve the absolute path of the launcher directory.
*
* @returns {string} The absolute path of the launcher directory.
*/
public static getLauncherDirectory(): string {
return ConfigManager.launcherDir
}
/**
* Get the launcher's data directory. This is where all files related
* to game launch are installed (common, instances, java, etc).
*
* @returns {string} The absolute path of the launcher's data directory.
*/
public static getDataDirectory(def = false): string {
return !def ? ConfigManager.config.settings.launcher.dataDirectory : ConfigManager.DEFAULT_CONFIG.settings.launcher.dataDirectory
}
/**
* Set the new data directory.
*
* @param {string} dataDirectory The new data directory.
*/
public static setDataDirectory(dataDirectory: string): void {
ConfigManager.config.settings.launcher.dataDirectory = dataDirectory
}
private static readonly configPath = join(ConfigManager.getLauncherDirectory(), 'config.json')
private static readonly firstLaunch = !pathExistsSync(ConfigManager.configPath)
/**
* Three types of values:
* Static = Explicitly declared.
* Dynamic = Calculated by a private function.
* Resolved = Resolved externally, defaults to null.
*/
private static readonly DEFAULT_CONFIG: LauncherConfig = {
settings: {
java: {
minRAM: ConfigManager.resolveMinRAM(),
maxRAM: ConfigManager.resolveMaxRAM(), // Dynamic
executable: null,
jvmOptions: [
'-XX:+UseConcMarkSweepGC',
'-XX:+CMSIncrementalMode',
'-XX:-UseAdaptiveSizePolicy',
'-Xmn128M'
]
},
game: {
resWidth: 1280,
resHeight: 720,
fullscreen: false,
autoConnect: true,
launchDetached: true
},
launcher: {
allowPrerelease: false,
dataDirectory: ConfigManager.dataPath
}
},
newsCache: {
date: null,
content: null,
dismissed: false
},
clientToken: null,
selectedServer: null, // Resolved
selectedAccount: null,
authenticationDatabase: {},
modConfigurations: []
}
private static config: LauncherConfig = null as unknown as LauncherConfig
public static getAbsoluteMinRAM(): number {
const mem = totalmem()
return mem >= 6000000000 ? 3 : 2
}
public static getAbsoluteMaxRAM(): number {
const mem = totalmem()
const gT16 = mem-16000000000
return Math.floor((mem-1000000000-(gT16 > 0 ? (Number.parseInt(gT16/8 as unknown as string) + 16000000000/4) : mem/4))/1000000000)
}
private static resolveMaxRAM(){
const mem = totalmem()
return mem >= 8000000000 ? '4G' : (mem >= 6000000000 ? '3G' : '2G')
}
private static resolveMinRAM(){
return ConfigManager.resolveMaxRAM()
}
// Persistance Utility Functions
/**
* Save the current configuration to a file.
*/
public static save(): void {
writeFileSync(ConfigManager.configPath, JSON.stringify(ConfigManager.config, null, 4), 'UTF-8')
}
/**
* Load the configuration into memory. If a configuration file exists,
* that will be read and saved. Otherwise, a default configuration will
* be generated. Note that "resolved" values default to null and will
* need to be externally assigned.
*/
public static load(): void {
let doLoad = true
if(!pathExistsSync(ConfigManager.configPath)){
// Create all parent directories.
ensureDirSync(join(ConfigManager.configPath, '..'))
doLoad = false
ConfigManager.config = ConfigManager.DEFAULT_CONFIG
ConfigManager.save()
}
if(doLoad){
let doValidate = false
try {
ConfigManager.config = JSON.parse(readFileSync(ConfigManager.configPath, 'UTF-8'))
doValidate = true
} catch (err){
ConfigManager.logger.error(err)
ConfigManager.logger.info('Configuration file contains malformed JSON or is corrupt.')
ConfigManager.logger.info('Generating a new configuration file.')
ensureDirSync(join(ConfigManager.configPath, '..'))
ConfigManager.config = ConfigManager.DEFAULT_CONFIG
ConfigManager.save()
}
if(doValidate){
ConfigManager.config = ConfigManager.validateKeySet(ConfigManager.DEFAULT_CONFIG, ConfigManager.config)
ConfigManager.save()
}
}
ConfigManager.logger.info('Successfully Loaded')
}
/**
* @returns {boolean} Whether or not the manager has been loaded.
*/
public static isLoaded(): boolean {
return ConfigManager.config != null
}
/**
* Validate that the destination object has at least every field
* present in the source object. Assign a default value otherwise.
*
* @param {Object} srcObj The source object to reference against.
* @param {Object} destObj The destination object.
* @returns {Object} A validated destination object.
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any
private static validateKeySet(srcObj: any, destObj: any){
if(srcObj == null){
srcObj = {}
}
const validationBlacklist = ['authenticationDatabase']
const keys = Object.keys(srcObj)
for(let i=0; i<keys.length; i++){
if(typeof destObj[keys[i]] === 'undefined'){
destObj[keys[i]] = srcObj[keys[i]]
} else if(typeof srcObj[keys[i]] === 'object' && srcObj[keys[i]] != null && !(srcObj[keys[i]] instanceof Array) && validationBlacklist.indexOf(keys[i]) === -1){
destObj[keys[i]] = ConfigManager.validateKeySet(srcObj[keys[i]], destObj[keys[i]])
}
}
return destObj
}
/**
* Check to see if this is the first time the user has launched the
* application. This is determined by the existance of the data path.
*
* @returns {boolean} True if this is the first launch, otherwise false.
*/
public static isFirstLaunch(): boolean {
return ConfigManager.firstLaunch
}
/**
* Returns the name of the folder in the OS temp directory which we
* will use to extract and store native dependencies for game launch.
*
* @returns {string} The name of the folder.
*/
public static getTempNativeFolder(): string {
return 'HeliosLauncherNatives'
}
// System Settings (Unconfigurable on UI)
/**
* Retrieve the news cache to determine
* whether or not there is newer news.
*
* @returns {NewsCache} The news cache object.
*/
public static getNewsCache(): NewsCache {
return ConfigManager.config.newsCache
}
/**
* Set the new news cache object.
*
* @param {Object} newsCache The new news cache object.
*/
public static setNewsCache(newsCache: NewsCache): void {
ConfigManager.config.newsCache = newsCache
}
/**
* Set whether or not the news has been dismissed (checked)
*
* @param {boolean} dismissed Whether or not the news has been dismissed (checked).
*/
public static setNewsCacheDismissed(dismissed: boolean): void {
ConfigManager.config.newsCache.dismissed = dismissed
}
/**
* Retrieve the common directory for shared
* game files (assets, libraries, etc).
*
* @returns {string} The launcher's common directory.
*/
public static getCommonDirectory(): string {
return join(ConfigManager.getDataDirectory(), 'common')
}
/**
* Retrieve the instance directory for the per
* server game directories.
*
* @returns {string} The launcher's instance directory.
*/
public static getInstanceDirectory(): string {
return join(ConfigManager.getDataDirectory(), 'instances')
}
/**
* Retrieve the launcher's Client Token.
* There is no default client token.
*
* @returns {string | null} The launcher's Client Token.
*/
public static getClientToken(): string | null {
return ConfigManager.config.clientToken
}
/**
* Set the launcher's Client Token.
*
* @param {string} clientToken The launcher's new Client Token.
*/
public static setClientToken(clientToken: string): void {
ConfigManager.config.clientToken = clientToken
}
/**
* Retrieve the ID of the selected serverpack.
*
* @param {boolean} def Optional. If true, the default value will be returned.
* @returns {string | null} The ID of the selected serverpack.
*/
public static getSelectedServer(def = false): string | null {
return !def ? ConfigManager.config.selectedServer : ConfigManager.DEFAULT_CONFIG.selectedServer
}
/**
* Set the ID of the selected serverpack.
*
* @param {string} serverID The ID of the new selected serverpack.
*/
public static setSelectedServer(serverID: string): void {
ConfigManager.config.selectedServer = serverID
}
/**
* Get an array of each account currently authenticated by the launcher.
*
* @returns {Array.<SavedAccount>} An array of each stored authenticated account.
*/
public static getAuthAccounts(): {[uuid: string]: SavedAccount} {
return ConfigManager.config.authenticationDatabase
}
/**
* Returns the authenticated account with the given uuid. Value may
* be null.
*
* @param {string} uuid The uuid of the authenticated account.
* @returns {SavedAccount} The authenticated account with the given uuid.
*/
public static getAuthAccount(uuid: string): SavedAccount {
return ConfigManager.config.authenticationDatabase[uuid]
}
/**
* Update the access token of an authenticated account.
*
* @param {string} uuid The uuid of the authenticated account.
* @param {string} accessToken The new Access Token.
*
* @returns {SavedAccount} The authenticated account object created by this action.
*/
public static updateAuthAccount(uuid: string, accessToken: string): SavedAccount {
ConfigManager.config.authenticationDatabase[uuid].accessToken = accessToken
return ConfigManager.config.authenticationDatabase[uuid]
}
/**
* Adds an authenticated account to the database to be stored.
*
* @param {string} uuid The uuid of the authenticated account.
* @param {string} accessToken The accessToken of the authenticated account.
* @param {string} username The username (usually email) of the authenticated account.
* @param {string} displayName The in game name of the authenticated account.
*
* @returns {SavedAccount} The authenticated account object created by this action.
*/
public static addAuthAccount(
uuid: string,
accessToken: string,
username: string,
displayName: string
): SavedAccount {
ConfigManager.config.selectedAccount = uuid
ConfigManager.config.authenticationDatabase[uuid] = {
accessToken,
username: username.trim(),
uuid: uuid.trim(),
displayName: displayName.trim()
}
return ConfigManager.config.authenticationDatabase[uuid]
}
/**
* Remove an authenticated account from the database. If the account
* was also the selected account, a new one will be selected. If there
* are no accounts, the selected account will be null.
*
* @param {string} uuid The uuid of the authenticated account.
*
* @returns {boolean} True if the account was removed, false if it never existed.
*/
public static removeAuthAccount(uuid: string): boolean {
if(ConfigManager.config.authenticationDatabase[uuid] != null){
delete ConfigManager.config.authenticationDatabase[uuid]
if(ConfigManager.config.selectedAccount === uuid){
const keys = Object.keys(ConfigManager.config.authenticationDatabase)
if(keys.length > 0){
ConfigManager.config.selectedAccount = keys[0]
} else {
ConfigManager.config.selectedAccount = null
ConfigManager.config.clientToken = null
}
}
return true
}
return false
}
/**
* Get the currently selected authenticated account.
*
* @returns {SavedAccount | null} The selected authenticated account.
*/
public static getSelectedAccount(): SavedAccount | null {
return ConfigManager.config.selectedAccount == null ?
null :
ConfigManager.config.authenticationDatabase[ConfigManager.config.selectedAccount]
}
/**
* Set the selected authenticated account.
*
* @param {string} uuid The UUID of the account which is to be set
* as the selected account.
*
* @returns {SavedAccount} The selected authenticated account.
*/
public static setSelectedAccount(uuid: string): SavedAccount {
const authAcc = ConfigManager.config.authenticationDatabase[uuid]
if(authAcc != null) {
ConfigManager.config.selectedAccount = uuid
}
return authAcc
}
/**
* Get an array of each mod configuration currently stored.
*
* @returns {Array.<ModConfig>} An array of each stored mod configuration.
*/
public static getModConfigurations(): ModConfig[] {
return ConfigManager.config.modConfigurations
}
/**
* Set the array of stored mod configurations.
*
* @param {Array.<ModConfig>} configurations An array of mod configurations.
*/
public static setModConfigurations(configurations: ModConfig[]): void {
ConfigManager.config.modConfigurations = configurations
}
/**
* Get the mod configuration for a specific server.
*
* @param {string} serverid The id of the server.
* @returns {ModConfig | null} The mod configuration for the given server.
*/
public static getModConfiguration(serverid: string): ModConfig | null {
const cfgs = ConfigManager.config.modConfigurations
for(let i=0; i<cfgs.length; i++){
if(cfgs[i].id === serverid){
return cfgs[i]
}
}
return null
}
/**
* Set the mod configuration for a specific server. This overrides any existing value.
*
* @param {string} serverid The id of the server for the given mod configuration.
* @param {ModConfig} configuration The mod configuration for the given server.
*/
public static setModConfiguration(serverid: string, configuration: ModConfig): void {
const cfgs = ConfigManager.config.modConfigurations
for(let i=0; i<cfgs.length; i++){
if(cfgs[i].id === serverid){
cfgs[i] = configuration
return
}
}
cfgs.push(configuration)
}
// User Configurable Settings
// Java Settings
/**
* Retrieve the minimum amount of memory for JVM initialization. This value
* contains the units of memory. For example, '5G' = 5 GigaBytes, '1024M' =
* 1024 MegaBytes, etc.
*
* @param {boolean} def Optional. If true, the default value will be returned.
* @returns {string} The minimum amount of memory for JVM initialization.
*/
public static getMinRAM(def = false): string {
return !def ? ConfigManager.config.settings.java.minRAM : ConfigManager.DEFAULT_CONFIG.settings.java.minRAM
}
/**
* Set the minimum amount of memory for JVM initialization. This value should
* contain the units of memory. For example, '5G' = 5 GigaBytes, '1024M' =
* 1024 MegaBytes, etc.
*
* @param {string} minRAM The new minimum amount of memory for JVM initialization.
*/
public static setMinRAM(minRAM: string): void {
ConfigManager.config.settings.java.minRAM = minRAM
}
/**
* Retrieve the maximum amount of memory for JVM initialization. This value
* contains the units of memory. For example, '5G' = 5 GigaBytes, '1024M' =
* 1024 MegaBytes, etc.
*
* @param {boolean} def Optional. If true, the default value will be returned.
* @returns {string} The maximum amount of memory for JVM initialization.
*/
public static getMaxRAM(def = false): string {
return !def ? ConfigManager.config.settings.java.maxRAM : ConfigManager.resolveMaxRAM()
}
/**
* Set the maximum amount of memory for JVM initialization. This value should
* contain the units of memory. For example, '5G' = 5 GigaBytes, '1024M' =
* 1024 MegaBytes, etc.
*
* @param {string} maxRAM The new maximum amount of memory for JVM initialization.
*/
public static setMaxRAM(maxRAM: string): void {
ConfigManager.config.settings.java.maxRAM = maxRAM
}
/**
* Retrieve the path of the Java Executable.
*
* This is a resolved configuration value and defaults to null until externally assigned.
*
* @returns {string | null} The path of the Java Executable.
*/
public static getJavaExecutable(): string | null {
return ConfigManager.config.settings.java.executable
}
/**
* Set the path of the Java Executable.
*
* @param {string} executable The new path of the Java Executable.
*/
public static setJavaExecutable(executable: string): void {
ConfigManager.config.settings.java.executable = executable
}
/**
* Retrieve the additional arguments for JVM initialization. Required arguments,
* such as memory allocation, will be dynamically resolved and will not be included
* in this value.
*
* @param {boolean} def Optional. If true, the default value will be returned.
* @returns {Array.<string>} An array of the additional arguments for JVM initialization.
*/
public static getJVMOptions(def = false): string[] {
return !def ? ConfigManager.config.settings.java.jvmOptions : ConfigManager.DEFAULT_CONFIG.settings.java.jvmOptions
}
/**
* Set the additional arguments for JVM initialization. Required arguments,
* such as memory allocation, will be dynamically resolved and should not be
* included in this value.
*
* @param {Array.<string>} jvmOptions An array of the new additional arguments for JVM
* initialization.
*/
public static setJVMOptions(jvmOptions: string[]): void {
ConfigManager.config.settings.java.jvmOptions = jvmOptions
}
// Game Settings
/**
* Retrieve the width of the game window.
*
* @param {boolean} def Optional. If true, the default value will be returned.
* @returns {number} The width of the game window.
*/
public static getGameWidth(def = false): number {
return !def ? ConfigManager.config.settings.game.resWidth : ConfigManager.DEFAULT_CONFIG.settings.game.resWidth
}
/**
* Set the width of the game window.
*
* @param {number} resWidth The new width of the game window.
*/
public static setGameWidth(resWidth: number): void {
ConfigManager.config.settings.game.resWidth = Number.parseInt(resWidth as unknown as string)
}
/**
* Validate a potential new width value.
*
* @param {number} resWidth The width value to validate.
* @returns {boolean} Whether or not the value is valid.
*/
public static validateGameWidth(resWidth: number): boolean {
const nVal = Number.parseInt(resWidth as unknown as string)
return Number.isInteger(nVal) && nVal >= 0
}
/**
* Retrieve the height of the game window.
*
* @param {boolean} def Optional. If true, the default value will be returned.
* @returns {number} The height of the game window.
*/
public static getGameHeight(def = false): number {
return !def ? ConfigManager.config.settings.game.resHeight : ConfigManager.DEFAULT_CONFIG.settings.game.resHeight
}
/**
* Set the height of the game window.
*
* @param {number} resHeight The new height of the game window.
*/
public static setGameHeight(resHeight: number): void {
ConfigManager.config.settings.game.resHeight = Number.parseInt(resHeight as unknown as string)
}
/**
* Validate a potential new height value.
*
* @param {number} resHeight The height value to validate.
* @returns {boolean} Whether or not the value is valid.
*/
public static validateGameHeight(resHeight: number): boolean {
const nVal = Number.parseInt(resHeight as unknown as string)
return Number.isInteger(nVal) && nVal >= 0
}
/**
* Check if the game should be launched in fullscreen mode.
*
* @param {boolean} def Optional. If true, the default value will be returned.
* @returns {boolean} Whether or not the game is set to launch in fullscreen mode.
*/
public static getFullscreen(def = false): boolean {
return !def ? ConfigManager.config.settings.game.fullscreen : ConfigManager.DEFAULT_CONFIG.settings.game.fullscreen
}
/**
* Change the status of if the game should be launched in fullscreen mode.
*
* @param {boolean} fullscreen Whether or not the game should launch in fullscreen mode.
*/
public static setFullscreen(fullscreen: boolean): void {
ConfigManager.config.settings.game.fullscreen = fullscreen
}
/**
* Check if the game should auto connect to servers.
*
* @param {boolean} def Optional. If true, the default value will be returned.
* @returns {boolean} Whether or not the game should auto connect to servers.
*/
public static getAutoConnect(def = false): boolean {
return !def ? ConfigManager.config.settings.game.autoConnect : ConfigManager.DEFAULT_CONFIG.settings.game.autoConnect
}
/**
* Change the status of whether or not the game should auto connect to servers.
*
* @param {boolean} autoConnect Whether or not the game should auto connect to servers.
*/
public static setAutoConnect(autoConnect: boolean): void {
ConfigManager.config.settings.game.autoConnect = autoConnect
}
/**
* Check if the game should launch as a detached process.
*
* @param {boolean} def Optional. If true, the default value will be returned.
* @returns {boolean} Whether or not the game will launch as a detached process.
*/
public static getLaunchDetached(def = false): boolean {
return !def ? ConfigManager.config.settings.game.launchDetached : ConfigManager.DEFAULT_CONFIG.settings.game.launchDetached
}
/**
* Change the status of whether or not the game should launch as a detached process.
*
* @param {boolean} launchDetached Whether or not the game should launch as a detached process.
*/
public static setLaunchDetached(launchDetached: boolean): void {
ConfigManager.config.settings.game.launchDetached = launchDetached
}
// Launcher Settings
/**
* Check if the launcher should download prerelease versions.
*
* @param {boolean} def Optional. If true, the default value will be returned.
* @returns {boolean} Whether or not the launcher should download prerelease versions.
*/
public static getAllowPrerelease(def = false): boolean {
return !def ? ConfigManager.config.settings.launcher.allowPrerelease : ConfigManager.DEFAULT_CONFIG.settings.launcher.allowPrerelease
}
/**
* Change the status of Whether or not the launcher should download prerelease versions.
*
* @param {boolean} launchDetached Whether or not the launcher should download prerelease versions.
*/
public static setAllowPrerelease(allowPrerelease: boolean): void {
ConfigManager.config.settings.launcher.allowPrerelease = allowPrerelease
}
}

View File

@ -0,0 +1,33 @@
import { SavedAccount } from './SavedAccount'
import { NewsCache } from './NewsCache'
import { ModConfig } from './ModConfig'
export interface LauncherConfig {
settings: {
java: {
minRAM: string
maxRAM: string
executable: string | null
jvmOptions: string[]
}
game: {
resWidth: number
resHeight: number
fullscreen: boolean
autoConnect: boolean
launchDetached: boolean
}
launcher: {
allowPrerelease: boolean
dataDirectory: string
}
}
newsCache: NewsCache
clientToken: string | null
selectedServer: string | null
selectedAccount: string | null
authenticationDatabase: {[uuid: string]: SavedAccount}
modConfigurations: ModConfig[]
}

View File

@ -0,0 +1,17 @@
export interface SubModConfig {
mods: {
[id: string]: boolean | SubModConfig
}
value: boolean
}
export interface ModConfig {
id: string
mods: {
[id: string]: boolean | SubModConfig
}
}

View File

@ -0,0 +1,7 @@
export interface NewsCache {
date: string | null
content: string | null
dismissed: boolean
}

View File

@ -0,0 +1,7 @@
export interface SavedAccount {
accessToken: string
username: string
uuid: string
displayName: string
}

View File

@ -0,0 +1,109 @@
import { resolve } from 'path'
import { Distribution } from 'helios-distribution-types'
import got from 'got'
import { LoggerUtil } from 'common/logging/loggerutil'
import { RestResponse, handleGotError, RestResponseStatus } from 'common/got/RestResponse'
import { pathExists, readFile, writeFile } from 'fs-extra'
// TODO Option to check endpoint for hash of distro for local compare
// Useful if distro is large (MBs)
export class DistributionAPI {
private static readonly logger = LoggerUtil.getLogger('DistributionAPI')
private readonly REMOTE_URL = 'http://mc.westeroscraft.com/WesterosCraftLauncher/distribution.json'
private readonly DISTRO_FILE = 'distribution.json'
private readonly DISTRO_FILE_DEV = 'distribution_dev.json'
private readonly DEV_MODE = false // placeholder
private distroPath: string
private distroDevPath: string
private rawDistribution!: Distribution
constructor(
private launcherDirectory: string
) {
this.distroPath = resolve(launcherDirectory, this.DISTRO_FILE)
this.distroDevPath = resolve(launcherDirectory, this.DISTRO_FILE_DEV)
}
public async testLoad(): Promise<Distribution> {
await this.loadDistribution()
return this.rawDistribution
}
protected async loadDistribution(): Promise<void> {
let distro
if(!this.DEV_MODE) {
distro = (await this.pullRemote()).data
if(distro == null) {
distro = await this.pullLocal(false)
} else {
this.writeDistributionToDisk(distro)
}
} else {
distro = await this.pullLocal(true)
}
if(distro == null) {
// TODO Bubble this up nicer
throw new Error('FATAL: Unable to load distribution from remote server or local disk.')
}
this.rawDistribution = distro
}
protected async pullRemote(): Promise<RestResponse<Distribution | null>> {
try {
const res = await got.get<Distribution>(this.REMOTE_URL, { responseType: 'json' })
return {
data: res.body,
responseStatus: RestResponseStatus.SUCCESS
}
} catch(error) {
return handleGotError('Pull Remote', error, DistributionAPI.logger, () => null)
}
}
protected async writeDistributionToDisk(distribution: Distribution): Promise<void> {
await writeFile(this.distroPath, distribution)
}
protected async pullLocal(dev: boolean): Promise<Distribution | null> {
return await this.readDistributionFromFile(!dev ? this.distroPath : this.distroDevPath)
}
protected async readDistributionFromFile(path: string): Promise<Distribution | null> {
if(await pathExists(path)) {
const raw = await readFile(path, 'utf-8')
try {
return JSON.parse(raw)
} catch(error) {
DistributionAPI.logger.error(`Malformed distribution file at ${path}`)
return null
}
} else {
DistributionAPI.logger.error(`No distribution file found at ${path}!`)
return null
}
}
}

View File

@ -0,0 +1,231 @@
import { Distribution, Server, Module, Type, Required as HeliosRequired } from 'helios-distribution-types'
import { MavenComponents, MavenUtil } from 'common/util/MavenUtil'
import { join } from 'path'
import { LoggerUtil } from 'common/logging/loggerutil'
const logger = LoggerUtil.getLogger('DistributionFactory')
export class HeliosDistribution {
private mainServerIndex!: number
public readonly servers: HeliosServer[]
constructor(
public readonly rawDistribution: Distribution
) {
this.resolveMainServerIndex()
this.servers = this.rawDistribution.servers.map(s => new HeliosServer(s))
}
private resolveMainServerIndex(): void {
if(this.rawDistribution.servers.length > 0) {
for(let i=0; i<this.rawDistribution.servers.length; i++) {
if(this.mainServerIndex == null) {
if(this.rawDistribution.servers[i].mainServer) {
this.mainServerIndex = i
}
} else {
this.rawDistribution.servers[i].mainServer = false
}
}
if(this.mainServerIndex == null) {
this.mainServerIndex = 0
this.rawDistribution.servers[this.mainServerIndex].mainServer = true
}
} else {
logger.warn('Distribution has 0 configured servers. This doesnt seem right..')
this.mainServerIndex = 0
}
}
public getMainServer(): HeliosServer | null {
return this.mainServerIndex < this.servers.length ? this.servers[this.mainServerIndex] : null
}
public getServerById(id: string): HeliosServer | null {
return this.servers.find(s => s.rawServer.id === id) || null
}
}
export class HeliosServer {
public readonly modules: HeliosModule[]
public readonly hostname: string
public readonly port: number
constructor(
public readonly rawServer: Server
) {
const { hostname, port } = this.parseAddress()
this.hostname = hostname
this.port = port
this.modules = rawServer.modules.map(m => new HeliosModule(m, rawServer.id))
}
private parseAddress(): { hostname: string, port: number } {
// Srv record lookup here if needed.
if(this.rawServer.address.includes(':')) {
const pieces = this.rawServer.address.split(':')
const port = Number(pieces[1])
if(!Number.isInteger(port)) {
throw new Error(`Malformed server address for ${this.rawServer.id}. Port must be an integer!`)
}
return { hostname: pieces[0], port }
} else {
return { hostname: this.rawServer.address, port: 25565 }
}
}
}
export class HeliosModule {
public readonly subModules: HeliosModule[]
private readonly mavenComponents: Readonly<MavenComponents>
private readonly required: Readonly<Required<HeliosRequired>>
private readonly localPath: string
constructor(
public readonly rawModule: Module,
private readonly serverId: string
) {
this.mavenComponents = this.resolveMavenComponents()
this.required = this.resolveRequired()
this.localPath = this.resolveLocalPath()
if(this.rawModule.subModules != null) {
this.subModules = this.rawModule.subModules.map(m => new HeliosModule(m, serverId))
} else {
this.subModules = []
}
}
private resolveMavenComponents(): MavenComponents {
// Files need not have a maven identifier if they provide a path.
if(this.rawModule.type === Type.File && this.rawModule.artifact.path != null) {
return null! as MavenComponents
}
// Version Manifests never provide a maven identifier.
if(this.rawModule.type === Type.VersionManifest) {
return null! as MavenComponents
}
const isMavenId = MavenUtil.isMavenIdentifier(this.rawModule.id)
if(!isMavenId) {
if(this.rawModule.type !== Type.File) {
throw new Error(`Module ${this.rawModule.name} (${this.rawModule.id}) of type ${this.rawModule.type} must have a valid maven identifier!`)
} else {
throw new Error(`Module ${this.rawModule.name} (${this.rawModule.id}) of type ${this.rawModule.type} must either declare an artifact path or have a valid maven identifier!`)
}
}
try {
return MavenUtil.getMavenComponents(this.rawModule.id)
} catch(err) {
throw new Error(`Failed to resolve maven components for module ${this.rawModule.name} (${this.rawModule.id}) of type ${this.rawModule.type}. Reason: ${err.message}`)
}
}
private resolveRequired(): Required<HeliosRequired> {
if(this.rawModule.required == null) {
return {
value: true,
def: true
}
} else {
return {
value: this.rawModule.required.value ?? true,
def: this.rawModule.required.def ?? true
}
}
}
private resolveLocalPath(): string {
// Version Manifests have a pre-determined path.
if(this.rawModule.type === Type.VersionManifest) {
return join('TODO_COMMON_DIR', 'versions', this.rawModule.id, `${this.rawModule.id}.json`)
}
const relativePath = this.rawModule.artifact.path ?? MavenUtil.mavenComponentsAsNormalizedPath(
this.mavenComponents.group,
this.mavenComponents.artifact,
this.mavenComponents.version,
this.mavenComponents.classifier,
this.mavenComponents.extension
)
switch (this.rawModule.type) {
case Type.Library:
case Type.Forge:
case Type.ForgeHosted:
case Type.LiteLoader:
return join('TODO_COMMON_DIR', 'libraries', relativePath)
case Type.ForgeMod:
case Type.LiteMod:
return join('TODO_COMMON_DIR', 'modstore', relativePath)
case Type.File:
default:
return join('TODO_INSTANCE_DIR', this.serverId, relativePath)
}
}
public hasMavenComponents(): boolean {
return this.mavenComponents != null
}
public getMavenComponents(): Readonly<MavenComponents> {
return this.mavenComponents
}
public getRequired(): Readonly<Required<HeliosRequired>> {
return this.required
}
public getPath(): string {
return this.localPath
}
public getMavenIdentifier(): string {
return MavenUtil.mavenComponentsToIdentifier(
this.mavenComponents.group,
this.mavenComponents.artifact,
this.mavenComponents.version,
this.mavenComponents.classifier,
this.mavenComponents.extension
)
}
public getExtensionlessMavenIdentifier(): string {
return MavenUtil.mavenComponentsToExtensionlessIdentifier(
this.mavenComponents.group,
this.mavenComponents.artifact,
this.mavenComponents.version,
this.mavenComponents.classifier
)
}
public getVersionlessMavenIdentifier(): string {
return MavenUtil.mavenComponentsToVersionlessIdentifier(
this.mavenComponents.group,
this.mavenComponents.artifact
)
}
public hasSubModules(): boolean {
return this.subModules.length > 0
}
}

View File

@ -0,0 +1,43 @@
import { RequestError, HTTPError, TimeoutError, ParseError } from 'got'
import { Logger } from 'winston'
export enum RestResponseStatus {
SUCCESS,
ERROR
}
export interface RestResponse<T> {
data: T
responseStatus: RestResponseStatus
error?: RequestError
}
export function handleGotError<T>(operation: string, error: RequestError, logger: Logger, dataProvider: () => T): RestResponse<T> {
const response: RestResponse<T> = {
data: dataProvider(),
responseStatus: RestResponseStatus.ERROR,
error
}
if(error instanceof HTTPError) {
logger.error(`Error during ${operation} request (HTTP Response ${error.response.statusCode})`, error)
logger.debug('Response Details:')
logger.debug('Body:', error.response.body)
logger.debug('Headers:', error.response.headers)
} else if(Object.getPrototypeOf(error) instanceof RequestError) {
logger.error(`${operation} request recieved no response (${error.code}).`, error)
} else if(error instanceof TimeoutError) {
logger.error(`${operation} request timed out (${error.timings.phases.total}ms).`)
} else if(error instanceof ParseError) {
logger.error(`${operation} request recieved unexepected body (Parse Error).`)
} else {
// CacheError, ReadError, MaxRedirectsError, UnsupportedProtocolError, CancelError
logger.error(`Error during ${operation} request.`, error)
}
return response
}

View File

@ -0,0 +1,41 @@
import { createLogger, format, transports, Logger } from 'winston'
import { SPLAT } from 'triple-beam'
import { DateTime } from 'luxon'
import { inspect } from 'util'
export class LoggerUtil {
public static getLogger(label: string): Logger {
return createLogger({
format: format.combine(
format.label(),
format.colorize(),
format.label({ label }),
format.printf(info => {
if(info[SPLAT]) {
if(info[SPLAT].length === 1 && info[SPLAT][0] instanceof Error) {
const err = info[SPLAT][0] as Error
if(info.message.length > err.message.length && info.message.endsWith(err.message)) {
info.message = info.message.substring(0, info.message.length-err.message.length)
}
} else if(info[SPLAT].length > 0) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
info.message += ' ' + info[SPLAT].map((it: any) => {
if(typeof it === 'object' && it != null) {
return inspect(it, false, null, true)
}
return it
}).join(' ')
}
}
return `[${DateTime.local().toFormat('yyyy-MM-dd TT').trim()}] [${info.level}] [${info.label}]: ${info.message}${info.stack ? `\n${info.stack}` : ''}`
})
),
level: process.env.NODE_ENV === 'test' ? 'emerg' : 'debug',
transports: [
new transports.Console()
]
})
}
}

View File

@ -0,0 +1,157 @@
/**
* Utility Class to construct a packet conforming to Minecraft's
* protocol. All data types are BE except VarInt and VarLong.
*
* @see https://wiki.vg/Protocol
*/
export class ServerBoundPacket {
private buffer: number[]
protected constructor() {
this.buffer = []
}
public static build(): ServerBoundPacket {
return new ServerBoundPacket()
}
/**
* Packet is prefixed with its data length as a VarInt.
*
* @see https://wiki.vg/Protocol#Packet_format
*/
public toBuffer(): Buffer {
const finalizedPacket = new ServerBoundPacket()
finalizedPacket.writeVarInt(this.buffer.length)
finalizedPacket.writeBytes(...this.buffer)
return Buffer.from(finalizedPacket.buffer)
}
public writeBytes(...bytes: number[]): ServerBoundPacket {
this.buffer.push(...bytes)
return this
}
/**
* @see https://wiki.vg/Protocol#VarInt_and_VarLong
*/
public writeVarInt(value: number): ServerBoundPacket {
do {
let temp = value & 0b01111111
value >>>= 7
if (value != 0) {
temp |= 0b10000000
}
this.writeBytes(temp)
} while (value != 0)
return this
}
/**
* Strings are prefixed with their length as a VarInt.
*
* @see https://wiki.vg/Protocol#Data_types
*/
public writeString(string: string): ServerBoundPacket {
this.writeVarInt(string.length)
for (let i=0; i<string.length; i++) {
this.writeBytes(string.codePointAt(i)!)
}
return this
}
public writeUnsignedShort(short: number): ServerBoundPacket {
const buf = Buffer.alloc(2)
buf.writeUInt16BE(short, 0)
this.writeBytes(...buf)
return this
}
}
/**
* Utility Class to read a client-bound packet conforming to
* Minecraft's protocol. All data types are BE except VarInt
* and VarLong.
*
* @see https://wiki.vg/Protocol
*/
export class ClientBoundPacket {
private buffer: number[]
constructor(buffer: Buffer) {
this.buffer = [...buffer]
}
public append(buffer: Buffer): void {
this.buffer.push(...buffer)
}
public readByte(): number {
return this.buffer.shift()!
}
public readBytes(length: number): number[] {
const value = this.buffer.slice(0, length)
this.buffer.splice(0, length)
return value
}
public readVarInt(): number {
let numRead = 0
let result = 0
let read
do {
read = this.readByte()
const value = (read & 0b01111111)
result |= (value << (7 * numRead))
numRead++
if (numRead > 5) {
throw new Error('VarInt is too big')
}
} while ((read & 0b10000000) != 0)
return result
}
public readString(): string {
const length = this.readVarInt()
const data = this.readBytes(length)
let value = ''
for (let i=0; i<data.length; i++) {
value += String.fromCharCode(data[i])
}
return value
}
}
export class ProtocolUtils {
public static getVarIntSize(value: number): number {
let size = 0
do {
value >>>= 7
size++
} while (value != 0)
return size
}
}

View File

@ -0,0 +1,186 @@
/* eslint-disable no-control-regex */
import { connect } from 'net'
import { LoggerUtil } from 'common/logging/loggerutil'
import { ServerBoundPacket, ClientBoundPacket, ProtocolUtils } from './Protocol'
const logger = LoggerUtil.getLogger('ServerStatusUtil')
export interface ServerStatus {
version: {
name: string
protocol: number
}
players: {
max: number
online: number
sample: {
name: string
id: string
}[]
}
description: {
text: string
}
favicon: string
modinfo?: { // Only for modded servers
type: string // Ex. FML
modList: {
modid: string
version: string
}[]
}
retrievedAt: number // Internal tracking
}
/**
* Get the handshake packet.
*
* @param protocol The client's protocol version.
* @param hostname The server hostname.
* @param port The server port.
*
* @see https://wiki.vg/Server_List_Ping#Handshake
*/
function getHandshakePacket(protocol: number, hostname: string, port: number): Buffer {
return ServerBoundPacket.build()
.writeVarInt(0x00) // Packet Id
.writeVarInt(protocol)
.writeString(hostname)
.writeUnsignedShort(port)
.writeVarInt(1) // State, 1 = status
.toBuffer()
}
/**
* Get the request packet.
*
* @see https://wiki.vg/Server_List_Ping#Request
*/
function getRequestPacket(): Buffer {
return ServerBoundPacket.build()
.writeVarInt(0x00)
.toBuffer()
}
/**
* Some servers do not return the same status object. Unify
* the response so that the caller need only worry about
* handling a single format.
*
* @param resp The servevr status response.
*/
function unifyStatusResponse(resp: ServerStatus): ServerStatus {
// Some servers don't wrap their description in a text object.
if(typeof resp.description === 'string') {
resp.description = {
text: resp.description
}
}
resp.retrievedAt = (new Date()).getTime()
return resp
}
export function getServerStatus(protocol: number, hostname: string, port = 25565): Promise<ServerStatus | undefined> {
return new Promise((resolve, reject) => {
const socket = connect(port, hostname, () => {
socket.write(getHandshakePacket(protocol, hostname, port))
socket.write(getRequestPacket())
})
socket.setTimeout(5000, () => {
socket.destroy()
logger.error(`Server Status Socket timed out (${hostname}:${port})`)
reject(new Error(`Server Status Socket timed out (${hostname}:${port})`))
})
const maxTries = 2
let iterations = 0
let bytesLeft = -1
socket.once('data', (data) => {
const inboundPacket = new ClientBoundPacket(data)
// Length of Packet ID + Data
const packetLength = inboundPacket.readVarInt() // First VarInt is packet length.
const packetType = inboundPacket.readVarInt() // Second VarInt is packet type.
if(packetType !== 0x00) {
// TODO
socket.destroy()
reject(new Error(`Invalid response. Expected packet type ${0x00}, received ${packetType}!`))
return
}
// Size of packetLength VarInt is not included in the packetLength.
bytesLeft = packetLength + ProtocolUtils.getVarIntSize(packetLength)
// Listener to keep reading until we have read all the bytes into the buffer.
const packetReadListener = (nextData: Buffer, doAppend: boolean) => {
if(iterations > maxTries) {
socket.destroy()
reject(new Error(`Data read from ${hostname}:${port} exceeded ${maxTries} iterations, closing connection.`))
return
}
++iterations
if(bytesLeft > 0) {
bytesLeft -= nextData.length
if(doAppend) {
inboundPacket.append(nextData)
}
}
// All bytes read, attempt conversion.
if(bytesLeft === 0) {
// Remainder of Buffer is the server status json.
const result = inboundPacket.readString()
try {
const parsed: ServerStatus = JSON.parse(result)
socket.end()
resolve(unifyStatusResponse(parsed))
} catch(err) {
socket.destroy()
logger.error('Failed to parse server status JSON', err)
reject(new Error('Failed to parse server status JSON'))
}
}
}
// Read the data we just received.
packetReadListener(data, false)
// Add a listener to keep reading if the data is too long.
socket.on('data', (data) => packetReadListener(data, true))
})
socket.on('error', (err: NodeJS.ErrnoException) => {
socket.destroy()
if(err.code === 'ENOTFOUND') {
// ENOTFOUND = Unable to resolve.
logger.error(`Server ${hostname}:${port} not found!`)
resolve(undefined)
return
} else if(err.code === 'ECONNREFUSED') {
// ECONNREFUSED = Unable to connect to port.
logger.error(`Server ${hostname}:${port} refused to connect, is the port correct?`)
resolve(undefined)
return
} else {
logger.error(`Error trying to pull server status (${hostname}:${port})`, err)
resolve(undefined)
return
}
})
})
}

View File

@ -0,0 +1,34 @@
export interface Agent {
name: 'Minecraft'
version: number
}
export interface AuthPayload {
agent: Agent
username: string
password: string
clientToken?: string
requestUser?: boolean
}
export interface Session {
accessToken: string
clientToken: string
selectedProfile: {
id: string
name: string
}
user?: {
id: string
properties: Array<{
name: string
value: string
}>
}
}

View File

@ -0,0 +1,306 @@
import { LoggerUtil } from '../../logging/loggerutil'
import { MojangStatus, MojangStatusColor } from './internal/MojangStatus'
import got, { RequestError, HTTPError } from 'got'
import { MojangResponse, MojangErrorCode, decipherErrorCode, isInternalError, MojangErrorBody } from './internal/MojangResponse'
import { RestResponseStatus, handleGotError } from 'common/got/RestResponse'
import { Agent, AuthPayload, Session } from './Auth'
export class MojangRestAPI {
private static readonly logger = LoggerUtil.getLogger('Mojang')
private static readonly TIMEOUT = 2500
public static readonly AUTH_ENDPOINT = 'https://authserver.mojang.com'
public static readonly STATUS_ENDPOINT = 'https://status.mojang.com'
private static authClient = got.extend({
prefixUrl: MojangRestAPI.AUTH_ENDPOINT,
responseType: 'json',
retry: 0
})
private static statusClient = got.extend({
prefixUrl: MojangRestAPI.STATUS_ENDPOINT,
responseType: 'json',
retry: 0
})
public static readonly MINECRAFT_AGENT: Agent = {
name: 'Minecraft',
version: 1
}
protected static statuses: MojangStatus[] = MojangRestAPI.getDefaultStatuses()
public static getDefaultStatuses(): MojangStatus[] {
return [
{
service: 'sessionserver.mojang.com',
status: MojangStatusColor.GREY,
name: 'Multiplayer Session Service',
essential: true
},
{
service: 'authserver.mojang.com',
status: MojangStatusColor.GREY,
name: 'Authentication Service',
essential: true
},
{
service: 'textures.minecraft.net',
status: MojangStatusColor.GREY,
name: 'Minecraft Skins',
essential: false
},
{
service: 'api.mojang.com',
status: MojangStatusColor.GREY,
name: 'Public API',
essential: false
},
{
service: 'minecraft.net',
status: MojangStatusColor.GREY,
name: 'Minecraft.net',
essential: false
},
{
service: 'account.mojang.com',
status: MojangStatusColor.GREY,
name: 'Mojang Accounts Website',
essential: false
}
]
}
/**
* Converts a Mojang status color to a hex value. Valid statuses
* are 'green', 'yellow', 'red', and 'grey'. Grey is a custom status
* to our project which represents an unknown status.
*/
public static statusToHex(status: string): string {
switch(status.toLowerCase()){
case MojangStatusColor.GREEN:
return '#a5c325'
case MojangStatusColor.YELLOW:
return '#eac918'
case MojangStatusColor.RED:
return '#c32625'
case MojangStatusColor.GREY:
default:
return '#848484'
}
}
private static handleGotError<T>(operation: string, error: RequestError, dataProvider: () => T): MojangResponse<T> {
const response: MojangResponse<T> = handleGotError(operation, error, MojangRestAPI.logger, dataProvider)
if(error instanceof HTTPError) {
response.mojangErrorCode = decipherErrorCode(error.response.body as MojangErrorBody)
} else {
response.mojangErrorCode = MojangErrorCode.UNKNOWN
}
response.isInternalError = isInternalError(response.mojangErrorCode)
return response
}
private static expectSpecificSuccess(operation: string, expected: number, actual: number) {
if(actual !== expected) {
MojangRestAPI.logger.warn(`${operation} expected ${expected} response, recieved ${actual}.`)
}
}
/**
* Retrieves the status of Mojang's services.
* The response is condensed into a single object. Each service is
* a key, where the value is an object containing a status and name
* property.
*
* @see http://wiki.vg/Mojang_API#API_Status
*/
public static async status(): Promise<MojangResponse<MojangStatus[]>>{
try {
const res = await MojangRestAPI.statusClient.get<{[service: string]: MojangStatusColor}[]>('check')
MojangRestAPI.expectSpecificSuccess('Mojang Status', 200, res.statusCode)
res.body.forEach(status => {
const entry = Object.entries(status)[0]
for(let i=0; i<MojangRestAPI.statuses.length; i++) {
if(MojangRestAPI.statuses[i].service === entry[0]) {
MojangRestAPI.statuses[i].status = entry[1]
break
}
}
})
return {
data: MojangRestAPI.statuses,
responseStatus: RestResponseStatus.SUCCESS
}
} catch(error) {
return MojangRestAPI.handleGotError('Mojang Status', error, () => {
for(let i=0; i<MojangRestAPI.statuses.length; i++){
MojangRestAPI.statuses[i].status = MojangStatusColor.GREY
}
return MojangRestAPI.statuses
})
}
}
/**
* Authenticate a user with their Mojang credentials.
*
* @param {string} username The user's username, this is often an email.
* @param {string} password The user's password.
* @param {string} clientToken The launcher's Client Token.
* @param {boolean} requestUser Optional. Adds user object to the reponse.
* @param {Object} agent Optional. Provided by default. Adds user info to the response.
*
* @see http://wiki.vg/Authentication#Authenticate
*/
public static async authenticate(
username: string,
password: string,
clientToken: string | null,
requestUser = true,
agent: Agent = MojangRestAPI.MINECRAFT_AGENT
): Promise<MojangResponse<Session | null>> {
try {
const json: AuthPayload = {
agent,
username,
password,
requestUser
}
if(clientToken != null){
json.clientToken = clientToken
}
const res = await MojangRestAPI.authClient.post<Session>('authenticate', { json, responseType: 'json' })
MojangRestAPI.expectSpecificSuccess('Mojang Authenticate', 200, res.statusCode)
return {
data: res.body,
responseStatus: RestResponseStatus.SUCCESS
}
} catch(err) {
return MojangRestAPI.handleGotError('Mojang Authenticate', err, () => null)
}
}
/**
* Validate an access token. This should always be done before launching.
* The client token should match the one used to create the access token.
*
* @param {string} accessToken The access token to validate.
* @param {string} clientToken The launcher's client token.
*
* @see http://wiki.vg/Authentication#Validate
*/
public static async validate(accessToken: string, clientToken: string): Promise<MojangResponse<boolean>> {
try {
const json = {
accessToken,
clientToken
}
const res = await MojangRestAPI.authClient.post('validate', { json })
MojangRestAPI.expectSpecificSuccess('Mojang Validate', 204, res.statusCode)
return {
data: res.statusCode === 204,
responseStatus: RestResponseStatus.SUCCESS
}
} catch(err) {
if(err instanceof HTTPError && err.response.statusCode === 403) {
return {
data: false,
responseStatus: RestResponseStatus.SUCCESS
}
}
return MojangRestAPI.handleGotError('Mojang Validate', err, () => false)
}
}
/**
* Invalidates an access token. The clientToken must match the
* token used to create the provided accessToken.
*
* @param {string} accessToken The access token to invalidate.
* @param {string} clientToken The launcher's client token.
*
* @see http://wiki.vg/Authentication#Invalidate
*/
public static async invalidate(accessToken: string, clientToken: string): Promise<MojangResponse<undefined>> {
try {
const json = {
accessToken,
clientToken
}
const res = await MojangRestAPI.authClient.post('invalidate', { json })
MojangRestAPI.expectSpecificSuccess('Mojang Invalidate', 204, res.statusCode)
return {
data: undefined,
responseStatus: RestResponseStatus.SUCCESS
}
} catch(err) {
return MojangRestAPI.handleGotError('Mojang Invalidate', err, () => undefined)
}
}
/**
* Refresh a user's authentication. This should be used to keep a user logged
* in without asking them for their credentials again. A new access token will
* be generated using a recent invalid access token. See Wiki for more info.
*
* @param {string} accessToken The old access token.
* @param {string} clientToken The launcher's client token.
* @param {boolean} requestUser Optional. Adds user object to the reponse.
*
* @see http://wiki.vg/Authentication#Refresh
*/
public static async refresh(accessToken: string, clientToken: string, requestUser = true): Promise<MojangResponse<Session | null>> {
try {
const json = {
accessToken,
clientToken,
requestUser
}
const res = await MojangRestAPI.authClient.post<Session>('refresh', { json, responseType: 'json' })
MojangRestAPI.expectSpecificSuccess('Mojang Refresh', 200, res.statusCode)
return {
data: res.body,
responseStatus: RestResponseStatus.SUCCESS
}
} catch(err) {
return MojangRestAPI.handleGotError('Mojang Refresh', err, () => null)
}
}
}

View File

@ -0,0 +1,87 @@
import { RestResponse } from 'common/got/RestResponse'
/**
* @see https://wiki.vg/Authentication#Errors
*/
export enum MojangErrorCode {
ERROR_METHOD_NOT_ALLOWED, // INTERNAL
ERROR_NOT_FOUND, // INTERNAL
ERROR_USER_MIGRATED,
ERROR_INVALID_CREDENTIALS,
ERROR_RATELIMIT,
ERROR_INVALID_TOKEN,
ERROR_ACCESS_TOKEN_HAS_PROFILE, // ??
ERROR_CREDENTIALS_ARE_NULL, // INTERNAL
ERROR_INVALID_SALT_VERSION, // ??
ERROR_UNSUPPORTED_MEDIA_TYPE, // INTERNAL
UNKNOWN
}
export interface MojangResponse<T> extends RestResponse<T> {
mojangErrorCode?: MojangErrorCode
isInternalError?: boolean
}
export interface MojangErrorBody {
error: string
errorMessage: string
cause?: string
}
/**
* Resolve the error response code from the response body.
*
* @param body The mojang error body response.
*/
export function decipherErrorCode(body: MojangErrorBody): MojangErrorCode {
if(body.error === 'Method Not Allowed') {
return MojangErrorCode.ERROR_METHOD_NOT_ALLOWED
} else if(body.error === 'Not Found') {
return MojangErrorCode.ERROR_NOT_FOUND
} else if(body.error === 'Unsupported Media Type') {
return MojangErrorCode.ERROR_UNSUPPORTED_MEDIA_TYPE
} else if(body.error === 'ForbiddenOperationException') {
if(body.cause && body.cause === 'UserMigratedException') {
return MojangErrorCode.ERROR_USER_MIGRATED
}
if(body.errorMessage === 'Invalid credentials. Invalid username or password.') {
return MojangErrorCode.ERROR_INVALID_CREDENTIALS
} else if(body.errorMessage === 'Invalid credentials.') {
return MojangErrorCode.ERROR_RATELIMIT
} else if(body.errorMessage === 'Invalid token.') {
return MojangErrorCode.ERROR_INVALID_TOKEN
}
} else if(body.error === 'IllegalArgumentException') {
if(body.errorMessage === 'Access token already has a profile assigned.') {
return MojangErrorCode.ERROR_ACCESS_TOKEN_HAS_PROFILE
} else if(body.errorMessage === 'credentials is null') {
return MojangErrorCode.ERROR_CREDENTIALS_ARE_NULL
} else if(body.errorMessage === 'Invalid salt version') {
return MojangErrorCode.ERROR_INVALID_SALT_VERSION
}
}
return MojangErrorCode.UNKNOWN
}
// These indicate problems with the code and not the data.
export function isInternalError(errorCode: MojangErrorCode): boolean {
switch(errorCode) {
case MojangErrorCode.ERROR_METHOD_NOT_ALLOWED: // We've sent the wrong method to an endpoint. (ex. GET to POST)
case MojangErrorCode.ERROR_NOT_FOUND: // Indicates endpoint has changed. (404)
case MojangErrorCode.ERROR_ACCESS_TOKEN_HAS_PROFILE: // Selecting profiles isn't implemented yet. (Shouldnt happen)
case MojangErrorCode.ERROR_CREDENTIALS_ARE_NULL: // Username/password was not submitted. (UI should forbid this)
case MojangErrorCode.ERROR_INVALID_SALT_VERSION: // ??? (Shouldnt happen)
case MojangErrorCode.ERROR_UNSUPPORTED_MEDIA_TYPE: // Data was not submitted as application/json
return true
default:
return false
}
}

View File

@ -0,0 +1,15 @@
export enum MojangStatusColor {
RED = 'red',
YELLOW = 'yellow',
GREEN = 'green',
GREY = 'grey'
}
export interface MojangStatus {
service: string
status: MojangStatusColor
name: string
essential: boolean
}

View File

@ -0,0 +1,34 @@
import { createHash } from 'crypto'
import { join } from 'path'
import { pathExists, readFile } from 'fs-extra'
export function calculateHash(buf: Buffer, algo: string): string {
return createHash(algo).update(buf).digest('hex')
}
export async function validateLocalFile(path: string, algo: string, hash?: string): Promise<boolean> {
if(await pathExists(path)) {
if(hash == null) {
return true
}
const buf = await readFile(path)
return calculateHash(buf, algo) === hash
}
return false
}
function getVersionExtPath(commonDir: string, version: string, ext: string) {
return join(commonDir, 'versions', version, `${version}.${ext}`)
}
export function getVersionJsonPath(commonDir: string, version: string): string {
return getVersionExtPath(commonDir, version, 'json')
}
export function getVersionJarPath(commonDir: string, version: string): string {
return getVersionExtPath(commonDir, version, 'jar')
}
export function getLibraryDir(commonDir: string): string {
return join(commonDir, 'libraries')
}

View File

@ -0,0 +1,107 @@
import { normalize } from 'path'
import { URL } from 'url'
export interface MavenComponents {
group: string
artifact: string
version: string
classifier?: string
extension: string
}
export class MavenUtil {
public static readonly ID_REGEX = /(.+):(.+):([^@]+)()(?:@{1}(.+)$)?/
public static readonly ID_REGEX_WITH_CLASSIFIER = /(.+):(.+):(?:([^@]+)(?:-([a-zA-Z]+)))(?:@{1}(.+)$)?/
public static mavenComponentsToIdentifier(
group: string,
artifact: string,
version: string,
classifier?: string,
extension?: string
): string {
return `${group}:${artifact}:${version}${classifier != null ? `:${classifier}` : ''}${extension != null ? `@${extension}` : ''}`
}
public static mavenComponentsToExtensionlessIdentifier(
group: string,
artifact: string,
version: string,
classifier?: string
): string {
return MavenUtil.mavenComponentsToIdentifier(group, artifact, version, classifier)
}
public static mavenComponentsToVersionlessIdentifier(
group: string,
artifact: string
): string {
return `${group}:${artifact}`
}
public static isMavenIdentifier(id: string): boolean {
return MavenUtil.ID_REGEX.test(id) || MavenUtil.ID_REGEX_WITH_CLASSIFIER.test(id)
}
public static getMavenComponents(id: string, extension = 'jar'): MavenComponents {
if (!MavenUtil.isMavenIdentifier(id)) {
throw new Error('Id is not a maven identifier.')
}
let result
if (MavenUtil.ID_REGEX_WITH_CLASSIFIER.test(id)) {
result = MavenUtil.ID_REGEX_WITH_CLASSIFIER.exec(id)
} else {
result = MavenUtil.ID_REGEX.exec(id)
}
if (result != null) {
return {
group: result[1],
artifact: result[2],
version: result[3],
classifier: result[4] || undefined,
extension: result[5] || extension
}
}
throw new Error('Failed to process maven data.')
}
public static mavenIdentifierAsPath(id: string, extension = 'jar'): string {
const tmp = MavenUtil.getMavenComponents(id, extension)
return MavenUtil.mavenComponentsAsPath(
tmp.group, tmp.artifact, tmp.version, tmp.classifier, tmp.extension
)
}
public static mavenComponentsAsPath(
group: string, artifact: string, version: string, classifier?: string, extension = 'jar'
): string {
return `${group.replace(/\./g, '/')}/${artifact}/${version}/${artifact}-${version}${classifier != null ? `-${classifier}` : ''}.${extension}`
}
public static mavenIdentifierToUrl(id: string, extension = 'jar'): URL {
return new URL(MavenUtil.mavenIdentifierAsPath(id, extension))
}
public static mavenComponentsToUrl(
group: string, artifact: string, version: string, classifier?: string, extension = 'jar'
): URL {
return new URL(MavenUtil.mavenComponentsAsPath(group, artifact, version, classifier, extension))
}
public static mavenIdentifierToPath(id: string, extension = 'jar'): string {
return normalize(MavenUtil.mavenIdentifierAsPath(id, extension))
}
public static mavenComponentsAsNormalizedPath(
group: string, artifact: string, version: string, classifier?: string, extension = 'jar'
): string {
return normalize(MavenUtil.mavenComponentsAsPath(group, artifact, version, classifier, extension))
}
}

View File

@ -0,0 +1,60 @@
import { Rule, Natives } from '../asset/model/mojang/VersionJson'
export function getMojangOS(): string {
const opSys = process.platform
switch(opSys) {
case 'darwin':
return 'osx'
case 'win32':
return 'windows'
case 'linux':
return 'linux'
default:
return opSys
}
}
export function validateLibraryRules(rules?: Rule[]): boolean {
if(rules == null) {
return false
}
for(const rule of rules){
if(rule.action != null && rule.os != null){
const osName = rule.os.name
const osMoj = getMojangOS()
if(rule.action === 'allow'){
return osName === osMoj
} else if(rule.action === 'disallow'){
return osName !== osMoj
}
}
}
return true
}
export function validateLibraryNatives(natives?: Natives): boolean {
return natives == null ? true : Object.hasOwnProperty.call(natives, getMojangOS())
}
export function isLibraryCompatible(rules?: Rule[], natives?: Natives): boolean {
return rules == null ? validateLibraryNatives(natives) : validateLibraryRules(rules)
}
/**
* Returns true if the actual version is greater than
* or equal to the desired version.
*
* @param {string} desired The desired version.
* @param {string} actual The actual version.
*/
export function mcVersionAtLeast(desired: string, actual: string): boolean {
const des = desired.split('.')
const act = actual.split('.')
for(let i=0; i<des.length; i++){
if(!(parseInt(act[i]) >= parseInt(des[i]))){
return false
}
}
return true
}

5
src/common/util/isdev.ts Normal file
View File

@ -0,0 +1,5 @@
'use strict'
const getFromEnv = parseInt(process.env.ELECTRON_IS_DEV as string, 10) === 1
const isEnvSet = 'ELECTRON_IS_DEV' in process.env
export default (isEnvSet ? getFromEnv : (process.defaultApp || /node_modules[\\/]electron[\\/]/.test(process.execPath))) as boolean

271
src/main/index.ts Normal file
View File

@ -0,0 +1,271 @@
import { ipcMain, app, BrowserWindow, Menu, MenuItem } from 'electron'
import { prerelease } from 'semver'
import { join } from 'path'
import { format } from 'url'
import { autoUpdater } from 'electron-updater'
import isdev from '../common/util/isdev'
declare const __static: string
const installExtensions = async () => {
const { default: installExtension, REACT_DEVELOPER_TOOLS, REDUX_DEVTOOLS } = await import('electron-devtools-installer')
const forceDownload = !!process.env.UPGRADE_EXTENSIONS
const extensions = [REACT_DEVELOPER_TOOLS, REDUX_DEVTOOLS]
return installExtension(extensions, forceDownload).catch(console.log) // eslint-disable-line no-console
}
// Setup auto updater.
function initAutoUpdater(event: any, data: any) {
if(data){
autoUpdater.allowPrerelease = true
} else {
// Defaults to true if application version contains prerelease components (e.g. 0.12.1-alpha.1)
// autoUpdater.allowPrerelease = true
}
if(isdev){
autoUpdater.autoInstallOnAppQuit = false
autoUpdater.updateConfigPath = join(__dirname, '..', 'dev-app-update.yml')
}
if(process.platform === 'darwin'){
autoUpdater.autoDownload = false
}
autoUpdater.on('update-available', (info) => {
event.sender.send('autoUpdateNotification', 'update-available', info)
})
autoUpdater.on('update-downloaded', (info) => {
event.sender.send('autoUpdateNotification', 'update-downloaded', info)
})
autoUpdater.on('update-not-available', (info) => {
event.sender.send('autoUpdateNotification', 'update-not-available', info)
})
autoUpdater.on('checking-for-update', () => {
event.sender.send('autoUpdateNotification', 'checking-for-update')
})
autoUpdater.on('error', (err) => {
event.sender.send('autoUpdateNotification', 'realerror', err)
})
}
// Open channel to listen for update actions.
ipcMain.on('autoUpdateAction', (event, arg, data) => {
switch(arg){
case 'initAutoUpdater':
console.log('Initializing auto updater.')
initAutoUpdater(event, data)
event.sender.send('autoUpdateNotification', 'ready')
break
case 'checkForUpdate':
autoUpdater.checkForUpdates()
.catch(err => {
event.sender.send('autoUpdateNotification', 'realerror', err)
})
break
case 'allowPrereleaseChange':
if(!data){
const preRelComp = prerelease(app.getVersion())
if(preRelComp != null && preRelComp.length > 0){
autoUpdater.allowPrerelease = true
} else {
autoUpdater.allowPrerelease = data
}
} else {
autoUpdater.allowPrerelease = data
}
break
case 'installUpdateNow':
autoUpdater.quitAndInstall()
break
default:
console.log('Unknown argument', arg)
break
}
})
// Redirect distribution index event from preloader to renderer.
ipcMain.on('distributionIndexDone', (event, res) => {
event.sender.send('distributionIndexDone', res)
})
// Disable hardware acceleration.
// https://electronjs.org/docs/tutorial/offscreen-rendering
app.disableHardwareAcceleration()
// Keep a global reference of the window object, if you don't, the window will
// be closed automatically when the JavaScript object is garbage collected.
let win: BrowserWindow | null
async function createWindow() {
if (process.env.NODE_ENV !== 'production') {
await installExtensions()
}
win = new BrowserWindow({
width: 980,
height: 552,
icon: getPlatformIcon('SealCircle'),
frame: false,
webPreferences: {
preload: join(__dirname, '..', 'out', 'preloader.js'),
nodeIntegration: true,
contextIsolation: false,
enableRemoteModule: true,
worldSafeExecuteJavaScript: true
},
backgroundColor: '#171614'
})
if (isdev) {
win.loadURL(`http://localhost:${process.env.ELECTRON_WEBPACK_WDS_PORT}`)
}
else {
win.loadURL(format({
pathname: join(__dirname, 'index.html'),
protocol: 'file',
slashes: true
}))
}
// console.log(__dirname)
// win.loadURL(format({
// pathname: join(__dirname, 'index.html'),
// protocol: 'file',
// slashes: true
// }))
/*win.once('ready-to-show', () => {
win.show()
})*/
win.removeMenu()
win.resizable = true
// win.webContents.on('new-window', (e, url) => {
// if(url != win!.webContents.getURL()) {
// e.preventDefault()
// shell.openExternal(url)
// }
// })
if (process.env.NODE_ENV !== 'production') {
// Open DevTools, see https://github.com/electron/electron/issues/12438 for why we wait for dom-ready
win.webContents.once('dom-ready', () => {
win!.webContents.openDevTools()
})
}
win.on('closed', () => {
win = null
})
}
function createMenu() {
if(process.platform === 'darwin') {
// Extend default included application menu to continue support for quit keyboard shortcut
const applicationSubMenu = new MenuItem({
label: 'Application',
submenu: [{
label: 'About Application',
role: 'about'
}, {
type: 'separator'
}, {
label: 'Quit',
accelerator: 'Command+Q',
role: 'quit',
click: () => {
app.quit()
}
}]
})
// New edit menu adds support for text-editing keyboard shortcuts
const editSubMenu = new MenuItem({
label: 'Edit',
submenu: [
{
label: 'Undo',
accelerator: 'CmdOrCtrl+Z',
role: 'undo'
},
{
label: 'Redo',
accelerator: 'Shift+CmdOrCtrl+Z',
role: 'redo'
},
{
type: 'separator'
},
{
label: 'Cut',
accelerator: 'CmdOrCtrl+X',
role: 'cut'
},
{
label: 'Copy',
accelerator: 'CmdOrCtrl+C',
role: 'copy'
},
{
label: 'Paste',
accelerator: 'CmdOrCtrl+V',
role: 'paste'
},
{
label: 'Select All',
accelerator: 'CmdOrCtrl+A',
role: 'selectAll'
}
]
})
// Bundle submenus into a single template and build a menu object with it
const menuTemplate: MenuItem[] = [applicationSubMenu, editSubMenu]
const menuObject = Menu.buildFromTemplate(menuTemplate)
// Assign it to the application
Menu.setApplicationMenu(menuObject)
}
}
function getPlatformIcon(filename: string){
let ext
switch(process.platform) {
case 'win32':
ext = 'ico'
break
case 'darwin':
case 'linux':
default:
ext = 'png'
break
}
return join(__static, 'images', `${filename}.${ext}`)
}
app.on('ready', createWindow)
app.on('ready', createMenu)
app.on('window-all-closed', () => {
// On macOS it is common for applications and their menu bar
// to stay active until the user quits explicitly with Cmd + Q
if (process.platform !== 'darwin') {
app.quit()
}
})
app.on('activate', () => {
// On macOS it's common to re-create a window in the app when the
// dock icon is clicked and there are no other windows open.
if (win === null) {
createWindow()
}
})

Some files were not shown because too many files have changed in this diff Show More