landing.js 34 KB

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