processbuilder.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371
  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. if(process.platform === 'darwin'){
  103. args.unshift('-Xdock:name=WesterosCraft')
  104. args.unshift('-Xdock:icon=' + path.join(__dirname, '..', 'images', 'minecraft.icns'))
  105. }
  106. args.splice(2, 0, ...ConfigManager.getJVMOptions())
  107. args = args.concat(this._resolveForgeArgs())
  108. return args
  109. }
  110. /**
  111. * Resolve the arguments required by forge.
  112. *
  113. * @returns {Array.<string>} An array containing the arguments required by forge.
  114. */
  115. _resolveForgeArgs(){
  116. const mcArgs = this.forgeData.minecraftArguments.split(' ')
  117. const argDiscovery = /\${*(.*)}/
  118. // Replace the declared variables with their proper values.
  119. for(let i=0; i<mcArgs.length; ++i){
  120. if(argDiscovery.test(mcArgs[i])){
  121. const identifier = mcArgs[i].match(argDiscovery)[1]
  122. let val = null;
  123. switch(identifier){
  124. case 'auth_player_name':
  125. val = this.authUser.displayName
  126. break
  127. case 'version_name':
  128. //val = versionData.id
  129. val = this.server.id
  130. break
  131. case 'game_directory':
  132. val = this.dir
  133. break
  134. case 'assets_root':
  135. val = path.join(this.dir, 'assets')
  136. break
  137. case 'assets_index_name':
  138. val = this.versionData.assets
  139. break
  140. case 'auth_uuid':
  141. val = this.authUser.uuid
  142. break
  143. case 'auth_access_token':
  144. val = this.authUser.accessToken
  145. break
  146. case 'user_type':
  147. val = 'MOJANG'
  148. break
  149. case 'version_type':
  150. val = this.versionData.type
  151. break
  152. }
  153. if(val != null){
  154. mcArgs[i] = val;
  155. }
  156. }
  157. }
  158. mcArgs.push('--modListFile')
  159. mcArgs.push('absolute:' + this.fmlDir)
  160. // Prepare game resolution
  161. if(ConfigManager.isFullscreen()){
  162. mcArgs.unshift('--fullscreen')
  163. } else {
  164. mcArgs.unshift(ConfigManager.getGameWidth())
  165. mcArgs.unshift('--width')
  166. mcArgs.unshift(ConfigManager.getGameHeight())
  167. mcArgs.unshift('--height')
  168. }
  169. // Prepare autoconnect
  170. if(ConfigManager.isAutoConnect() && this.server.autoconnect){
  171. const serverURL = new URL('my://' + this.server.server_ip)
  172. mcArgs.unshift(serverURL.hostname)
  173. mcArgs.unshift('--server')
  174. if(serverURL.port){
  175. mcArgs.unshift(serverURL.port)
  176. mcArgs.unshift('--port')
  177. }
  178. }
  179. return mcArgs
  180. }
  181. /**
  182. * Resolve the full classpath argument list for this process. This method will resolve all Mojang-declared
  183. * libraries as well as the libraries declared by the server. Since mods are permitted to declare libraries,
  184. * this method requires all enabled mods as an input
  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 paths of each library required by this process.
  189. */
  190. classpathArg(mods, tempNativePath){
  191. let cpArgs = []
  192. // Add the version.jar to the classpath.
  193. const version = this.versionData.id
  194. cpArgs.push(path.join(this.dir, 'versions', version, version + '.jar'))
  195. // Resolve the Mojang declared libraries.
  196. const mojangLibs = this._resolveMojangLibraries(tempNativePath)
  197. cpArgs = cpArgs.concat(mojangLibs)
  198. // Resolve the server declared libraries.
  199. const servLibs = this._resolveServerLibraries(mods)
  200. cpArgs = cpArgs.concat(servLibs)
  201. return cpArgs
  202. }
  203. /**
  204. * Resolve the libraries defined by Mojang's version data. This method will also extract
  205. * native libraries and point to the correct location for its classpath.
  206. *
  207. * TODO - clean up function
  208. *
  209. * @param {string} tempNativePath The path to store the native libraries.
  210. * @returns {Array.<string>} An array containing the paths of each library mojang declares.
  211. */
  212. _resolveMojangLibraries(tempNativePath){
  213. const libs = []
  214. const libArr = this.versionData.libraries
  215. mkpath.sync(tempNativePath)
  216. for(let i=0; i<libArr.length; i++){
  217. const lib = libArr[i]
  218. if(Library.validateRules(lib.rules)){
  219. if(lib.natives == null){
  220. const dlInfo = lib.downloads
  221. const artifact = dlInfo.artifact
  222. const to = path.join(this.libPath, artifact.path)
  223. libs.push(to)
  224. } else {
  225. // Extract the native library.
  226. const natives = lib.natives
  227. const extractInst = lib.extract
  228. const exclusionArr = extractInst.exclude
  229. const opSys = Library.mojangFriendlyOS()
  230. const indexId = natives[opSys]
  231. const dlInfo = lib.downloads
  232. const classifiers = dlInfo.classifiers
  233. const artifact = classifiers[indexId]
  234. // Location of native zip.
  235. const to = path.join(this.libPath, artifact.path)
  236. let zip = new AdmZip(to)
  237. let zipEntries = zip.getEntries()
  238. // Unzip the native zip.
  239. for(let i=0; i<zipEntries.length; i++){
  240. const fileName = zipEntries[i].entryName
  241. let shouldExclude = false
  242. // Exclude noted files.
  243. exclusionArr.forEach(function(exclusion){
  244. if(fileName.indexOf(exclusion) > -1){
  245. shouldExclude = true
  246. }
  247. })
  248. // Extract the file.
  249. if(!shouldExclude){
  250. fs.writeFile(path.join(tempNativePath, fileName), zipEntries[i].getData(), (err) => {
  251. if(err){
  252. console.error('Error while extracting native library:', err)
  253. }
  254. })
  255. }
  256. }
  257. }
  258. }
  259. }
  260. return libs
  261. }
  262. /**
  263. * Resolve the libraries declared by this server in order to add them to the classpath.
  264. * This method will also check each enabled mod for libraries, as mods are permitted to
  265. * declare libraries.
  266. *
  267. * @param {Array.<Object>} mods An array of enabled mods which will be launched with this process.
  268. * @returns {Array.<string>} An array containing the paths of each library this server requires.
  269. */
  270. _resolveServerLibraries(mods){
  271. const mdles = this.server.modules
  272. let libs = []
  273. // Locate Forge/Libraries
  274. for(let i=0; i<mdles.length; i++){
  275. if(mdles[i].type != null && (mdles[i].type === 'forge-hosted' || mdles[i].type === 'library')){
  276. let lib = mdles[i]
  277. libs.push(path.join(this.libPath, lib.artifact.path == null ? AssetGuard._resolvePath(lib.id, lib.artifact.extension) : lib.artifact.path))
  278. if(lib.sub_modules != null){
  279. const res = this._resolveModuleLibraries(lib)
  280. if(res.length > 0){
  281. libs = libs.concat(res)
  282. }
  283. }
  284. }
  285. }
  286. //Check for any libraries in our mod list.
  287. for(let i=0; i<mods.length; i++){
  288. if(mods.sub_modules != null){
  289. const res = this._resolveModuleLibraries(mods[i])
  290. if(res.length > 0){
  291. libs = libs.concat(res)
  292. }
  293. }
  294. }
  295. return libs
  296. }
  297. /**
  298. * Recursively resolve the path of each library required by this module.
  299. *
  300. * @param {Object} mdle A module object from the server distro index.
  301. * @returns {Array.<string>} An array containing the paths of each library this module requires.
  302. */
  303. _resolveModuleLibraries(mdle){
  304. if(mdle.sub_modules == null){
  305. return []
  306. }
  307. let libs = []
  308. for(let i=0; i<mdle.sub_modules.length; i++){
  309. const sm = mdle.sub_modules[i]
  310. if(sm.type != null && sm.type == 'library'){
  311. libs.push(path.join(this.libPath, sm.artifact.path == null ? AssetGuard._resolvePath(sm.id, sm.artifact.extension) : sm.artifact.path))
  312. }
  313. // If this module has submodules, we need to resolve the libraries for those.
  314. // To avoid unnecessary recursive calls, base case is checked here.
  315. if(mdle.sub_modules != null){
  316. const res = this._resolveModuleLibraries(sm)
  317. if(res.length > 0){
  318. libs = libs.concat(res)
  319. }
  320. }
  321. }
  322. return libs
  323. }
  324. }
  325. module.exports = ProcessBuilder