landing.js 19 KB

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