processbuilder.js 18 KB

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