landing.js 41 KB

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