landing.js 21 KB

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