actionbinder.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384
  1. const cp = require('child_process')
  2. const path = require('path')
  3. const {AssetGuard} = require(path.join(__dirname, 'assets', 'js', 'assetguard.js'))
  4. const ProcessBuilder = require(path.join(__dirname, 'assets', 'js', 'processbuilder.js'))
  5. const ConfigManager = require(path.join(__dirname, 'assets', 'js', 'configmanager.js'))
  6. const DiscordWrapper = require(path.join(__dirname, 'assets', 'js', 'discordwrapper.js'))
  7. const Mojang = require(path.join(__dirname, 'assets', 'js', 'mojang.js'))
  8. const AuthManager = require(path.join(__dirname, 'assets', 'js', 'authmanager.js'))
  9. let mojangStatusListener
  10. // Launch Elements
  11. let launch_content, launch_details, launch_progress, launch_progress_label, launch_details_text
  12. // Synchronous Listener
  13. document.addEventListener('readystatechange', function(){
  14. if (document.readyState === 'complete'){
  15. if(ConfigManager.isFirstLaunch()){
  16. $('#welcomeContainer').fadeIn(500)
  17. } else {
  18. $('#landingContainer').fadeIn(500)
  19. }
  20. }
  21. if (document.readyState === 'interactive'){
  22. // Save a reference to the launch elements.
  23. launch_content = document.getElementById('launch_content')
  24. launch_details = document.getElementById('launch_details')
  25. launch_progress = document.getElementById('launch_progress')
  26. launch_progress_label = document.getElementById('launch_progress_label')
  27. launch_details_text = document.getElementById('launch_details_text')
  28. // Bind launch button
  29. document.getElementById('launch_button').addEventListener('click', function(e){
  30. console.log('Launching game..')
  31. const jExe = ConfigManager.getJavaExecutable()
  32. if(jExe == null){
  33. asyncSystemScan()
  34. } else {
  35. AssetGuard._validateJavaBinary(jExe).then((v) => {
  36. if(v){
  37. dlAsync()
  38. } else {
  39. asyncSystemScan()
  40. }
  41. })
  42. }
  43. })
  44. // TODO convert this to dropdown menu.
  45. // Bind selected server
  46. document.getElementById('server_selection').innerHTML = '\u2022 ' + AssetGuard.getServerById(ConfigManager.getGameDirectory(), ConfigManager.getSelectedServer()).name
  47. // Update Mojang Status Color
  48. const refreshMojangStatuses = async function(){
  49. console.log('Refreshing Mojang Statuses..')
  50. try {
  51. let status = 'grey'
  52. const statuses = await Mojang.status()
  53. greenCount = 0
  54. for(let i=0; i<statuses.length; i++){
  55. if(statuses[i].status === 'yellow' && status !== 'red'){
  56. status = 'yellow'
  57. continue
  58. } else if(statuses[i].status === 'red'){
  59. status = 'red'
  60. break
  61. }
  62. ++greenCount
  63. }
  64. if(greenCount == statuses.length){
  65. status = 'green'
  66. }
  67. document.getElementById('mojang_status_icon').style.color = Mojang.statusToHex(status)
  68. } catch (err) {
  69. console.error('Unable to refresh Mojang service status..', err)
  70. }
  71. }
  72. refreshMojangStatuses()
  73. // Set refresh rate to once every 5 minutes.
  74. mojangStatusListener = setInterval(refreshMojangStatuses, 300000)
  75. }
  76. }, false)
  77. /* Overlay Wrapper Functions */
  78. /**
  79. * Toggle the visibility of the overlay.
  80. *
  81. * @param {boolean} toggleState True to display, false to hide.
  82. */
  83. function toggleOverlay(toggleState){
  84. if(toggleState == null){
  85. toggleState = !document.getElementById('main').hasAttribute('overlay')
  86. }
  87. if(toggleState){
  88. document.getElementById('main').setAttribute('overlay', true)
  89. $('#overlayContainer').fadeToggle(500)
  90. } else {
  91. document.getElementById('main').removeAttribute('overlay')
  92. $('#overlayContainer').fadeToggle(500)
  93. }
  94. }
  95. /* Launch Progress Wrapper Functions */
  96. /**
  97. * Show/hide the loading area.
  98. *
  99. * @param {boolean} loading True if the loading area should be shown, otherwise false.
  100. */
  101. function toggleLaunchArea(loading){
  102. if(loading){
  103. launch_details.style.display = 'flex'
  104. launch_content.style.display = 'none'
  105. } else {
  106. launch_details.style.display = 'none'
  107. launch_content.style.display = 'inline-flex'
  108. }
  109. }
  110. /**
  111. * Set the details text of the loading area.
  112. *
  113. * @param {string} details The new text for the loading details.
  114. */
  115. function setLaunchDetails(details){
  116. launch_details_text.innerHTML = details
  117. }
  118. /**
  119. * Set the value of the loading progress bar and display that value.
  120. *
  121. * @param {number} value The progress value.
  122. * @param {number} max The total size.
  123. * @param {number|string} percent Optional. The percentage to display on the progress label.
  124. */
  125. function setLaunchPercentage(value, max, percent = ((value/max)*100)){
  126. launch_progress.setAttribute('max', max)
  127. launch_progress.setAttribute('value', value)
  128. launch_progress_label.innerHTML = percent + '%'
  129. }
  130. /**
  131. * Set the value of the OS progress bar and display that on the UI.
  132. *
  133. * @param {number} value The progress value.
  134. * @param {number} max The total download size.
  135. * @param {number|string} percent Optional. The percentage to display on the progress label.
  136. */
  137. function setDownloadPercentage(value, max, percent = ((value/max)*100)){
  138. remote.getCurrentWindow().setProgressBar(value/max)
  139. setLaunchPercentage(value, max, percent)
  140. }
  141. /* System (Java) Scan */
  142. let sysAEx
  143. let scanAt
  144. function asyncSystemScan(){
  145. setLaunchDetails('Please wait..')
  146. toggleLaunchArea(true)
  147. setLaunchPercentage(0, 100)
  148. sysAEx = cp.fork(path.join(__dirname, 'assets', 'js', 'assetexec.js'), [
  149. ConfigManager.getGameDirectory(),
  150. ConfigManager.getJavaExecutable()
  151. ])
  152. sysAEx.on('message', (m) => {
  153. if(m.content === 'validateJava'){
  154. jPath = m.result
  155. console.log(m.result)
  156. sysAEx.disconnect()
  157. }
  158. })
  159. setLaunchDetails('Checking system info..')
  160. sysAEx.send({task: 0, content: 'validateJava', argsArr: [ConfigManager.getLauncherDirectory()]})
  161. }
  162. function overlayError(){
  163. }
  164. // Keep reference to Minecraft Process
  165. let proc
  166. // Is DiscordRPC enabled
  167. let hasRPC = false
  168. // Joined server regex
  169. const servJoined = /[[0-2][0-9]:[0-6][0-9]:[0-6][0-9]\] \[Client thread\/INFO\]: \[CHAT\] [a-zA-Z0-9_]{1,16} joined the game/g
  170. const gameJoined = /\[[0-2][0-9]:[0-6][0-9]:[0-6][0-9]\] \[Client thread\/WARN\]: Skipping bad option: lastServer:/g
  171. const gameJoined2 = /\[[0-2][0-9]:[0-6][0-9]:[0-6][0-9]\] \[Client thread\/INFO\]: Created: \d+x\d+ textures-atlas/g
  172. let aEx
  173. let serv
  174. let versionData
  175. let forgeData
  176. function dlAsync(login = true){
  177. // Login parameter is temporary for debug purposes. Allows testing the validation/downloads without
  178. // launching the game.
  179. if(login) {
  180. if(ConfigManager.getSelectedAccount() == null){
  181. console.error('login first.')
  182. //in devtools AuthManager.addAccount(username, pass)
  183. return
  184. }
  185. }
  186. setLaunchDetails('Please wait..')
  187. toggleLaunchArea(true)
  188. setLaunchPercentage(0, 100)
  189. // Start AssetExec to run validations and downloads in a forked process.
  190. aEx = cp.fork(path.join(__dirname, 'assets', 'js', 'assetexec.js'), [
  191. ConfigManager.getGameDirectory(),
  192. ConfigManager.getJavaExecutable()
  193. ])
  194. // Establish communications between the AssetExec and current process.
  195. aEx.on('message', (m) => {
  196. if(m.content === 'validateDistribution'){
  197. setLaunchPercentage(20, 100)
  198. serv = m.result
  199. console.log('Forge Validation Complete.')
  200. // Begin version load.
  201. setLaunchDetails('Loading version information..')
  202. aEx.send({task: 0, content: 'loadVersionData', argsArr: [serv.mc_version]})
  203. } else if(m.content === 'loadVersionData'){
  204. setLaunchPercentage(40, 100)
  205. versionData = m.result
  206. console.log('Version data loaded.')
  207. // Begin asset validation.
  208. setLaunchDetails('Validating asset integrity..')
  209. aEx.send({task: 0, content: 'validateAssets', argsArr: [versionData]})
  210. } else if(m.content === 'validateAssets'){
  211. setLaunchPercentage(60, 100)
  212. console.log('Asset Validation Complete')
  213. // Begin library validation.
  214. setLaunchDetails('Validating library integrity..')
  215. aEx.send({task: 0, content: 'validateLibraries', argsArr: [versionData]})
  216. } else if(m.content === 'validateLibraries'){
  217. setLaunchPercentage(80, 100)
  218. console.log('Library validation complete.')
  219. // Begin miscellaneous validation.
  220. setLaunchDetails('Validating miscellaneous file integrity..')
  221. aEx.send({task: 0, content: 'validateMiscellaneous', argsArr: [versionData]})
  222. } else if(m.content === 'validateMiscellaneous'){
  223. setLaunchPercentage(100, 100)
  224. console.log('File validation complete.')
  225. // Download queued files.
  226. setLaunchDetails('Downloading files..')
  227. aEx.send({task: 0, content: 'processDlQueues'})
  228. } else if(m.content === 'dl'){
  229. if(m.task === 0){
  230. setDownloadPercentage(m.value, m.total, m.percent)
  231. } else if(m.task === 1){
  232. // Download will be at 100%, remove the loading from the OS progress bar.
  233. remote.getCurrentWindow().setProgressBar(-1)
  234. setLaunchDetails('Preparing to launch..')
  235. aEx.send({task: 0, content: 'loadForgeData', argsArr: [serv.id]})
  236. } else {
  237. console.error('Unknown download data type.', m)
  238. }
  239. } else if(m.content === 'loadForgeData'){
  240. forgeData = m.result
  241. if(login) {
  242. //if(!(await AuthManager.validateSelected())){
  243. //
  244. //}
  245. const authUser = ConfigManager.getSelectedAccount();
  246. console.log('authu', authUser)
  247. let pb = new ProcessBuilder(ConfigManager.getGameDirectory(), serv, versionData, forgeData, authUser)
  248. setLaunchDetails('Launching game..')
  249. try {
  250. // Build Minecraft process.
  251. proc = pb.build()
  252. setLaunchDetails('Done. Enjoy the server!')
  253. // Attach a temporary listener to the client output.
  254. // Will wait for a certain bit of text meaning that
  255. // the client application has started, and we can hide
  256. // the progress bar stuff.
  257. const tempListener = function(data){
  258. if(data.indexOf('[Client thread/INFO]: -- System Details --') > -1){
  259. toggleLaunchArea(false)
  260. if(hasRPC){
  261. DiscordWrapper.updateDetails('Loading game..')
  262. }
  263. proc.stdout.removeListener('data', tempListener)
  264. }
  265. }
  266. // Listener for Discord RPC.
  267. const gameStateChange = function(data){
  268. if(servJoined.test(data)){
  269. DiscordWrapper.updateDetails('Exploring the Realm!')
  270. } else if(gameJoined.test(data)){
  271. DiscordWrapper.updateDetails('Idling on Main Menu')
  272. }
  273. }
  274. // Bind listeners to stdout.
  275. proc.stdout.on('data', tempListener)
  276. proc.stdout.on('data', gameStateChange)
  277. // Init Discord Hook
  278. const distro = AssetGuard.retrieveDistributionDataSync(ConfigManager.getGameDirectory)
  279. if(distro.discord != null && serv.discord != null){
  280. DiscordWrapper.initRPC(distro.discord, serv.discord)
  281. hasRPC = true
  282. proc.on('close', (code, signal) => {
  283. console.log('Shutting down Discord Rich Presence..')
  284. DiscordWrapper.shutdownRPC()
  285. hasRPC = false
  286. proc = null
  287. })
  288. }
  289. } catch(err) {
  290. // Show that there was an error then hide the
  291. // progress area. Maybe switch this to an error
  292. // alert in the future. TODO
  293. setLaunchDetails('Error: See log for details..')
  294. console.log(err)
  295. setTimeout(function(){
  296. toggleLaunchArea(false)
  297. }, 5000)
  298. }
  299. }
  300. // Disconnect from AssetExec
  301. aEx.disconnect()
  302. }
  303. })
  304. // Begin Validations
  305. // Validate Forge files.
  306. setLaunchDetails('Loading server information..')
  307. aEx.send({task: 0, content: 'validateDistribution', argsArr: [ConfigManager.getSelectedServer()]})
  308. }