actionbinder.js 22 KB

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