landing.js 41 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147
  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 { getServerStatus } = require('helios-core')
  9. // Internal Requirements
  10. const DiscordWrapper = require('./assets/js/discordwrapper')
  11. const Mojang = require('./assets/js/mojang')
  12. const ProcessBuilder = require('./assets/js/processbuilder')
  13. const ServerStatus = require('./assets/js/serverstatus')
  14. // Launch Elements
  15. const launch_content = document.getElementById('launch_content')
  16. const launch_details = document.getElementById('launch_details')
  17. const launch_progress = document.getElementById('launch_progress')
  18. const launch_progress_label = document.getElementById('launch_progress_label')
  19. const launch_details_text = document.getElementById('launch_details_text')
  20. const server_selection_button = document.getElementById('server_selection_button')
  21. const user_text = document.getElementById('user_text')
  22. const loggerLanding = LoggerUtil('%c[Landing]', 'color: #000668; font-weight: bold')
  23. /* Launch Progress Wrapper Functions */
  24. /**
  25. * Show/hide the loading area.
  26. *
  27. * @param {boolean} loading True if the loading area should be shown, otherwise false.
  28. */
  29. function toggleLaunchArea(loading){
  30. if(loading){
  31. launch_details.style.display = 'flex'
  32. launch_content.style.display = 'none'
  33. } else {
  34. launch_details.style.display = 'none'
  35. launch_content.style.display = 'inline-flex'
  36. }
  37. }
  38. /**
  39. * Set the details text of the loading area.
  40. *
  41. * @param {string} details The new text for the loading details.
  42. */
  43. function setLaunchDetails(details){
  44. launch_details_text.innerHTML = details
  45. }
  46. /**
  47. * Set the value of the loading progress bar and display that value.
  48. *
  49. * @param {number} value The progress value.
  50. * @param {number} max The total size.
  51. * @param {number|string} percent Optional. The percentage to display on the progress label.
  52. */
  53. function setLaunchPercentage(value, max, percent = ((value/max)*100)){
  54. launch_progress.setAttribute('max', max)
  55. launch_progress.setAttribute('value', value)
  56. launch_progress_label.innerHTML = percent + '%'
  57. }
  58. /**
  59. * Set the value of the OS progress bar and display that on the UI.
  60. *
  61. * @param {number} value The progress value.
  62. * @param {number} max The total download size.
  63. * @param {number|string} percent Optional. The percentage to display on the progress label.
  64. */
  65. function setDownloadPercentage(value, max, percent = ((value/max)*100)){
  66. remote.getCurrentWindow().setProgressBar(value/max)
  67. setLaunchPercentage(value, max, percent)
  68. }
  69. /**
  70. * Enable or disable the launch button.
  71. *
  72. * @param {boolean} val True to enable, false to disable.
  73. */
  74. function setLaunchEnabled(val){
  75. document.getElementById('launch_button').disabled = !val
  76. }
  77. // Bind launch button
  78. document.getElementById('launch_button').addEventListener('click', function(e){
  79. loggerLanding.log('Launching game..')
  80. const mcVersion = DistroManager.getDistribution().getServer(ConfigManager.getSelectedServer()).getMinecraftVersion()
  81. const jExe = ConfigManager.getJavaExecutable()
  82. if(jExe == null){
  83. asyncSystemScan(mcVersion)
  84. } else {
  85. setLaunchDetails(Lang.queryJS('landing.launch.pleaseWait'))
  86. toggleLaunchArea(true)
  87. setLaunchPercentage(0, 100)
  88. const jg = new JavaGuard(mcVersion)
  89. jg._validateJavaBinary(jExe).then((v) => {
  90. loggerLanding.log('Java version meta', v)
  91. if(v.valid){
  92. dlAsync()
  93. } else {
  94. asyncSystemScan(mcVersion)
  95. }
  96. })
  97. }
  98. })
  99. // Bind settings button
  100. document.getElementById('settingsMediaButton').onclick = (e) => {
  101. prepareSettings()
  102. switchView(getCurrentView(), VIEWS.settings)
  103. }
  104. // Bind avatar overlay button.
  105. document.getElementById('avatarOverlay').onclick = (e) => {
  106. prepareSettings()
  107. switchView(getCurrentView(), VIEWS.settings, 500, 500, () => {
  108. settingsNavItemListener(document.getElementById('settingsNavAccount'), false)
  109. })
  110. }
  111. // Bind selected account
  112. function updateSelectedAccount(authUser){
  113. let username = 'No Account Selected'
  114. if(authUser != null){
  115. if(authUser.displayName != null){
  116. username = authUser.displayName
  117. }
  118. if(authUser.uuid != null){
  119. document.getElementById('avatarContainer').style.backgroundImage = `url('https://mc-heads.net/body/${authUser.uuid}/right')`
  120. }
  121. }
  122. user_text.innerHTML = username
  123. }
  124. updateSelectedAccount(ConfigManager.getSelectedAccount())
  125. // Bind selected server
  126. function updateSelectedServer(serv){
  127. if(getCurrentView() === VIEWS.settings){
  128. saveAllModConfigurations()
  129. }
  130. ConfigManager.setSelectedServer(serv != null ? serv.getID() : null)
  131. ConfigManager.save()
  132. server_selection_button.innerHTML = '\u2022 ' + (serv != null ? serv.getName() : 'No Server Selected')
  133. if(getCurrentView() === VIEWS.settings){
  134. animateModsTabRefresh()
  135. }
  136. setLaunchEnabled(serv != null)
  137. }
  138. // Real text is set in uibinder.js on distributionIndexDone.
  139. server_selection_button.innerHTML = '\u2022 Loading..'
  140. server_selection_button.onclick = (e) => {
  141. e.target.blur()
  142. toggleServerSelection(true)
  143. }
  144. // Update Mojang Status Color
  145. const refreshMojangStatuses = async function(){
  146. loggerLanding.log('Refreshing Mojang Statuses..')
  147. let status = 'grey'
  148. let tooltipEssentialHTML = ''
  149. let tooltipNonEssentialHTML = ''
  150. try {
  151. const statuses = await Mojang.status()
  152. greenCount = 0
  153. greyCount = 0
  154. for(let i=0; i<statuses.length; i++){
  155. const service = statuses[i]
  156. if(service.essential){
  157. tooltipEssentialHTML += `<div class="mojangStatusContainer">
  158. <span class="mojangStatusIcon" style="color: ${Mojang.statusToHex(service.status)};">&#8226;</span>
  159. <span class="mojangStatusName">${service.name}</span>
  160. </div>`
  161. } else {
  162. tooltipNonEssentialHTML += `<div class="mojangStatusContainer">
  163. <span class="mojangStatusIcon" style="color: ${Mojang.statusToHex(service.status)};">&#8226;</span>
  164. <span class="mojangStatusName">${service.name}</span>
  165. </div>`
  166. }
  167. if(service.status === 'yellow' && status !== 'red'){
  168. status = 'yellow'
  169. } else if(service.status === 'red'){
  170. status = 'red'
  171. } else {
  172. if(service.status === 'grey'){
  173. ++greyCount
  174. }
  175. ++greenCount
  176. }
  177. }
  178. if(greenCount === statuses.length){
  179. if(greyCount === statuses.length){
  180. status = 'grey'
  181. } else {
  182. status = 'green'
  183. }
  184. }
  185. } catch (err) {
  186. loggerLanding.warn('Unable to refresh Mojang service status.')
  187. loggerLanding.debug(err)
  188. }
  189. document.getElementById('mojangStatusEssentialContainer').innerHTML = tooltipEssentialHTML
  190. document.getElementById('mojangStatusNonEssentialContainer').innerHTML = tooltipNonEssentialHTML
  191. document.getElementById('mojang_status_icon').style.color = Mojang.statusToHex(status)
  192. }
  193. const refreshServerStatus = async function(fade = false){
  194. loggerLanding.log('Refreshing Server Status')
  195. const serv = DistroManager.getDistribution().getServer(ConfigManager.getSelectedServer())
  196. let pLabel = 'SERVER'
  197. let pVal = 'OFFLINE'
  198. try {
  199. const serverURL = new URL('my://' + serv.getAddress())
  200. const servStat = await getServerStatus(47, serverURL.hostname, Number(serverURL.port))
  201. console.log(servStat)
  202. pLabel = 'PLAYERS'
  203. pVal = servStat.players.online + '/' + servStat.players.max
  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?',
  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 GAME_JOINED_REGEX = /\[.+\]: Sound engine started/
  404. const GAME_LAUNCH_REGEX = /^\[.+\]: (?:MinecraftForge .+ Initialized|ModLauncher .+ starting: .+)$/
  405. const MIN_LINGER = 5000
  406. let aEx
  407. let serv
  408. let versionData
  409. let forgeData
  410. let progressListener
  411. function dlAsync(login = true){
  412. // Login parameter is temporary for debug purposes. Allows testing the validation/downloads without
  413. // launching the game.
  414. if(login) {
  415. if(ConfigManager.getSelectedAccount() == null){
  416. loggerLanding.error('You must be logged into an account.')
  417. return
  418. }
  419. }
  420. setLaunchDetails('Please wait..')
  421. toggleLaunchArea(true)
  422. setLaunchPercentage(0, 100)
  423. const loggerAEx = LoggerUtil('%c[AEx]', 'color: #353232; font-weight: bold')
  424. const loggerLaunchSuite = LoggerUtil('%c[LaunchSuite]', 'color: #000668; font-weight: bold')
  425. const forkEnv = JSON.parse(JSON.stringify(process.env))
  426. forkEnv.CONFIG_DIRECT_PATH = ConfigManager.getLauncherDirectory()
  427. // Start AssetExec to run validations and downloads in a forked process.
  428. aEx = cp.fork(path.join(__dirname, 'assets', 'js', 'assetexec.js'), [
  429. 'AssetGuard',
  430. ConfigManager.getCommonDirectory(),
  431. ConfigManager.getJavaExecutable()
  432. ], {
  433. env: forkEnv,
  434. stdio: 'pipe'
  435. })
  436. // Stdout
  437. aEx.stdio[1].setEncoding('utf8')
  438. aEx.stdio[1].on('data', (data) => {
  439. loggerAEx.log(data)
  440. })
  441. // Stderr
  442. aEx.stdio[2].setEncoding('utf8')
  443. aEx.stdio[2].on('data', (data) => {
  444. loggerAEx.log(data)
  445. })
  446. aEx.on('error', (err) => {
  447. loggerLaunchSuite.error('Error during launch', err)
  448. showLaunchFailure('Error During Launch', err.message || 'See console (CTRL + Shift + i) for more details.')
  449. })
  450. aEx.on('close', (code, signal) => {
  451. if(code !== 0){
  452. loggerLaunchSuite.error(`AssetExec exited with code ${code}, assuming error.`)
  453. showLaunchFailure('Error During Launch', 'See console (CTRL + Shift + i) for more details.')
  454. }
  455. })
  456. // Establish communications between the AssetExec and current process.
  457. aEx.on('message', (m) => {
  458. if(m.context === 'validate'){
  459. switch(m.data){
  460. case 'distribution':
  461. setLaunchPercentage(20, 100)
  462. loggerLaunchSuite.log('Validated distibution index.')
  463. setLaunchDetails('Loading version information..')
  464. break
  465. case 'version':
  466. setLaunchPercentage(40, 100)
  467. loggerLaunchSuite.log('Version data loaded.')
  468. setLaunchDetails('Validating asset integrity..')
  469. break
  470. case 'assets':
  471. setLaunchPercentage(60, 100)
  472. loggerLaunchSuite.log('Asset Validation Complete')
  473. setLaunchDetails('Validating library integrity..')
  474. break
  475. case 'libraries':
  476. setLaunchPercentage(80, 100)
  477. loggerLaunchSuite.log('Library validation complete.')
  478. setLaunchDetails('Validating miscellaneous file integrity..')
  479. break
  480. case 'files':
  481. setLaunchPercentage(100, 100)
  482. loggerLaunchSuite.log('File validation complete.')
  483. setLaunchDetails('Downloading files..')
  484. break
  485. }
  486. } else if(m.context === 'progress'){
  487. switch(m.data){
  488. case 'assets': {
  489. const perc = (m.value/m.total)*20
  490. setLaunchPercentage(40+perc, 100, parseInt(40+perc))
  491. break
  492. }
  493. case 'download':
  494. setDownloadPercentage(m.value, m.total, m.percent)
  495. break
  496. case 'extract': {
  497. // Show installing progress bar.
  498. remote.getCurrentWindow().setProgressBar(2)
  499. // Download done, extracting.
  500. const eLStr = 'Extracting libraries'
  501. let dotStr = ''
  502. setLaunchDetails(eLStr)
  503. progressListener = setInterval(() => {
  504. if(dotStr.length >= 3){
  505. dotStr = ''
  506. } else {
  507. dotStr += '.'
  508. }
  509. setLaunchDetails(eLStr + dotStr)
  510. }, 750)
  511. break
  512. }
  513. }
  514. } else if(m.context === 'complete'){
  515. switch(m.data){
  516. case 'download':
  517. // Download and extraction complete, remove the loading from the OS progress bar.
  518. remote.getCurrentWindow().setProgressBar(-1)
  519. if(progressListener != null){
  520. clearInterval(progressListener)
  521. progressListener = null
  522. }
  523. setLaunchDetails('Preparing to launch..')
  524. break
  525. }
  526. } else if(m.context === 'error'){
  527. switch(m.data){
  528. case 'download':
  529. loggerLaunchSuite.error('Error while downloading:', m.error)
  530. if(m.error.code === 'ENOENT'){
  531. showLaunchFailure(
  532. 'Download Error',
  533. 'Could not connect to the file server. Ensure that you are connected to the internet and try again.'
  534. )
  535. } else {
  536. showLaunchFailure(
  537. 'Download Error',
  538. 'Check the console (CTRL + Shift + i) for more details. Please try again.'
  539. )
  540. }
  541. remote.getCurrentWindow().setProgressBar(-1)
  542. // Disconnect from AssetExec
  543. aEx.disconnect()
  544. break
  545. }
  546. } else if(m.context === 'validateEverything'){
  547. let allGood = true
  548. // If these properties are not defined it's likely an error.
  549. if(m.result.forgeData == null || m.result.versionData == null){
  550. loggerLaunchSuite.error('Error during validation:', m.result)
  551. loggerLaunchSuite.error('Error during launch', m.result.error)
  552. showLaunchFailure('Error During Launch', 'Please check the console (CTRL + Shift + i) for more details.')
  553. allGood = false
  554. }
  555. forgeData = m.result.forgeData
  556. versionData = m.result.versionData
  557. if(login && allGood) {
  558. const authUser = ConfigManager.getSelectedAccount()
  559. loggerLaunchSuite.log(`Sending selected account (${authUser.displayName}) to ProcessBuilder.`)
  560. let pb = new ProcessBuilder(serv, versionData, forgeData, authUser, remote.app.getVersion())
  561. setLaunchDetails('Launching game..')
  562. // const SERVER_JOINED_REGEX = /\[.+\]: \[CHAT\] [a-zA-Z0-9_]{1,16} joined the game/
  563. const SERVER_JOINED_REGEX = new RegExp(`\\[.+\\]: \\[CHAT\\] ${authUser.displayName} joined the game`)
  564. const onLoadComplete = () => {
  565. toggleLaunchArea(false)
  566. if(hasRPC){
  567. DiscordWrapper.updateDetails('Loading game..')
  568. }
  569. proc.stdout.on('data', gameStateChange)
  570. proc.stdout.removeListener('data', tempListener)
  571. proc.stderr.removeListener('data', gameErrorListener)
  572. }
  573. const start = Date.now()
  574. // Attach a temporary listener to the client output.
  575. // Will wait for a certain bit of text meaning that
  576. // the client application has started, and we can hide
  577. // the progress bar stuff.
  578. const tempListener = function(data){
  579. if(GAME_LAUNCH_REGEX.test(data.trim())){
  580. const diff = Date.now()-start
  581. if(diff < MIN_LINGER) {
  582. setTimeout(onLoadComplete, MIN_LINGER-diff)
  583. } else {
  584. onLoadComplete()
  585. }
  586. }
  587. }
  588. // Listener for Discord RPC.
  589. const gameStateChange = function(data){
  590. data = data.trim()
  591. if(SERVER_JOINED_REGEX.test(data)){
  592. DiscordWrapper.updateDetails('Exploring the Realm!')
  593. } else if(GAME_JOINED_REGEX.test(data)){
  594. DiscordWrapper.updateDetails('Sailing to Westeros!')
  595. }
  596. }
  597. const gameErrorListener = function(data){
  598. data = data.trim()
  599. if(data.indexOf('Could not find or load main class net.minecraft.launchwrapper.Launch') > -1){
  600. loggerLaunchSuite.error('Game launch failed, LaunchWrapper was not downloaded properly.')
  601. 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.')
  602. }
  603. }
  604. try {
  605. // Build Minecraft process.
  606. proc = pb.build()
  607. // Bind listeners to stdout.
  608. proc.stdout.on('data', tempListener)
  609. proc.stderr.on('data', gameErrorListener)
  610. setLaunchDetails('Done. Enjoy the server!')
  611. // Init Discord Hook
  612. const distro = DistroManager.getDistribution()
  613. if(distro.discord != null && serv.discord != null){
  614. DiscordWrapper.initRPC(distro.discord, serv.discord)
  615. hasRPC = true
  616. proc.on('close', (code, signal) => {
  617. loggerLaunchSuite.log('Shutting down Discord Rich Presence..')
  618. DiscordWrapper.shutdownRPC()
  619. hasRPC = false
  620. proc = null
  621. })
  622. }
  623. } catch(err) {
  624. loggerLaunchSuite.error('Error during launch', err)
  625. showLaunchFailure('Error During Launch', 'Please check the console (CTRL + Shift + i) for more details.')
  626. }
  627. }
  628. // Disconnect from AssetExec
  629. aEx.disconnect()
  630. }
  631. })
  632. // Begin Validations
  633. // Validate Forge files.
  634. setLaunchDetails('Loading server information..')
  635. refreshDistributionIndex(true, (data) => {
  636. onDistroRefresh(data)
  637. serv = data.getServer(ConfigManager.getSelectedServer())
  638. aEx.send({task: 'execute', function: 'validateEverything', argsArr: [ConfigManager.getSelectedServer(), DistroManager.isDevMode()]})
  639. }, (err) => {
  640. loggerLaunchSuite.log('Error while fetching a fresh copy of the distribution index.', err)
  641. refreshDistributionIndex(false, (data) => {
  642. onDistroRefresh(data)
  643. serv = data.getServer(ConfigManager.getSelectedServer())
  644. aEx.send({task: 'execute', function: 'validateEverything', argsArr: [ConfigManager.getSelectedServer(), DistroManager.isDevMode()]})
  645. }, (err) => {
  646. loggerLaunchSuite.error('Unable to refresh distribution index.', err)
  647. if(DistroManager.getDistribution() == null){
  648. showLaunchFailure('Fatal Error', 'Could not load a copy of the distribution index. See the console (CTRL + Shift + i) for more details.')
  649. // Disconnect from AssetExec
  650. aEx.disconnect()
  651. } else {
  652. serv = data.getServer(ConfigManager.getSelectedServer())
  653. aEx.send({task: 'execute', function: 'validateEverything', argsArr: [ConfigManager.getSelectedServer(), DistroManager.isDevMode()]})
  654. }
  655. })
  656. })
  657. }
  658. /**
  659. * News Loading Functions
  660. */
  661. // DOM Cache
  662. const newsContent = document.getElementById('newsContent')
  663. const newsArticleTitle = document.getElementById('newsArticleTitle')
  664. const newsArticleDate = document.getElementById('newsArticleDate')
  665. const newsArticleAuthor = document.getElementById('newsArticleAuthor')
  666. const newsArticleComments = document.getElementById('newsArticleComments')
  667. const newsNavigationStatus = document.getElementById('newsNavigationStatus')
  668. const newsArticleContentScrollable = document.getElementById('newsArticleContentScrollable')
  669. const nELoadSpan = document.getElementById('nELoadSpan')
  670. // News slide caches.
  671. let newsActive = false
  672. let newsGlideCount = 0
  673. /**
  674. * Show the news UI via a slide animation.
  675. *
  676. * @param {boolean} up True to slide up, otherwise false.
  677. */
  678. function slide_(up){
  679. const lCUpper = document.querySelector('#landingContainer > #upper')
  680. const lCLLeft = document.querySelector('#landingContainer > #lower > #left')
  681. const lCLCenter = document.querySelector('#landingContainer > #lower > #center')
  682. const lCLRight = document.querySelector('#landingContainer > #lower > #right')
  683. const newsBtn = document.querySelector('#landingContainer > #lower > #center #content')
  684. const landingContainer = document.getElementById('landingContainer')
  685. const newsContainer = document.querySelector('#landingContainer > #newsContainer')
  686. newsGlideCount++
  687. if(up){
  688. lCUpper.style.top = '-200vh'
  689. lCLLeft.style.top = '-200vh'
  690. lCLCenter.style.top = '-200vh'
  691. lCLRight.style.top = '-200vh'
  692. newsBtn.style.top = '130vh'
  693. newsContainer.style.top = '0px'
  694. //date.toLocaleDateString('en-US', {month: 'short', day: 'numeric', year: 'numeric', hour: 'numeric', minute: 'numeric'})
  695. //landingContainer.style.background = 'rgba(29, 29, 29, 0.55)'
  696. landingContainer.style.background = 'rgba(0, 0, 0, 0.50)'
  697. setTimeout(() => {
  698. if(newsGlideCount === 1){
  699. lCLCenter.style.transition = 'none'
  700. newsBtn.style.transition = 'none'
  701. }
  702. newsGlideCount--
  703. }, 2000)
  704. } else {
  705. setTimeout(() => {
  706. newsGlideCount--
  707. }, 2000)
  708. landingContainer.style.background = null
  709. lCLCenter.style.transition = null
  710. newsBtn.style.transition = null
  711. newsContainer.style.top = '100%'
  712. lCUpper.style.top = '0px'
  713. lCLLeft.style.top = '0px'
  714. lCLCenter.style.top = '0px'
  715. lCLRight.style.top = '0px'
  716. newsBtn.style.top = '10px'
  717. }
  718. }
  719. // Bind news button.
  720. document.getElementById('newsButton').onclick = () => {
  721. // Toggle tabbing.
  722. if(newsActive){
  723. $('#landingContainer *').removeAttr('tabindex')
  724. $('#newsContainer *').attr('tabindex', '-1')
  725. } else {
  726. $('#landingContainer *').attr('tabindex', '-1')
  727. $('#newsContainer, #newsContainer *, #lower, #lower #center *').removeAttr('tabindex')
  728. if(newsAlertShown){
  729. $('#newsButtonAlert').fadeOut(2000)
  730. newsAlertShown = false
  731. ConfigManager.setNewsCacheDismissed(true)
  732. ConfigManager.save()
  733. }
  734. }
  735. slide_(!newsActive)
  736. newsActive = !newsActive
  737. }
  738. // Array to store article meta.
  739. let newsArr = null
  740. // News load animation listener.
  741. let newsLoadingListener = null
  742. /**
  743. * Set the news loading animation.
  744. *
  745. * @param {boolean} val True to set loading animation, otherwise false.
  746. */
  747. function setNewsLoading(val){
  748. if(val){
  749. const nLStr = 'Checking for News'
  750. let dotStr = '..'
  751. nELoadSpan.innerHTML = nLStr + dotStr
  752. newsLoadingListener = setInterval(() => {
  753. if(dotStr.length >= 3){
  754. dotStr = ''
  755. } else {
  756. dotStr += '.'
  757. }
  758. nELoadSpan.innerHTML = nLStr + dotStr
  759. }, 750)
  760. } else {
  761. if(newsLoadingListener != null){
  762. clearInterval(newsLoadingListener)
  763. newsLoadingListener = null
  764. }
  765. }
  766. }
  767. // Bind retry button.
  768. newsErrorRetry.onclick = () => {
  769. $('#newsErrorFailed').fadeOut(250, () => {
  770. initNews()
  771. $('#newsErrorLoading').fadeIn(250)
  772. })
  773. }
  774. newsArticleContentScrollable.onscroll = (e) => {
  775. if(e.target.scrollTop > Number.parseFloat($('.newsArticleSpacerTop').css('height'))){
  776. newsContent.setAttribute('scrolled', '')
  777. } else {
  778. newsContent.removeAttribute('scrolled')
  779. }
  780. }
  781. /**
  782. * Reload the news without restarting.
  783. *
  784. * @returns {Promise.<void>} A promise which resolves when the news
  785. * content has finished loading and transitioning.
  786. */
  787. function reloadNews(){
  788. return new Promise((resolve, reject) => {
  789. $('#newsContent').fadeOut(250, () => {
  790. $('#newsErrorLoading').fadeIn(250)
  791. initNews().then(() => {
  792. resolve()
  793. })
  794. })
  795. })
  796. }
  797. let newsAlertShown = false
  798. /**
  799. * Show the news alert indicating there is new news.
  800. */
  801. function showNewsAlert(){
  802. newsAlertShown = true
  803. $(newsButtonAlert).fadeIn(250)
  804. }
  805. /**
  806. * Initialize News UI. This will load the news and prepare
  807. * the UI accordingly.
  808. *
  809. * @returns {Promise.<void>} A promise which resolves when the news
  810. * content has finished loading and transitioning.
  811. */
  812. function initNews(){
  813. return new Promise((resolve, reject) => {
  814. setNewsLoading(true)
  815. let news = {}
  816. loadNews().then(news => {
  817. newsArr = news.articles || null
  818. if(newsArr == null){
  819. // News Loading Failed
  820. setNewsLoading(false)
  821. $('#newsErrorLoading').fadeOut(250, () => {
  822. $('#newsErrorFailed').fadeIn(250, () => {
  823. resolve()
  824. })
  825. })
  826. } else if(newsArr.length === 0) {
  827. // No News Articles
  828. setNewsLoading(false)
  829. ConfigManager.setNewsCache({
  830. date: null,
  831. content: null,
  832. dismissed: false
  833. })
  834. ConfigManager.save()
  835. $('#newsErrorLoading').fadeOut(250, () => {
  836. $('#newsErrorNone').fadeIn(250, () => {
  837. resolve()
  838. })
  839. })
  840. } else {
  841. // Success
  842. setNewsLoading(false)
  843. const lN = newsArr[0]
  844. const cached = ConfigManager.getNewsCache()
  845. let newHash = crypto.createHash('sha1').update(lN.content).digest('hex')
  846. let newDate = new Date(lN.date)
  847. let isNew = false
  848. if(cached.date != null && cached.content != null){
  849. if(new Date(cached.date) >= newDate){
  850. // Compare Content
  851. if(cached.content !== newHash){
  852. isNew = true
  853. showNewsAlert()
  854. } else {
  855. if(!cached.dismissed){
  856. isNew = true
  857. showNewsAlert()
  858. }
  859. }
  860. } else {
  861. isNew = true
  862. showNewsAlert()
  863. }
  864. } else {
  865. isNew = true
  866. showNewsAlert()
  867. }
  868. if(isNew){
  869. ConfigManager.setNewsCache({
  870. date: newDate.getTime(),
  871. content: newHash,
  872. dismissed: false
  873. })
  874. ConfigManager.save()
  875. }
  876. const switchHandler = (forward) => {
  877. let cArt = parseInt(newsContent.getAttribute('article'))
  878. let nxtArt = forward ? (cArt >= newsArr.length-1 ? 0 : cArt + 1) : (cArt <= 0 ? newsArr.length-1 : cArt - 1)
  879. displayArticle(newsArr[nxtArt], nxtArt+1)
  880. }
  881. document.getElementById('newsNavigateRight').onclick = () => { switchHandler(true) }
  882. document.getElementById('newsNavigateLeft').onclick = () => { switchHandler(false) }
  883. $('#newsErrorContainer').fadeOut(250, () => {
  884. displayArticle(newsArr[0], 1)
  885. $('#newsContent').fadeIn(250, () => {
  886. resolve()
  887. })
  888. })
  889. }
  890. })
  891. })
  892. }
  893. /**
  894. * Add keyboard controls to the news UI. Left and right arrows toggle
  895. * between articles. If you are on the landing page, the up arrow will
  896. * open the news UI.
  897. */
  898. document.addEventListener('keydown', (e) => {
  899. if(newsActive){
  900. if(e.key === 'ArrowRight' || e.key === 'ArrowLeft'){
  901. document.getElementById(e.key === 'ArrowRight' ? 'newsNavigateRight' : 'newsNavigateLeft').click()
  902. }
  903. // Interferes with scrolling an article using the down arrow.
  904. // Not sure of a straight forward solution at this point.
  905. // if(e.key === 'ArrowDown'){
  906. // document.getElementById('newsButton').click()
  907. // }
  908. } else {
  909. if(getCurrentView() === VIEWS.landing){
  910. if(e.key === 'ArrowUp'){
  911. document.getElementById('newsButton').click()
  912. }
  913. }
  914. }
  915. })
  916. /**
  917. * Display a news article on the UI.
  918. *
  919. * @param {Object} articleObject The article meta object.
  920. * @param {number} index The article index.
  921. */
  922. function displayArticle(articleObject, index){
  923. newsArticleTitle.innerHTML = articleObject.title
  924. newsArticleTitle.href = articleObject.link
  925. newsArticleAuthor.innerHTML = 'by ' + articleObject.author
  926. newsArticleDate.innerHTML = articleObject.date
  927. newsArticleComments.innerHTML = articleObject.comments
  928. newsArticleComments.href = articleObject.commentsLink
  929. newsArticleContentScrollable.innerHTML = '<div id="newsArticleContentWrapper"><div class="newsArticleSpacerTop"></div>' + articleObject.content + '<div class="newsArticleSpacerBot"></div></div>'
  930. Array.from(newsArticleContentScrollable.getElementsByClassName('bbCodeSpoilerButton')).forEach(v => {
  931. v.onclick = () => {
  932. const text = v.parentElement.getElementsByClassName('bbCodeSpoilerText')[0]
  933. text.style.display = text.style.display === 'block' ? 'none' : 'block'
  934. }
  935. })
  936. newsNavigationStatus.innerHTML = index + ' of ' + newsArr.length
  937. newsContent.setAttribute('article', index-1)
  938. }
  939. /**
  940. * Load news information from the RSS feed specified in the
  941. * distribution index.
  942. */
  943. function loadNews(){
  944. return new Promise((resolve, reject) => {
  945. const distroData = DistroManager.getDistribution()
  946. const newsFeed = distroData.getRSS()
  947. const newsHost = new URL(newsFeed).origin + '/'
  948. $.ajax({
  949. url: newsFeed,
  950. success: (data) => {
  951. const items = $(data).find('item')
  952. const articles = []
  953. for(let i=0; i<items.length; i++){
  954. // JQuery Element
  955. const el = $(items[i])
  956. // Resolve date.
  957. const date = new Date(el.find('pubDate').text()).toLocaleDateString('en-US', {month: 'short', day: 'numeric', year: 'numeric', hour: 'numeric', minute: 'numeric'})
  958. // Resolve comments.
  959. let comments = el.find('slash\\:comments').text() || '0'
  960. comments = comments + ' Comment' + (comments === '1' ? '' : 's')
  961. // Fix relative links in content.
  962. let content = el.find('content\\:encoded').text()
  963. let regex = /src="(?!http:\/\/|https:\/\/)(.+?)"/g
  964. let matches
  965. while((matches = regex.exec(content))){
  966. content = content.replace(`"${matches[1]}"`, `"${newsHost + matches[1]}"`)
  967. }
  968. let link = el.find('link').text()
  969. let title = el.find('title').text()
  970. let author = el.find('dc\\:creator').text()
  971. // Generate article.
  972. articles.push(
  973. {
  974. link,
  975. title,
  976. date,
  977. author,
  978. content,
  979. comments,
  980. commentsLink: link + '#comments'
  981. }
  982. )
  983. }
  984. resolve({
  985. articles
  986. })
  987. },
  988. timeout: 2500
  989. }).catch(err => {
  990. resolve({
  991. articles: null
  992. })
  993. })
  994. })
  995. }