landing.js 37 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057
  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. case 'java':
  334. // Download & extraction complete, remove the loading from the OS progress bar.
  335. remote.getCurrentWindow().setProgressBar(-1)
  336. // Extraction completed successfully.
  337. ConfigManager.setJavaExecutable(m.args[0])
  338. ConfigManager.save()
  339. if(extractListener != null){
  340. clearInterval(extractListener)
  341. extractListener = null
  342. }
  343. setLaunchDetails('Java Installed!')
  344. if(launchAfter){
  345. dlAsync()
  346. }
  347. sysAEx.disconnect()
  348. break
  349. }
  350. }
  351. })
  352. // Begin system Java scan.
  353. setLaunchDetails('Checking system info..')
  354. sysAEx.send({task: 'execute', function: 'validateJava', argsArr: [ConfigManager.getLauncherDirectory()]})
  355. }
  356. // Keep reference to Minecraft Process
  357. let proc
  358. // Is DiscordRPC enabled
  359. let hasRPC = false
  360. // Joined server regex
  361. 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
  362. const gameJoined = /\[[0-2][0-9]:[0-6][0-9]:[0-6][0-9]\] \[Client thread\/WARN\]: Skipping bad option: lastServer:/g
  363. const gameJoined2 = /\[[0-2][0-9]:[0-6][0-9]:[0-6][0-9]\] \[Client thread\/INFO\]: Created: \d+x\d+ textures-atlas/g
  364. let aEx
  365. let serv
  366. let versionData
  367. let forgeData
  368. let progressListener
  369. function dlAsync(login = true){
  370. // Login parameter is temporary for debug purposes. Allows testing the validation/downloads without
  371. // launching the game.
  372. if(login) {
  373. if(ConfigManager.getSelectedAccount() == null){
  374. console.error('login first.')
  375. //in devtools AuthManager.addAccount(username, pass)
  376. return
  377. }
  378. }
  379. setLaunchDetails('Please wait..')
  380. toggleLaunchArea(true)
  381. setLaunchPercentage(0, 100)
  382. // Start AssetExec to run validations and downloads in a forked process.
  383. aEx = cp.fork(path.join(__dirname, 'assets', 'js', 'assetexec.js'), [
  384. ConfigManager.getCommonDirectory(),
  385. ConfigManager.getJavaExecutable()
  386. ], {
  387. stdio: 'pipe'
  388. })
  389. // Stdout
  390. aEx.stdio[1].on('data', (data) => {
  391. console.log('%c[AEx]', 'color: #353232; font-weight: bold', data.toString('utf-8'))
  392. })
  393. // Stderr
  394. aEx.stdio[2].on('data', (data) => {
  395. console.log('%c[AEx]', 'color: #353232; font-weight: bold', data.toString('utf-8'))
  396. })
  397. // Establish communications between the AssetExec and current process.
  398. aEx.on('message', (m) => {
  399. if(m.context === 'validate'){
  400. switch(m.data){
  401. case 'distribution':
  402. setLaunchPercentage(20, 100)
  403. console.log('Validated distibution index.')
  404. setLaunchDetails('Loading version information..')
  405. break
  406. case 'version':
  407. setLaunchPercentage(40, 100)
  408. console.log('Version data loaded.')
  409. setLaunchDetails('Validating asset integrity..')
  410. break
  411. case 'assets':
  412. setLaunchPercentage(60, 100)
  413. console.log('Asset Validation Complete')
  414. setLaunchDetails('Validating library integrity..')
  415. break
  416. case 'libraries':
  417. setLaunchPercentage(80, 100)
  418. console.log('Library validation complete.')
  419. setLaunchDetails('Validating miscellaneous file integrity..')
  420. break
  421. case 'files':
  422. setLaunchPercentage(100, 100)
  423. console.log('File validation complete.')
  424. setLaunchDetails('Downloading files..')
  425. break
  426. }
  427. } else if(m.context === 'progress'){
  428. switch(m.data){
  429. case 'assets':
  430. const perc = (m.value/m.total)*20
  431. setLaunchPercentage(40+perc, 100, parseInt(40+perc))
  432. break
  433. case 'download':
  434. setDownloadPercentage(m.value, m.total, m.percent)
  435. break
  436. case 'extract':
  437. // Show installing progress bar.
  438. remote.getCurrentWindow().setProgressBar(2)
  439. // Download done, extracting.
  440. const eLStr = 'Extracting libraries'
  441. let dotStr = ''
  442. setLaunchDetails(eLStr)
  443. progressListener = setInterval(() => {
  444. if(dotStr.length >= 3){
  445. dotStr = ''
  446. } else {
  447. dotStr += '.'
  448. }
  449. setLaunchDetails(eLStr + dotStr)
  450. }, 750)
  451. break
  452. }
  453. } else if(m.context === 'complete'){
  454. switch(m.data){
  455. case 'download':
  456. // Download and extraction complete, remove the loading from the OS progress bar.
  457. remote.getCurrentWindow().setProgressBar(-1)
  458. if(progressListener != null){
  459. clearInterval(progressListener)
  460. progressListener = null
  461. }
  462. setLaunchDetails('Preparing to launch..')
  463. break
  464. }
  465. } else if(m.context === 'error'){
  466. switch(m.data){
  467. case 'download':
  468. console.error(m.error)
  469. if(m.error.code === 'ENOENT'){
  470. setOverlayContent(
  471. 'Download Error',
  472. 'Could not connect to the file server. Ensure that you are connected to the internet and try again.',
  473. 'Okay'
  474. )
  475. setOverlayHandler(null)
  476. } else {
  477. setOverlayContent(
  478. 'Download Error',
  479. 'Check the console for more details. Please try again.',
  480. 'Okay'
  481. )
  482. setOverlayHandler(null)
  483. }
  484. remote.getCurrentWindow().setProgressBar(-1)
  485. toggleOverlay(true)
  486. toggleLaunchArea(false)
  487. // Disconnect from AssetExec
  488. aEx.disconnect()
  489. break
  490. }
  491. } else if(m.context === 'validateEverything'){
  492. forgeData = m.result.forgeData
  493. versionData = m.result.versionData
  494. if(login) {
  495. const authUser = ConfigManager.getSelectedAccount()
  496. console.log('authu', authUser)
  497. let pb = new ProcessBuilder(serv, versionData, forgeData, authUser)
  498. setLaunchDetails('Launching game..')
  499. try {
  500. // Build Minecraft process.
  501. proc = pb.build()
  502. setLaunchDetails('Done. Enjoy the server!')
  503. // Attach a temporary listener to the client output.
  504. // Will wait for a certain bit of text meaning that
  505. // the client application has started, and we can hide
  506. // the progress bar stuff.
  507. const tempListener = function(data){
  508. if(data.indexOf('[Client thread/INFO]: -- System Details --') > -1){
  509. toggleLaunchArea(false)
  510. if(hasRPC){
  511. DiscordWrapper.updateDetails('Loading game..')
  512. }
  513. proc.stdout.removeListener('data', tempListener)
  514. }
  515. }
  516. // Listener for Discord RPC.
  517. const gameStateChange = function(data){
  518. if(servJoined.test(data)){
  519. DiscordWrapper.updateDetails('Exploring the Realm!')
  520. } else if(gameJoined.test(data)){
  521. DiscordWrapper.updateDetails('Sailing to Westeros!')
  522. }
  523. }
  524. // Bind listeners to stdout.
  525. proc.stdout.on('data', tempListener)
  526. proc.stdout.on('data', gameStateChange)
  527. // Init Discord Hook
  528. const distro = DistroManager.getDistribution()
  529. if(distro.discord != null && serv.discord != null){
  530. DiscordWrapper.initRPC(distro.discord, serv.discord)
  531. hasRPC = true
  532. proc.on('close', (code, signal) => {
  533. console.log('Shutting down Discord Rich Presence..')
  534. DiscordWrapper.shutdownRPC()
  535. hasRPC = false
  536. proc = null
  537. })
  538. }
  539. } catch(err) {
  540. console.error('Error during launch', err)
  541. setOverlayContent(
  542. 'Error During Launch',
  543. 'Please check the console for more details.',
  544. 'Okay'
  545. )
  546. setOverlayHandler(null)
  547. toggleOverlay(true)
  548. toggleLaunchArea(false)
  549. }
  550. }
  551. // Disconnect from AssetExec
  552. aEx.disconnect()
  553. }
  554. })
  555. // Begin Validations
  556. // Validate Forge files.
  557. setLaunchDetails('Loading server information..')
  558. refreshDistributionIndex(true, (data) => {
  559. onDistroRefresh(data)
  560. serv = data.getServer(ConfigManager.getSelectedServer())
  561. aEx.send({task: 'execute', function: 'validateEverything', argsArr: [ConfigManager.getSelectedServer(), DistroManager.isDevMode()]})
  562. }, (err) => {
  563. console.log(err)
  564. refreshDistributionIndex(false, (data) => {
  565. onDistroRefresh(data)
  566. serv = data.getServer(ConfigManager.getSelectedServer())
  567. aEx.send({task: 'execute', function: 'validateEverything', argsArr: [ConfigManager.getSelectedServer(), DistroManager.isDevMode()]})
  568. }, (err) => {
  569. console.error('Unable to refresh distribution index.', err)
  570. if(DistroManager.getDistribution() == null){
  571. setOverlayContent(
  572. 'Fatal Error',
  573. 'Could not load a copy of the distribution index. See the console for more details.',
  574. 'Okay'
  575. )
  576. setOverlayHandler(null)
  577. toggleOverlay(true)
  578. toggleLaunchArea(false)
  579. // Disconnect from AssetExec
  580. aEx.disconnect()
  581. } else {
  582. serv = data.getServer(ConfigManager.getSelectedServer())
  583. aEx.send({task: 'execute', function: 'validateEverything', argsArr: [ConfigManager.getSelectedServer(), DistroManager.isDevMode()]})
  584. }
  585. })
  586. })
  587. }
  588. /**
  589. * News Loading Functions
  590. */
  591. // DOM Cache
  592. const newsContent = document.getElementById('newsContent')
  593. const newsArticleTitle = document.getElementById('newsArticleTitle')
  594. const newsArticleDate = document.getElementById('newsArticleDate')
  595. const newsArticleAuthor = document.getElementById('newsArticleAuthor')
  596. const newsArticleComments = document.getElementById('newsArticleComments')
  597. const newsNavigationStatus = document.getElementById('newsNavigationStatus')
  598. const newsArticleContentScrollable = document.getElementById('newsArticleContentScrollable')
  599. const nELoadSpan = document.getElementById('nELoadSpan')
  600. // News slide caches.
  601. let newsActive = false
  602. let newsGlideCount = 0
  603. /**
  604. * Show the news UI via a slide animation.
  605. *
  606. * @param {boolean} up True to slide up, otherwise false.
  607. */
  608. function slide_(up){
  609. const lCUpper = document.querySelector('#landingContainer > #upper')
  610. const lCLLeft = document.querySelector('#landingContainer > #lower > #left')
  611. const lCLCenter = document.querySelector('#landingContainer > #lower > #center')
  612. const lCLRight = document.querySelector('#landingContainer > #lower > #right')
  613. const newsBtn = document.querySelector('#landingContainer > #lower > #center #content')
  614. const landingContainer = document.getElementById('landingContainer')
  615. const newsContainer = document.querySelector('#landingContainer > #newsContainer')
  616. newsGlideCount++
  617. if(up){
  618. lCUpper.style.top = '-200vh'
  619. lCLLeft.style.top = '-200vh'
  620. lCLCenter.style.top = '-200vh'
  621. lCLRight.style.top = '-200vh'
  622. newsBtn.style.top = '130vh'
  623. newsContainer.style.top = '0px'
  624. //date.toLocaleDateString('en-US', {month: 'short', day: 'numeric', year: 'numeric', hour: 'numeric', minute: 'numeric'})
  625. //landingContainer.style.background = 'rgba(29, 29, 29, 0.55)'
  626. landingContainer.style.background = 'rgba(0, 0, 0, 0.50)'
  627. setTimeout(() => {
  628. if(newsGlideCount === 1){
  629. lCLCenter.style.transition = 'none'
  630. newsBtn.style.transition = 'none'
  631. }
  632. newsGlideCount--
  633. }, 2000)
  634. } else {
  635. setTimeout(() => {
  636. newsGlideCount--
  637. }, 2000)
  638. landingContainer.style.background = null
  639. lCLCenter.style.transition = null
  640. newsBtn.style.transition = null
  641. newsContainer.style.top = '100%'
  642. lCUpper.style.top = '0px'
  643. lCLLeft.style.top = '0px'
  644. lCLCenter.style.top = '0px'
  645. lCLRight.style.top = '0px'
  646. newsBtn.style.top = '10px'
  647. }
  648. }
  649. // Bind news button.
  650. document.getElementById('newsButton').onclick = () => {
  651. // Toggle tabbing.
  652. if(newsActive){
  653. $('#landingContainer *').removeAttr('tabindex')
  654. $('#newsContainer *').attr('tabindex', '-1')
  655. } else {
  656. $('#landingContainer *').attr('tabindex', '-1')
  657. $('#newsContainer, #newsContainer *, #lower, #lower #center *').removeAttr('tabindex')
  658. if(newsAlertShown){
  659. $('#newsButtonAlert').fadeOut(2000)
  660. newsAlertShown = false
  661. ConfigManager.setNewsCacheDismissed(true)
  662. ConfigManager.save()
  663. }
  664. }
  665. slide_(!newsActive)
  666. newsActive = !newsActive
  667. }
  668. // Array to store article meta.
  669. let newsArr = null
  670. // News load animation listener.
  671. let newsLoadingListener = null
  672. /**
  673. * Set the news loading animation.
  674. *
  675. * @param {boolean} val True to set loading animation, otherwise false.
  676. */
  677. function setNewsLoading(val){
  678. if(val){
  679. const nLStr = 'Checking for News'
  680. let dotStr = '..'
  681. nELoadSpan.innerHTML = nLStr + dotStr
  682. newsLoadingListener = setInterval(() => {
  683. if(dotStr.length >= 3){
  684. dotStr = ''
  685. } else {
  686. dotStr += '.'
  687. }
  688. nELoadSpan.innerHTML = nLStr + dotStr
  689. }, 750)
  690. } else {
  691. if(newsLoadingListener != null){
  692. clearInterval(newsLoadingListener)
  693. newsLoadingListener = null
  694. }
  695. }
  696. }
  697. // Bind retry button.
  698. newsErrorRetry.onclick = () => {
  699. $('#newsErrorFailed').fadeOut(250, () => {
  700. initNews()
  701. $('#newsErrorLoading').fadeIn(250)
  702. })
  703. }
  704. newsArticleContentScrollable.onscroll = (e) => {
  705. if(e.target.scrollTop > Number.parseFloat($('.newsArticleSpacerTop').css('height'))){
  706. newsContent.setAttribute('scrolled', '')
  707. } else {
  708. newsContent.removeAttribute('scrolled')
  709. }
  710. }
  711. /**
  712. * Reload the news without restarting.
  713. *
  714. * @returns {Promise.<void>} A promise which resolves when the news
  715. * content has finished loading and transitioning.
  716. */
  717. function reloadNews(){
  718. return new Promise((resolve, reject) => {
  719. $('#newsContent').fadeOut(250, () => {
  720. $('#newsErrorLoading').fadeIn(250)
  721. initNews().then(() => {
  722. resolve()
  723. })
  724. })
  725. })
  726. }
  727. let newsAlertShown = false
  728. /**
  729. * Show the news alert indicating there is new news.
  730. */
  731. function showNewsAlert(){
  732. newsAlertShown = true
  733. $(newsButtonAlert).fadeIn(250)
  734. }
  735. /**
  736. * Initialize News UI. This will load the news and prepare
  737. * the UI accordingly.
  738. *
  739. * @returns {Promise.<void>} A promise which resolves when the news
  740. * content has finished loading and transitioning.
  741. */
  742. function initNews(){
  743. return new Promise((resolve, reject) => {
  744. setNewsLoading(true)
  745. let news = {}
  746. loadNews().then(news => {
  747. newsArr = news.articles || null
  748. if(newsArr == null){
  749. // News Loading Failed
  750. setNewsLoading(false)
  751. $('#newsErrorLoading').fadeOut(250, () => {
  752. $('#newsErrorFailed').fadeIn(250, () => {
  753. resolve()
  754. })
  755. })
  756. } else if(newsArr.length === 0) {
  757. // No News Articles
  758. setNewsLoading(false)
  759. ConfigManager.setNewsCache({
  760. date: null,
  761. content: null,
  762. dismissed: false
  763. })
  764. ConfigManager.save()
  765. $('#newsErrorLoading').fadeOut(250, () => {
  766. $('#newsErrorNone').fadeIn(250, () => {
  767. resolve()
  768. })
  769. })
  770. } else {
  771. // Success
  772. setNewsLoading(false)
  773. const lN = newsArr[0]
  774. const cached = ConfigManager.getNewsCache()
  775. let newHash = crypto.createHash('sha1').update(lN.content).digest('hex')
  776. let newDate = new Date(lN.date)
  777. let isNew = false
  778. if(cached.date != null && cached.content != null){
  779. if(new Date(cached.date) >= newDate){
  780. // Compare Content
  781. if(cached.content !== newHash){
  782. isNew = true
  783. showNewsAlert()
  784. } else {
  785. if(!cached.dismissed){
  786. isNew = true
  787. showNewsAlert()
  788. }
  789. }
  790. } else {
  791. isNew = true
  792. showNewsAlert()
  793. }
  794. } else {
  795. isNew = true
  796. showNewsAlert()
  797. }
  798. if(isNew){
  799. ConfigManager.setNewsCache({
  800. date: newDate.getTime(),
  801. content: newHash,
  802. dismissed: false
  803. })
  804. ConfigManager.save()
  805. }
  806. const switchHandler = (forward) => {
  807. let cArt = parseInt(newsContent.getAttribute('article'))
  808. let nxtArt = forward ? (cArt >= newsArr.length-1 ? 0 : cArt + 1) : (cArt <= 0 ? newsArr.length-1 : cArt - 1)
  809. displayArticle(newsArr[nxtArt], nxtArt+1)
  810. }
  811. document.getElementById('newsNavigateRight').onclick = () => { switchHandler(true) }
  812. document.getElementById('newsNavigateLeft').onclick = () => { switchHandler(false) }
  813. $('#newsErrorContainer').fadeOut(250, () => {
  814. displayArticle(newsArr[0], 1)
  815. $('#newsContent').fadeIn(250, () => {
  816. resolve()
  817. })
  818. })
  819. }
  820. })
  821. })
  822. }
  823. /**
  824. * Add keyboard controls to the news UI. Left and right arrows toggle
  825. * between articles. If you are on the landing page, the up arrow will
  826. * open the news UI.
  827. */
  828. document.addEventListener('keydown', (e) => {
  829. if(newsActive){
  830. if(e.key === 'ArrowRight' || e.key === 'ArrowLeft'){
  831. document.getElementById(e.key === 'ArrowRight' ? 'newsNavigateRight' : 'newsNavigateLeft').click()
  832. }
  833. // Interferes with scrolling an article using the down arrow.
  834. // Not sure of a straight forward solution at this point.
  835. // if(e.key === 'ArrowDown'){
  836. // document.getElementById('newsButton').click()
  837. // }
  838. } else {
  839. if(getCurrentView() === VIEWS.landing){
  840. if(e.key === 'ArrowUp'){
  841. document.getElementById('newsButton').click()
  842. }
  843. }
  844. }
  845. })
  846. /**
  847. * Display a news article on the UI.
  848. *
  849. * @param {Object} articleObject The article meta object.
  850. * @param {number} index The article index.
  851. */
  852. function displayArticle(articleObject, index){
  853. newsArticleTitle.innerHTML = articleObject.title
  854. newsArticleTitle.href = articleObject.link
  855. newsArticleAuthor.innerHTML = 'by ' + articleObject.author
  856. newsArticleDate.innerHTML = articleObject.date
  857. newsArticleComments.innerHTML = articleObject.comments
  858. newsArticleComments.href = articleObject.commentsLink
  859. newsArticleContentScrollable.innerHTML = '<div id="newsArticleContentWrapper"><div class="newsArticleSpacerTop"></div>' + articleObject.content + '<div class="newsArticleSpacerBot"></div></div>'
  860. newsNavigationStatus.innerHTML = index + ' of ' + newsArr.length
  861. newsContent.setAttribute('article', index-1)
  862. }
  863. /**
  864. * Load news information from the RSS feed specified in the
  865. * distribution index.
  866. */
  867. function loadNews(){
  868. return new Promise((resolve, reject) => {
  869. const distroData = DistroManager.getDistribution()
  870. const newsFeed = distroData.getRSS()
  871. const newsHost = new URL(newsFeed).origin + '/'
  872. $.ajax(
  873. {
  874. url: newsFeed,
  875. success: (data) => {
  876. const items = $(data).find('item')
  877. const articles = []
  878. for(let i=0; i<items.length; i++){
  879. // JQuery Element
  880. const el = $(items[i])
  881. // Resolve date.
  882. const date = new Date(el.find('pubDate').text()).toLocaleDateString('en-US', {month: 'short', day: 'numeric', year: 'numeric', hour: 'numeric', minute: 'numeric'})
  883. // Resolve comments.
  884. let comments = el.find('slash\\:comments').text() || '0'
  885. comments = comments + ' Comment' + (comments === '1' ? '' : 's')
  886. // Fix relative links in content.
  887. let content = el.find('content\\:encoded').text()
  888. let regex = /src="(?!http:\/\/|https:\/\/)(.+)"/g
  889. let matches
  890. while(matches = regex.exec(content)){
  891. content = content.replace(matches[1], newsHost + matches[1])
  892. }
  893. let link = el.find('link').text()
  894. let title = el.find('title').text()
  895. let author = el.find('dc\\:creator').text()
  896. // Generate article.
  897. articles.push(
  898. {
  899. link,
  900. title,
  901. date,
  902. author,
  903. content,
  904. comments,
  905. commentsLink: link + '#comments'
  906. }
  907. )
  908. }
  909. resolve({
  910. articles
  911. })
  912. },
  913. timeout: 2500
  914. }).catch(err => {
  915. resolve({
  916. articles: null
  917. })
  918. })
  919. })
  920. }