actionbinder.js 21 KB

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