landing.js 32 KB

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