configmanager.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588
  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. }
  67. let config = null;
  68. // Persistance Utility Functions
  69. /**
  70. * Save the current configuration to a file.
  71. */
  72. exports.save = function(){
  73. const filePath = path.join(dataPath, 'config.json')
  74. fs.writeFileSync(filePath, JSON.stringify(config, null, 4), 'UTF-8')
  75. }
  76. /**
  77. * Load the configuration into memory. If a configuration file exists,
  78. * that will be read and saved. Otherwise, a default configuration will
  79. * be generated. Note that "resolved" values default to null and will
  80. * need to be externally assigned.
  81. */
  82. exports.load = function(){
  83. // Determine the effective configuration.
  84. //const EFFECTIVE_CONFIG = config == null ? DEFAULT_CONFIG : config
  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. // User Configurable Settings
  323. // Java Settings
  324. /**
  325. * Retrieve the minimum amount of memory for JVM initialization. This value
  326. * contains the units of memory. For example, '5G' = 5 GigaBytes, '1024M' =
  327. * 1024 MegaBytes, etc.
  328. *
  329. * @param {boolean} def Optional. If true, the default value will be returned.
  330. * @returns {string} The minimum amount of memory for JVM initialization.
  331. */
  332. exports.getMinRAM = function(def = false){
  333. return !def ? config.settings.java.minRAM : DEFAULT_CONFIG.settings.java.minRAM
  334. }
  335. /**
  336. * Set the minimum amount of memory for JVM initialization. This value should
  337. * contain the units of memory. For example, '5G' = 5 GigaBytes, '1024M' =
  338. * 1024 MegaBytes, etc.
  339. *
  340. * @param {string} minRAM The new minimum amount of memory for JVM initialization.
  341. */
  342. exports.setMinRAM = function(minRAM){
  343. config.settings.java.minRAM = minRAM
  344. }
  345. /**
  346. * Retrieve the maximum amount of memory for JVM initialization. This value
  347. * contains the units of memory. For example, '5G' = 5 GigaBytes, '1024M' =
  348. * 1024 MegaBytes, etc.
  349. *
  350. * @param {boolean} def Optional. If true, the default value will be returned.
  351. * @returns {string} The maximum amount of memory for JVM initialization.
  352. */
  353. exports.getMaxRAM = function(def = false){
  354. return !def ? config.settings.java.maxRAM : resolveMaxRAM()
  355. }
  356. /**
  357. * Set the maximum amount of memory for JVM initialization. This value should
  358. * contain the units of memory. For example, '5G' = 5 GigaBytes, '1024M' =
  359. * 1024 MegaBytes, etc.
  360. *
  361. * @param {string} maxRAM The new maximum amount of memory for JVM initialization.
  362. */
  363. exports.setMaxRAM = function(maxRAM){
  364. config.settings.java.maxRAM = maxRAM
  365. }
  366. /**
  367. * Retrieve the path of the Java Executable.
  368. *
  369. * This is a resolved configuration value and defaults to null until externally assigned.
  370. *
  371. * @returns {string} The path of the Java Executable.
  372. */
  373. exports.getJavaExecutable = function(){
  374. return config.settings.java.executable
  375. }
  376. /**
  377. * Set the path of the Java Executable.
  378. *
  379. * @param {string} executable The new path of the Java Executable.
  380. */
  381. exports.setJavaExecutable = function(executable){
  382. config.settings.java.executable = executable
  383. }
  384. /**
  385. * Retrieve the additional arguments for JVM initialization. Required arguments,
  386. * such as memory allocation, will be dynamically resolved and will not be included
  387. * in this value.
  388. *
  389. * @param {boolean} def Optional. If true, the default value will be returned.
  390. * @returns {Array.<string>} An array of the additional arguments for JVM initialization.
  391. */
  392. exports.getJVMOptions = function(def = false){
  393. return !def ? config.settings.java.jvmOptions : DEFAULT_CONFIG.settings.java.jvmOptions
  394. }
  395. /**
  396. * Set the additional arguments for JVM initialization. Required arguments,
  397. * such as memory allocation, will be dynamically resolved and should not be
  398. * included in this value.
  399. *
  400. * @param {Array.<string>} jvmOptions An array of the new additional arguments for JVM
  401. * initialization.
  402. */
  403. exports.setJVMOptions = function(jvmOptions){
  404. config.settings.java.jvmOptions = jvmOptions
  405. }
  406. // Game Settings
  407. /**
  408. * Retrieve the width of the game window.
  409. *
  410. * @param {boolean} def Optional. If true, the default value will be returned.
  411. * @returns {number} The width of the game window.
  412. */
  413. exports.getGameWidth = function(def = false){
  414. return !def ? config.settings.game.resWidth : DEFAULT_CONFIG.settings.game.resWidth
  415. }
  416. /**
  417. * Set the width of the game window.
  418. *
  419. * @param {number} resWidth The new width of the game window.
  420. */
  421. exports.setGameWidth = function(resWidth){
  422. config.settings.game.resWidth = Number.parseInt(resWidth)
  423. }
  424. /**
  425. * Validate a potential new width value.
  426. *
  427. * @param {number} resWidth The width value to validate.
  428. * @returns {boolean} Whether or not the value is valid.
  429. */
  430. exports.validateGameWidth = function(resWidth){
  431. const nVal = Number.parseInt(resWidth)
  432. return Number.isInteger(nVal) && nVal >= 0
  433. }
  434. /**
  435. * Retrieve the height of the game window.
  436. *
  437. * @param {boolean} def Optional. If true, the default value will be returned.
  438. * @returns {number} The height of the game window.
  439. */
  440. exports.getGameHeight = function(def = false){
  441. return !def ? config.settings.game.resHeight : DEFAULT_CONFIG.settings.game.resHeight
  442. }
  443. /**
  444. * Set the height of the game window.
  445. *
  446. * @param {number} resHeight The new height of the game window.
  447. */
  448. exports.setGameHeight = function(resHeight){
  449. config.settings.game.resHeight = Number.parseInt(resHeight)
  450. }
  451. /**
  452. * Validate a potential new height value.
  453. *
  454. * @param {number} resHeight The height value to validate.
  455. * @returns {boolean} Whether or not the value is valid.
  456. */
  457. exports.validateGameHeight = function(resHeight){
  458. const nVal = Number.parseInt(resHeight)
  459. return Number.isInteger(nVal) && nVal >= 0
  460. }
  461. /**
  462. * Check if the game should be launched in fullscreen mode.
  463. *
  464. * @param {boolean} def Optional. If true, the default value will be returned.
  465. * @returns {boolean} Whether or not the game is set to launch in fullscreen mode.
  466. */
  467. exports.getFullscreen = function(def = false){
  468. return !def ? config.settings.game.fullscreen : DEFAULT_CONFIG.settings.game.fullscreen
  469. }
  470. /**
  471. * Change the status of if the game should be launched in fullscreen mode.
  472. *
  473. * @param {boolean} fullscreen Whether or not the game should launch in fullscreen mode.
  474. */
  475. exports.setFullscreen = function(fullscreen){
  476. config.settings.game.fullscreen = fullscreen
  477. }
  478. /**
  479. * Check if the game should auto connect to servers.
  480. *
  481. * @param {boolean} def Optional. If true, the default value will be returned.
  482. * @returns {boolean} Whether or not the game should auto connect to servers.
  483. */
  484. exports.getAutoConnect = function(def = false){
  485. return !def ? config.settings.game.autoConnect : DEFAULT_CONFIG.settings.game.autoConnect
  486. }
  487. /**
  488. * Change the status of whether or not the game should auto connect to servers.
  489. *
  490. * @param {boolean} autoConnect Whether or not the game should auto connect to servers.
  491. */
  492. exports.setAutoConnect = function(autoConnect){
  493. config.settings.game.autoConnect = autoConnect
  494. }
  495. /**
  496. * Check if the game should launch as a detached process.
  497. *
  498. * @param {boolean} def Optional. If true, the default value will be returned.
  499. * @returns {boolean} Whether or not the game will launch as a detached process.
  500. */
  501. exports.getLaunchDetached = function(def = false){
  502. return !def ? config.settings.game.launchDetached : DEFAULT_CONFIG.settings.game.launchDetached
  503. }
  504. /**
  505. * Change the status of whether or not the game should launch as a detached process.
  506. *
  507. * @param {boolean} launchDetached Whether or not the game should launch as a detached process.
  508. */
  509. exports.setLaunchDetached = function(launchDetached){
  510. config.settings.game.launchDetached = launchDetached
  511. }
  512. // Launcher Settings
  513. /**
  514. * Check if the launcher should download prerelease versions.
  515. *
  516. * @param {boolean} def Optional. If true, the default value will be returned.
  517. * @returns {boolean} Whether or not the launcher should download prerelease versions.
  518. */
  519. exports.getAllowPrerelease = function(def = false){
  520. return !def ? config.settings.launcher.allowPrerelease : DEFAULT_CONFIG.settings.launcher.allowPrerelease
  521. }
  522. /**
  523. * Change the status of Whether or not the launcher should download prerelease versions.
  524. *
  525. * @param {boolean} launchDetached Whether or not the launcher should download prerelease versions.
  526. */
  527. exports.setAllowPrerelease = function(allowPrerelease){
  528. config.settings.launcher.allowPrerelease = allowPrerelease
  529. }