landing.js 39 KB

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