configmanager.js 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687
  1. const fs = require('fs-extra')
  2. const os = require('os')
  3. const path = require('path')
  4. const logger = require('./loggerutil')('%c[ConfigManager]', 'color: #a02d2a; font-weight: bold')
  5. const sysRoot = process.env.APPDATA || (process.platform == 'darwin' ? process.env.HOME + '/Library/Application Support' : process.env.HOME)
  6. const dataPath = path.join(sysRoot, '.westeroscraft')
  7. // Forked processes do not have access to electron, so we have this workaround.
  8. const launcherDir = process.env.CONFIG_DIRECT_PATH || require('electron').remote.app.getPath('userData')
  9. /**
  10. * Retrieve the absolute path of the launcher directory.
  11. *
  12. * @returns {string} The absolute path of the launcher directory.
  13. */
  14. exports.getLauncherDirectory = function(){
  15. return launcherDir
  16. }
  17. /**
  18. * Get the launcher's data directory. This is where all files related
  19. * to game launch are installed (common, instances, java, etc).
  20. *
  21. * @returns {string} The absolute path of the launcher's data directory.
  22. */
  23. exports.getDataDirectory = function(def = false){
  24. return !def ? config.settings.launcher.dataDirectory : DEFAULT_CONFIG.settings.launcher.dataDirectory
  25. }
  26. /**
  27. * Set the new data directory.
  28. *
  29. * @param {string} dataDirectory The new data directory.
  30. */
  31. exports.setDataDirectory = function(dataDirectory){
  32. config.settings.launcher.dataDirectory = dataDirectory
  33. }
  34. const configPath = path.join(exports.getLauncherDirectory(), 'config.json')
  35. const configPathLEGACY = path.join(dataPath, 'config.json')
  36. const firstLaunch = !fs.existsSync(configPath) && !fs.existsSync(configPathLEGACY)
  37. exports.getAbsoluteMinRAM = function(){
  38. const mem = os.totalmem()
  39. return mem >= 6000000000 ? 3 : 2
  40. }
  41. exports.getAbsoluteMaxRAM = function(){
  42. const mem = os.totalmem()
  43. const gT16 = mem-16000000000
  44. return Math.floor((mem-1000000000-(gT16 > 0 ? (Number.parseInt(gT16/8) + 16000000000/4) : mem/4))/1000000000)
  45. }
  46. function resolveMaxRAM(){
  47. const mem = os.totalmem()
  48. return mem >= 8000000000 ? '4G' : (mem >= 6000000000 ? '3G' : '2G')
  49. }
  50. function resolveMinRAM(){
  51. return resolveMaxRAM()
  52. }
  53. /**
  54. * Three types of values:
  55. * Static = Explicitly declared.
  56. * Dynamic = Calculated by a private function.
  57. * Resolved = Resolved externally, defaults to null.
  58. */
  59. const DEFAULT_CONFIG = {
  60. settings: {
  61. java: {
  62. minRAM: resolveMinRAM(),
  63. maxRAM: resolveMaxRAM(), // Dynamic
  64. executable: null,
  65. jvmOptions: [
  66. '-XX:+UseConcMarkSweepGC',
  67. '-XX:+CMSIncrementalMode',
  68. '-XX:-UseAdaptiveSizePolicy',
  69. '-Xmn128M'
  70. ],
  71. },
  72. game: {
  73. resWidth: 1280,
  74. resHeight: 720,
  75. fullscreen: false,
  76. autoConnect: true,
  77. launchDetached: true
  78. },
  79. launcher: {
  80. allowPrerelease: false,
  81. dataDirectory: dataPath
  82. }
  83. },
  84. newsCache: {
  85. date: null,
  86. content: null,
  87. dismissed: false
  88. },
  89. clientToken: null,
  90. selectedServer: null, // Resolved
  91. selectedAccount: null,
  92. authenticationDatabase: {},
  93. modConfigurations: []
  94. }
  95. let config = null
  96. // Persistance Utility Functions
  97. /**
  98. * Save the current configuration to a file.
  99. */
  100. exports.save = function(){
  101. fs.writeFileSync(configPath, JSON.stringify(config, null, 4), 'UTF-8')
  102. }
  103. /**
  104. * Load the configuration into memory. If a configuration file exists,
  105. * that will be read and saved. Otherwise, a default configuration will
  106. * be generated. Note that "resolved" values default to null and will
  107. * need to be externally assigned.
  108. */
  109. exports.load = function(){
  110. let doLoad = true
  111. if(!fs.existsSync(configPath)){
  112. // Create all parent directories.
  113. fs.ensureDirSync(path.join(configPath, '..'))
  114. if(fs.existsSync(configPathLEGACY)){
  115. fs.moveSync(configPathLEGACY, configPath)
  116. } else {
  117. doLoad = false
  118. config = DEFAULT_CONFIG
  119. exports.save()
  120. }
  121. }
  122. if(doLoad){
  123. let doValidate = false
  124. try {
  125. config = JSON.parse(fs.readFileSync(configPath, 'UTF-8'))
  126. doValidate = true
  127. } catch (err){
  128. logger.error(err)
  129. logger.log('Configuration file contains malformed JSON or is corrupt.')
  130. logger.log('Generating a new configuration file.')
  131. fs.ensureDirSync(path.join(configPath, '..'))
  132. config = DEFAULT_CONFIG
  133. exports.save()
  134. }
  135. if(doValidate){
  136. config = validateKeySet(DEFAULT_CONFIG, config)
  137. exports.save()
  138. }
  139. }
  140. logger.log('Successfully Loaded')
  141. }
  142. /**
  143. * @returns {boolean} Whether or not the manager has been loaded.
  144. */
  145. exports.isLoaded = function(){
  146. return config != null
  147. }
  148. /**
  149. * Validate that the destination object has at least every field
  150. * present in the source object. Assign a default value otherwise.
  151. *
  152. * @param {Object} srcObj The source object to reference against.
  153. * @param {Object} destObj The destination object.
  154. * @returns {Object} A validated destination object.
  155. */
  156. function validateKeySet(srcObj, destObj){
  157. if(srcObj == null){
  158. srcObj = {}
  159. }
  160. const validationBlacklist = ['authenticationDatabase']
  161. const keys = Object.keys(srcObj)
  162. for(let i=0; i<keys.length; i++){
  163. if(typeof destObj[keys[i]] === 'undefined'){
  164. destObj[keys[i]] = srcObj[keys[i]]
  165. } else if(typeof srcObj[keys[i]] === 'object' && srcObj[keys[i]] != null && !(srcObj[keys[i]] instanceof Array) && validationBlacklist.indexOf(keys[i]) === -1){
  166. destObj[keys[i]] = validateKeySet(srcObj[keys[i]], destObj[keys[i]])
  167. }
  168. }
  169. return destObj
  170. }
  171. /**
  172. * Check to see if this is the first time the user has launched the
  173. * application. This is determined by the existance of the data path.
  174. *
  175. * @returns {boolean} True if this is the first launch, otherwise false.
  176. */
  177. exports.isFirstLaunch = function(){
  178. return firstLaunch
  179. }
  180. /**
  181. * Returns the name of the folder in the OS temp directory which we
  182. * will use to extract and store native dependencies for game launch.
  183. *
  184. * @returns {string} The name of the folder.
  185. */
  186. exports.getTempNativeFolder = function(){
  187. return 'WCNatives'
  188. }
  189. // System Settings (Unconfigurable on UI)
  190. /**
  191. * Retrieve the news cache to determine
  192. * whether or not there is newer news.
  193. *
  194. * @returns {Object} The news cache object.
  195. */
  196. exports.getNewsCache = function(){
  197. return config.newsCache
  198. }
  199. /**
  200. * Set the new news cache object.
  201. *
  202. * @param {Object} newsCache The new news cache object.
  203. */
  204. exports.setNewsCache = function(newsCache){
  205. config.newsCache = newsCache
  206. }
  207. /**
  208. * Set whether or not the news has been dismissed (checked)
  209. *
  210. * @param {boolean} dismissed Whether or not the news has been dismissed (checked).
  211. */
  212. exports.setNewsCacheDismissed = function(dismissed){
  213. config.newsCache.dismissed = dismissed
  214. }
  215. /**
  216. * Retrieve the common directory for shared
  217. * game files (assets, libraries, etc).
  218. *
  219. * @returns {string} The launcher's common directory.
  220. */
  221. exports.getCommonDirectory = function(){
  222. return path.join(exports.getDataDirectory(), 'common')
  223. }
  224. /**
  225. * Retrieve the instance directory for the per
  226. * server game directories.
  227. *
  228. * @returns {string} The launcher's instance directory.
  229. */
  230. exports.getInstanceDirectory = function(){
  231. return path.join(exports.getDataDirectory(), 'instances')
  232. }
  233. /**
  234. * Retrieve the launcher's Client Token.
  235. * There is no default client token.
  236. *
  237. * @returns {string} The launcher's Client Token.
  238. */
  239. exports.getClientToken = function(){
  240. return config.clientToken
  241. }
  242. /**
  243. * Set the launcher's Client Token.
  244. *
  245. * @param {string} clientToken The launcher's new Client Token.
  246. */
  247. exports.setClientToken = function(clientToken){
  248. config.clientToken = clientToken
  249. }
  250. /**
  251. * Retrieve the ID of the selected serverpack.
  252. *
  253. * @param {boolean} def Optional. If true, the default value will be returned.
  254. * @returns {string} The ID of the selected serverpack.
  255. */
  256. exports.getSelectedServer = function(def = false){
  257. return !def ? config.selectedServer : DEFAULT_CONFIG.clientToken
  258. }
  259. /**
  260. * Set the ID of the selected serverpack.
  261. *
  262. * @param {string} serverID The ID of the new selected serverpack.
  263. */
  264. exports.setSelectedServer = function(serverID){
  265. config.selectedServer = serverID
  266. }
  267. /**
  268. * Get an array of each account currently authenticated by the launcher.
  269. *
  270. * @returns {Array.<Object>} An array of each stored authenticated account.
  271. */
  272. exports.getAuthAccounts = function(){
  273. return config.authenticationDatabase
  274. }
  275. /**
  276. * Returns the authenticated account with the given uuid. Value may
  277. * be null.
  278. *
  279. * @param {string} uuid The uuid of the authenticated account.
  280. * @returns {Object} The authenticated account with the given uuid.
  281. */
  282. exports.getAuthAccount = function(uuid){
  283. return config.authenticationDatabase[uuid]
  284. }
  285. /**
  286. * Update the access token of an authenticated account.
  287. *
  288. * @param {string} uuid The uuid of the authenticated account.
  289. * @param {string} accessToken The new Access Token.
  290. *
  291. * @returns {Object} The authenticated account object created by this action.
  292. */
  293. exports.updateAuthAccount = function(uuid, accessToken){
  294. config.authenticationDatabase[uuid].accessToken = accessToken
  295. return config.authenticationDatabase[uuid]
  296. }
  297. /**
  298. * Adds an authenticated account to the database to be stored.
  299. *
  300. * @param {string} uuid The uuid of the authenticated account.
  301. * @param {string} accessToken The accessToken of the authenticated account.
  302. * @param {string} username The username (usually email) of the authenticated account.
  303. * @param {string} displayName The in game name of the authenticated account.
  304. *
  305. * @returns {Object} The authenticated account object created by this action.
  306. */
  307. exports.addAuthAccount = function(uuid, accessToken, username, displayName){
  308. config.selectedAccount = uuid
  309. config.authenticationDatabase[uuid] = {
  310. accessToken,
  311. username: username.trim(),
  312. uuid: uuid.trim(),
  313. displayName: displayName.trim()
  314. }
  315. return config.authenticationDatabase[uuid]
  316. }
  317. /**
  318. * Remove an authenticated account from the database. If the account
  319. * was also the selected account, a new one will be selected. If there
  320. * are no accounts, the selected account will be null.
  321. *
  322. * @param {string} uuid The uuid of the authenticated account.
  323. *
  324. * @returns {boolean} True if the account was removed, false if it never existed.
  325. */
  326. exports.removeAuthAccount = function(uuid){
  327. if(config.authenticationDatabase[uuid] != null){
  328. delete config.authenticationDatabase[uuid]
  329. if(config.selectedAccount === uuid){
  330. const keys = Object.keys(config.authenticationDatabase)
  331. if(keys.length > 0){
  332. config.selectedAccount = keys[0]
  333. } else {
  334. config.selectedAccount = null
  335. config.clientToken = null
  336. }
  337. }
  338. return true
  339. }
  340. return false
  341. }
  342. /**
  343. * Get the currently selected authenticated account.
  344. *
  345. * @returns {Object} The selected authenticated account.
  346. */
  347. exports.getSelectedAccount = function(){
  348. return config.authenticationDatabase[config.selectedAccount]
  349. }
  350. /**
  351. * Set the selected authenticated account.
  352. *
  353. * @param {string} uuid The UUID of the account which is to be set
  354. * as the selected account.
  355. *
  356. * @returns {Object} The selected authenticated account.
  357. */
  358. exports.setSelectedAccount = function(uuid){
  359. const authAcc = config.authenticationDatabase[uuid]
  360. if(authAcc != null) {
  361. config.selectedAccount = uuid
  362. }
  363. return authAcc
  364. }
  365. /**
  366. * Get an array of each mod configuration currently stored.
  367. *
  368. * @returns {Array.<Object>} An array of each stored mod configuration.
  369. */
  370. exports.getModConfigurations = function(){
  371. return config.modConfigurations
  372. }
  373. /**
  374. * Set the array of stored mod configurations.
  375. *
  376. * @param {Array.<Object>} configurations An array of mod configurations.
  377. */
  378. exports.setModConfigurations = function(configurations){
  379. config.modConfigurations = configurations
  380. }
  381. /**
  382. * Get the mod configuration for a specific server.
  383. *
  384. * @param {string} serverid The id of the server.
  385. * @returns {Object} The mod configuration for the given server.
  386. */
  387. exports.getModConfiguration = function(serverid){
  388. const cfgs = config.modConfigurations
  389. for(let i=0; i<cfgs.length; i++){
  390. if(cfgs[i].id === serverid){
  391. return cfgs[i]
  392. }
  393. }
  394. return null
  395. }
  396. /**
  397. * Set the mod configuration for a specific server. This overrides any existing value.
  398. *
  399. * @param {string} serverid The id of the server for the given mod configuration.
  400. * @param {Object} configuration The mod configuration for the given server.
  401. */
  402. exports.setModConfiguration = function(serverid, configuration){
  403. const cfgs = config.modConfigurations
  404. for(let i=0; i<cfgs.length; i++){
  405. if(cfgs[i].id === serverid){
  406. cfgs[i] = configuration
  407. return
  408. }
  409. }
  410. cfgs.push(configuration)
  411. }
  412. // User Configurable Settings
  413. // Java Settings
  414. /**
  415. * Retrieve the minimum amount of memory for JVM initialization. This value
  416. * contains the units of memory. For example, '5G' = 5 GigaBytes, '1024M' =
  417. * 1024 MegaBytes, etc.
  418. *
  419. * @param {boolean} def Optional. If true, the default value will be returned.
  420. * @returns {string} The minimum amount of memory for JVM initialization.
  421. */
  422. exports.getMinRAM = function(def = false){
  423. return !def ? config.settings.java.minRAM : DEFAULT_CONFIG.settings.java.minRAM
  424. }
  425. /**
  426. * Set the minimum amount of memory for JVM initialization. This value should
  427. * contain the units of memory. For example, '5G' = 5 GigaBytes, '1024M' =
  428. * 1024 MegaBytes, etc.
  429. *
  430. * @param {string} minRAM The new minimum amount of memory for JVM initialization.
  431. */
  432. exports.setMinRAM = function(minRAM){
  433. config.settings.java.minRAM = minRAM
  434. }
  435. /**
  436. * Retrieve the maximum amount of memory for JVM initialization. This value
  437. * contains the units of memory. For example, '5G' = 5 GigaBytes, '1024M' =
  438. * 1024 MegaBytes, etc.
  439. *
  440. * @param {boolean} def Optional. If true, the default value will be returned.
  441. * @returns {string} The maximum amount of memory for JVM initialization.
  442. */
  443. exports.getMaxRAM = function(def = false){
  444. return !def ? config.settings.java.maxRAM : resolveMaxRAM()
  445. }
  446. /**
  447. * Set the maximum amount of memory for JVM initialization. This value should
  448. * contain the units of memory. For example, '5G' = 5 GigaBytes, '1024M' =
  449. * 1024 MegaBytes, etc.
  450. *
  451. * @param {string} maxRAM The new maximum amount of memory for JVM initialization.
  452. */
  453. exports.setMaxRAM = function(maxRAM){
  454. config.settings.java.maxRAM = maxRAM
  455. }
  456. /**
  457. * Retrieve the path of the Java Executable.
  458. *
  459. * This is a resolved configuration value and defaults to null until externally assigned.
  460. *
  461. * @returns {string} The path of the Java Executable.
  462. */
  463. exports.getJavaExecutable = function(){
  464. return config.settings.java.executable
  465. }
  466. /**
  467. * Set the path of the Java Executable.
  468. *
  469. * @param {string} executable The new path of the Java Executable.
  470. */
  471. exports.setJavaExecutable = function(executable){
  472. config.settings.java.executable = executable
  473. }
  474. /**
  475. * Retrieve the additional arguments for JVM initialization. Required arguments,
  476. * such as memory allocation, will be dynamically resolved and will not be included
  477. * in this value.
  478. *
  479. * @param {boolean} def Optional. If true, the default value will be returned.
  480. * @returns {Array.<string>} An array of the additional arguments for JVM initialization.
  481. */
  482. exports.getJVMOptions = function(def = false){
  483. return !def ? config.settings.java.jvmOptions : DEFAULT_CONFIG.settings.java.jvmOptions
  484. }
  485. /**
  486. * Set the additional arguments for JVM initialization. Required arguments,
  487. * such as memory allocation, will be dynamically resolved and should not be
  488. * included in this value.
  489. *
  490. * @param {Array.<string>} jvmOptions An array of the new additional arguments for JVM
  491. * initialization.
  492. */
  493. exports.setJVMOptions = function(jvmOptions){
  494. config.settings.java.jvmOptions = jvmOptions
  495. }
  496. // Game Settings
  497. /**
  498. * Retrieve the width of the game window.
  499. *
  500. * @param {boolean} def Optional. If true, the default value will be returned.
  501. * @returns {number} The width of the game window.
  502. */
  503. exports.getGameWidth = function(def = false){
  504. return !def ? config.settings.game.resWidth : DEFAULT_CONFIG.settings.game.resWidth
  505. }
  506. /**
  507. * Set the width of the game window.
  508. *
  509. * @param {number} resWidth The new width of the game window.
  510. */
  511. exports.setGameWidth = function(resWidth){
  512. config.settings.game.resWidth = Number.parseInt(resWidth)
  513. }
  514. /**
  515. * Validate a potential new width value.
  516. *
  517. * @param {number} resWidth The width value to validate.
  518. * @returns {boolean} Whether or not the value is valid.
  519. */
  520. exports.validateGameWidth = function(resWidth){
  521. const nVal = Number.parseInt(resWidth)
  522. return Number.isInteger(nVal) && nVal >= 0
  523. }
  524. /**
  525. * Retrieve the height of the game window.
  526. *
  527. * @param {boolean} def Optional. If true, the default value will be returned.
  528. * @returns {number} The height of the game window.
  529. */
  530. exports.getGameHeight = function(def = false){
  531. return !def ? config.settings.game.resHeight : DEFAULT_CONFIG.settings.game.resHeight
  532. }
  533. /**
  534. * Set the height of the game window.
  535. *
  536. * @param {number} resHeight The new height of the game window.
  537. */
  538. exports.setGameHeight = function(resHeight){
  539. config.settings.game.resHeight = Number.parseInt(resHeight)
  540. }
  541. /**
  542. * Validate a potential new height value.
  543. *
  544. * @param {number} resHeight The height value to validate.
  545. * @returns {boolean} Whether or not the value is valid.
  546. */
  547. exports.validateGameHeight = function(resHeight){
  548. const nVal = Number.parseInt(resHeight)
  549. return Number.isInteger(nVal) && nVal >= 0
  550. }
  551. /**
  552. * Check if the game should be launched in fullscreen mode.
  553. *
  554. * @param {boolean} def Optional. If true, the default value will be returned.
  555. * @returns {boolean} Whether or not the game is set to launch in fullscreen mode.
  556. */
  557. exports.getFullscreen = function(def = false){
  558. return !def ? config.settings.game.fullscreen : DEFAULT_CONFIG.settings.game.fullscreen
  559. }
  560. /**
  561. * Change the status of if the game should be launched in fullscreen mode.
  562. *
  563. * @param {boolean} fullscreen Whether or not the game should launch in fullscreen mode.
  564. */
  565. exports.setFullscreen = function(fullscreen){
  566. config.settings.game.fullscreen = fullscreen
  567. }
  568. /**
  569. * Check if the game should auto connect to servers.
  570. *
  571. * @param {boolean} def Optional. If true, the default value will be returned.
  572. * @returns {boolean} Whether or not the game should auto connect to servers.
  573. */
  574. exports.getAutoConnect = function(def = false){
  575. return !def ? config.settings.game.autoConnect : DEFAULT_CONFIG.settings.game.autoConnect
  576. }
  577. /**
  578. * Change the status of whether or not the game should auto connect to servers.
  579. *
  580. * @param {boolean} autoConnect Whether or not the game should auto connect to servers.
  581. */
  582. exports.setAutoConnect = function(autoConnect){
  583. config.settings.game.autoConnect = autoConnect
  584. }
  585. /**
  586. * Check if the game should launch as a detached process.
  587. *
  588. * @param {boolean} def Optional. If true, the default value will be returned.
  589. * @returns {boolean} Whether or not the game will launch as a detached process.
  590. */
  591. exports.getLaunchDetached = function(def = false){
  592. return !def ? config.settings.game.launchDetached : DEFAULT_CONFIG.settings.game.launchDetached
  593. }
  594. /**
  595. * Change the status of whether or not the game should launch as a detached process.
  596. *
  597. * @param {boolean} launchDetached Whether or not the game should launch as a detached process.
  598. */
  599. exports.setLaunchDetached = function(launchDetached){
  600. config.settings.game.launchDetached = launchDetached
  601. }
  602. // Launcher Settings
  603. /**
  604. * Check if the launcher should download prerelease versions.
  605. *
  606. * @param {boolean} def Optional. If true, the default value will be returned.
  607. * @returns {boolean} Whether or not the launcher should download prerelease versions.
  608. */
  609. exports.getAllowPrerelease = function(def = false){
  610. return !def ? config.settings.launcher.allowPrerelease : DEFAULT_CONFIG.settings.launcher.allowPrerelease
  611. }
  612. /**
  613. * Change the status of Whether or not the launcher should download prerelease versions.
  614. *
  615. * @param {boolean} launchDetached Whether or not the launcher should download prerelease versions.
  616. */
  617. exports.setAllowPrerelease = function(allowPrerelease){
  618. config.settings.launcher.allowPrerelease = allowPrerelease
  619. }