landing.js 40 KB

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