landing.js 41 KB

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