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. if(m.result == null){
  208. // If the result is null, no valid Java installation was found.
  209. // Show this information to the user.
  210. setOverlayContent(
  211. 'No Compatible<br>Java Installation Found',
  212. '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>.',
  213. 'Install Java',
  214. 'Install Manually'
  215. )
  216. setOverlayHandler(() => {
  217. setLaunchDetails('Preparing Java Download..')
  218. sysAEx.send({task: 0, content: '_enqueueOracleJRE', argsArr: [ConfigManager.getLauncherDirectory()]})
  219. toggleOverlay(false)
  220. })
  221. setDismissHandler(() => {
  222. $('#overlayContent').fadeOut(250, () => {
  223. //$('#overlayDismiss').toggle(false)
  224. setOverlayContent(
  225. 'Don\'t Forget!<br>Java is Required',
  226. '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.',
  227. 'I Understand',
  228. 'Go Back'
  229. )
  230. setOverlayHandler(() => {
  231. toggleLaunchArea(false)
  232. toggleOverlay(false)
  233. })
  234. setDismissHandler(() => {
  235. toggleOverlay(false, true)
  236. asyncSystemScan()
  237. })
  238. $('#overlayContent').fadeIn(250)
  239. })
  240. })
  241. toggleOverlay(true, true)
  242. // TODO Add option to not install Java x64.
  243. } else {
  244. // Java installation found, use this to launch the game.
  245. ConfigManager.setJavaExecutable(m.result)
  246. ConfigManager.save()
  247. if(launchAfter){
  248. dlAsync()
  249. }
  250. sysAEx.disconnect()
  251. }
  252. } else if(m.content === '_enqueueOracleJRE'){
  253. if(m.result === true){
  254. // Oracle JRE enqueued successfully, begin download.
  255. setLaunchDetails('Downloading Java..')
  256. sysAEx.send({task: 0, content: 'processDlQueues', argsArr: [[{id:'java', limit:1}]]})
  257. } else {
  258. // Oracle JRE enqueue failed. Probably due to a change in their website format.
  259. // User will have to follow the guide to install Java.
  260. setOverlayContent(
  261. 'Unexpected Issue:<br>Java Download Failed',
  262. '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.',
  263. 'I Understand'
  264. )
  265. setOverlayHandler(() => {
  266. toggleOverlay(false)
  267. toggleLaunchArea(false)
  268. })
  269. toggleOverlay(true)
  270. sysAEx.disconnect()
  271. }
  272. } else if(m.content === 'dl'){
  273. if(m.task === 0){
  274. // Downloading..
  275. setDownloadPercentage(m.value, m.total, m.percent)
  276. } else if(m.task === 1){
  277. // Download will be at 100%, remove the loading from the OS progress bar.
  278. remote.getCurrentWindow().setProgressBar(-1)
  279. // Wait for extration to complete.
  280. setLaunchDetails('Extracting..')
  281. } else if(m.task === 2){
  282. // Extraction completed successfully.
  283. ConfigManager.setJavaExecutable(m.jPath)
  284. ConfigManager.save()
  285. setLaunchDetails('Java Installed!')
  286. if(launchAfter){
  287. dlAsync()
  288. }
  289. sysAEx.disconnect()
  290. } else {
  291. console.error('Unknown download data type.', m)
  292. }
  293. }
  294. })
  295. // Begin system Java scan.
  296. setLaunchDetails('Checking system info..')
  297. sysAEx.send({task: 0, content: 'validateJava', argsArr: [ConfigManager.getLauncherDirectory()]})
  298. }
  299. // Keep reference to Minecraft Process
  300. let proc
  301. // Is DiscordRPC enabled
  302. let hasRPC = false
  303. // Joined server regex
  304. 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
  305. const gameJoined = /\[[0-2][0-9]:[0-6][0-9]:[0-6][0-9]\] \[Client thread\/WARN\]: Skipping bad option: lastServer:/g
  306. const gameJoined2 = /\[[0-2][0-9]:[0-6][0-9]:[0-6][0-9]\] \[Client thread\/INFO\]: Created: \d+x\d+ textures-atlas/g
  307. let aEx
  308. let serv
  309. let versionData
  310. let forgeData
  311. function dlAsync(login = true){
  312. // Login parameter is temporary for debug purposes. Allows testing the validation/downloads without
  313. // launching the game.
  314. if(login) {
  315. if(ConfigManager.getSelectedAccount() == null){
  316. console.error('login first.')
  317. //in devtools AuthManager.addAccount(username, pass)
  318. return
  319. }
  320. }
  321. setLaunchDetails('Please wait..')
  322. toggleLaunchArea(true)
  323. setLaunchPercentage(0, 100)
  324. // Start AssetExec to run validations and downloads in a forked process.
  325. aEx = cp.fork(path.join(__dirname, 'assets', 'js', 'assetexec.js'), [
  326. ConfigManager.getGameDirectory(),
  327. ConfigManager.getJavaExecutable()
  328. ])
  329. // Establish communications between the AssetExec and current process.
  330. aEx.on('message', (m) => {
  331. if(m.content === 'validateDistribution'){
  332. setLaunchPercentage(20, 100)
  333. serv = m.result
  334. console.log('Forge Validation Complete.')
  335. // Begin version load.
  336. setLaunchDetails('Loading version information..')
  337. aEx.send({task: 0, content: 'loadVersionData', argsArr: [serv.mc_version]})
  338. } else if(m.content === 'loadVersionData'){
  339. setLaunchPercentage(40, 100)
  340. versionData = m.result
  341. console.log('Version data loaded.')
  342. // Begin asset validation.
  343. setLaunchDetails('Validating asset integrity..')
  344. aEx.send({task: 0, content: 'validateAssets', argsArr: [versionData]})
  345. } else if(m.content === 'validateAssets'){
  346. // Asset validation can *potentially* take longer, so let's track progress.
  347. if(m.task === 0){
  348. const perc = (m.value/m.total)*20
  349. setLaunchPercentage(40+perc, 100, parseInt(40+perc))
  350. } else {
  351. setLaunchPercentage(60, 100)
  352. console.log('Asset Validation Complete')
  353. // Begin library validation.
  354. setLaunchDetails('Validating library integrity..')
  355. aEx.send({task: 0, content: 'validateLibraries', argsArr: [versionData]})
  356. }
  357. } else if(m.content === 'validateLibraries'){
  358. setLaunchPercentage(80, 100)
  359. console.log('Library validation complete.')
  360. // Begin miscellaneous validation.
  361. setLaunchDetails('Validating miscellaneous file integrity..')
  362. aEx.send({task: 0, content: 'validateMiscellaneous', argsArr: [versionData]})
  363. } else if(m.content === 'validateMiscellaneous'){
  364. setLaunchPercentage(100, 100)
  365. console.log('File validation complete.')
  366. // Download queued files.
  367. setLaunchDetails('Downloading files..')
  368. aEx.send({task: 0, content: 'processDlQueues'})
  369. } else if(m.content === 'dl'){
  370. if(m.task === 0){
  371. setDownloadPercentage(m.value, m.total, m.percent)
  372. } else if(m.task === 1){
  373. // Download will be at 100%, remove the loading from the OS progress bar.
  374. remote.getCurrentWindow().setProgressBar(-1)
  375. setLaunchDetails('Preparing to launch..')
  376. aEx.send({task: 0, content: 'loadForgeData', argsArr: [serv.id]})
  377. } else {
  378. console.error('Unknown download data type.', m)
  379. }
  380. } else if(m.content === 'loadForgeData'){
  381. forgeData = m.result
  382. if(login) {
  383. //if(!(await AuthManager.validateSelected())){
  384. //
  385. //}
  386. const authUser = ConfigManager.getSelectedAccount()
  387. console.log('authu', authUser)
  388. let pb = new ProcessBuilder(ConfigManager.getGameDirectory(), serv, versionData, forgeData, authUser)
  389. setLaunchDetails('Launching game..')
  390. try {
  391. // Build Minecraft process.
  392. proc = pb.build()
  393. setLaunchDetails('Done. Enjoy the server!')
  394. // Attach a temporary listener to the client output.
  395. // Will wait for a certain bit of text meaning that
  396. // the client application has started, and we can hide
  397. // the progress bar stuff.
  398. const tempListener = function(data){
  399. if(data.indexOf('[Client thread/INFO]: -- System Details --') > -1){
  400. toggleLaunchArea(false)
  401. if(hasRPC){
  402. DiscordWrapper.updateDetails('Loading game..')
  403. }
  404. proc.stdout.removeListener('data', tempListener)
  405. }
  406. }
  407. // Listener for Discord RPC.
  408. const gameStateChange = function(data){
  409. if(servJoined.test(data)){
  410. DiscordWrapper.updateDetails('Exploring the Realm!')
  411. } else if(gameJoined.test(data)){
  412. DiscordWrapper.updateDetails('Idling on Main Menu')
  413. }
  414. }
  415. // Bind listeners to stdout.
  416. proc.stdout.on('data', tempListener)
  417. proc.stdout.on('data', gameStateChange)
  418. // Init Discord Hook
  419. const distro = AssetGuard.retrieveDistributionDataSync(ConfigManager.getGameDirectory)
  420. if(distro.discord != null && serv.discord != null){
  421. DiscordWrapper.initRPC(distro.discord, serv.discord)
  422. hasRPC = true
  423. proc.on('close', (code, signal) => {
  424. console.log('Shutting down Discord Rich Presence..')
  425. DiscordWrapper.shutdownRPC()
  426. hasRPC = false
  427. proc = null
  428. })
  429. }
  430. } catch(err) {
  431. // Show that there was an error then hide the
  432. // progress area. Maybe switch this to an error
  433. // alert in the future. TODO
  434. setLaunchDetails('Error: See log for details..')
  435. console.log(err)
  436. setTimeout(function(){
  437. toggleLaunchArea(false)
  438. }, 5000)
  439. }
  440. }
  441. // Disconnect from AssetExec
  442. aEx.disconnect()
  443. }
  444. })
  445. // Begin Validations
  446. // Validate Forge files.
  447. setLaunchDetails('Loading server information..')
  448. aEx.send({task: 0, content: 'validateDistribution', argsArr: [ConfigManager.getSelectedServer()]})
  449. }