landing.js 30 KB

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