configmanager.js 20 KB

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