landing.js 41 KB

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