configmanager.js 17 KB

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