processbuilder.js 14 KB

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