landing.js 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588
  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. // Test menu transform.
  117. function slide_(up){
  118. const lCUpper = document.querySelector('#landingContainer > #upper')
  119. const lCLLeft = document.querySelector('#landingContainer > #lower > #left')
  120. const lCLCenter = document.querySelector('#landingContainer > #lower > #center')
  121. const lCLRight = document.querySelector('#landingContainer > #lower > #right')
  122. const menuBtn = document.querySelector('#landingContainer > #lower > #center #content')
  123. if(up){
  124. lCUpper.style.top = '-200vh'
  125. lCLLeft.style.top = '-200vh'
  126. lCLCenter.style.top = '-200vh'
  127. lCLRight.style.top = '-200vh'
  128. menuBtn.style.top = '130vh'
  129. setTimeout(() => {
  130. lCLCenter.style.transition = 'none'
  131. menuBtn.style.transition = 'none'
  132. }, 2000)
  133. } else {
  134. lCLCenter.style.transition = null
  135. menuBtn.style.transition = null
  136. lCUpper.style.top = '0px'
  137. lCLLeft.style.top = '0px'
  138. lCLCenter.style.top = '0px'
  139. lCLRight.style.top = '0px'
  140. menuBtn.style.top = '10px'
  141. }
  142. }
  143. // Update Mojang Status Color
  144. const refreshMojangStatuses = async function(){
  145. console.log('Refreshing Mojang Statuses..')
  146. let status = 'grey'
  147. try {
  148. const statuses = await Mojang.status()
  149. greenCount = 0
  150. for(let i=0; i<statuses.length; i++){
  151. if(statuses[i].status === 'yellow' && status !== 'red'){
  152. status = 'yellow'
  153. continue
  154. } else if(statuses[i].status === 'red'){
  155. status = 'red'
  156. break
  157. }
  158. ++greenCount
  159. }
  160. if(greenCount == statuses.length){
  161. status = 'green'
  162. }
  163. } catch (err) {
  164. console.warn('Unable to refresh Mojang service status.')
  165. console.debug(err)
  166. }
  167. document.getElementById('mojang_status_icon').style.color = Mojang.statusToHex(status)
  168. }
  169. const refreshServerStatus = async function(fade = false){
  170. console.log('Refreshing Server Status')
  171. const serv = AssetGuard.getServerById(ConfigManager.getGameDirectory(), ConfigManager.getSelectedServer())
  172. let pLabel = 'SERVER'
  173. let pVal = 'OFFLINE'
  174. try {
  175. const serverURL = new URL('my://' + serv.server_ip)
  176. const servStat = await ServerStatus.getStatus(serverURL.hostname, serverURL.port)
  177. if(servStat.online){
  178. pLabel = 'PLAYERS'
  179. pVal = servStat.onlinePlayers + '/' + servStat.maxPlayers
  180. }
  181. } catch (err) {
  182. console.warn('Unable to refresh server status, assuming offline.')
  183. console.debug(err)
  184. }
  185. if(fade){
  186. $('#server_status_wrapper').fadeOut(250, () => {
  187. document.getElementById('landingPlayerLabel').innerHTML = pLabel
  188. document.getElementById('player_count').innerHTML = pVal
  189. $('#server_status_wrapper').fadeIn(500)
  190. })
  191. } else {
  192. document.getElementById('landingPlayerLabel').innerHTML = pLabel
  193. document.getElementById('player_count').innerHTML = pVal
  194. }
  195. }
  196. refreshMojangStatuses()
  197. refreshServerStatus()
  198. // Set refresh rate to once every 5 minutes.
  199. let mojangStatusListener = setInterval(() => refreshMojangStatuses(true), 300000)
  200. let serverStatusListener = setInterval(() => refreshServerStatus(true), 300000)
  201. /* System (Java) Scan */
  202. let sysAEx
  203. let scanAt
  204. let extractListener
  205. function asyncSystemScan(launchAfter = true){
  206. setLaunchDetails('Please wait..')
  207. toggleLaunchArea(true)
  208. setLaunchPercentage(0, 100)
  209. // Fork a process to run validations.
  210. sysAEx = cp.fork(path.join(__dirname, 'assets', 'js', 'assetexec.js'), [
  211. ConfigManager.getGameDirectory(),
  212. ConfigManager.getJavaExecutable()
  213. ])
  214. sysAEx.on('message', (m) => {
  215. if(m.content === 'validateJava'){
  216. if(m.result == null){
  217. // If the result is null, no valid Java installation was found.
  218. // Show this information to the user.
  219. setOverlayContent(
  220. 'No Compatible<br>Java Installation Found',
  221. '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>.',
  222. 'Install Java',
  223. 'Install Manually'
  224. )
  225. setOverlayHandler(() => {
  226. setLaunchDetails('Preparing Java Download..')
  227. sysAEx.send({task: 0, content: '_enqueueOracleJRE', argsArr: [ConfigManager.getLauncherDirectory()]})
  228. toggleOverlay(false)
  229. })
  230. setDismissHandler(() => {
  231. $('#overlayContent').fadeOut(250, () => {
  232. //$('#overlayDismiss').toggle(false)
  233. setOverlayContent(
  234. 'Don\'t Forget!<br>Java is Required',
  235. '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.',
  236. 'I Understand',
  237. 'Go Back'
  238. )
  239. setOverlayHandler(() => {
  240. toggleLaunchArea(false)
  241. toggleOverlay(false)
  242. })
  243. setDismissHandler(() => {
  244. toggleOverlay(false, true)
  245. asyncSystemScan()
  246. })
  247. $('#overlayContent').fadeIn(250)
  248. })
  249. })
  250. toggleOverlay(true, true)
  251. // TODO Add option to not install Java x64.
  252. } else {
  253. // Java installation found, use this to launch the game.
  254. ConfigManager.setJavaExecutable(m.result)
  255. ConfigManager.save()
  256. if(launchAfter){
  257. dlAsync()
  258. }
  259. sysAEx.disconnect()
  260. }
  261. } else if(m.content === '_enqueueOracleJRE'){
  262. if(m.result === true){
  263. // Oracle JRE enqueued successfully, begin download.
  264. setLaunchDetails('Downloading Java..')
  265. sysAEx.send({task: 0, content: 'processDlQueues', argsArr: [[{id:'java', limit:1}]]})
  266. } else {
  267. // Oracle JRE enqueue failed. Probably due to a change in their website format.
  268. // User will have to follow the guide to install Java.
  269. setOverlayContent(
  270. 'Unexpected Issue:<br>Java Download Failed',
  271. '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.',
  272. 'I Understand'
  273. )
  274. setOverlayHandler(() => {
  275. toggleOverlay(false)
  276. toggleLaunchArea(false)
  277. })
  278. toggleOverlay(true)
  279. sysAEx.disconnect()
  280. }
  281. } else if(m.content === 'dl'){
  282. if(m.task === 0){
  283. // Downloading..
  284. setDownloadPercentage(m.value, m.total, m.percent)
  285. } else if(m.task === 1){
  286. // Download will be at 100%, remove the loading from the OS progress bar.
  287. remote.getCurrentWindow().setProgressBar(-1)
  288. // Wait for extration to complete.
  289. const eLStr = 'Extracting'
  290. let dotStr = ''
  291. setLaunchDetails(eLStr)
  292. extractListener = setInterval(() => {
  293. if(dotStr.length >= 3){
  294. dotStr = ''
  295. } else {
  296. dotStr += '.'
  297. }
  298. setLaunchDetails(eLStr + dotStr)
  299. }, 750)
  300. } else if(m.task === 2){
  301. // Extraction completed successfully.
  302. ConfigManager.setJavaExecutable(m.jPath)
  303. ConfigManager.save()
  304. if(extractListener != null){
  305. clearInterval(extractListener)
  306. extractListener = null
  307. }
  308. setLaunchDetails('Java Installed!')
  309. if(launchAfter){
  310. dlAsync()
  311. }
  312. sysAEx.disconnect()
  313. } else {
  314. console.error('Unknown download data type.', m)
  315. }
  316. }
  317. })
  318. // Begin system Java scan.
  319. setLaunchDetails('Checking system info..')
  320. sysAEx.send({task: 0, content: 'validateJava', argsArr: [ConfigManager.getLauncherDirectory()]})
  321. }
  322. // Keep reference to Minecraft Process
  323. let proc
  324. // Is DiscordRPC enabled
  325. let hasRPC = false
  326. // Joined server regex
  327. 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
  328. const gameJoined = /\[[0-2][0-9]:[0-6][0-9]:[0-6][0-9]\] \[Client thread\/WARN\]: Skipping bad option: lastServer:/g
  329. const gameJoined2 = /\[[0-2][0-9]:[0-6][0-9]:[0-6][0-9]\] \[Client thread\/INFO\]: Created: \d+x\d+ textures-atlas/g
  330. let aEx
  331. let serv
  332. let versionData
  333. let forgeData
  334. let progressListener
  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 === 0.7){
  397. // Download done, extracting.
  398. const eLStr = 'Extracting libraries'
  399. let dotStr = ''
  400. setLaunchDetails(eLStr)
  401. progressListener = setInterval(() => {
  402. if(dotStr.length >= 3){
  403. dotStr = ''
  404. } else {
  405. dotStr += '.'
  406. }
  407. setLaunchDetails(eLStr + dotStr)
  408. }, 750)
  409. } else if(m.task === 1){
  410. // Download will be at 100%, remove the loading from the OS progress bar.
  411. remote.getCurrentWindow().setProgressBar(-1)
  412. if(progressListener != null){
  413. clearInterval(progressListener)
  414. progressListener = null
  415. }
  416. setLaunchDetails('Preparing to launch..')
  417. aEx.send({task: 0, content: 'loadForgeData', argsArr: [serv.id]})
  418. } else {
  419. console.error('Unknown download data type.', m)
  420. }
  421. } else if(m.content === 'loadForgeData'){
  422. forgeData = m.result
  423. if(login) {
  424. //if(!(await AuthManager.validateSelected())){
  425. //
  426. //}
  427. const authUser = ConfigManager.getSelectedAccount()
  428. console.log('authu', authUser)
  429. let pb = new ProcessBuilder(ConfigManager.getGameDirectory(), serv, versionData, forgeData, authUser)
  430. setLaunchDetails('Launching game..')
  431. try {
  432. // Build Minecraft process.
  433. proc = pb.build()
  434. setLaunchDetails('Done. Enjoy the server!')
  435. // Attach a temporary listener to the client output.
  436. // Will wait for a certain bit of text meaning that
  437. // the client application has started, and we can hide
  438. // the progress bar stuff.
  439. const tempListener = function(data){
  440. if(data.indexOf('[Client thread/INFO]: -- System Details --') > -1){
  441. toggleLaunchArea(false)
  442. if(hasRPC){
  443. DiscordWrapper.updateDetails('Loading game..')
  444. }
  445. proc.stdout.removeListener('data', tempListener)
  446. }
  447. }
  448. // Listener for Discord RPC.
  449. const gameStateChange = function(data){
  450. if(servJoined.test(data)){
  451. DiscordWrapper.updateDetails('Exploring the Realm!')
  452. } else if(gameJoined.test(data)){
  453. DiscordWrapper.updateDetails('Idling on Main Menu')
  454. }
  455. }
  456. // Bind listeners to stdout.
  457. proc.stdout.on('data', tempListener)
  458. proc.stdout.on('data', gameStateChange)
  459. // Init Discord Hook
  460. const distro = AssetGuard.retrieveDistributionDataSync(ConfigManager.getGameDirectory)
  461. if(distro.discord != null && serv.discord != null){
  462. DiscordWrapper.initRPC(distro.discord, serv.discord)
  463. hasRPC = true
  464. proc.on('close', (code, signal) => {
  465. console.log('Shutting down Discord Rich Presence..')
  466. DiscordWrapper.shutdownRPC()
  467. hasRPC = false
  468. proc = null
  469. })
  470. }
  471. } catch(err) {
  472. // Show that there was an error then hide the
  473. // progress area. Maybe switch this to an error
  474. // alert in the future. TODO
  475. setLaunchDetails('Error: See log for details..')
  476. console.log(err)
  477. setTimeout(function(){
  478. toggleLaunchArea(false)
  479. }, 5000)
  480. }
  481. }
  482. // Disconnect from AssetExec
  483. aEx.disconnect()
  484. }
  485. })
  486. // Begin Validations
  487. // Validate Forge files.
  488. setLaunchDetails('Loading server information..')
  489. aEx.send({task: 0, content: 'validateDistribution', argsArr: [ConfigManager.getSelectedServer()]})
  490. }