landing.js 21 KB

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