landing.js 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143
  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. const SERVER_JOINED_REGEX = /\[.+\]: \[CHAT\] [a-zA-Z0-9_]{1,16} joined the game/
  403. const GAME_JOINED_REGEX = /\[.+\]: Skipping bad option: lastServer:/
  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 onLoadComplete = () => {
  563. toggleLaunchArea(false)
  564. if(hasRPC){
  565. DiscordWrapper.updateDetails('Loading game..')
  566. }
  567. proc.stdout.on('data', gameStateChange)
  568. proc.stdout.removeListener('data', tempListener)
  569. proc.stderr.removeListener('data', gameErrorListener)
  570. }
  571. const start = Date.now()
  572. // Attach a temporary listener to the client output.
  573. // Will wait for a certain bit of text meaning that
  574. // the client application has started, and we can hide
  575. // the progress bar stuff.
  576. const tempListener = function(data){
  577. if(GAME_LAUNCH_REGEX.test(data.trim())){
  578. const diff = Date.now()-start
  579. if(diff < MIN_LINGER) {
  580. setTimeout(onLoadComplete, MIN_LINGER-diff)
  581. } else {
  582. onLoadComplete()
  583. }
  584. }
  585. }
  586. // Listener for Discord RPC.
  587. const gameStateChange = function(data){
  588. data = data.trim()
  589. if(SERVER_JOINED_REGEX.test(data)){
  590. DiscordWrapper.updateDetails('Exploring the Realm!')
  591. } else if(GAME_JOINED_REGEX.test(data)){
  592. DiscordWrapper.updateDetails('Sailing to Westeros!')
  593. }
  594. }
  595. const gameErrorListener = function(data){
  596. data = data.trim()
  597. if(data.indexOf('Could not find or load main class net.minecraft.launchwrapper.Launch') > -1){
  598. loggerLaunchSuite.error('Game launch failed, LaunchWrapper was not downloaded properly.')
  599. 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.')
  600. }
  601. }
  602. try {
  603. // Build Minecraft process.
  604. proc = pb.build()
  605. // Bind listeners to stdout.
  606. proc.stdout.on('data', tempListener)
  607. proc.stderr.on('data', gameErrorListener)
  608. setLaunchDetails('Done. Enjoy the server!')
  609. // Init Discord Hook
  610. const distro = DistroManager.getDistribution()
  611. if(distro.discord != null && serv.discord != null){
  612. DiscordWrapper.initRPC(distro.discord, serv.discord)
  613. hasRPC = true
  614. proc.on('close', (code, signal) => {
  615. loggerLaunchSuite.log('Shutting down Discord Rich Presence..')
  616. DiscordWrapper.shutdownRPC()
  617. hasRPC = false
  618. proc = null
  619. })
  620. }
  621. } catch(err) {
  622. loggerLaunchSuite.error('Error during launch', err)
  623. showLaunchFailure('Error During Launch', 'Please check the console (CTRL + Shift + i) for more details.')
  624. }
  625. }
  626. // Disconnect from AssetExec
  627. aEx.disconnect()
  628. }
  629. })
  630. // Begin Validations
  631. // Validate Forge files.
  632. setLaunchDetails('Loading server information..')
  633. refreshDistributionIndex(true, (data) => {
  634. onDistroRefresh(data)
  635. serv = data.getServer(ConfigManager.getSelectedServer())
  636. aEx.send({task: 'execute', function: 'validateEverything', argsArr: [ConfigManager.getSelectedServer(), DistroManager.isDevMode()]})
  637. }, (err) => {
  638. loggerLaunchSuite.log('Error while fetching a fresh copy of the distribution index.', err)
  639. refreshDistributionIndex(false, (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.error('Unable to refresh distribution index.', err)
  645. if(DistroManager.getDistribution() == null){
  646. showLaunchFailure('Fatal Error', 'Could not load a copy of the distribution index. See the console (CTRL + Shift + i) for more details.')
  647. // Disconnect from AssetExec
  648. aEx.disconnect()
  649. } else {
  650. serv = data.getServer(ConfigManager.getSelectedServer())
  651. aEx.send({task: 'execute', function: 'validateEverything', argsArr: [ConfigManager.getSelectedServer(), DistroManager.isDevMode()]})
  652. }
  653. })
  654. })
  655. }
  656. /**
  657. * News Loading Functions
  658. */
  659. // DOM Cache
  660. const newsContent = document.getElementById('newsContent')
  661. const newsArticleTitle = document.getElementById('newsArticleTitle')
  662. const newsArticleDate = document.getElementById('newsArticleDate')
  663. const newsArticleAuthor = document.getElementById('newsArticleAuthor')
  664. const newsArticleComments = document.getElementById('newsArticleComments')
  665. const newsNavigationStatus = document.getElementById('newsNavigationStatus')
  666. const newsArticleContentScrollable = document.getElementById('newsArticleContentScrollable')
  667. const nELoadSpan = document.getElementById('nELoadSpan')
  668. // News slide caches.
  669. let newsActive = false
  670. let newsGlideCount = 0
  671. /**
  672. * Show the news UI via a slide animation.
  673. *
  674. * @param {boolean} up True to slide up, otherwise false.
  675. */
  676. function slide_(up){
  677. const lCUpper = document.querySelector('#landingContainer > #upper')
  678. const lCLLeft = document.querySelector('#landingContainer > #lower > #left')
  679. const lCLCenter = document.querySelector('#landingContainer > #lower > #center')
  680. const lCLRight = document.querySelector('#landingContainer > #lower > #right')
  681. const newsBtn = document.querySelector('#landingContainer > #lower > #center #content')
  682. const landingContainer = document.getElementById('landingContainer')
  683. const newsContainer = document.querySelector('#landingContainer > #newsContainer')
  684. newsGlideCount++
  685. if(up){
  686. lCUpper.style.top = '-200vh'
  687. lCLLeft.style.top = '-200vh'
  688. lCLCenter.style.top = '-200vh'
  689. lCLRight.style.top = '-200vh'
  690. newsBtn.style.top = '130vh'
  691. newsContainer.style.top = '0px'
  692. //date.toLocaleDateString('en-US', {month: 'short', day: 'numeric', year: 'numeric', hour: 'numeric', minute: 'numeric'})
  693. //landingContainer.style.background = 'rgba(29, 29, 29, 0.55)'
  694. landingContainer.style.background = 'rgba(0, 0, 0, 0.50)'
  695. setTimeout(() => {
  696. if(newsGlideCount === 1){
  697. lCLCenter.style.transition = 'none'
  698. newsBtn.style.transition = 'none'
  699. }
  700. newsGlideCount--
  701. }, 2000)
  702. } else {
  703. setTimeout(() => {
  704. newsGlideCount--
  705. }, 2000)
  706. landingContainer.style.background = null
  707. lCLCenter.style.transition = null
  708. newsBtn.style.transition = null
  709. newsContainer.style.top = '100%'
  710. lCUpper.style.top = '0px'
  711. lCLLeft.style.top = '0px'
  712. lCLCenter.style.top = '0px'
  713. lCLRight.style.top = '0px'
  714. newsBtn.style.top = '10px'
  715. }
  716. }
  717. // Bind news button.
  718. document.getElementById('newsButton').onclick = () => {
  719. // Toggle tabbing.
  720. if(newsActive){
  721. $('#landingContainer *').removeAttr('tabindex')
  722. $('#newsContainer *').attr('tabindex', '-1')
  723. } else {
  724. $('#landingContainer *').attr('tabindex', '-1')
  725. $('#newsContainer, #newsContainer *, #lower, #lower #center *').removeAttr('tabindex')
  726. if(newsAlertShown){
  727. $('#newsButtonAlert').fadeOut(2000)
  728. newsAlertShown = false
  729. ConfigManager.setNewsCacheDismissed(true)
  730. ConfigManager.save()
  731. }
  732. }
  733. slide_(!newsActive)
  734. newsActive = !newsActive
  735. }
  736. // Array to store article meta.
  737. let newsArr = null
  738. // News load animation listener.
  739. let newsLoadingListener = null
  740. /**
  741. * Set the news loading animation.
  742. *
  743. * @param {boolean} val True to set loading animation, otherwise false.
  744. */
  745. function setNewsLoading(val){
  746. if(val){
  747. const nLStr = 'Checking for News'
  748. let dotStr = '..'
  749. nELoadSpan.innerHTML = nLStr + dotStr
  750. newsLoadingListener = setInterval(() => {
  751. if(dotStr.length >= 3){
  752. dotStr = ''
  753. } else {
  754. dotStr += '.'
  755. }
  756. nELoadSpan.innerHTML = nLStr + dotStr
  757. }, 750)
  758. } else {
  759. if(newsLoadingListener != null){
  760. clearInterval(newsLoadingListener)
  761. newsLoadingListener = null
  762. }
  763. }
  764. }
  765. // Bind retry button.
  766. newsErrorRetry.onclick = () => {
  767. $('#newsErrorFailed').fadeOut(250, () => {
  768. initNews()
  769. $('#newsErrorLoading').fadeIn(250)
  770. })
  771. }
  772. newsArticleContentScrollable.onscroll = (e) => {
  773. if(e.target.scrollTop > Number.parseFloat($('.newsArticleSpacerTop').css('height'))){
  774. newsContent.setAttribute('scrolled', '')
  775. } else {
  776. newsContent.removeAttribute('scrolled')
  777. }
  778. }
  779. /**
  780. * Reload the news without restarting.
  781. *
  782. * @returns {Promise.<void>} A promise which resolves when the news
  783. * content has finished loading and transitioning.
  784. */
  785. function reloadNews(){
  786. return new Promise((resolve, reject) => {
  787. $('#newsContent').fadeOut(250, () => {
  788. $('#newsErrorLoading').fadeIn(250)
  789. initNews().then(() => {
  790. resolve()
  791. })
  792. })
  793. })
  794. }
  795. let newsAlertShown = false
  796. /**
  797. * Show the news alert indicating there is new news.
  798. */
  799. function showNewsAlert(){
  800. newsAlertShown = true
  801. $(newsButtonAlert).fadeIn(250)
  802. }
  803. /**
  804. * Initialize News UI. This will load the news and prepare
  805. * the UI accordingly.
  806. *
  807. * @returns {Promise.<void>} A promise which resolves when the news
  808. * content has finished loading and transitioning.
  809. */
  810. function initNews(){
  811. return new Promise((resolve, reject) => {
  812. setNewsLoading(true)
  813. let news = {}
  814. loadNews().then(news => {
  815. newsArr = news.articles || null
  816. if(newsArr == null){
  817. // News Loading Failed
  818. setNewsLoading(false)
  819. $('#newsErrorLoading').fadeOut(250, () => {
  820. $('#newsErrorFailed').fadeIn(250, () => {
  821. resolve()
  822. })
  823. })
  824. } else if(newsArr.length === 0) {
  825. // No News Articles
  826. setNewsLoading(false)
  827. ConfigManager.setNewsCache({
  828. date: null,
  829. content: null,
  830. dismissed: false
  831. })
  832. ConfigManager.save()
  833. $('#newsErrorLoading').fadeOut(250, () => {
  834. $('#newsErrorNone').fadeIn(250, () => {
  835. resolve()
  836. })
  837. })
  838. } else {
  839. // Success
  840. setNewsLoading(false)
  841. const lN = newsArr[0]
  842. const cached = ConfigManager.getNewsCache()
  843. let newHash = crypto.createHash('sha1').update(lN.content).digest('hex')
  844. let newDate = new Date(lN.date)
  845. let isNew = false
  846. if(cached.date != null && cached.content != null){
  847. if(new Date(cached.date) >= newDate){
  848. // Compare Content
  849. if(cached.content !== newHash){
  850. isNew = true
  851. showNewsAlert()
  852. } else {
  853. if(!cached.dismissed){
  854. isNew = true
  855. showNewsAlert()
  856. }
  857. }
  858. } else {
  859. isNew = true
  860. showNewsAlert()
  861. }
  862. } else {
  863. isNew = true
  864. showNewsAlert()
  865. }
  866. if(isNew){
  867. ConfigManager.setNewsCache({
  868. date: newDate.getTime(),
  869. content: newHash,
  870. dismissed: false
  871. })
  872. ConfigManager.save()
  873. }
  874. const switchHandler = (forward) => {
  875. let cArt = parseInt(newsContent.getAttribute('article'))
  876. let nxtArt = forward ? (cArt >= newsArr.length-1 ? 0 : cArt + 1) : (cArt <= 0 ? newsArr.length-1 : cArt - 1)
  877. displayArticle(newsArr[nxtArt], nxtArt+1)
  878. }
  879. document.getElementById('newsNavigateRight').onclick = () => { switchHandler(true) }
  880. document.getElementById('newsNavigateLeft').onclick = () => { switchHandler(false) }
  881. $('#newsErrorContainer').fadeOut(250, () => {
  882. displayArticle(newsArr[0], 1)
  883. $('#newsContent').fadeIn(250, () => {
  884. resolve()
  885. })
  886. })
  887. }
  888. })
  889. })
  890. }
  891. /**
  892. * Add keyboard controls to the news UI. Left and right arrows toggle
  893. * between articles. If you are on the landing page, the up arrow will
  894. * open the news UI.
  895. */
  896. document.addEventListener('keydown', (e) => {
  897. if(newsActive){
  898. if(e.key === 'ArrowRight' || e.key === 'ArrowLeft'){
  899. document.getElementById(e.key === 'ArrowRight' ? 'newsNavigateRight' : 'newsNavigateLeft').click()
  900. }
  901. // Interferes with scrolling an article using the down arrow.
  902. // Not sure of a straight forward solution at this point.
  903. // if(e.key === 'ArrowDown'){
  904. // document.getElementById('newsButton').click()
  905. // }
  906. } else {
  907. if(getCurrentView() === VIEWS.landing){
  908. if(e.key === 'ArrowUp'){
  909. document.getElementById('newsButton').click()
  910. }
  911. }
  912. }
  913. })
  914. /**
  915. * Display a news article on the UI.
  916. *
  917. * @param {Object} articleObject The article meta object.
  918. * @param {number} index The article index.
  919. */
  920. function displayArticle(articleObject, index){
  921. newsArticleTitle.innerHTML = articleObject.title
  922. newsArticleTitle.href = articleObject.link
  923. newsArticleAuthor.innerHTML = 'by ' + articleObject.author
  924. newsArticleDate.innerHTML = articleObject.date
  925. newsArticleComments.innerHTML = articleObject.comments
  926. newsArticleComments.href = articleObject.commentsLink
  927. newsArticleContentScrollable.innerHTML = '<div id="newsArticleContentWrapper"><div class="newsArticleSpacerTop"></div>' + articleObject.content + '<div class="newsArticleSpacerBot"></div></div>'
  928. Array.from(newsArticleContentScrollable.getElementsByClassName('bbCodeSpoilerButton')).forEach(v => {
  929. v.onclick = () => {
  930. const text = v.parentElement.getElementsByClassName('bbCodeSpoilerText')[0]
  931. text.style.display = text.style.display === 'block' ? 'none' : 'block'
  932. }
  933. })
  934. newsNavigationStatus.innerHTML = index + ' of ' + newsArr.length
  935. newsContent.setAttribute('article', index-1)
  936. }
  937. /**
  938. * Load news information from the RSS feed specified in the
  939. * distribution index.
  940. */
  941. function loadNews(){
  942. return new Promise((resolve, reject) => {
  943. const distroData = DistroManager.getDistribution()
  944. const newsFeed = distroData.getRSS()
  945. const newsHost = new URL(newsFeed).origin + '/'
  946. $.ajax({
  947. url: newsFeed,
  948. success: (data) => {
  949. const items = $(data).find('item')
  950. const articles = []
  951. for(let i=0; i<items.length; i++){
  952. // JQuery Element
  953. const el = $(items[i])
  954. // Resolve date.
  955. const date = new Date(el.find('pubDate').text()).toLocaleDateString('en-US', {month: 'short', day: 'numeric', year: 'numeric', hour: 'numeric', minute: 'numeric'})
  956. // Resolve comments.
  957. let comments = el.find('slash\\:comments').text() || '0'
  958. comments = comments + ' Comment' + (comments === '1' ? '' : 's')
  959. // Fix relative links in content.
  960. let content = el.find('content\\:encoded').text()
  961. let regex = /src="(?!http:\/\/|https:\/\/)(.+?)"/g
  962. let matches
  963. while((matches = regex.exec(content))){
  964. content = content.replace(`"${matches[1]}"`, `"${newsHost + matches[1]}"`)
  965. }
  966. let link = el.find('link').text()
  967. let title = el.find('title').text()
  968. let author = el.find('dc\\:creator').text()
  969. // Generate article.
  970. articles.push(
  971. {
  972. link,
  973. title,
  974. date,
  975. author,
  976. content,
  977. comments,
  978. commentsLink: link + '#comments'
  979. }
  980. )
  981. }
  982. resolve({
  983. articles
  984. })
  985. },
  986. timeout: 2500
  987. }).catch(err => {
  988. resolve({
  989. articles: null
  990. })
  991. })
  992. })
  993. }