actionbinder.js 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543
  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. setLaunchDetails('Please wait..')
  36. toggleLaunchArea(true)
  37. setLaunchPercentage(0, 100)
  38. AssetGuard._validateJavaBinary(jExe).then((v) => {
  39. if(v){
  40. dlAsync()
  41. } else {
  42. asyncSystemScan()
  43. }
  44. })
  45. }
  46. })
  47. // TODO convert this to dropdown menu.
  48. // Bind selected server
  49. document.getElementById('server_selection').innerHTML = '\u2022 ' + AssetGuard.getServerById(ConfigManager.getGameDirectory(), ConfigManager.getSelectedServer()).name
  50. // Update Mojang Status Color
  51. const refreshMojangStatuses = async function(){
  52. console.log('Refreshing Mojang Statuses..')
  53. let status = 'grey'
  54. try {
  55. const statuses = await Mojang.status()
  56. greenCount = 0
  57. for(let i=0; i<statuses.length; i++){
  58. if(statuses[i].status === 'yellow' && status !== 'red'){
  59. status = 'yellow'
  60. continue
  61. } else if(statuses[i].status === 'red'){
  62. status = 'red'
  63. break
  64. }
  65. ++greenCount
  66. }
  67. if(greenCount == statuses.length){
  68. status = 'green'
  69. }
  70. } catch (err) {
  71. console.warn('Unable to refresh Mojang service status.')
  72. console.debug(err)
  73. }
  74. document.getElementById('mojang_status_icon').style.color = Mojang.statusToHex(status)
  75. }
  76. refreshMojangStatuses()
  77. // Set refresh rate to once every 5 minutes.
  78. mojangStatusListener = setInterval(refreshMojangStatuses, 300000)
  79. }
  80. }, false)
  81. /* Overlay Wrapper Functions */
  82. /**
  83. * Toggle the visibility of the overlay.
  84. *
  85. * @param {boolean} toggleState True to display, false to hide.
  86. * @param {boolean} dismissable Optional. True to show the dismiss option, otherwise false.
  87. */
  88. function toggleOverlay(toggleState, dismissable = false){
  89. if(toggleState == null){
  90. toggleState = !document.getElementById('main').hasAttribute('overlay')
  91. }
  92. if(toggleState){
  93. document.getElementById('main').setAttribute('overlay', true)
  94. $('#overlayDismiss').toggle(dismissable)
  95. $('#overlayContainer').fadeToggle(250)
  96. } else {
  97. document.getElementById('main').removeAttribute('overlay')
  98. $('#overlayContainer').fadeToggle(250, () => {
  99. $('#overlayDismiss').toggle(dismissable)
  100. })
  101. }
  102. }
  103. /**
  104. * Set the content of the overlay.
  105. *
  106. * @param {string} title Overlay title text.
  107. * @param {string} description Overlay description text.
  108. * @param {string} acknowledge Acknowledge button text.
  109. * @param {string} dismiss Dismiss button text.
  110. */
  111. function setOverlayContent(title, description, acknowledge, dismiss = 'Dismiss'){
  112. document.getElementById('overlayTitle').innerHTML = title
  113. document.getElementById('overlayDesc').innerHTML = description
  114. document.getElementById('overlayAcknowledge').innerHTML = acknowledge
  115. document.getElementById('overlayDismiss').innerHTML = dismiss
  116. }
  117. /**
  118. * Set the onclick handler of the overlay acknowledge button.
  119. * If the handler is null, a default handler will be added.
  120. *
  121. * @param {function} handler
  122. */
  123. function setOverlayHandler(handler){
  124. if(handler == null){
  125. document.getElementById('overlayAcknowledge').onclick = () => {
  126. toggleOverlay(false)
  127. }
  128. } else {
  129. document.getElementById('overlayAcknowledge').onclick = handler
  130. }
  131. }
  132. /**
  133. * Set the onclick handler of the overlay dismiss button.
  134. * If the handler is null, a default handler will be added.
  135. *
  136. * @param {function} handler
  137. */
  138. function setDismissHandler(handler){
  139. if(handler == null){
  140. document.getElementById('overlayDismiss').onclick = () => {
  141. toggleOverlay(false)
  142. }
  143. } else {
  144. document.getElementById('overlayDismiss').onclick = handler
  145. }
  146. }
  147. /* Launch Progress Wrapper Functions */
  148. /**
  149. * Show/hide the loading area.
  150. *
  151. * @param {boolean} loading True if the loading area should be shown, otherwise false.
  152. */
  153. function toggleLaunchArea(loading){
  154. if(loading){
  155. launch_details.style.display = 'flex'
  156. launch_content.style.display = 'none'
  157. } else {
  158. launch_details.style.display = 'none'
  159. launch_content.style.display = 'inline-flex'
  160. }
  161. }
  162. /**
  163. * Set the details text of the loading area.
  164. *
  165. * @param {string} details The new text for the loading details.
  166. */
  167. function setLaunchDetails(details){
  168. launch_details_text.innerHTML = details
  169. }
  170. /**
  171. * Set the value of the loading progress bar and display that value.
  172. *
  173. * @param {number} value The progress value.
  174. * @param {number} max The total size.
  175. * @param {number|string} percent Optional. The percentage to display on the progress label.
  176. */
  177. function setLaunchPercentage(value, max, percent = ((value/max)*100)){
  178. launch_progress.setAttribute('max', max)
  179. launch_progress.setAttribute('value', value)
  180. launch_progress_label.innerHTML = percent + '%'
  181. }
  182. /**
  183. * Set the value of the OS progress bar and display that on the UI.
  184. *
  185. * @param {number} value The progress value.
  186. * @param {number} max The total download size.
  187. * @param {number|string} percent Optional. The percentage to display on the progress label.
  188. */
  189. function setDownloadPercentage(value, max, percent = ((value/max)*100)){
  190. remote.getCurrentWindow().setProgressBar(value/max)
  191. setLaunchPercentage(value, max, percent)
  192. }
  193. /* System (Java) Scan */
  194. let sysAEx
  195. let scanAt
  196. function asyncSystemScan(launchAfter = true){
  197. setLaunchDetails('Please wait..')
  198. toggleLaunchArea(true)
  199. setLaunchPercentage(0, 100)
  200. // Fork a process to run validations.
  201. sysAEx = cp.fork(path.join(__dirname, 'assets', 'js', 'assetexec.js'), [
  202. ConfigManager.getGameDirectory(),
  203. ConfigManager.getJavaExecutable()
  204. ])
  205. sysAEx.on('message', (m) => {
  206. if(m.content === 'validateJava'){
  207. m.result = null
  208. if(m.result == null){
  209. // If the result is null, no valid Java installation was found.
  210. // Show this information to the user.
  211. setOverlayContent(
  212. 'No Compatible<br>Java Installation Found',
  213. 'In order to join WesterosCraft, you need a 64-bit installation of Java 8. Would you like us to install a copy? By installing, you accept <a href="http://www.oracle.com/technetwork/java/javase/terms/license/index.html">Oracle\'s license agreement</a>.',
  214. 'Install Java',
  215. 'Install Manually'
  216. )
  217. setOverlayHandler(() => {
  218. setLaunchDetails('Preparing Java Download..')
  219. sysAEx.send({task: 0, content: '_enqueueOracleJRE', argsArr: [ConfigManager.getLauncherDirectory()]})
  220. toggleOverlay(false)
  221. })
  222. setDismissHandler(() => {
  223. $('#overlayContent').fadeOut(250, () => {
  224. //$('#overlayDismiss').toggle(false)
  225. setOverlayContent(
  226. 'Don\'t Forget!<br>Java is Required',
  227. 'A valid x64 installation of Java 8 is required to launch. Downloads can be found on <a href="http://www.oracle.com/technetwork/java/javase/downloads/jre8-downloads-2133155.html">Oracle\'s website</a>. Once installed, you will be able to connect to the server.<br><br>Please refer to our <a href="http://westeroscraft.wikia.com/wiki/Troubleshooting_Guide">Troubleshooting Guide</a> if you have any difficulty.',
  228. 'I Understand',
  229. 'Go Back'
  230. )
  231. setOverlayHandler(() => {
  232. toggleLaunchArea(false)
  233. toggleOverlay(false)
  234. })
  235. setDismissHandler(() => {
  236. toggleOverlay(false, true)
  237. asyncSystemScan()
  238. })
  239. $('#overlayContent').fadeIn(250)
  240. })
  241. })
  242. toggleOverlay(true, true)
  243. // TODO Add option to not install Java x64.
  244. } else {
  245. // Java installation found, use this to launch the game.
  246. ConfigManager.setJavaExecutable(m.result)
  247. ConfigManager.save()
  248. if(launchAfter){
  249. dlAsync()
  250. }
  251. sysAEx.disconnect()
  252. }
  253. } else if(m.content === '_enqueueOracleJRE'){
  254. if(m.result === true){
  255. // Oracle JRE enqueued successfully, begin download.
  256. setLaunchDetails('Downloading Java..')
  257. sysAEx.send({task: 0, content: 'processDlQueues', argsArr: [[{id:'java', limit:1}]]})
  258. } else {
  259. // Oracle JRE enqueue failed. Probably due to a change in their website format.
  260. // User will have to follow the guide to install Java.
  261. setOverlayContent(
  262. 'Unexpected Issue:<br>Java Download Failed',
  263. 'Unfortunately we\'ve encountered an issue while attempting to install Java. You will need to manually install a copy. Please check out our <a href="http://westeroscraft.wikia.com/wiki/Troubleshooting_Guide">Troubleshooting Guide</a> for more details and instructions.',
  264. 'I Understand'
  265. )
  266. setOverlayHandler(() => {
  267. toggleOverlay(false)
  268. toggleLaunchArea(false)
  269. })
  270. toggleOverlay(true)
  271. sysAEx.disconnect()
  272. }
  273. } else if(m.content === 'dl'){
  274. if(m.task === 0){
  275. // Downloading..
  276. setDownloadPercentage(m.value, m.total, m.percent)
  277. } else if(m.task === 1){
  278. // Download will be at 100%, remove the loading from the OS progress bar.
  279. remote.getCurrentWindow().setProgressBar(-1)
  280. // Wait for extration to complete.
  281. setLaunchDetails('Extracting..')
  282. } else if(m.task === 2){
  283. // Extraction completed successfully.
  284. ConfigManager.setJavaExecutable(m.jPath)
  285. ConfigManager.save()
  286. setLaunchDetails('Java Installed!')
  287. if(launchAfter){
  288. dlAsync()
  289. }
  290. sysAEx.disconnect()
  291. } else {
  292. console.error('Unknown download data type.', m)
  293. }
  294. }
  295. })
  296. // Begin system Java scan.
  297. setLaunchDetails('Checking system info..')
  298. sysAEx.send({task: 0, content: 'validateJava', argsArr: [ConfigManager.getLauncherDirectory()]})
  299. }
  300. // Keep reference to Minecraft Process
  301. let proc
  302. // Is DiscordRPC enabled
  303. let hasRPC = false
  304. // Joined server regex
  305. 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
  306. const gameJoined = /\[[0-2][0-9]:[0-6][0-9]:[0-6][0-9]\] \[Client thread\/WARN\]: Skipping bad option: lastServer:/g
  307. const gameJoined2 = /\[[0-2][0-9]:[0-6][0-9]:[0-6][0-9]\] \[Client thread\/INFO\]: Created: \d+x\d+ textures-atlas/g
  308. let aEx
  309. let serv
  310. let versionData
  311. let forgeData
  312. function dlAsync(login = true){
  313. // Login parameter is temporary for debug purposes. Allows testing the validation/downloads without
  314. // launching the game.
  315. if(login) {
  316. if(ConfigManager.getSelectedAccount() == null){
  317. console.error('login first.')
  318. //in devtools AuthManager.addAccount(username, pass)
  319. return
  320. }
  321. }
  322. setLaunchDetails('Please wait..')
  323. toggleLaunchArea(true)
  324. setLaunchPercentage(0, 100)
  325. // Start AssetExec to run validations and downloads in a forked process.
  326. aEx = cp.fork(path.join(__dirname, 'assets', 'js', 'assetexec.js'), [
  327. ConfigManager.getGameDirectory(),
  328. ConfigManager.getJavaExecutable()
  329. ])
  330. // Establish communications between the AssetExec and current process.
  331. aEx.on('message', (m) => {
  332. if(m.content === 'validateDistribution'){
  333. setLaunchPercentage(20, 100)
  334. serv = m.result
  335. console.log('Forge Validation Complete.')
  336. // Begin version load.
  337. setLaunchDetails('Loading version information..')
  338. aEx.send({task: 0, content: 'loadVersionData', argsArr: [serv.mc_version]})
  339. } else if(m.content === 'loadVersionData'){
  340. setLaunchPercentage(40, 100)
  341. versionData = m.result
  342. console.log('Version data loaded.')
  343. // Begin asset validation.
  344. setLaunchDetails('Validating asset integrity..')
  345. aEx.send({task: 0, content: 'validateAssets', argsArr: [versionData]})
  346. } else if(m.content === 'validateAssets'){
  347. // Asset validation can *potentially* take longer, so let's track progress.
  348. if(m.task === 0){
  349. const perc = (m.value/m.total)*20
  350. setLaunchPercentage(40+perc, 100, parseInt(40+perc))
  351. } else {
  352. setLaunchPercentage(60, 100)
  353. console.log('Asset Validation Complete')
  354. // Begin library validation.
  355. setLaunchDetails('Validating library integrity..')
  356. aEx.send({task: 0, content: 'validateLibraries', argsArr: [versionData]})
  357. }
  358. } else if(m.content === 'validateLibraries'){
  359. setLaunchPercentage(80, 100)
  360. console.log('Library validation complete.')
  361. // Begin miscellaneous validation.
  362. setLaunchDetails('Validating miscellaneous file integrity..')
  363. aEx.send({task: 0, content: 'validateMiscellaneous', argsArr: [versionData]})
  364. } else if(m.content === 'validateMiscellaneous'){
  365. setLaunchPercentage(100, 100)
  366. console.log('File validation complete.')
  367. // Download queued files.
  368. setLaunchDetails('Downloading files..')
  369. aEx.send({task: 0, content: 'processDlQueues'})
  370. } else if(m.content === 'dl'){
  371. if(m.task === 0){
  372. setDownloadPercentage(m.value, m.total, m.percent)
  373. } else if(m.task === 1){
  374. // Download will be at 100%, remove the loading from the OS progress bar.
  375. remote.getCurrentWindow().setProgressBar(-1)
  376. setLaunchDetails('Preparing to launch..')
  377. aEx.send({task: 0, content: 'loadForgeData', argsArr: [serv.id]})
  378. } else {
  379. console.error('Unknown download data type.', m)
  380. }
  381. } else if(m.content === 'loadForgeData'){
  382. forgeData = m.result
  383. if(login) {
  384. //if(!(await AuthManager.validateSelected())){
  385. //
  386. //}
  387. const authUser = ConfigManager.getSelectedAccount()
  388. console.log('authu', authUser)
  389. let pb = new ProcessBuilder(ConfigManager.getGameDirectory(), serv, versionData, forgeData, authUser)
  390. setLaunchDetails('Launching game..')
  391. try {
  392. // Build Minecraft process.
  393. proc = pb.build()
  394. setLaunchDetails('Done. Enjoy the server!')
  395. // Attach a temporary listener to the client output.
  396. // Will wait for a certain bit of text meaning that
  397. // the client application has started, and we can hide
  398. // the progress bar stuff.
  399. const tempListener = function(data){
  400. if(data.indexOf('[Client thread/INFO]: -- System Details --') > -1){
  401. toggleLaunchArea(false)
  402. if(hasRPC){
  403. DiscordWrapper.updateDetails('Loading game..')
  404. }
  405. proc.stdout.removeListener('data', tempListener)
  406. }
  407. }
  408. // Listener for Discord RPC.
  409. const gameStateChange = function(data){
  410. if(servJoined.test(data)){
  411. DiscordWrapper.updateDetails('Exploring the Realm!')
  412. } else if(gameJoined.test(data)){
  413. DiscordWrapper.updateDetails('Idling on Main Menu')
  414. }
  415. }
  416. // Bind listeners to stdout.
  417. proc.stdout.on('data', tempListener)
  418. proc.stdout.on('data', gameStateChange)
  419. // Init Discord Hook
  420. const distro = AssetGuard.retrieveDistributionDataSync(ConfigManager.getGameDirectory)
  421. if(distro.discord != null && serv.discord != null){
  422. DiscordWrapper.initRPC(distro.discord, serv.discord)
  423. hasRPC = true
  424. proc.on('close', (code, signal) => {
  425. console.log('Shutting down Discord Rich Presence..')
  426. DiscordWrapper.shutdownRPC()
  427. hasRPC = false
  428. proc = null
  429. })
  430. }
  431. } catch(err) {
  432. // Show that there was an error then hide the
  433. // progress area. Maybe switch this to an error
  434. // alert in the future. TODO
  435. setLaunchDetails('Error: See log for details..')
  436. console.log(err)
  437. setTimeout(function(){
  438. toggleLaunchArea(false)
  439. }, 5000)
  440. }
  441. }
  442. // Disconnect from AssetExec
  443. aEx.disconnect()
  444. }
  445. })
  446. // Begin Validations
  447. // Validate Forge files.
  448. setLaunchDetails('Loading server information..')
  449. aEx.send({task: 0, content: 'validateDistribution', argsArr: [ConfigManager.getSelectedServer()]})
  450. }