landing.js 38 KB

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