configmanager.js 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668
  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(),
  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. if(!/.{8}-.{4}-.{4}-.{4}-.{12}/.test(uuid)){
  287. const val = Array.from(uuid.match(/(.{8})(.{4})(.{4})(.{4})(.{12})/))
  288. val.shift()
  289. uuid = val.join('-')
  290. }
  291. config.selectedAccount = uuid
  292. config.authenticationDatabase[uuid] = {
  293. accessToken,
  294. username: username.trim(),
  295. uuid,
  296. displayName: displayName.trim()
  297. }
  298. return config.authenticationDatabase[uuid]
  299. }
  300. /**
  301. * Remove an authenticated account from the database. If the account
  302. * was also the selected account, a new one will be selected. If there
  303. * are no accounts, the selected account will be null.
  304. *
  305. * @param {string} uuid The uuid of the authenticated account.
  306. *
  307. * @returns {boolean} True if the account was removed, false if it never existed.
  308. */
  309. exports.removeAuthAccount = function(uuid){
  310. if(config.authenticationDatabase[uuid] != null){
  311. delete config.authenticationDatabase[uuid]
  312. if(config.selectedAccount === uuid){
  313. const keys = Object.keys(config.authenticationDatabase)
  314. if(keys.length > 0){
  315. config.selectedAccount = keys[0]
  316. } else {
  317. config.selectedAccount = null
  318. }
  319. }
  320. return true
  321. }
  322. return false
  323. }
  324. /**
  325. * Get the currently selected authenticated account.
  326. *
  327. * @returns {Object} The selected authenticated account.
  328. */
  329. exports.getSelectedAccount = function(){
  330. return config.authenticationDatabase[config.selectedAccount]
  331. }
  332. /**
  333. * Set the selected authenticated account.
  334. *
  335. * @param {string} uuid The UUID of the account which is to be set
  336. * as the selected account.
  337. *
  338. * @returns {Object} The selected authenticated account.
  339. */
  340. exports.setSelectedAccount = function(uuid){
  341. const authAcc = config.authenticationDatabase[uuid]
  342. if(authAcc != null) {
  343. config.selectedAccount = uuid
  344. }
  345. return authAcc
  346. }
  347. /**
  348. * Get an array of each mod configuration currently stored.
  349. *
  350. * @returns {Array.<Object>} An array of each stored mod configuration.
  351. */
  352. exports.getModConfigurations = function(){
  353. return config.modConfigurations
  354. }
  355. /**
  356. * Set the array of stored mod configurations.
  357. *
  358. * @param {Array.<Object>} configurations An array of mod configurations.
  359. */
  360. exports.setModConfigurations = function(configurations){
  361. config.modConfigurations = configurations
  362. }
  363. /**
  364. * Get the mod configuration for a specific server.
  365. *
  366. * @param {string} serverid The id of the server.
  367. * @returns {Object} The mod configuration for the given server.
  368. */
  369. exports.getModConfiguration = function(serverid){
  370. const cfgs = config.modConfigurations
  371. for(let i=0; i<cfgs.length; i++){
  372. if(cfgs[i].id === serverid){
  373. return cfgs[i]
  374. }
  375. }
  376. return null
  377. }
  378. /**
  379. * Set the mod configuration for a specific server. This overrides any existing value.
  380. *
  381. * @param {string} serverid The id of the server for the given mod configuration.
  382. * @param {Object} configuration The mod configuration for the given server.
  383. */
  384. exports.setModConfiguration = function(serverid, configuration){
  385. const cfgs = config.modConfigurations
  386. for(let i=0; i<cfgs.length; i++){
  387. if(cfgs[i].id === serverid){
  388. cfgs[i] = configuration
  389. return
  390. }
  391. }
  392. cfgs.push(configuration)
  393. }
  394. // User Configurable Settings
  395. // Java Settings
  396. /**
  397. * Retrieve the minimum amount of memory for JVM initialization. This value
  398. * contains the units of memory. For example, '5G' = 5 GigaBytes, '1024M' =
  399. * 1024 MegaBytes, etc.
  400. *
  401. * @param {boolean} def Optional. If true, the default value will be returned.
  402. * @returns {string} The minimum amount of memory for JVM initialization.
  403. */
  404. exports.getMinRAM = function(def = false){
  405. return !def ? config.settings.java.minRAM : DEFAULT_CONFIG.settings.java.minRAM
  406. }
  407. /**
  408. * Set the minimum amount of memory for JVM initialization. This value should
  409. * contain the units of memory. For example, '5G' = 5 GigaBytes, '1024M' =
  410. * 1024 MegaBytes, etc.
  411. *
  412. * @param {string} minRAM The new minimum amount of memory for JVM initialization.
  413. */
  414. exports.setMinRAM = function(minRAM){
  415. config.settings.java.minRAM = minRAM
  416. }
  417. /**
  418. * Retrieve the maximum amount of memory for JVM initialization. This value
  419. * contains the units of memory. For example, '5G' = 5 GigaBytes, '1024M' =
  420. * 1024 MegaBytes, etc.
  421. *
  422. * @param {boolean} def Optional. If true, the default value will be returned.
  423. * @returns {string} The maximum amount of memory for JVM initialization.
  424. */
  425. exports.getMaxRAM = function(def = false){
  426. return !def ? config.settings.java.maxRAM : resolveMaxRAM()
  427. }
  428. /**
  429. * Set the maximum amount of memory for JVM initialization. This value should
  430. * contain the units of memory. For example, '5G' = 5 GigaBytes, '1024M' =
  431. * 1024 MegaBytes, etc.
  432. *
  433. * @param {string} maxRAM The new maximum amount of memory for JVM initialization.
  434. */
  435. exports.setMaxRAM = function(maxRAM){
  436. config.settings.java.maxRAM = maxRAM
  437. }
  438. /**
  439. * Retrieve the path of the Java Executable.
  440. *
  441. * This is a resolved configuration value and defaults to null until externally assigned.
  442. *
  443. * @returns {string} The path of the Java Executable.
  444. */
  445. exports.getJavaExecutable = function(){
  446. return config.settings.java.executable
  447. }
  448. /**
  449. * Set the path of the Java Executable.
  450. *
  451. * @param {string} executable The new path of the Java Executable.
  452. */
  453. exports.setJavaExecutable = function(executable){
  454. config.settings.java.executable = executable
  455. }
  456. /**
  457. * Retrieve the additional arguments for JVM initialization. Required arguments,
  458. * such as memory allocation, will be dynamically resolved and will not be included
  459. * in this value.
  460. *
  461. * @param {boolean} def Optional. If true, the default value will be returned.
  462. * @returns {Array.<string>} An array of the additional arguments for JVM initialization.
  463. */
  464. exports.getJVMOptions = function(def = false){
  465. return !def ? config.settings.java.jvmOptions : DEFAULT_CONFIG.settings.java.jvmOptions
  466. }
  467. /**
  468. * Set the additional arguments for JVM initialization. Required arguments,
  469. * such as memory allocation, will be dynamically resolved and should not be
  470. * included in this value.
  471. *
  472. * @param {Array.<string>} jvmOptions An array of the new additional arguments for JVM
  473. * initialization.
  474. */
  475. exports.setJVMOptions = function(jvmOptions){
  476. config.settings.java.jvmOptions = jvmOptions
  477. }
  478. // Game Settings
  479. /**
  480. * Retrieve the width of the game window.
  481. *
  482. * @param {boolean} def Optional. If true, the default value will be returned.
  483. * @returns {number} The width of the game window.
  484. */
  485. exports.getGameWidth = function(def = false){
  486. return !def ? config.settings.game.resWidth : DEFAULT_CONFIG.settings.game.resWidth
  487. }
  488. /**
  489. * Set the width of the game window.
  490. *
  491. * @param {number} resWidth The new width of the game window.
  492. */
  493. exports.setGameWidth = function(resWidth){
  494. config.settings.game.resWidth = Number.parseInt(resWidth)
  495. }
  496. /**
  497. * Validate a potential new width value.
  498. *
  499. * @param {number} resWidth The width value to validate.
  500. * @returns {boolean} Whether or not the value is valid.
  501. */
  502. exports.validateGameWidth = function(resWidth){
  503. const nVal = Number.parseInt(resWidth)
  504. return Number.isInteger(nVal) && nVal >= 0
  505. }
  506. /**
  507. * Retrieve the height of the game window.
  508. *
  509. * @param {boolean} def Optional. If true, the default value will be returned.
  510. * @returns {number} The height of the game window.
  511. */
  512. exports.getGameHeight = function(def = false){
  513. return !def ? config.settings.game.resHeight : DEFAULT_CONFIG.settings.game.resHeight
  514. }
  515. /**
  516. * Set the height of the game window.
  517. *
  518. * @param {number} resHeight The new height of the game window.
  519. */
  520. exports.setGameHeight = function(resHeight){
  521. config.settings.game.resHeight = Number.parseInt(resHeight)
  522. }
  523. /**
  524. * Validate a potential new height value.
  525. *
  526. * @param {number} resHeight The height value to validate.
  527. * @returns {boolean} Whether or not the value is valid.
  528. */
  529. exports.validateGameHeight = function(resHeight){
  530. const nVal = Number.parseInt(resHeight)
  531. return Number.isInteger(nVal) && nVal >= 0
  532. }
  533. /**
  534. * Check if the game should be launched in fullscreen mode.
  535. *
  536. * @param {boolean} def Optional. If true, the default value will be returned.
  537. * @returns {boolean} Whether or not the game is set to launch in fullscreen mode.
  538. */
  539. exports.getFullscreen = function(def = false){
  540. return !def ? config.settings.game.fullscreen : DEFAULT_CONFIG.settings.game.fullscreen
  541. }
  542. /**
  543. * Change the status of if the game should be launched in fullscreen mode.
  544. *
  545. * @param {boolean} fullscreen Whether or not the game should launch in fullscreen mode.
  546. */
  547. exports.setFullscreen = function(fullscreen){
  548. config.settings.game.fullscreen = fullscreen
  549. }
  550. /**
  551. * Check if the game should auto connect to servers.
  552. *
  553. * @param {boolean} def Optional. If true, the default value will be returned.
  554. * @returns {boolean} Whether or not the game should auto connect to servers.
  555. */
  556. exports.getAutoConnect = function(def = false){
  557. return !def ? config.settings.game.autoConnect : DEFAULT_CONFIG.settings.game.autoConnect
  558. }
  559. /**
  560. * Change the status of whether or not the game should auto connect to servers.
  561. *
  562. * @param {boolean} autoConnect Whether or not the game should auto connect to servers.
  563. */
  564. exports.setAutoConnect = function(autoConnect){
  565. config.settings.game.autoConnect = autoConnect
  566. }
  567. /**
  568. * Check if the game should launch as a detached process.
  569. *
  570. * @param {boolean} def Optional. If true, the default value will be returned.
  571. * @returns {boolean} Whether or not the game will launch as a detached process.
  572. */
  573. exports.getLaunchDetached = function(def = false){
  574. return !def ? config.settings.game.launchDetached : DEFAULT_CONFIG.settings.game.launchDetached
  575. }
  576. /**
  577. * Change the status of whether or not the game should launch as a detached process.
  578. *
  579. * @param {boolean} launchDetached Whether or not the game should launch as a detached process.
  580. */
  581. exports.setLaunchDetached = function(launchDetached){
  582. config.settings.game.launchDetached = launchDetached
  583. }
  584. // Launcher Settings
  585. /**
  586. * Check if the launcher should download prerelease versions.
  587. *
  588. * @param {boolean} def Optional. If true, the default value will be returned.
  589. * @returns {boolean} Whether or not the launcher should download prerelease versions.
  590. */
  591. exports.getAllowPrerelease = function(def = false){
  592. return !def ? config.settings.launcher.allowPrerelease : DEFAULT_CONFIG.settings.launcher.allowPrerelease
  593. }
  594. /**
  595. * Change the status of Whether or not the launcher should download prerelease versions.
  596. *
  597. * @param {boolean} launchDetached Whether or not the launcher should download prerelease versions.
  598. */
  599. exports.setAllowPrerelease = function(allowPrerelease){
  600. config.settings.launcher.allowPrerelease = allowPrerelease
  601. }