configmanager.js 16 KB

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