configmanager.js 19 KB

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