landing.js 41 KB

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