landing.js 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850
  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. setLaunchPercentage(20, 100)
  363. serv = m.result
  364. console.log('Forge Validation Complete.')
  365. // Begin version load.
  366. setLaunchDetails('Loading version information..')
  367. aEx.send({task: 0, content: 'loadVersionData', argsArr: [serv.mc_version]})
  368. } else if(m.content === 'loadVersionData'){
  369. setLaunchPercentage(40, 100)
  370. versionData = m.result
  371. console.log('Version data loaded.')
  372. // Begin asset validation.
  373. setLaunchDetails('Validating asset integrity..')
  374. aEx.send({task: 0, content: 'validateAssets', argsArr: [versionData]})
  375. } else if(m.content === 'validateAssets'){
  376. // Asset validation can *potentially* take longer, so let's track progress.
  377. if(m.task === 0){
  378. const perc = (m.value/m.total)*20
  379. setLaunchPercentage(40+perc, 100, parseInt(40+perc))
  380. } else {
  381. setLaunchPercentage(60, 100)
  382. console.log('Asset Validation Complete')
  383. // Begin library validation.
  384. setLaunchDetails('Validating library integrity..')
  385. aEx.send({task: 0, content: 'validateLibraries', argsArr: [versionData]})
  386. }
  387. } else if(m.content === 'validateLibraries'){
  388. setLaunchPercentage(80, 100)
  389. console.log('Library validation complete.')
  390. // Begin miscellaneous validation.
  391. setLaunchDetails('Validating miscellaneous file integrity..')
  392. aEx.send({task: 0, content: 'validateMiscellaneous', argsArr: [versionData]})
  393. } else if(m.content === 'validateMiscellaneous'){
  394. setLaunchPercentage(100, 100)
  395. console.log('File validation complete.')
  396. // Download queued files.
  397. setLaunchDetails('Downloading files..')
  398. aEx.send({task: 0, content: 'processDlQueues'})
  399. } else if(m.content === 'dl'){
  400. if(m.task === 0){
  401. setDownloadPercentage(m.value, m.total, m.percent)
  402. } else if(m.task === 0.7){
  403. // Download done, extracting.
  404. const eLStr = 'Extracting libraries'
  405. let dotStr = ''
  406. setLaunchDetails(eLStr)
  407. progressListener = setInterval(() => {
  408. if(dotStr.length >= 3){
  409. dotStr = ''
  410. } else {
  411. dotStr += '.'
  412. }
  413. setLaunchDetails(eLStr + dotStr)
  414. }, 750)
  415. } else if(m.task === 0.9) {
  416. if(m.err.code === 'ENOENT'){
  417. setLaunchDetails('Download error.. internet?')
  418. } else {
  419. setLaunchDetails('Download error.. try again.')
  420. }
  421. setTimeout(() => {
  422. toggleLaunchArea(false)
  423. }, 5000)
  424. } else if(m.task === 1){
  425. // Download will be at 100%, remove the loading from the OS progress bar.
  426. remote.getCurrentWindow().setProgressBar(-1)
  427. if(progressListener != null){
  428. clearInterval(progressListener)
  429. progressListener = null
  430. }
  431. setLaunchDetails('Preparing to launch..')
  432. aEx.send({task: 0, content: 'loadForgeData', argsArr: [serv.id]})
  433. } else {
  434. console.error('Unknown download data type.', m)
  435. }
  436. } else if(m.content === 'loadForgeData'){
  437. forgeData = m.result
  438. if(login) {
  439. //if(!(await AuthManager.validateSelected())){
  440. //
  441. //}
  442. const authUser = ConfigManager.getSelectedAccount()
  443. console.log('authu', authUser)
  444. let pb = new ProcessBuilder(ConfigManager.getGameDirectory(), serv, versionData, forgeData, authUser)
  445. setLaunchDetails('Launching game..')
  446. try {
  447. // Build Minecraft process.
  448. proc = pb.build()
  449. setLaunchDetails('Done. Enjoy the server!')
  450. // Attach a temporary listener to the client output.
  451. // Will wait for a certain bit of text meaning that
  452. // the client application has started, and we can hide
  453. // the progress bar stuff.
  454. const tempListener = function(data){
  455. if(data.indexOf('[Client thread/INFO]: -- System Details --') > -1){
  456. toggleLaunchArea(false)
  457. if(hasRPC){
  458. DiscordWrapper.updateDetails('Loading game..')
  459. }
  460. proc.stdout.removeListener('data', tempListener)
  461. }
  462. }
  463. // Listener for Discord RPC.
  464. const gameStateChange = function(data){
  465. if(servJoined.test(data)){
  466. DiscordWrapper.updateDetails('Exploring the Realm!')
  467. } else if(gameJoined.test(data)){
  468. DiscordWrapper.updateDetails('Idling on Main Menu')
  469. }
  470. }
  471. // Bind listeners to stdout.
  472. proc.stdout.on('data', tempListener)
  473. proc.stdout.on('data', gameStateChange)
  474. // Init Discord Hook
  475. const distro = AssetGuard.retrieveDistributionDataSync(ConfigManager.getLauncherDirectory())
  476. if(distro.discord != null && serv.discord != null){
  477. DiscordWrapper.initRPC(distro.discord, serv.discord)
  478. hasRPC = true
  479. proc.on('close', (code, signal) => {
  480. console.log('Shutting down Discord Rich Presence..')
  481. DiscordWrapper.shutdownRPC()
  482. hasRPC = false
  483. proc = null
  484. })
  485. }
  486. } catch(err) {
  487. // Show that there was an error then hide the
  488. // progress area. Maybe switch this to an error
  489. // alert in the future. TODO
  490. setLaunchDetails('Error: See log for details..')
  491. console.log(err)
  492. setTimeout(function(){
  493. toggleLaunchArea(false)
  494. }, 5000)
  495. }
  496. }
  497. // Disconnect from AssetExec
  498. aEx.disconnect()
  499. }
  500. })
  501. // Begin Validations
  502. // Validate Forge files.
  503. setLaunchDetails('Loading server information..')
  504. aEx.send({task: 0, content: 'validateDistribution', argsArr: [ConfigManager.getSelectedServer()]})
  505. }
  506. /**
  507. * News Loading Functions
  508. */
  509. // News slide caches.
  510. let newsActive = false
  511. let newsGlideCount = 0
  512. /**
  513. * Show the news UI via a slide animation.
  514. *
  515. * @param {boolean} up True to slide up, otherwise false.
  516. */
  517. function slide_(up){
  518. const lCUpper = document.querySelector('#landingContainer > #upper')
  519. const lCLLeft = document.querySelector('#landingContainer > #lower > #left')
  520. const lCLCenter = document.querySelector('#landingContainer > #lower > #center')
  521. const lCLRight = document.querySelector('#landingContainer > #lower > #right')
  522. const newsBtn = document.querySelector('#landingContainer > #lower > #center #content')
  523. const landingContainer = document.getElementById('landingContainer')
  524. const newsContainer = document.querySelector('#landingContainer > #newsContainer')
  525. newsGlideCount++
  526. if(up){
  527. lCUpper.style.top = '-200vh'
  528. lCLLeft.style.top = '-200vh'
  529. lCLCenter.style.top = '-200vh'
  530. lCLRight.style.top = '-200vh'
  531. newsBtn.style.top = '130vh'
  532. newsContainer.style.top = '0px'
  533. //date.toLocaleDateString('en-US', {month: 'short', day: 'numeric', year: 'numeric', hour: 'numeric', minute: 'numeric'})
  534. //landingContainer.style.background = 'rgba(29, 29, 29, 0.55)'
  535. landingContainer.style.background = 'rgba(0, 0, 0, 0.50)'
  536. setTimeout(() => {
  537. if(newsGlideCount === 1){
  538. lCLCenter.style.transition = 'none'
  539. newsBtn.style.transition = 'none'
  540. }
  541. newsGlideCount--
  542. }, 2000)
  543. } else {
  544. setTimeout(() => {
  545. newsGlideCount--
  546. }, 2000)
  547. landingContainer.style.background = null
  548. lCLCenter.style.transition = null
  549. newsBtn.style.transition = null
  550. newsContainer.style.top = '100%'
  551. lCUpper.style.top = '0px'
  552. lCLLeft.style.top = '0px'
  553. lCLCenter.style.top = '0px'
  554. lCLRight.style.top = '0px'
  555. newsBtn.style.top = '10px'
  556. }
  557. }
  558. // Bind news button.
  559. document.getElementById('newsButton').onclick = () => {
  560. slide_(!newsActive)
  561. newsActive = !newsActive
  562. }
  563. // Array to store article meta.
  564. let newsArr = null
  565. // News load animation listener.
  566. let newsLoadingListener = null
  567. /**
  568. * Set the news loading animation.
  569. *
  570. * @param {boolean} val True to set loading animation, otherwise false.
  571. */
  572. function setNewsLoading(val){
  573. if(val){
  574. const nLStr = 'Checking for News'
  575. let dotStr = '..'
  576. nELoadSpan.innerHTML = nLStr + dotStr
  577. newsLoadingListener = setInterval(() => {
  578. if(dotStr.length >= 3){
  579. dotStr = ''
  580. } else {
  581. dotStr += '.'
  582. }
  583. nELoadSpan.innerHTML = nLStr + dotStr
  584. }, 750)
  585. } else {
  586. if(newsLoadingListener != null){
  587. clearInterval(newsLoadingListener)
  588. newsLoadingListener = null
  589. }
  590. }
  591. }
  592. // Bind retry button.
  593. newsErrorRetry.onclick = () => {
  594. $('#newsErrorFailed').fadeOut(250, () => {
  595. initNews()
  596. $('#newsErrorLoading').fadeIn(250)
  597. })
  598. }
  599. /**
  600. * Reload the news without restarting.
  601. */
  602. async function reloadNews(){
  603. $('#newsContent').fadeOut(250, () => {
  604. $('#newsErrorLoading').fadeIn(250)
  605. })
  606. await initNews()
  607. }
  608. /**
  609. * Initialize News UI. This will load the news and prepare
  610. * the UI accordingly.
  611. */
  612. async function initNews(){
  613. setNewsLoading(true)
  614. let news = {}
  615. try {
  616. news = await loadNews()
  617. } catch (err) {
  618. // Empty
  619. }
  620. newsArr = news.articles || null
  621. if(newsArr == null){
  622. // News Loading Failed
  623. setNewsLoading(false)
  624. $('#newsErrorLoading').fadeOut(250, () => {
  625. $('#newsErrorFailed').fadeIn(250)
  626. })
  627. } else if(newsArr.length === 0) {
  628. // No News Articles
  629. setNewsLoading(false)
  630. $('#newsErrorLoading').fadeOut(250, () => {
  631. $('#newsErrorNone').fadeIn(250)
  632. })
  633. } else {
  634. // Success
  635. setNewsLoading(false)
  636. $('#newsErrorContainer').fadeOut(250, () => {
  637. displayArticle(newsArr[0], 1)
  638. $('#newsContent').fadeIn(250)
  639. })
  640. const switchHandler = (forward) => {
  641. let cArt = parseInt(newsContent.getAttribute('article'))
  642. let nxtArt = forward ? (cArt >= newsArr.length-1 ? 0 : cArt + 1) : (cArt <= 0 ? newsArr.length-1 : cArt - 1)
  643. displayArticle(newsArr[nxtArt], nxtArt+1)
  644. }
  645. document.getElementById('newsNavigateRight').onclick = () => { switchHandler(true) }
  646. document.getElementById('newsNavigateLeft').onclick = () => { switchHandler(false) }
  647. }
  648. }
  649. /**
  650. * Display a news article on the UI.
  651. *
  652. * @param {Object} articleObject The article meta object.
  653. * @param {number} index The article index.
  654. */
  655. function displayArticle(articleObject, index){
  656. newsArticleTitle.innerHTML = articleObject.title
  657. newsArticleTitle.href = articleObject.link
  658. newsArticleAuthor.innerHTML = 'by ' + articleObject.author
  659. newsArticleDate.innerHTML = articleObject.date
  660. newsArticleComments.innerHTML = articleObject.comments
  661. newsArticleComments.href = articleObject.commentsLink
  662. newsArticleContent.innerHTML = articleObject.content
  663. newsNavigationStatus.innerHTML = index + ' of ' + newsArr.length
  664. newsContent.setAttribute('article', index-1)
  665. }
  666. /**
  667. * Load news information from the RSS feed specified in the
  668. * distribution index.
  669. */
  670. function loadNews(){
  671. return new Promise((resolve, reject) => {
  672. AssetGuard.retrieveDistributionData(ConfigManager.getLauncherDirectory(), true).then((v) => {
  673. const newsFeed = v['news_feed']
  674. const newsHost = new URL(newsFeed).origin + '/'
  675. $.get(newsFeed, (data) => {
  676. const items = $(data).find('item')
  677. const articles = []
  678. for(let i=0; i<items.length; i++){
  679. // JQuery Element
  680. const el = $(items[i])
  681. // Resolve date.
  682. const date = new Date(el.find('pubDate').text()).toLocaleDateString('en-US', {month: 'short', day: 'numeric', year: 'numeric', hour: 'numeric', minute: 'numeric'})
  683. // Resolve comments.
  684. let comments = el.find('slash\\:comments').text() || '0'
  685. comments = comments + ' Comment' + (comments === '1' ? '' : 's')
  686. // Fix relative links in content.
  687. let content = el.find('content\\:encoded').text()
  688. let regex = /src="(?!http:\/\/|https:\/\/)(.+)"/g
  689. let matches
  690. while(matches = regex.exec(content)){
  691. content = content.replace(matches[1], newsHost + matches[1])
  692. }
  693. let link = el.find('link').text()
  694. let title = el.find('title').text()
  695. let author = el.find('dc\\:creator').text()
  696. // Generate article.
  697. articles.push(
  698. {
  699. link,
  700. title,
  701. date,
  702. author,
  703. content,
  704. comments,
  705. commentsLink: link + '#comments'
  706. }
  707. )
  708. }
  709. resolve({
  710. articles
  711. })
  712. }).catch(err => {
  713. reject(err)
  714. })
  715. })
  716. })
  717. }
  718. // Load News
  719. initNews()