configmanager.js 19 KB

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