landing.js 40 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108
  1. /**
  2. * Script for landing.ejs
  3. */
  4. // Requirements
  5. const cp = require('child_process')
  6. const crypto = require('crypto')
  7. const {URL} = require('url')
  8. // Internal Requirements
  9. const DiscordWrapper = require('./assets/js/discordwrapper')
  10. const Mojang = require('./assets/js/mojang')
  11. const ProcessBuilder = require('./assets/js/processbuilder')
  12. const ServerStatus = require('./assets/js/serverstatus')
  13. // Launch Elements
  14. const launch_content = document.getElementById('launch_content')
  15. const launch_details = document.getElementById('launch_details')
  16. const launch_progress = document.getElementById('launch_progress')
  17. const launch_progress_label = document.getElementById('launch_progress_label')
  18. const launch_details_text = document.getElementById('launch_details_text')
  19. const server_selection_button = document.getElementById('server_selection_button')
  20. const user_text = document.getElementById('user_text')
  21. const loggerLanding = LoggerUtil('%c[Landing]', 'color: #000668; font-weight: bold')
  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. loggerLanding.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. loggerLanding.log('Java version meta', v)
  88. if(v.valid){
  89. dlAsync()
  90. } else {
  91. asyncSystemScan()
  92. }
  93. })
  94. }
  95. })
  96. // Bind settings button
  97. document.getElementById('settingsMediaButton').onclick = (e) => {
  98. prepareSettings()
  99. switchView(getCurrentView(), VIEWS.settings)
  100. }
  101. // Bind avatar overlay button.
  102. document.getElementById('avatarOverlay').onclick = (e) => {
  103. prepareSettings()
  104. switchView(getCurrentView(), VIEWS.settings, 500, 500, () => {
  105. settingsNavItemListener(document.getElementById('settingsNavAccount'), false)
  106. })
  107. }
  108. // Bind selected account
  109. function updateSelectedAccount(authUser){
  110. let username = 'No Account Selected'
  111. if(authUser != null){
  112. if(authUser.displayName != null){
  113. username = authUser.displayName
  114. }
  115. if(authUser.uuid != null){
  116. document.getElementById('avatarContainer').style.backgroundImage = `url('https://crafatar.com/renders/body/${authUser.uuid}')`
  117. }
  118. }
  119. user_text.innerHTML = username
  120. }
  121. updateSelectedAccount(ConfigManager.getSelectedAccount())
  122. // Bind selected server
  123. function updateSelectedServer(serv){
  124. if(getCurrentView() === VIEWS.settings){
  125. saveAllModConfigurations()
  126. }
  127. ConfigManager.setSelectedServer(serv != null ? serv.getID() : null)
  128. ConfigManager.save()
  129. server_selection_button.innerHTML = '\u2022 ' + (serv != null ? serv.getName() : 'No Server Selected')
  130. if(getCurrentView() === VIEWS.settings){
  131. animateModsTabRefresh()
  132. }
  133. setLaunchEnabled(serv != null)
  134. }
  135. // Real text is set in uibinder.js on distributionIndexDone.
  136. server_selection_button.innerHTML = '\u2022 Loading..'
  137. server_selection_button.onclick = (e) => {
  138. e.target.blur()
  139. toggleServerSelection(true)
  140. }
  141. // Update Mojang Status Color
  142. const refreshMojangStatuses = async function(){
  143. loggerLanding.log('Refreshing Mojang Statuses..')
  144. let status = 'grey'
  145. let tooltipEssentialHTML = ''
  146. let tooltipNonEssentialHTML = ''
  147. try {
  148. const statuses = await Mojang.status()
  149. greenCount = 0
  150. greyCount = 0
  151. for(let i=0; i<statuses.length; i++){
  152. const service = statuses[i]
  153. if(service.essential){
  154. tooltipEssentialHTML += `<div class="mojangStatusContainer">
  155. <span class="mojangStatusIcon" style="color: ${Mojang.statusToHex(service.status)};">&#8226;</span>
  156. <span class="mojangStatusName">${service.name}</span>
  157. </div>`
  158. } else {
  159. tooltipNonEssentialHTML += `<div class="mojangStatusContainer">
  160. <span class="mojangStatusIcon" style="color: ${Mojang.statusToHex(service.status)};">&#8226;</span>
  161. <span class="mojangStatusName">${service.name}</span>
  162. </div>`
  163. }
  164. if(service.status === 'yellow' && status !== 'red'){
  165. status = 'yellow'
  166. } else if(service.status === 'red'){
  167. status = 'red'
  168. } else {
  169. if(service.status === 'grey'){
  170. ++greyCount
  171. }
  172. ++greenCount
  173. }
  174. }
  175. if(greenCount === statuses.length){
  176. if(greyCount === statuses.length){
  177. status = 'grey'
  178. } else {
  179. status = 'green'
  180. }
  181. }
  182. } catch (err) {
  183. loggerLanding.warn('Unable to refresh Mojang service status.')
  184. loggerLanding.debug(err)
  185. }
  186. document.getElementById('mojangStatusEssentialContainer').innerHTML = tooltipEssentialHTML
  187. document.getElementById('mojangStatusNonEssentialContainer').innerHTML = tooltipNonEssentialHTML
  188. document.getElementById('mojang_status_icon').style.color = Mojang.statusToHex(status)
  189. }
  190. const refreshServerStatus = async function(fade = false){
  191. loggerLanding.log('Refreshing Server Status')
  192. const serv = DistroManager.getDistribution().getServer(ConfigManager.getSelectedServer())
  193. let pLabel = 'SERVER'
  194. let pVal = 'OFFLINE'
  195. try {
  196. const serverURL = new URL('my://' + serv.getAddress())
  197. const servStat = await ServerStatus.getStatus(serverURL.hostname, serverURL.port)
  198. if(servStat.online){
  199. pLabel = 'PLAYERS'
  200. pVal = servStat.onlinePlayers + '/' + servStat.maxPlayers
  201. }
  202. } catch (err) {
  203. loggerLanding.warn('Unable to refresh server status, assuming offline.')
  204. loggerLanding.debug(err)
  205. }
  206. if(fade){
  207. $('#server_status_wrapper').fadeOut(250, () => {
  208. document.getElementById('landingPlayerLabel').innerHTML = pLabel
  209. document.getElementById('player_count').innerHTML = pVal
  210. $('#server_status_wrapper').fadeIn(500)
  211. })
  212. } else {
  213. document.getElementById('landingPlayerLabel').innerHTML = pLabel
  214. document.getElementById('player_count').innerHTML = pVal
  215. }
  216. }
  217. refreshMojangStatuses()
  218. // Server Status is refreshed in uibinder.js on distributionIndexDone.
  219. // Set refresh rate to once every 5 minutes.
  220. let mojangStatusListener = setInterval(() => refreshMojangStatuses(true), 300000)
  221. let serverStatusListener = setInterval(() => refreshServerStatus(true), 300000)
  222. /* System (Java) Scan */
  223. let sysAEx
  224. let scanAt
  225. let extractListener
  226. function asyncSystemScan(launchAfter = true){
  227. setLaunchDetails('Please wait..')
  228. toggleLaunchArea(true)
  229. setLaunchPercentage(0, 100)
  230. const loggerSysAEx = LoggerUtil('%c[SysAEx]', 'color: #353232; font-weight: bold')
  231. // Fork a process to run validations.
  232. sysAEx = cp.fork(path.join(__dirname, 'assets', 'js', 'assetexec.js'), [
  233. ConfigManager.getCommonDirectory(),
  234. ConfigManager.getJavaExecutable()
  235. ], {
  236. stdio: 'pipe'
  237. })
  238. // Stdout
  239. sysAEx.stdio[1].setEncoding('utf8')
  240. sysAEx.stdio[1].on('data', (data) => {
  241. loggerSysAEx.log(data)
  242. })
  243. // Stderr
  244. sysAEx.stdio[2].setEncoding('utf8')
  245. sysAEx.stdio[2].on('data', (data) => {
  246. loggerSysAEx.log(data)
  247. })
  248. sysAEx.on('message', (m) => {
  249. if(m.context === 'validateJava'){
  250. if(m.result == null){
  251. // If the result is null, no valid Java installation was found.
  252. // Show this information to the user.
  253. setOverlayContent(
  254. 'No Compatible<br>Java Installation Found',
  255. '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>.',
  256. 'Install Java',
  257. 'Install Manually'
  258. )
  259. setOverlayHandler(() => {
  260. setLaunchDetails('Preparing Java Download..')
  261. sysAEx.send({task: 'execute', function: '_enqueueOracleJRE', argsArr: [ConfigManager.getLauncherDirectory()]})
  262. toggleOverlay(false)
  263. })
  264. setDismissHandler(() => {
  265. $('#overlayContent').fadeOut(250, () => {
  266. //$('#overlayDismiss').toggle(false)
  267. setOverlayContent(
  268. 'Java is Required<br>to Launch',
  269. 'A valid x64 installation of Java 8 is required to launch.<br><br>Please refer to our <a href="https://github.com/WesterosCraftCode/ElectronLauncher/wiki/Java-Management#manually-installing-a-valid-version-of-java">Java Management Guide</a> for instructions on how to manually install Java.',
  270. 'I Understand',
  271. 'Go Back'
  272. )
  273. setOverlayHandler(() => {
  274. toggleLaunchArea(false)
  275. toggleOverlay(false)
  276. })
  277. setDismissHandler(() => {
  278. toggleOverlay(false, true)
  279. asyncSystemScan()
  280. })
  281. $('#overlayContent').fadeIn(250)
  282. })
  283. })
  284. toggleOverlay(true, true)
  285. } else {
  286. // Java installation found, use this to launch the game.
  287. ConfigManager.setJavaExecutable(m.result)
  288. ConfigManager.save()
  289. // We need to make sure that the updated value is on the settings UI.
  290. // Just incase the settings UI is already open.
  291. settingsJavaExecVal.value = m.result
  292. populateJavaExecDetails(settingsJavaExecVal.value)
  293. if(launchAfter){
  294. dlAsync()
  295. }
  296. sysAEx.disconnect()
  297. }
  298. } else if(m.context === '_enqueueOracleJRE'){
  299. if(m.result === true){
  300. // Oracle JRE enqueued successfully, begin download.
  301. setLaunchDetails('Downloading Java..')
  302. sysAEx.send({task: 'execute', function: 'processDlQueues', argsArr: [[{id:'java', limit:1}]]})
  303. } else {
  304. // Oracle JRE enqueue failed. Probably due to a change in their website format.
  305. // User will have to follow the guide to install Java.
  306. setOverlayContent(
  307. 'Unexpected Issue:<br>Java Download Failed',
  308. '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.',
  309. 'I Understand'
  310. )
  311. setOverlayHandler(() => {
  312. toggleOverlay(false)
  313. toggleLaunchArea(false)
  314. })
  315. toggleOverlay(true)
  316. sysAEx.disconnect()
  317. }
  318. } else if(m.context === 'progress'){
  319. switch(m.data){
  320. case 'download':
  321. // Downloading..
  322. setDownloadPercentage(m.value, m.total, m.percent)
  323. break
  324. }
  325. } else if(m.context === 'complete'){
  326. switch(m.data){
  327. case 'download': {
  328. // Show installing progress bar.
  329. remote.getCurrentWindow().setProgressBar(2)
  330. // Wait for extration to complete.
  331. const eLStr = 'Extracting'
  332. let dotStr = ''
  333. setLaunchDetails(eLStr)
  334. extractListener = setInterval(() => {
  335. if(dotStr.length >= 3){
  336. dotStr = ''
  337. } else {
  338. dotStr += '.'
  339. }
  340. setLaunchDetails(eLStr + dotStr)
  341. }, 750)
  342. break
  343. }
  344. case 'java':
  345. // Download & extraction complete, remove the loading from the OS progress bar.
  346. remote.getCurrentWindow().setProgressBar(-1)
  347. // Extraction completed successfully.
  348. ConfigManager.setJavaExecutable(m.args[0])
  349. ConfigManager.save()
  350. if(extractListener != null){
  351. clearInterval(extractListener)
  352. extractListener = null
  353. }
  354. setLaunchDetails('Java Installed!')
  355. if(launchAfter){
  356. dlAsync()
  357. }
  358. sysAEx.disconnect()
  359. break
  360. }
  361. }
  362. })
  363. // Begin system Java scan.
  364. setLaunchDetails('Checking system info..')
  365. sysAEx.send({task: 'execute', function: 'validateJava', argsArr: [ConfigManager.getLauncherDirectory()]})
  366. }
  367. // Keep reference to Minecraft Process
  368. let proc
  369. // Is DiscordRPC enabled
  370. let hasRPC = false
  371. // Joined server regex
  372. const SERVER_JOINED_REGEX = /\[.+\]: \[CHAT\] [a-zA-Z0-9_]{1,16} joined the game/
  373. const GAME_JOINED_REGEX = /\[.+\]: Skipping bad option: lastServer:/
  374. const GAME_LAUNCH_REGEX = /^\[.+\]: MinecraftForge .+ Initialized$/
  375. let aEx
  376. let serv
  377. let versionData
  378. let forgeData
  379. let progressListener
  380. function dlAsync(login = true){
  381. // Login parameter is temporary for debug purposes. Allows testing the validation/downloads without
  382. // launching the game.
  383. if(login) {
  384. if(ConfigManager.getSelectedAccount() == null){
  385. loggerLanding.error('You must be logged into an account.')
  386. return
  387. }
  388. }
  389. setLaunchDetails('Please wait..')
  390. toggleLaunchArea(true)
  391. setLaunchPercentage(0, 100)
  392. const loggerAEx = LoggerUtil('%c[AEx]', 'color: #353232; font-weight: bold')
  393. const loggerLaunchSuite = LoggerUtil('%c[LaunchSuite]', 'color: #000668; font-weight: bold')
  394. // Start AssetExec to run validations and downloads in a forked process.
  395. aEx = cp.fork(path.join(__dirname, 'assets', 'js', 'assetexec.js'), [
  396. ConfigManager.getCommonDirectory(),
  397. ConfigManager.getJavaExecutable()
  398. ], {
  399. stdio: 'pipe'
  400. })
  401. // Stdout
  402. aEx.stdio[1].setEncoding('utf8')
  403. aEx.stdio[1].on('data', (data) => {
  404. loggerAEx.log(data)
  405. })
  406. // Stderr
  407. aEx.stdio[2].setEncoding('utf8')
  408. aEx.stdio[2].on('data', (data) => {
  409. loggerAEx.log(data)
  410. })
  411. // Establish communications between the AssetExec and current process.
  412. aEx.on('message', (m) => {
  413. if(m.context === 'validate'){
  414. switch(m.data){
  415. case 'distribution':
  416. setLaunchPercentage(20, 100)
  417. loggerLaunchSuite.log('Validated distibution index.')
  418. setLaunchDetails('Loading version information..')
  419. break
  420. case 'version':
  421. setLaunchPercentage(40, 100)
  422. loggerLaunchSuite.log('Version data loaded.')
  423. setLaunchDetails('Validating asset integrity..')
  424. break
  425. case 'assets':
  426. setLaunchPercentage(60, 100)
  427. loggerLaunchSuite.log('Asset Validation Complete')
  428. setLaunchDetails('Validating library integrity..')
  429. break
  430. case 'libraries':
  431. setLaunchPercentage(80, 100)
  432. loggerLaunchSuite.log('Library validation complete.')
  433. setLaunchDetails('Validating miscellaneous file integrity..')
  434. break
  435. case 'files':
  436. setLaunchPercentage(100, 100)
  437. loggerLaunchSuite.log('File validation complete.')
  438. setLaunchDetails('Downloading files..')
  439. break
  440. }
  441. } else if(m.context === 'progress'){
  442. switch(m.data){
  443. case 'assets': {
  444. const perc = (m.value/m.total)*20
  445. setLaunchPercentage(40+perc, 100, parseInt(40+perc))
  446. break
  447. }
  448. case 'download':
  449. setDownloadPercentage(m.value, m.total, m.percent)
  450. break
  451. case 'extract': {
  452. // Show installing progress bar.
  453. remote.getCurrentWindow().setProgressBar(2)
  454. // Download done, extracting.
  455. const eLStr = 'Extracting libraries'
  456. let dotStr = ''
  457. setLaunchDetails(eLStr)
  458. progressListener = setInterval(() => {
  459. if(dotStr.length >= 3){
  460. dotStr = ''
  461. } else {
  462. dotStr += '.'
  463. }
  464. setLaunchDetails(eLStr + dotStr)
  465. }, 750)
  466. break
  467. }
  468. }
  469. } else if(m.context === 'complete'){
  470. switch(m.data){
  471. case 'download':
  472. // Download and extraction complete, remove the loading from the OS progress bar.
  473. remote.getCurrentWindow().setProgressBar(-1)
  474. if(progressListener != null){
  475. clearInterval(progressListener)
  476. progressListener = null
  477. }
  478. setLaunchDetails('Preparing to launch..')
  479. break
  480. }
  481. } else if(m.context === 'error'){
  482. switch(m.data){
  483. case 'download':
  484. loggerLaunchSuite.error('Error while downloading:', m.error)
  485. if(m.error.code === 'ENOENT'){
  486. setOverlayContent(
  487. 'Download Error',
  488. 'Could not connect to the file server. Ensure that you are connected to the internet and try again.',
  489. 'Okay'
  490. )
  491. setOverlayHandler(null)
  492. } else {
  493. setOverlayContent(
  494. 'Download Error',
  495. 'Check the console for more details. Please try again.',
  496. 'Okay'
  497. )
  498. setOverlayHandler(null)
  499. }
  500. remote.getCurrentWindow().setProgressBar(-1)
  501. toggleOverlay(true)
  502. toggleLaunchArea(false)
  503. // Disconnect from AssetExec
  504. aEx.disconnect()
  505. break
  506. }
  507. } else if(m.context === 'validateEverything'){
  508. // If these properties are not defined it's likely an error.
  509. if(m.result.forgeData == null || m.result.versionData == null){
  510. loggerLaunchSuite.error('Error during validation:', m.result)
  511. }
  512. forgeData = m.result.forgeData
  513. versionData = m.result.versionData
  514. if(login) {
  515. const authUser = ConfigManager.getSelectedAccount()
  516. loggerLaunchSuite.log(`Sending selected account (${authUser.displayName}) to ProcessBuilder.`)
  517. let pb = new ProcessBuilder(serv, versionData, forgeData, authUser)
  518. setLaunchDetails('Launching game..')
  519. // Attach a temporary listener to the client output.
  520. // Will wait for a certain bit of text meaning that
  521. // the client application has started, and we can hide
  522. // the progress bar stuff.
  523. const tempListener = function(data){
  524. if(GAME_LAUNCH_REGEX.test(data.trim())){
  525. toggleLaunchArea(false)
  526. if(hasRPC){
  527. DiscordWrapper.updateDetails('Loading game..')
  528. }
  529. proc.stdout.on('data', gameStateChange)
  530. proc.stdout.removeListener('data', tempListener)
  531. proc.stderr.removeListener('data', gameErrorListener)
  532. }
  533. }
  534. // Listener for Discord RPC.
  535. const gameStateChange = function(data){
  536. data = data.trim()
  537. if(SERVER_JOINED_REGEX.test(data)){
  538. DiscordWrapper.updateDetails('Exploring the Realm!')
  539. } else if(GAME_JOINED_REGEX.test(data)){
  540. DiscordWrapper.updateDetails('Sailing to Westeros!')
  541. }
  542. }
  543. const gameErrorListener = function(data){
  544. data = data.trim()
  545. if(data.indexOf('Could not find or load main class net.minecraft.launchwrapper.Launch') > -1){
  546. loggerLaunchSuite.error('Game launch failed, LaunchWrapper was not downloaded properly.')
  547. setOverlayContent(
  548. 'Error During Launch',
  549. 'The main file, LaunchWrapper, failed to download properly. As a result, the game cannot launch.<br><br>To fix this issue, temporarily turn off your antivirus software and launch the game again.<br><br>If you have time, please <a href="https://github.com/WesterosCraftCode/ElectronLauncher/issues">submit an issue</a> and let us know what antivirus software you use. We\'ll contact them and try to straighten things out.',
  550. 'Okay'
  551. )
  552. setOverlayHandler(null)
  553. toggleOverlay(true)
  554. toggleLaunchArea(false)
  555. }
  556. }
  557. try {
  558. // Build Minecraft process.
  559. proc = pb.build()
  560. // Bind listeners to stdout.
  561. proc.stdout.on('data', tempListener)
  562. proc.stderr.on('data', gameErrorListener)
  563. setLaunchDetails('Done. Enjoy the server!')
  564. // Init Discord Hook
  565. const distro = DistroManager.getDistribution()
  566. if(distro.discord != null && serv.discord != null){
  567. DiscordWrapper.initRPC(distro.discord, serv.discord)
  568. hasRPC = true
  569. proc.on('close', (code, signal) => {
  570. loggerLaunchSuite.log('Shutting down Discord Rich Presence..')
  571. DiscordWrapper.shutdownRPC()
  572. hasRPC = false
  573. proc = null
  574. })
  575. }
  576. } catch(err) {
  577. loggerLaunchSuite.error('Error during launch', err)
  578. setOverlayContent(
  579. 'Error During Launch',
  580. 'Please check the console for more details.',
  581. 'Okay'
  582. )
  583. setOverlayHandler(null)
  584. toggleOverlay(true)
  585. toggleLaunchArea(false)
  586. }
  587. }
  588. // Disconnect from AssetExec
  589. aEx.disconnect()
  590. }
  591. })
  592. // Begin Validations
  593. // Validate Forge files.
  594. setLaunchDetails('Loading server information..')
  595. refreshDistributionIndex(true, (data) => {
  596. onDistroRefresh(data)
  597. serv = data.getServer(ConfigManager.getSelectedServer())
  598. aEx.send({task: 'execute', function: 'validateEverything', argsArr: [ConfigManager.getSelectedServer(), DistroManager.isDevMode()]})
  599. }, (err) => {
  600. loggerLaunchSuite.log('Error while fetching a fresh copy of the distribution index.', err)
  601. refreshDistributionIndex(false, (data) => {
  602. onDistroRefresh(data)
  603. serv = data.getServer(ConfigManager.getSelectedServer())
  604. aEx.send({task: 'execute', function: 'validateEverything', argsArr: [ConfigManager.getSelectedServer(), DistroManager.isDevMode()]})
  605. }, (err) => {
  606. loggerLaunchSuite.error('Unable to refresh distribution index.', err)
  607. if(DistroManager.getDistribution() == null){
  608. setOverlayContent(
  609. 'Fatal Error',
  610. 'Could not load a copy of the distribution index. See the console for more details.',
  611. 'Okay'
  612. )
  613. setOverlayHandler(null)
  614. toggleOverlay(true)
  615. toggleLaunchArea(false)
  616. // Disconnect from AssetExec
  617. aEx.disconnect()
  618. } else {
  619. serv = data.getServer(ConfigManager.getSelectedServer())
  620. aEx.send({task: 'execute', function: 'validateEverything', argsArr: [ConfigManager.getSelectedServer(), DistroManager.isDevMode()]})
  621. }
  622. })
  623. })
  624. }
  625. /**
  626. * News Loading Functions
  627. */
  628. // DOM Cache
  629. const newsContent = document.getElementById('newsContent')
  630. const newsArticleTitle = document.getElementById('newsArticleTitle')
  631. const newsArticleDate = document.getElementById('newsArticleDate')
  632. const newsArticleAuthor = document.getElementById('newsArticleAuthor')
  633. const newsArticleComments = document.getElementById('newsArticleComments')
  634. const newsNavigationStatus = document.getElementById('newsNavigationStatus')
  635. const newsArticleContentScrollable = document.getElementById('newsArticleContentScrollable')
  636. const nELoadSpan = document.getElementById('nELoadSpan')
  637. // News slide caches.
  638. let newsActive = false
  639. let newsGlideCount = 0
  640. /**
  641. * Show the news UI via a slide animation.
  642. *
  643. * @param {boolean} up True to slide up, otherwise false.
  644. */
  645. function slide_(up){
  646. const lCUpper = document.querySelector('#landingContainer > #upper')
  647. const lCLLeft = document.querySelector('#landingContainer > #lower > #left')
  648. const lCLCenter = document.querySelector('#landingContainer > #lower > #center')
  649. const lCLRight = document.querySelector('#landingContainer > #lower > #right')
  650. const newsBtn = document.querySelector('#landingContainer > #lower > #center #content')
  651. const landingContainer = document.getElementById('landingContainer')
  652. const newsContainer = document.querySelector('#landingContainer > #newsContainer')
  653. newsGlideCount++
  654. if(up){
  655. lCUpper.style.top = '-200vh'
  656. lCLLeft.style.top = '-200vh'
  657. lCLCenter.style.top = '-200vh'
  658. lCLRight.style.top = '-200vh'
  659. newsBtn.style.top = '130vh'
  660. newsContainer.style.top = '0px'
  661. //date.toLocaleDateString('en-US', {month: 'short', day: 'numeric', year: 'numeric', hour: 'numeric', minute: 'numeric'})
  662. //landingContainer.style.background = 'rgba(29, 29, 29, 0.55)'
  663. landingContainer.style.background = 'rgba(0, 0, 0, 0.50)'
  664. setTimeout(() => {
  665. if(newsGlideCount === 1){
  666. lCLCenter.style.transition = 'none'
  667. newsBtn.style.transition = 'none'
  668. }
  669. newsGlideCount--
  670. }, 2000)
  671. } else {
  672. setTimeout(() => {
  673. newsGlideCount--
  674. }, 2000)
  675. landingContainer.style.background = null
  676. lCLCenter.style.transition = null
  677. newsBtn.style.transition = null
  678. newsContainer.style.top = '100%'
  679. lCUpper.style.top = '0px'
  680. lCLLeft.style.top = '0px'
  681. lCLCenter.style.top = '0px'
  682. lCLRight.style.top = '0px'
  683. newsBtn.style.top = '10px'
  684. }
  685. }
  686. // Bind news button.
  687. document.getElementById('newsButton').onclick = () => {
  688. // Toggle tabbing.
  689. if(newsActive){
  690. $('#landingContainer *').removeAttr('tabindex')
  691. $('#newsContainer *').attr('tabindex', '-1')
  692. } else {
  693. $('#landingContainer *').attr('tabindex', '-1')
  694. $('#newsContainer, #newsContainer *, #lower, #lower #center *').removeAttr('tabindex')
  695. if(newsAlertShown){
  696. $('#newsButtonAlert').fadeOut(2000)
  697. newsAlertShown = false
  698. ConfigManager.setNewsCacheDismissed(true)
  699. ConfigManager.save()
  700. }
  701. }
  702. slide_(!newsActive)
  703. newsActive = !newsActive
  704. }
  705. // Array to store article meta.
  706. let newsArr = null
  707. // News load animation listener.
  708. let newsLoadingListener = null
  709. /**
  710. * Set the news loading animation.
  711. *
  712. * @param {boolean} val True to set loading animation, otherwise false.
  713. */
  714. function setNewsLoading(val){
  715. if(val){
  716. const nLStr = 'Checking for News'
  717. let dotStr = '..'
  718. nELoadSpan.innerHTML = nLStr + dotStr
  719. newsLoadingListener = setInterval(() => {
  720. if(dotStr.length >= 3){
  721. dotStr = ''
  722. } else {
  723. dotStr += '.'
  724. }
  725. nELoadSpan.innerHTML = nLStr + dotStr
  726. }, 750)
  727. } else {
  728. if(newsLoadingListener != null){
  729. clearInterval(newsLoadingListener)
  730. newsLoadingListener = null
  731. }
  732. }
  733. }
  734. // Bind retry button.
  735. newsErrorRetry.onclick = () => {
  736. $('#newsErrorFailed').fadeOut(250, () => {
  737. initNews()
  738. $('#newsErrorLoading').fadeIn(250)
  739. })
  740. }
  741. newsArticleContentScrollable.onscroll = (e) => {
  742. if(e.target.scrollTop > Number.parseFloat($('.newsArticleSpacerTop').css('height'))){
  743. newsContent.setAttribute('scrolled', '')
  744. } else {
  745. newsContent.removeAttribute('scrolled')
  746. }
  747. }
  748. /**
  749. * Reload the news without restarting.
  750. *
  751. * @returns {Promise.<void>} A promise which resolves when the news
  752. * content has finished loading and transitioning.
  753. */
  754. function reloadNews(){
  755. return new Promise((resolve, reject) => {
  756. $('#newsContent').fadeOut(250, () => {
  757. $('#newsErrorLoading').fadeIn(250)
  758. initNews().then(() => {
  759. resolve()
  760. })
  761. })
  762. })
  763. }
  764. let newsAlertShown = false
  765. /**
  766. * Show the news alert indicating there is new news.
  767. */
  768. function showNewsAlert(){
  769. newsAlertShown = true
  770. $(newsButtonAlert).fadeIn(250)
  771. }
  772. /**
  773. * Initialize News UI. This will load the news and prepare
  774. * the UI accordingly.
  775. *
  776. * @returns {Promise.<void>} A promise which resolves when the news
  777. * content has finished loading and transitioning.
  778. */
  779. function initNews(){
  780. return new Promise((resolve, reject) => {
  781. setNewsLoading(true)
  782. let news = {}
  783. loadNews().then(news => {
  784. newsArr = news.articles || null
  785. if(newsArr == null){
  786. // News Loading Failed
  787. setNewsLoading(false)
  788. $('#newsErrorLoading').fadeOut(250, () => {
  789. $('#newsErrorFailed').fadeIn(250, () => {
  790. resolve()
  791. })
  792. })
  793. } else if(newsArr.length === 0) {
  794. // No News Articles
  795. setNewsLoading(false)
  796. ConfigManager.setNewsCache({
  797. date: null,
  798. content: null,
  799. dismissed: false
  800. })
  801. ConfigManager.save()
  802. $('#newsErrorLoading').fadeOut(250, () => {
  803. $('#newsErrorNone').fadeIn(250, () => {
  804. resolve()
  805. })
  806. })
  807. } else {
  808. // Success
  809. setNewsLoading(false)
  810. const lN = newsArr[0]
  811. const cached = ConfigManager.getNewsCache()
  812. let newHash = crypto.createHash('sha1').update(lN.content).digest('hex')
  813. let newDate = new Date(lN.date)
  814. let isNew = false
  815. if(cached.date != null && cached.content != null){
  816. if(new Date(cached.date) >= newDate){
  817. // Compare Content
  818. if(cached.content !== newHash){
  819. isNew = true
  820. showNewsAlert()
  821. } else {
  822. if(!cached.dismissed){
  823. isNew = true
  824. showNewsAlert()
  825. }
  826. }
  827. } else {
  828. isNew = true
  829. showNewsAlert()
  830. }
  831. } else {
  832. isNew = true
  833. showNewsAlert()
  834. }
  835. if(isNew){
  836. ConfigManager.setNewsCache({
  837. date: newDate.getTime(),
  838. content: newHash,
  839. dismissed: false
  840. })
  841. ConfigManager.save()
  842. }
  843. const switchHandler = (forward) => {
  844. let cArt = parseInt(newsContent.getAttribute('article'))
  845. let nxtArt = forward ? (cArt >= newsArr.length-1 ? 0 : cArt + 1) : (cArt <= 0 ? newsArr.length-1 : cArt - 1)
  846. displayArticle(newsArr[nxtArt], nxtArt+1)
  847. }
  848. document.getElementById('newsNavigateRight').onclick = () => { switchHandler(true) }
  849. document.getElementById('newsNavigateLeft').onclick = () => { switchHandler(false) }
  850. $('#newsErrorContainer').fadeOut(250, () => {
  851. displayArticle(newsArr[0], 1)
  852. $('#newsContent').fadeIn(250, () => {
  853. resolve()
  854. })
  855. })
  856. }
  857. })
  858. })
  859. }
  860. /**
  861. * Add keyboard controls to the news UI. Left and right arrows toggle
  862. * between articles. If you are on the landing page, the up arrow will
  863. * open the news UI.
  864. */
  865. document.addEventListener('keydown', (e) => {
  866. if(newsActive){
  867. if(e.key === 'ArrowRight' || e.key === 'ArrowLeft'){
  868. document.getElementById(e.key === 'ArrowRight' ? 'newsNavigateRight' : 'newsNavigateLeft').click()
  869. }
  870. // Interferes with scrolling an article using the down arrow.
  871. // Not sure of a straight forward solution at this point.
  872. // if(e.key === 'ArrowDown'){
  873. // document.getElementById('newsButton').click()
  874. // }
  875. } else {
  876. if(getCurrentView() === VIEWS.landing){
  877. if(e.key === 'ArrowUp'){
  878. document.getElementById('newsButton').click()
  879. }
  880. }
  881. }
  882. })
  883. /**
  884. * Display a news article on the UI.
  885. *
  886. * @param {Object} articleObject The article meta object.
  887. * @param {number} index The article index.
  888. */
  889. function displayArticle(articleObject, index){
  890. newsArticleTitle.innerHTML = articleObject.title
  891. newsArticleTitle.href = articleObject.link
  892. newsArticleAuthor.innerHTML = 'by ' + articleObject.author
  893. newsArticleDate.innerHTML = articleObject.date
  894. newsArticleComments.innerHTML = articleObject.comments
  895. newsArticleComments.href = articleObject.commentsLink
  896. newsArticleContentScrollable.innerHTML = '<div id="newsArticleContentWrapper"><div class="newsArticleSpacerTop"></div>' + articleObject.content + '<div class="newsArticleSpacerBot"></div></div>'
  897. Array.from(newsArticleContentScrollable.getElementsByClassName('bbCodeSpoilerButton')).forEach(v => {
  898. v.onclick = () => {
  899. const text = v.parentElement.getElementsByClassName('bbCodeSpoilerText')[0]
  900. text.style.display = text.style.display === 'block' ? 'none' : 'block'
  901. }
  902. })
  903. newsNavigationStatus.innerHTML = index + ' of ' + newsArr.length
  904. newsContent.setAttribute('article', index-1)
  905. }
  906. /**
  907. * Load news information from the RSS feed specified in the
  908. * distribution index.
  909. */
  910. function loadNews(){
  911. return new Promise((resolve, reject) => {
  912. const distroData = DistroManager.getDistribution()
  913. const newsFeed = distroData.getRSS()
  914. const newsHost = new URL(newsFeed).origin + '/'
  915. $.ajax(
  916. {
  917. url: newsFeed,
  918. success: (data) => {
  919. const items = $(data).find('item')
  920. const articles = []
  921. for(let i=0; i<items.length; i++){
  922. // JQuery Element
  923. const el = $(items[i])
  924. // Resolve date.
  925. const date = new Date(el.find('pubDate').text()).toLocaleDateString('en-US', {month: 'short', day: 'numeric', year: 'numeric', hour: 'numeric', minute: 'numeric'})
  926. // Resolve comments.
  927. let comments = el.find('slash\\:comments').text() || '0'
  928. comments = comments + ' Comment' + (comments === '1' ? '' : 's')
  929. // Fix relative links in content.
  930. let content = el.find('content\\:encoded').text()
  931. let regex = /src="(?!http:\/\/|https:\/\/)(.+?)"/g
  932. let matches
  933. while((matches = regex.exec(content))){
  934. content = content.replace(`"${matches[1]}"`, `"${newsHost + matches[1]}"`)
  935. }
  936. let link = el.find('link').text()
  937. let title = el.find('title').text()
  938. let author = el.find('dc\\:creator').text()
  939. // Generate article.
  940. articles.push(
  941. {
  942. link,
  943. title,
  944. date,
  945. author,
  946. content,
  947. comments,
  948. commentsLink: link + '#comments'
  949. }
  950. )
  951. }
  952. resolve({
  953. articles
  954. })
  955. },
  956. timeout: 2500
  957. }
  958. ).catch(err => {
  959. resolve({
  960. articles: null
  961. })
  962. })
  963. })
  964. }