processbuilder.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361
  1. /**
  2. * The initial iteration of this file will not support optional submodules.
  3. * Support will be added down the line, only top-level modules will recieve optional support.
  4. *
  5. *
  6. * TODO why are logs not working??????
  7. */
  8. const AdmZip = require('adm-zip')
  9. const {AssetGuard, Library} = require('./assetguard.js')
  10. const child_process = require('child_process')
  11. const ConfigManager = require('./configmanager.js')
  12. const fs = require('fs')
  13. const mkpath = require('mkdirp')
  14. const path = require('path')
  15. const {URL} = require('url')
  16. class ProcessBuilder {
  17. constructor(gameDirectory, distroServer, versionData, forgeData, authUser){
  18. this.dir = gameDirectory
  19. this.server = distroServer
  20. this.versionData = versionData
  21. this.forgeData = forgeData
  22. this.authUser = authUser
  23. this.fmlDir = path.join(this.dir, 'versions', this.server.id + '.json')
  24. this.libPath = path.join(this.dir, 'libraries')
  25. }
  26. static shouldInclude(mdle){
  27. //If the module should be included by default
  28. return mdle.required == null || mdle.required.value == null || mdle.required.value === true || (mdle.required.value === false && (mdle.required.def == null || mdle.required.def === true))
  29. }
  30. /**
  31. * Convienence method to run the functions typically used to build a process.
  32. */
  33. build(){
  34. process.throwDeprecation = true
  35. const mods = this.resolveDefaultMods()
  36. this.constructFMLModList(mods, true)
  37. const args = this.constructJVMArguments(mods)
  38. console.log(args)
  39. const child = child_process.spawn(ConfigManager.getJavaExecutable(), args, {
  40. cwd: ConfigManager.getGameDirectory()
  41. })
  42. child.stdout.on('data', (data) => {
  43. console.log('Minecraft:', data.toString('utf8'))
  44. })
  45. child.stderr.on('data', (data) => {
  46. console.log('Minecraft:', data.toString('utf8'))
  47. })
  48. child.on('close', (code, signal) => {
  49. console.log('Exited with code', code)
  50. })
  51. return child
  52. }
  53. resolveDefaultMods(options = {type: 'forgemod'}){
  54. //Returns array of default forge mods to load.
  55. const mods = []
  56. const mdles = this.server.modules
  57. for(let i=0; i<mdles.length; ++i){
  58. if(mdles[i].type != null && mdles[i].type === options.type){
  59. if(ProcessBuilder.shouldInclude(mdles[i])){
  60. mods.push(mdles[i])
  61. }
  62. }
  63. }
  64. return mods
  65. }
  66. constructFMLModList(mods, save = false){
  67. const modList = {}
  68. modList.repositoryRoot = path.join(this.dir, 'modstore')
  69. const ids = []
  70. for(let i=0; i<mods.length; ++i){
  71. ids.push(mods[i].id)
  72. }
  73. modList.modRef = ids
  74. if(save){
  75. const json = JSON.stringify(modList, null, 4)
  76. fs.writeFileSync(this.fmlDir, json, 'UTF-8')
  77. }
  78. return modList
  79. }
  80. /**
  81. * Construct the argument array that will be passed to the JVM process.
  82. *
  83. * @param {Array.<Object>} mods An array of enabled mods which will be launched with this process.
  84. * @returns {Array.<string>} An array containing the full JVM arguments for this process.
  85. */
  86. constructJVMArguments(mods){
  87. let args = ['-Xmx' + ConfigManager.getMaxRAM(),
  88. '-Xms' + ConfigManager.getMinRAM(),,
  89. '-Djava.library.path=' + path.join(this.dir, 'natives'),
  90. '-cp',
  91. this.classpathArg(mods).join(';'),
  92. this.forgeData.mainClass]
  93. // For some reason this will add an undefined value unless
  94. // the delete count is 1. I suspect this is unintended behavior
  95. // by the function.. need to keep an eye on this.
  96. args.splice(2, 1, ...ConfigManager.getJVMOptions())
  97. args = args.concat(this._resolveForgeArgs())
  98. return args
  99. }
  100. /**
  101. * Resolve the arguments required by forge.
  102. *
  103. * @returns {Array.<string>} An array containing the arguments required by forge.
  104. */
  105. _resolveForgeArgs(){
  106. const mcArgs = this.forgeData.minecraftArguments.split(' ')
  107. const argDiscovery = /\${*(.*)}/
  108. // Replace the declared variables with their proper values.
  109. for(let i=0; i<mcArgs.length; ++i){
  110. if(argDiscovery.test(mcArgs[i])){
  111. const identifier = mcArgs[i].match(argDiscovery)[1]
  112. let val = null;
  113. switch(identifier){
  114. case 'auth_player_name':
  115. val = this.authUser.displayName
  116. break
  117. case 'version_name':
  118. //val = versionData.id
  119. val = this.server.id
  120. break
  121. case 'game_directory':
  122. val = this.dir
  123. break
  124. case 'assets_root':
  125. val = path.join(this.dir, 'assets')
  126. break
  127. case 'assets_index_name':
  128. val = this.versionData.assets
  129. break
  130. case 'auth_uuid':
  131. val = this.authUser.uuid
  132. break
  133. case 'auth_access_token':
  134. val = this.authUser.accessToken
  135. break
  136. case 'user_type':
  137. val = 'MOJANG'
  138. break
  139. case 'version_type':
  140. val = this.versionData.type
  141. break
  142. }
  143. if(val != null){
  144. mcArgs[i] = val;
  145. }
  146. }
  147. }
  148. mcArgs.push('--modListFile')
  149. mcArgs.push('absolute:' + this.fmlDir)
  150. // Prepare game resolution
  151. if(ConfigManager.isFullscreen()){
  152. mcArgs.unshift('--fullscreen')
  153. } else {
  154. mcArgs.unshift(ConfigManager.getGameWidth())
  155. mcArgs.unshift('--width')
  156. mcArgs.unshift(ConfigManager.getGameHeight())
  157. mcArgs.unshift('--height')
  158. }
  159. // Prepare autoconnect
  160. if(ConfigManager.isAutoConnect() && this.server.autoconnect){
  161. const serverURL = new URL('my://' + this.server.server_ip)
  162. mcArgs.unshift(serverURL.hostname)
  163. mcArgs.unshift('--server')
  164. if(serverURL.port){
  165. mcArgs.unshift(serverURL.port)
  166. mcArgs.unshift('--port')
  167. }
  168. }
  169. return mcArgs
  170. }
  171. /**
  172. * Resolve the full classpath argument list for this process. This method will resolve all Mojang-declared
  173. * libraries as well as the libraries declared by the server. Since mods are permitted to declare libraries,
  174. * this method requires all enabled mods as an input
  175. *
  176. * @param {Array.<Object>} mods An array of enabled mods which will be launched with this process.
  177. * @returns {Array.<string>} An array containing the paths of each library required by this process.
  178. */
  179. classpathArg(mods){
  180. let cpArgs = []
  181. // Add the version.jar to the classpath.
  182. const version = this.versionData.id
  183. cpArgs.push(path.join(this.dir, 'versions', version, version + '.jar'))
  184. // Resolve the Mojang declared libraries.
  185. const mojangLibs = this._resolveMojangLibraries()
  186. cpArgs = cpArgs.concat(mojangLibs)
  187. // Resolve the server declared libraries.
  188. const servLibs = this._resolveServerLibraries(mods)
  189. cpArgs = cpArgs.concat(servLibs)
  190. return cpArgs
  191. }
  192. /**
  193. * Resolve the libraries defined by Mojang's version data. This method will also extract
  194. * native libraries and point to the correct location for its classpath.
  195. *
  196. * TODO - clean up function
  197. *
  198. * @returns {Array.<string>} An array containing the paths of each library mojang declares.
  199. */
  200. _resolveMojangLibraries(){
  201. const libs = []
  202. const libArr = this.versionData.libraries
  203. const nativePath = path.join(this.dir, 'natives')
  204. for(let i=0; i<libArr.length; i++){
  205. const lib = libArr[i]
  206. if(Library.validateRules(lib.rules)){
  207. if(lib.natives == null){
  208. const dlInfo = lib.downloads
  209. const artifact = dlInfo.artifact
  210. const to = path.join(this.libPath, artifact.path)
  211. libs.push(to)
  212. } else {
  213. // Extract the native library.
  214. const natives = lib.natives
  215. const extractInst = lib.extract
  216. const exclusionArr = extractInst.exclude
  217. const opSys = Library.mojangFriendlyOS()
  218. const indexId = natives[opSys]
  219. const dlInfo = lib.downloads
  220. const classifiers = dlInfo.classifiers
  221. const artifact = classifiers[indexId]
  222. // Location of native zip.
  223. const to = path.join(this.libPath, artifact.path)
  224. let zip = new AdmZip(to)
  225. let zipEntries = zip.getEntries()
  226. // Unzip the native zip.
  227. for(let i=0; i<zipEntries.length; i++){
  228. const fileName = zipEntries[i].entryName
  229. let shouldExclude = false
  230. // Exclude noted files.
  231. exclusionArr.forEach(function(exclusion){
  232. if(fileName.indexOf(exclusion) > -1){
  233. shouldExclude = true
  234. }
  235. })
  236. // Extract the file.
  237. if(!shouldExclude){
  238. mkpath.sync(path.join(nativePath, fileName, '..'))
  239. fs.writeFile(path.join(nativePath, fileName), zipEntries[i].getData(), (err) => {
  240. if(err){
  241. console.error('Error while extracting native library:', err)
  242. }
  243. })
  244. }
  245. }
  246. libs.push(to)
  247. }
  248. }
  249. }
  250. return libs
  251. }
  252. /**
  253. * Resolve the libraries declared by this server in order to add them to the classpath.
  254. * This method will also check each enabled mod for libraries, as mods are permitted to
  255. * declare libraries.
  256. *
  257. * @param {Array.<Object>} mods An array of enabled mods which will be launched with this process.
  258. * @returns {Array.<string>} An array containing the paths of each library this server requires.
  259. */
  260. _resolveServerLibraries(mods){
  261. const mdles = this.server.modules
  262. let libs = []
  263. // Locate Forge/Libraries
  264. for(let i=0; i<mdles.length; i++){
  265. if(mdles[i].type != null && (mdles[i].type === 'forge-hosted' || mdles[i].type === 'library')){
  266. let lib = mdles[i]
  267. libs.push(path.join(this.libPath, lib.artifact.path == null ? AssetGuard._resolvePath(lib.id, lib.artifact.extension) : lib.artifact.path))
  268. if(lib.sub_modules != null){
  269. const res = this._resolveModuleLibraries(lib)
  270. if(res.length > 0){
  271. libs = libs.concat(res)
  272. }
  273. }
  274. }
  275. }
  276. //Check for any libraries in our mod list.
  277. for(let i=0; i<mods.length; i++){
  278. if(mods.sub_modules != null){
  279. const res = this._resolveModuleLibraries(mods[i])
  280. if(res.length > 0){
  281. libs = libs.concat(res)
  282. }
  283. }
  284. }
  285. return libs
  286. }
  287. /**
  288. * Recursively resolve the path of each library required by this module.
  289. *
  290. * @param {Object} mdle A module object from the server distro index.
  291. * @returns {Array.<string>} An array containing the paths of each library this module requires.
  292. */
  293. _resolveModuleLibraries(mdle){
  294. if(mdle.sub_modules == null){
  295. return []
  296. }
  297. let libs = []
  298. for(let i=0; i<mdle.sub_modules.length; i++){
  299. const sm = mdle.sub_modules[i]
  300. if(sm.type != null && sm.type == 'library'){
  301. libs.push(path.join(this.libPath, sm.artifact.path == null ? AssetGuard._resolvePath(sm.id, sm.artifact.extension) : sm.artifact.path))
  302. }
  303. // If this module has submodules, we need to resolve the libraries for those.
  304. // To avoid unnecessary recursive calls, base case is checked here.
  305. if(mdle.sub_modules != null){
  306. const res = this._resolveModuleLibraries(sm)
  307. if(res.length > 0){
  308. libs = libs.concat(res)
  309. }
  310. }
  311. }
  312. return libs
  313. }
  314. }
  315. module.exports = ProcessBuilder