actionbinder.js 21 KB

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