landing.js 34 KB

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