processbuilder.js 14 KB

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