processbuilder.js 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484
  1. const AdmZip = require('adm-zip')
  2. const child_process = require('child_process')
  3. const crypto = require('crypto')
  4. const fs = require('fs')
  5. const mkpath = require('mkdirp')
  6. const os = require('os')
  7. const path = require('path')
  8. const rimraf = require('rimraf')
  9. const {URL} = require('url')
  10. const { Library } = require('./assetguard')
  11. const ConfigManager = require('./configmanager')
  12. const DistroManager = require('./distromanager')
  13. class ProcessBuilder {
  14. constructor(distroServer, versionData, forgeData, authUser){
  15. this.gameDir = path.join(ConfigManager.getInstanceDirectory(), distroServer.getID())
  16. this.commonDir = ConfigManager.getCommonDirectory()
  17. this.server = distroServer
  18. this.versionData = versionData
  19. this.forgeData = forgeData
  20. this.authUser = authUser
  21. this.fmlDir = path.join(this.gameDir, 'forgeModList.json')
  22. this.llDir = path.join(this.gameDir, 'liteloaderModList.json')
  23. this.libPath = path.join(this.commonDir, 'libraries')
  24. this.usingLiteLoader = false
  25. this.llPath = null
  26. }
  27. /**
  28. * Convienence method to run the functions typically used to build a process.
  29. */
  30. build(){
  31. mkpath.sync(this.gameDir)
  32. const tempNativePath = path.join(os.tmpdir(), ConfigManager.getTempNativeFolder(), crypto.pseudoRandomBytes(16).toString('hex'))
  33. process.throwDeprecation = true
  34. this.setupLiteLoader()
  35. console.log('%c[ProcessBuilder]', 'color: #003996; font-weight: bold', 'Using liteloader:', this.usingLiteLoader)
  36. const modObj = this.resolveModConfiguration(ConfigManager.getModConfiguration(this.server.getID()).mods, this.server.getModules())
  37. this.constructModList('forge', modObj.fMods, true)
  38. if(this.usingLiteLoader){
  39. this.constructModList('liteloader', modObj.lMods, true)
  40. }
  41. const uberModArr = modObj.fMods.concat(modObj.lMods)
  42. const args = this.constructJVMArguments(uberModArr, tempNativePath)
  43. console.log(args)
  44. const child = child_process.spawn(ConfigManager.getJavaExecutable(), args, {
  45. cwd: this.gameDir,
  46. detached: ConfigManager.getLaunchDetached()
  47. })
  48. if(ConfigManager.getLaunchDetached()){
  49. child.unref()
  50. }
  51. child.stdout.setEncoding('utf8')
  52. child.stderr.setEncoding('utf8')
  53. child.stdout.on('data', (data) => {
  54. console.log('%c[Minecraft]', 'color: #36b030; font-weight: bold', data)
  55. })
  56. child.stderr.on('data', (data) => {
  57. console.log('%c[Minecraft]', 'color: #b03030; font-weight: bold', data)
  58. })
  59. child.on('close', (code, signal) => {
  60. console.log('%c[ProcessBuilder]', 'color: #003996; font-weight: bold', 'Exited with code', code)
  61. rimraf(tempNativePath, (err) => {
  62. if(err){
  63. console.warn('%c[ProcessBuilder]', 'color: #003996; font-weight: bold', 'Error while deleting temp dir', err)
  64. } else {
  65. console.log('%c[ProcessBuilder]', 'color: #003996; font-weight: bold', 'Temp dir deleted successfully.')
  66. }
  67. })
  68. })
  69. return child
  70. }
  71. /**
  72. * Determine if an optional mod is enabled from its configuration value. If the
  73. * configuration value is null, the required object will be used to
  74. * determine if it is enabled.
  75. *
  76. * A mod is enabled if:
  77. * * The configuration is not null and one of the following:
  78. * * The configuration is a boolean and true.
  79. * * The configuration is an object and its 'value' property is true.
  80. * * The configuration is null and one of the following:
  81. * * The required object is null.
  82. * * The required object's 'def' property is null or true.
  83. *
  84. * @param {Object | boolean} modCfg The mod configuration object.
  85. * @param {Object} required Optional. The required object from the mod's distro declaration.
  86. * @returns {boolean} True if the mod is enabled, false otherwise.
  87. */
  88. static isModEnabled(modCfg, required = null){
  89. return modCfg != null ? ((typeof modCfg === 'boolean' && modCfg) || (typeof modCfg === 'object' && (typeof modCfg.value !== 'undefined' ? modCfg.value : true))) : required != null ? required.isDefault() : true
  90. }
  91. /**
  92. * Function which performs a preliminary scan of the top level
  93. * mods. If liteloader is present here, we setup the special liteloader
  94. * launch options. Note that liteloader is only allowed as a top level
  95. * mod. It must not be declared as a submodule.
  96. */
  97. setupLiteLoader(){
  98. for(let ll of this.server.getModules()){
  99. if(ll.getType() === DistroManager.Types.LiteLoader){
  100. if(!ll.getRequired().isRequired()){
  101. const modCfg = ConfigManager.getModConfiguration(this.server.getID()).mods
  102. if(ProcessBuilder.isModEnabled(modCfg[ll.getVersionlessID()], ll.getRequired())){
  103. if(fs.existsSync(ll.getArtifact().getPath())){
  104. this.usingLiteLoader = true
  105. this.llPath = ll.getArtifact().getPath()
  106. }
  107. }
  108. } else {
  109. if(fs.existsSync(ll.getArtifact().getPath())){
  110. this.usingLiteLoader = true
  111. this.llPath = ll.getArtifact().getPath()
  112. }
  113. }
  114. }
  115. }
  116. }
  117. /**
  118. * Resolve an array of all enabled mods. These mods will be constructed into
  119. * a mod list format and enabled at launch.
  120. *
  121. * @param {Object} modCfg The mod configuration object.
  122. * @param {Array.<Object>} mdls An array of modules to parse.
  123. * @returns {{fMods: Array.<Object>, lMods: Array.<Object>}} An object which contains
  124. * a list of enabled forge mods and litemods.
  125. */
  126. resolveModConfiguration(modCfg, mdls){
  127. let fMods = []
  128. let lMods = []
  129. for(let mdl of mdls){
  130. const type = mdl.getType()
  131. if(type === DistroManager.Types.ForgeMod || type === DistroManager.Types.LiteMod || type === DistroManager.Types.LiteLoader){
  132. const o = !mdl.getRequired().isRequired()
  133. const e = ProcessBuilder.isModEnabled(modCfg[mdl.getVersionlessID()], mdl.getRequired())
  134. if(!o || (o && e)){
  135. if(mdl.hasSubModules()){
  136. const v = this.resolveModConfiguration(modCfg[mdl.getVersionlessID()].mods, mdl.getSubModules())
  137. fMods = fMods.concat(v.fMods)
  138. lMods = lMods.concat(v.lMods)
  139. if(mdl.type === DistroManager.Types.LiteLoader){
  140. continue
  141. }
  142. }
  143. if(mdl.type === DistroManager.Types.ForgeMod){
  144. fMods.push(mdl)
  145. } else {
  146. lMods.push(mdl)
  147. }
  148. }
  149. }
  150. }
  151. return {
  152. fMods,
  153. lMods
  154. }
  155. }
  156. /**
  157. * Construct a mod list json object.
  158. *
  159. * @param {'forge' | 'liteloader'} type The mod list type to construct.
  160. * @param {Array.<Object>} mods An array of mods to add to the mod list.
  161. * @param {boolean} save Optional. Whether or not we should save the mod list file.
  162. */
  163. constructModList(type, mods, save = false){
  164. const modList = {
  165. repositoryRoot: path.join(this.commonDir, 'modstore')
  166. }
  167. const ids = []
  168. if(type === 'forge'){
  169. for(let mod of mods){
  170. ids.push(mod.getExtensionlessID())
  171. }
  172. } else {
  173. for(let mod of mods){
  174. ids.push(mod.getExtensionlessID() + '@' + mod.getExtension())
  175. }
  176. }
  177. modList.modRef = ids
  178. if(save){
  179. const json = JSON.stringify(modList, null, 4)
  180. fs.writeFileSync(type === 'forge' ? this.fmlDir : this.llDir, json, 'UTF-8')
  181. }
  182. return modList
  183. }
  184. /**
  185. * Construct the argument array that will be passed to the JVM process.
  186. *
  187. * @param {Array.<Object>} mods An array of enabled mods which will be launched with this process.
  188. * @param {string} tempNativePath The path to store the native libraries.
  189. * @returns {Array.<string>} An array containing the full JVM arguments for this process.
  190. */
  191. constructJVMArguments(mods, tempNativePath){
  192. let args = ['-Xmx' + ConfigManager.getMaxRAM(),
  193. '-Xms' + ConfigManager.getMinRAM(),
  194. '-Djava.library.path=' + tempNativePath,
  195. '-cp',
  196. this.classpathArg(mods, tempNativePath).join(process.platform === 'win32' ? ';' : ':'),
  197. this.forgeData.mainClass]
  198. if(process.platform === 'darwin'){
  199. args.unshift('-Xdock:name=WesterosCraft')
  200. args.unshift('-Xdock:icon=' + path.join(__dirname, '..', 'images', 'minecraft.icns'))
  201. }
  202. args.splice(2, 0, ...ConfigManager.getJVMOptions())
  203. args = args.concat(this._resolveForgeArgs())
  204. return args
  205. }
  206. /**
  207. * Resolve the arguments required by forge.
  208. *
  209. * @returns {Array.<string>} An array containing the arguments required by forge.
  210. */
  211. _resolveForgeArgs(){
  212. const mcArgs = this.forgeData.minecraftArguments.split(' ')
  213. const argDiscovery = /\${*(.*)}/
  214. // Replace the declared variables with their proper values.
  215. for(let i=0; i<mcArgs.length; ++i){
  216. if(argDiscovery.test(mcArgs[i])){
  217. const identifier = mcArgs[i].match(argDiscovery)[1]
  218. let val = null
  219. switch(identifier){
  220. case 'auth_player_name':
  221. val = this.authUser.displayName
  222. break
  223. case 'version_name':
  224. //val = versionData.id
  225. val = this.server.getID()
  226. break
  227. case 'game_directory':
  228. val = this.gameDir
  229. break
  230. case 'assets_root':
  231. val = path.join(this.commonDir, 'assets')
  232. break
  233. case 'assets_index_name':
  234. val = this.versionData.assets
  235. break
  236. case 'auth_uuid':
  237. val = this.authUser.uuid
  238. break
  239. case 'auth_access_token':
  240. val = this.authUser.accessToken
  241. break
  242. case 'user_type':
  243. val = 'MOJANG'
  244. break
  245. case 'version_type':
  246. val = this.versionData.type
  247. break
  248. }
  249. if(val != null){
  250. mcArgs[i] = val
  251. }
  252. }
  253. }
  254. mcArgs.push('--modListFile')
  255. mcArgs.push('absolute:' + this.fmlDir)
  256. if(this.usingLiteLoader){
  257. mcArgs.push('--modRepo')
  258. mcArgs.push(this.llDir)
  259. mcArgs.unshift('com.mumfrey.liteloader.launch.LiteLoaderTweaker')
  260. mcArgs.unshift('--tweakClass')
  261. }
  262. // Prepare game resolution
  263. if(ConfigManager.getFullscreen()){
  264. mcArgs.unshift('--fullscreen')
  265. } else {
  266. mcArgs.unshift(ConfigManager.getGameWidth())
  267. mcArgs.unshift('--width')
  268. mcArgs.unshift(ConfigManager.getGameHeight())
  269. mcArgs.unshift('--height')
  270. }
  271. // Prepare autoconnect
  272. if(ConfigManager.getAutoConnect() && this.server.isAutoConnect()){
  273. const serverURL = new URL('my://' + this.server.getAddress())
  274. mcArgs.unshift(serverURL.hostname)
  275. mcArgs.unshift('--server')
  276. if(serverURL.port){
  277. mcArgs.unshift(serverURL.port)
  278. mcArgs.unshift('--port')
  279. }
  280. }
  281. return mcArgs
  282. }
  283. /**
  284. * Resolve the full classpath argument list for this process. This method will resolve all Mojang-declared
  285. * libraries as well as the libraries declared by the server. Since mods are permitted to declare libraries,
  286. * this method requires all enabled mods as an input
  287. *
  288. * @param {Array.<Object>} mods An array of enabled mods which will be launched with this process.
  289. * @param {string} tempNativePath The path to store the native libraries.
  290. * @returns {Array.<string>} An array containing the paths of each library required by this process.
  291. */
  292. classpathArg(mods, tempNativePath){
  293. let cpArgs = []
  294. // Add the version.jar to the classpath.
  295. const version = this.versionData.id
  296. cpArgs.push(path.join(this.commonDir, 'versions', version, version + '.jar'))
  297. if(this.usingLiteLoader){
  298. cpArgs.push(this.llPath)
  299. }
  300. // Resolve the Mojang declared libraries.
  301. const mojangLibs = this._resolveMojangLibraries(tempNativePath)
  302. cpArgs = cpArgs.concat(mojangLibs)
  303. // Resolve the server declared libraries.
  304. const servLibs = this._resolveServerLibraries(mods)
  305. cpArgs = cpArgs.concat(servLibs)
  306. return cpArgs
  307. }
  308. /**
  309. * Resolve the libraries defined by Mojang's version data. This method will also extract
  310. * native libraries and point to the correct location for its classpath.
  311. *
  312. * TODO - clean up function
  313. *
  314. * @param {string} tempNativePath The path to store the native libraries.
  315. * @returns {Array.<string>} An array containing the paths of each library mojang declares.
  316. */
  317. _resolveMojangLibraries(tempNativePath){
  318. const libs = []
  319. const libArr = this.versionData.libraries
  320. mkpath.sync(tempNativePath)
  321. for(let i=0; i<libArr.length; i++){
  322. const lib = libArr[i]
  323. if(Library.validateRules(lib.rules)){
  324. if(lib.natives == null){
  325. const dlInfo = lib.downloads
  326. const artifact = dlInfo.artifact
  327. const to = path.join(this.libPath, artifact.path)
  328. libs.push(to)
  329. } else {
  330. // Extract the native library.
  331. const natives = lib.natives
  332. const extractInst = lib.extract
  333. const exclusionArr = extractInst.exclude
  334. const opSys = Library.mojangFriendlyOS()
  335. const indexId = natives[opSys]
  336. const dlInfo = lib.downloads
  337. const classifiers = dlInfo.classifiers
  338. const artifact = classifiers[indexId]
  339. // Location of native zip.
  340. const to = path.join(this.libPath, artifact.path)
  341. let zip = new AdmZip(to)
  342. let zipEntries = zip.getEntries()
  343. // Unzip the native zip.
  344. for(let i=0; i<zipEntries.length; i++){
  345. const fileName = zipEntries[i].entryName
  346. let shouldExclude = false
  347. // Exclude noted files.
  348. exclusionArr.forEach(function(exclusion){
  349. if(fileName.indexOf(exclusion) > -1){
  350. shouldExclude = true
  351. }
  352. })
  353. // Extract the file.
  354. if(!shouldExclude){
  355. fs.writeFile(path.join(tempNativePath, fileName), zipEntries[i].getData(), (err) => {
  356. if(err){
  357. console.error('Error while extracting native library:', err)
  358. }
  359. })
  360. }
  361. }
  362. }
  363. }
  364. }
  365. return libs
  366. }
  367. /**
  368. * Resolve the libraries declared by this server in order to add them to the classpath.
  369. * This method will also check each enabled mod for libraries, as mods are permitted to
  370. * declare libraries.
  371. *
  372. * @param {Array.<Object>} mods An array of enabled mods which will be launched with this process.
  373. * @returns {Array.<string>} An array containing the paths of each library this server requires.
  374. */
  375. _resolveServerLibraries(mods){
  376. const mdls = this.server.getModules()
  377. let libs = []
  378. // Locate Forge/Libraries
  379. for(let mdl of mdls){
  380. const type = mdl.getType()
  381. if(type === DistroManager.Types.ForgeHosted || type === DistroManager.Types.Library){
  382. libs.push(mdl.getArtifact().getPath())
  383. if(mdl.hasSubModules()){
  384. const res = this._resolveModuleLibraries(mdl)
  385. if(res.length > 0){
  386. libs = libs.concat(res)
  387. }
  388. }
  389. }
  390. }
  391. //Check for any libraries in our mod list.
  392. for(let i=0; i<mods.length; i++){
  393. if(mods.sub_modules != null){
  394. const res = this._resolveModuleLibraries(mods[i])
  395. if(res.length > 0){
  396. libs = libs.concat(res)
  397. }
  398. }
  399. }
  400. return libs
  401. }
  402. /**
  403. * Recursively resolve the path of each library required by this module.
  404. *
  405. * @param {Object} mdl A module object from the server distro index.
  406. * @returns {Array.<string>} An array containing the paths of each library this module requires.
  407. */
  408. _resolveModuleLibraries(mdl){
  409. if(!mdl.hasSubModules()){
  410. return []
  411. }
  412. let libs = []
  413. for(let sm of mdl.getSubModules()){
  414. if(sm.getType() === DistroManager.Types.Library){
  415. libs.push(sm.getArtifact().getPath())
  416. }
  417. // If this module has submodules, we need to resolve the libraries for those.
  418. // To avoid unnecessary recursive calls, base case is checked here.
  419. if(mdl.hasSubModules()){
  420. const res = this._resolveModuleLibraries(sm)
  421. if(res.length > 0){
  422. libs = libs.concat(res)
  423. }
  424. }
  425. }
  426. return libs
  427. }
  428. }
  429. module.exports = ProcessBuilder