landing.js 34 KB

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