landing.js 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544
  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. function asyncSystemScan(launchAfter = true){
  195. setLaunchDetails('Please wait..')
  196. toggleLaunchArea(true)
  197. setLaunchPercentage(0, 100)
  198. // Fork a process to run validations.
  199. sysAEx = cp.fork(path.join(__dirname, 'assets', 'js', 'assetexec.js'), [
  200. ConfigManager.getGameDirectory(),
  201. ConfigManager.getJavaExecutable()
  202. ])
  203. sysAEx.on('message', (m) => {
  204. if(m.content === 'validateJava'){
  205. if(m.result == null){
  206. // If the result is null, no valid Java installation was found.
  207. // Show this information to the user.
  208. setOverlayContent(
  209. 'No Compatible<br>Java Installation Found',
  210. '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>.',
  211. 'Install Java',
  212. 'Install Manually'
  213. )
  214. setOverlayHandler(() => {
  215. setLaunchDetails('Preparing Java Download..')
  216. sysAEx.send({task: 0, content: '_enqueueOracleJRE', argsArr: [ConfigManager.getLauncherDirectory()]})
  217. toggleOverlay(false)
  218. })
  219. setDismissHandler(() => {
  220. $('#overlayContent').fadeOut(250, () => {
  221. //$('#overlayDismiss').toggle(false)
  222. setOverlayContent(
  223. 'Don\'t Forget!<br>Java is Required',
  224. '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.',
  225. 'I Understand',
  226. 'Go Back'
  227. )
  228. setOverlayHandler(() => {
  229. toggleLaunchArea(false)
  230. toggleOverlay(false)
  231. })
  232. setDismissHandler(() => {
  233. toggleOverlay(false, true)
  234. asyncSystemScan()
  235. })
  236. $('#overlayContent').fadeIn(250)
  237. })
  238. })
  239. toggleOverlay(true, true)
  240. // TODO Add option to not install Java x64.
  241. } else {
  242. // Java installation found, use this to launch the game.
  243. ConfigManager.setJavaExecutable(m.result)
  244. ConfigManager.save()
  245. if(launchAfter){
  246. dlAsync()
  247. }
  248. sysAEx.disconnect()
  249. }
  250. } else if(m.content === '_enqueueOracleJRE'){
  251. if(m.result === true){
  252. // Oracle JRE enqueued successfully, begin download.
  253. setLaunchDetails('Downloading Java..')
  254. sysAEx.send({task: 0, content: 'processDlQueues', argsArr: [[{id:'java', limit:1}]]})
  255. } else {
  256. // Oracle JRE enqueue failed. Probably due to a change in their website format.
  257. // User will have to follow the guide to install Java.
  258. setOverlayContent(
  259. 'Unexpected Issue:<br>Java Download Failed',
  260. '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.',
  261. 'I Understand'
  262. )
  263. setOverlayHandler(() => {
  264. toggleOverlay(false)
  265. toggleLaunchArea(false)
  266. })
  267. toggleOverlay(true)
  268. sysAEx.disconnect()
  269. }
  270. } else if(m.content === 'dl'){
  271. if(m.task === 0){
  272. // Downloading..
  273. setDownloadPercentage(m.value, m.total, m.percent)
  274. } else if(m.task === 1){
  275. // Download will be at 100%, remove the loading from the OS progress bar.
  276. remote.getCurrentWindow().setProgressBar(-1)
  277. // Wait for extration to complete.
  278. setLaunchDetails('Extracting..')
  279. } else if(m.task === 2){
  280. // Extraction completed successfully.
  281. ConfigManager.setJavaExecutable(m.jPath)
  282. ConfigManager.save()
  283. setLaunchDetails('Java Installed!')
  284. if(launchAfter){
  285. dlAsync()
  286. }
  287. sysAEx.disconnect()
  288. } else {
  289. console.error('Unknown download data type.', m)
  290. }
  291. }
  292. })
  293. // Begin system Java scan.
  294. setLaunchDetails('Checking system info..')
  295. sysAEx.send({task: 0, content: 'validateJava', argsArr: [ConfigManager.getLauncherDirectory()]})
  296. }
  297. // Keep reference to Minecraft Process
  298. let proc
  299. // Is DiscordRPC enabled
  300. let hasRPC = false
  301. // Joined server regex
  302. 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
  303. const gameJoined = /\[[0-2][0-9]:[0-6][0-9]:[0-6][0-9]\] \[Client thread\/WARN\]: Skipping bad option: lastServer:/g
  304. const gameJoined2 = /\[[0-2][0-9]:[0-6][0-9]:[0-6][0-9]\] \[Client thread\/INFO\]: Created: \d+x\d+ textures-atlas/g
  305. let aEx
  306. let serv
  307. let versionData
  308. let forgeData
  309. function dlAsync(login = true){
  310. // Login parameter is temporary for debug purposes. Allows testing the validation/downloads without
  311. // launching the game.
  312. if(login) {
  313. if(ConfigManager.getSelectedAccount() == null){
  314. console.error('login first.')
  315. //in devtools AuthManager.addAccount(username, pass)
  316. return
  317. }
  318. }
  319. setLaunchDetails('Please wait..')
  320. toggleLaunchArea(true)
  321. setLaunchPercentage(0, 100)
  322. // Start AssetExec to run validations and downloads in a forked process.
  323. aEx = cp.fork(path.join(__dirname, 'assets', 'js', 'assetexec.js'), [
  324. ConfigManager.getGameDirectory(),
  325. ConfigManager.getJavaExecutable()
  326. ])
  327. // Establish communications between the AssetExec and current process.
  328. aEx.on('message', (m) => {
  329. if(m.content === 'validateDistribution'){
  330. setLaunchPercentage(20, 100)
  331. serv = m.result
  332. console.log('Forge Validation Complete.')
  333. // Begin version load.
  334. setLaunchDetails('Loading version information..')
  335. aEx.send({task: 0, content: 'loadVersionData', argsArr: [serv.mc_version]})
  336. } else if(m.content === 'loadVersionData'){
  337. setLaunchPercentage(40, 100)
  338. versionData = m.result
  339. console.log('Version data loaded.')
  340. // Begin asset validation.
  341. setLaunchDetails('Validating asset integrity..')
  342. aEx.send({task: 0, content: 'validateAssets', argsArr: [versionData]})
  343. } else if(m.content === 'validateAssets'){
  344. // Asset validation can *potentially* take longer, so let's track progress.
  345. if(m.task === 0){
  346. const perc = (m.value/m.total)*20
  347. setLaunchPercentage(40+perc, 100, parseInt(40+perc))
  348. } else {
  349. setLaunchPercentage(60, 100)
  350. console.log('Asset Validation Complete')
  351. // Begin library validation.
  352. setLaunchDetails('Validating library integrity..')
  353. aEx.send({task: 0, content: 'validateLibraries', argsArr: [versionData]})
  354. }
  355. } else if(m.content === 'validateLibraries'){
  356. setLaunchPercentage(80, 100)
  357. console.log('Library validation complete.')
  358. // Begin miscellaneous validation.
  359. setLaunchDetails('Validating miscellaneous file integrity..')
  360. aEx.send({task: 0, content: 'validateMiscellaneous', argsArr: [versionData]})
  361. } else if(m.content === 'validateMiscellaneous'){
  362. setLaunchPercentage(100, 100)
  363. console.log('File validation complete.')
  364. // Download queued files.
  365. setLaunchDetails('Downloading files..')
  366. aEx.send({task: 0, content: 'processDlQueues'})
  367. } else if(m.content === 'dl'){
  368. if(m.task === 0){
  369. setDownloadPercentage(m.value, m.total, m.percent)
  370. } else if(m.task === 0.7){
  371. // Download done, extracting.
  372. setLaunchDetails('Extracting libraries..')
  373. } else if(m.task === 1){
  374. // Download will be at 100%, remove the loading from the OS progress bar.
  375. remote.getCurrentWindow().setProgressBar(-1)
  376. setLaunchDetails('Preparing to launch..')
  377. aEx.send({task: 0, content: 'loadForgeData', argsArr: [serv.id]})
  378. } else {
  379. console.error('Unknown download data type.', m)
  380. }
  381. } else if(m.content === 'loadForgeData'){
  382. forgeData = m.result
  383. if(login) {
  384. //if(!(await AuthManager.validateSelected())){
  385. //
  386. //}
  387. const authUser = ConfigManager.getSelectedAccount()
  388. console.log('authu', authUser)
  389. let pb = new ProcessBuilder(ConfigManager.getGameDirectory(), serv, versionData, forgeData, authUser)
  390. setLaunchDetails('Launching game..')
  391. try {
  392. // Build Minecraft process.
  393. proc = pb.build()
  394. setLaunchDetails('Done. Enjoy the server!')
  395. // Attach a temporary listener to the client output.
  396. // Will wait for a certain bit of text meaning that
  397. // the client application has started, and we can hide
  398. // the progress bar stuff.
  399. const tempListener = function(data){
  400. if(data.indexOf('[Client thread/INFO]: -- System Details --') > -1){
  401. toggleLaunchArea(false)
  402. if(hasRPC){
  403. DiscordWrapper.updateDetails('Loading game..')
  404. }
  405. proc.stdout.removeListener('data', tempListener)
  406. }
  407. }
  408. // Listener for Discord RPC.
  409. const gameStateChange = function(data){
  410. if(servJoined.test(data)){
  411. DiscordWrapper.updateDetails('Exploring the Realm!')
  412. } else if(gameJoined.test(data)){
  413. DiscordWrapper.updateDetails('Idling on Main Menu')
  414. }
  415. }
  416. // Bind listeners to stdout.
  417. proc.stdout.on('data', tempListener)
  418. proc.stdout.on('data', gameStateChange)
  419. // Init Discord Hook
  420. const distro = AssetGuard.retrieveDistributionDataSync(ConfigManager.getGameDirectory)
  421. if(distro.discord != null && serv.discord != null){
  422. DiscordWrapper.initRPC(distro.discord, serv.discord)
  423. hasRPC = true
  424. proc.on('close', (code, signal) => {
  425. console.log('Shutting down Discord Rich Presence..')
  426. DiscordWrapper.shutdownRPC()
  427. hasRPC = false
  428. proc = null
  429. })
  430. }
  431. } catch(err) {
  432. // Show that there was an error then hide the
  433. // progress area. Maybe switch this to an error
  434. // alert in the future. TODO
  435. setLaunchDetails('Error: See log for details..')
  436. console.log(err)
  437. setTimeout(function(){
  438. toggleLaunchArea(false)
  439. }, 5000)
  440. }
  441. }
  442. // Disconnect from AssetExec
  443. aEx.disconnect()
  444. }
  445. })
  446. // Begin Validations
  447. // Validate Forge files.
  448. setLaunchDetails('Loading server information..')
  449. aEx.send({task: 0, content: 'validateDistribution', argsArr: [ConfigManager.getSelectedServer()]})
  450. }