configmanager.js 19 KB

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