configmanager.js 19 KB

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