actionbinder.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413
  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(250)
  90. } else {
  91. document.getElementById('main').removeAttribute('overlay')
  92. $('#overlayContainer').fadeToggle(250)
  93. }
  94. }
  95. /**
  96. * Set the content of the overlay.
  97. *
  98. * @param {string} title Overlay title text.
  99. * @param {string} description Overlay description text.
  100. * @param {string} acknowledge Acknowledge button text.
  101. */
  102. function setOverlayContent(title, description, acknowledge){
  103. document.getElementById('overlayTitle').innerHTML = title
  104. document.getElementById('overlayDesc').innerHTML = description
  105. document.getElementById('overlayAcknowledge').innerHTML = acknowledge
  106. }
  107. /**
  108. * Set the onclick handler of the overlay acknowledge button.
  109. * If the handler is null, a default handler will be added.
  110. *
  111. * @param {function} handler
  112. */
  113. function setOverlayHandler(handler){
  114. if(handler == null){
  115. document.getElementById('overlayAcknowledge').onclick = () => {
  116. toggleOverlay(false)
  117. }
  118. } else {
  119. document.getElementById('overlayAcknowledge').onclick = handler
  120. }
  121. }
  122. /* Launch Progress Wrapper Functions */
  123. /**
  124. * Show/hide the loading area.
  125. *
  126. * @param {boolean} loading True if the loading area should be shown, otherwise false.
  127. */
  128. function toggleLaunchArea(loading){
  129. if(loading){
  130. launch_details.style.display = 'flex'
  131. launch_content.style.display = 'none'
  132. } else {
  133. launch_details.style.display = 'none'
  134. launch_content.style.display = 'inline-flex'
  135. }
  136. }
  137. /**
  138. * Set the details text of the loading area.
  139. *
  140. * @param {string} details The new text for the loading details.
  141. */
  142. function setLaunchDetails(details){
  143. launch_details_text.innerHTML = details
  144. }
  145. /**
  146. * Set the value of the loading progress bar and display that value.
  147. *
  148. * @param {number} value The progress value.
  149. * @param {number} max The total size.
  150. * @param {number|string} percent Optional. The percentage to display on the progress label.
  151. */
  152. function setLaunchPercentage(value, max, percent = ((value/max)*100)){
  153. launch_progress.setAttribute('max', max)
  154. launch_progress.setAttribute('value', value)
  155. launch_progress_label.innerHTML = percent + '%'
  156. }
  157. /**
  158. * Set the value of the OS progress bar and display that on the UI.
  159. *
  160. * @param {number} value The progress value.
  161. * @param {number} max The total download size.
  162. * @param {number|string} percent Optional. The percentage to display on the progress label.
  163. */
  164. function setDownloadPercentage(value, max, percent = ((value/max)*100)){
  165. remote.getCurrentWindow().setProgressBar(value/max)
  166. setLaunchPercentage(value, max, percent)
  167. }
  168. /* System (Java) Scan */
  169. let sysAEx
  170. let scanAt
  171. function asyncSystemScan(){
  172. setLaunchDetails('Please wait..')
  173. toggleLaunchArea(true)
  174. setLaunchPercentage(0, 100)
  175. sysAEx = cp.fork(path.join(__dirname, 'assets', 'js', 'assetexec.js'), [
  176. ConfigManager.getGameDirectory(),
  177. ConfigManager.getJavaExecutable()
  178. ])
  179. sysAEx.on('message', (m) => {
  180. if(m.content === 'validateJava'){
  181. jPath = m.result
  182. console.log(m.result)
  183. sysAEx.disconnect()
  184. }
  185. })
  186. setLaunchDetails('Checking system info..')
  187. sysAEx.send({task: 0, content: 'validateJava', argsArr: [ConfigManager.getLauncherDirectory()]})
  188. }
  189. function overlayError(){
  190. }
  191. // Keep reference to Minecraft Process
  192. let proc
  193. // Is DiscordRPC enabled
  194. let hasRPC = false
  195. // Joined server regex
  196. 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
  197. const gameJoined = /\[[0-2][0-9]:[0-6][0-9]:[0-6][0-9]\] \[Client thread\/WARN\]: Skipping bad option: lastServer:/g
  198. const gameJoined2 = /\[[0-2][0-9]:[0-6][0-9]:[0-6][0-9]\] \[Client thread\/INFO\]: Created: \d+x\d+ textures-atlas/g
  199. let aEx
  200. let serv
  201. let versionData
  202. let forgeData
  203. function dlAsync(login = true){
  204. // Login parameter is temporary for debug purposes. Allows testing the validation/downloads without
  205. // launching the game.
  206. if(login) {
  207. if(ConfigManager.getSelectedAccount() == null){
  208. console.error('login first.')
  209. //in devtools AuthManager.addAccount(username, pass)
  210. return
  211. }
  212. }
  213. setLaunchDetails('Please wait..')
  214. toggleLaunchArea(true)
  215. setLaunchPercentage(0, 100)
  216. // Start AssetExec to run validations and downloads in a forked process.
  217. aEx = cp.fork(path.join(__dirname, 'assets', 'js', 'assetexec.js'), [
  218. ConfigManager.getGameDirectory(),
  219. ConfigManager.getJavaExecutable()
  220. ])
  221. // Establish communications between the AssetExec and current process.
  222. aEx.on('message', (m) => {
  223. if(m.content === 'validateDistribution'){
  224. setLaunchPercentage(20, 100)
  225. serv = m.result
  226. console.log('Forge Validation Complete.')
  227. // Begin version load.
  228. setLaunchDetails('Loading version information..')
  229. aEx.send({task: 0, content: 'loadVersionData', argsArr: [serv.mc_version]})
  230. } else if(m.content === 'loadVersionData'){
  231. setLaunchPercentage(40, 100)
  232. versionData = m.result
  233. console.log('Version data loaded.')
  234. // Begin asset validation.
  235. setLaunchDetails('Validating asset integrity..')
  236. aEx.send({task: 0, content: 'validateAssets', argsArr: [versionData]})
  237. } else if(m.content === 'validateAssets'){
  238. setLaunchPercentage(60, 100)
  239. console.log('Asset Validation Complete')
  240. // Begin library validation.
  241. setLaunchDetails('Validating library integrity..')
  242. aEx.send({task: 0, content: 'validateLibraries', argsArr: [versionData]})
  243. } else if(m.content === 'validateLibraries'){
  244. setLaunchPercentage(80, 100)
  245. console.log('Library validation complete.')
  246. // Begin miscellaneous validation.
  247. setLaunchDetails('Validating miscellaneous file integrity..')
  248. aEx.send({task: 0, content: 'validateMiscellaneous', argsArr: [versionData]})
  249. } else if(m.content === 'validateMiscellaneous'){
  250. setLaunchPercentage(100, 100)
  251. console.log('File validation complete.')
  252. // Download queued files.
  253. setLaunchDetails('Downloading files..')
  254. aEx.send({task: 0, content: 'processDlQueues'})
  255. } else if(m.content === 'dl'){
  256. if(m.task === 0){
  257. setDownloadPercentage(m.value, m.total, m.percent)
  258. } else if(m.task === 1){
  259. // Download will be at 100%, remove the loading from the OS progress bar.
  260. remote.getCurrentWindow().setProgressBar(-1)
  261. setLaunchDetails('Preparing to launch..')
  262. aEx.send({task: 0, content: 'loadForgeData', argsArr: [serv.id]})
  263. } else {
  264. console.error('Unknown download data type.', m)
  265. }
  266. } else if(m.content === 'loadForgeData'){
  267. forgeData = m.result
  268. if(login) {
  269. //if(!(await AuthManager.validateSelected())){
  270. //
  271. //}
  272. const authUser = ConfigManager.getSelectedAccount();
  273. console.log('authu', authUser)
  274. let pb = new ProcessBuilder(ConfigManager.getGameDirectory(), serv, versionData, forgeData, authUser)
  275. setLaunchDetails('Launching game..')
  276. try {
  277. // Build Minecraft process.
  278. proc = pb.build()
  279. setLaunchDetails('Done. Enjoy the server!')
  280. // Attach a temporary listener to the client output.
  281. // Will wait for a certain bit of text meaning that
  282. // the client application has started, and we can hide
  283. // the progress bar stuff.
  284. const tempListener = function(data){
  285. if(data.indexOf('[Client thread/INFO]: -- System Details --') > -1){
  286. toggleLaunchArea(false)
  287. if(hasRPC){
  288. DiscordWrapper.updateDetails('Loading game..')
  289. }
  290. proc.stdout.removeListener('data', tempListener)
  291. }
  292. }
  293. // Listener for Discord RPC.
  294. const gameStateChange = function(data){
  295. if(servJoined.test(data)){
  296. DiscordWrapper.updateDetails('Exploring the Realm!')
  297. } else if(gameJoined.test(data)){
  298. DiscordWrapper.updateDetails('Idling on Main Menu')
  299. }
  300. }
  301. // Bind listeners to stdout.
  302. proc.stdout.on('data', tempListener)
  303. proc.stdout.on('data', gameStateChange)
  304. // Init Discord Hook
  305. const distro = AssetGuard.retrieveDistributionDataSync(ConfigManager.getGameDirectory)
  306. if(distro.discord != null && serv.discord != null){
  307. DiscordWrapper.initRPC(distro.discord, serv.discord)
  308. hasRPC = true
  309. proc.on('close', (code, signal) => {
  310. console.log('Shutting down Discord Rich Presence..')
  311. DiscordWrapper.shutdownRPC()
  312. hasRPC = false
  313. proc = null
  314. })
  315. }
  316. } catch(err) {
  317. // Show that there was an error then hide the
  318. // progress area. Maybe switch this to an error
  319. // alert in the future. TODO
  320. setLaunchDetails('Error: See log for details..')
  321. console.log(err)
  322. setTimeout(function(){
  323. toggleLaunchArea(false)
  324. }, 5000)
  325. }
  326. }
  327. // Disconnect from AssetExec
  328. aEx.disconnect()
  329. }
  330. })
  331. // Begin Validations
  332. // Validate Forge files.
  333. setLaunchDetails('Loading server information..')
  334. aEx.send({task: 0, content: 'validateDistribution', argsArr: [ConfigManager.getSelectedServer()]})
  335. }