landing.js 34 KB

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