landing.js 42 KB

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