landing.js 40 KB

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