landing.js 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830
  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(path.join(__dirname, 'assets', 'js', 'assetguard.js'))
  9. const AuthManager = require(path.join(__dirname, 'assets', 'js', 'authmanager.js'))
  10. const DiscordWrapper = require(path.join(__dirname, 'assets', 'js', 'discordwrapper.js'))
  11. const Mojang = require(path.join(__dirname, 'assets', 'js', 'mojang.js'))
  12. const ProcessBuilder = require(path.join(__dirname, 'assets', 'js', 'processbuilder.js'))
  13. const ServerStatus = require(path.join(__dirname, '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. sysAEx.on('message', (m) => {
  200. if(m.content === 'validateJava'){
  201. if(m.result == null){
  202. // If the result is null, no valid Java installation was found.
  203. // Show this information to the user.
  204. setOverlayContent(
  205. 'No Compatible<br>Java Installation Found',
  206. '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>.',
  207. 'Install Java',
  208. 'Install Manually'
  209. )
  210. setOverlayHandler(() => {
  211. setLaunchDetails('Preparing Java Download..')
  212. sysAEx.send({task: 0, content: '_enqueueOracleJRE', argsArr: [ConfigManager.getLauncherDirectory()]})
  213. toggleOverlay(false)
  214. })
  215. setDismissHandler(() => {
  216. $('#overlayContent').fadeOut(250, () => {
  217. //$('#overlayDismiss').toggle(false)
  218. setOverlayContent(
  219. 'Don\'t Forget!<br>Java is Required',
  220. '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.',
  221. 'I Understand',
  222. 'Go Back'
  223. )
  224. setOverlayHandler(() => {
  225. toggleLaunchArea(false)
  226. toggleOverlay(false)
  227. })
  228. setDismissHandler(() => {
  229. toggleOverlay(false, true)
  230. asyncSystemScan()
  231. })
  232. $('#overlayContent').fadeIn(250)
  233. })
  234. })
  235. toggleOverlay(true, true)
  236. // TODO Add option to not install Java x64.
  237. } else {
  238. // Java installation found, use this to launch the game.
  239. ConfigManager.setJavaExecutable(m.result)
  240. ConfigManager.save()
  241. if(launchAfter){
  242. dlAsync()
  243. }
  244. sysAEx.disconnect()
  245. }
  246. } else if(m.content === '_enqueueOracleJRE'){
  247. if(m.result === true){
  248. // Oracle JRE enqueued successfully, begin download.
  249. setLaunchDetails('Downloading Java..')
  250. sysAEx.send({task: 0, content: 'processDlQueues', argsArr: [[{id:'java', limit:1}]]})
  251. } else {
  252. // Oracle JRE enqueue failed. Probably due to a change in their website format.
  253. // User will have to follow the guide to install Java.
  254. setOverlayContent(
  255. 'Unexpected Issue:<br>Java Download Failed',
  256. '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.',
  257. 'I Understand'
  258. )
  259. setOverlayHandler(() => {
  260. toggleOverlay(false)
  261. toggleLaunchArea(false)
  262. })
  263. toggleOverlay(true)
  264. sysAEx.disconnect()
  265. }
  266. } else if(m.content === 'dl'){
  267. if(m.task === 0){
  268. // Downloading..
  269. setDownloadPercentage(m.value, m.total, m.percent)
  270. } else if(m.task === 1){
  271. // Download will be at 100%, remove the loading from the OS progress bar.
  272. remote.getCurrentWindow().setProgressBar(-1)
  273. // Wait for extration to complete.
  274. const eLStr = 'Extracting'
  275. let dotStr = ''
  276. setLaunchDetails(eLStr)
  277. extractListener = setInterval(() => {
  278. if(dotStr.length >= 3){
  279. dotStr = ''
  280. } else {
  281. dotStr += '.'
  282. }
  283. setLaunchDetails(eLStr + dotStr)
  284. }, 750)
  285. } else if(m.task === 2){
  286. // Extraction completed successfully.
  287. ConfigManager.setJavaExecutable(m.jPath)
  288. ConfigManager.save()
  289. if(extractListener != null){
  290. clearInterval(extractListener)
  291. extractListener = null
  292. }
  293. setLaunchDetails('Java Installed!')
  294. if(launchAfter){
  295. dlAsync()
  296. }
  297. sysAEx.disconnect()
  298. } else {
  299. console.error('Unknown download data type.', m)
  300. }
  301. }
  302. })
  303. // Begin system Java scan.
  304. setLaunchDetails('Checking system info..')
  305. sysAEx.send({task: 0, content: 'validateJava', argsArr: [ConfigManager.getLauncherDirectory()]})
  306. }
  307. // Keep reference to Minecraft Process
  308. let proc
  309. // Is DiscordRPC enabled
  310. let hasRPC = false
  311. // Joined server regex
  312. 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
  313. const gameJoined = /\[[0-2][0-9]:[0-6][0-9]:[0-6][0-9]\] \[Client thread\/WARN\]: Skipping bad option: lastServer:/g
  314. const gameJoined2 = /\[[0-2][0-9]:[0-6][0-9]:[0-6][0-9]\] \[Client thread\/INFO\]: Created: \d+x\d+ textures-atlas/g
  315. let aEx
  316. let serv
  317. let versionData
  318. let forgeData
  319. let progressListener
  320. function dlAsync(login = true){
  321. // Login parameter is temporary for debug purposes. Allows testing the validation/downloads without
  322. // launching the game.
  323. if(login) {
  324. if(ConfigManager.getSelectedAccount() == null){
  325. console.error('login first.')
  326. //in devtools AuthManager.addAccount(username, pass)
  327. return
  328. }
  329. }
  330. setLaunchDetails('Please wait..')
  331. toggleLaunchArea(true)
  332. setLaunchPercentage(0, 100)
  333. // Start AssetExec to run validations and downloads in a forked process.
  334. aEx = cp.fork(path.join(__dirname, 'assets', 'js', 'assetexec.js'), [
  335. ConfigManager.getGameDirectory(),
  336. ConfigManager.getLauncherDirectory(),
  337. ConfigManager.getJavaExecutable()
  338. ])
  339. // Establish communications between the AssetExec and current process.
  340. aEx.on('message', (m) => {
  341. if(m.content === 'validateDistribution'){
  342. setLaunchPercentage(20, 100)
  343. serv = m.result
  344. console.log('Forge Validation Complete.')
  345. // Begin version load.
  346. setLaunchDetails('Loading version information..')
  347. aEx.send({task: 0, content: 'loadVersionData', argsArr: [serv.mc_version]})
  348. } else if(m.content === 'loadVersionData'){
  349. setLaunchPercentage(40, 100)
  350. versionData = m.result
  351. console.log('Version data loaded.')
  352. // Begin asset validation.
  353. setLaunchDetails('Validating asset integrity..')
  354. aEx.send({task: 0, content: 'validateAssets', argsArr: [versionData]})
  355. } else if(m.content === 'validateAssets'){
  356. // Asset validation can *potentially* take longer, so let's track progress.
  357. if(m.task === 0){
  358. const perc = (m.value/m.total)*20
  359. setLaunchPercentage(40+perc, 100, parseInt(40+perc))
  360. } else {
  361. setLaunchPercentage(60, 100)
  362. console.log('Asset Validation Complete')
  363. // Begin library validation.
  364. setLaunchDetails('Validating library integrity..')
  365. aEx.send({task: 0, content: 'validateLibraries', argsArr: [versionData]})
  366. }
  367. } else if(m.content === 'validateLibraries'){
  368. setLaunchPercentage(80, 100)
  369. console.log('Library validation complete.')
  370. // Begin miscellaneous validation.
  371. setLaunchDetails('Validating miscellaneous file integrity..')
  372. aEx.send({task: 0, content: 'validateMiscellaneous', argsArr: [versionData]})
  373. } else if(m.content === 'validateMiscellaneous'){
  374. setLaunchPercentage(100, 100)
  375. console.log('File validation complete.')
  376. // Download queued files.
  377. setLaunchDetails('Downloading files..')
  378. aEx.send({task: 0, content: 'processDlQueues'})
  379. } else if(m.content === 'dl'){
  380. if(m.task === 0){
  381. setDownloadPercentage(m.value, m.total, m.percent)
  382. } else if(m.task === 0.7){
  383. // Download done, extracting.
  384. const eLStr = 'Extracting libraries'
  385. let dotStr = ''
  386. setLaunchDetails(eLStr)
  387. progressListener = setInterval(() => {
  388. if(dotStr.length >= 3){
  389. dotStr = ''
  390. } else {
  391. dotStr += '.'
  392. }
  393. setLaunchDetails(eLStr + dotStr)
  394. }, 750)
  395. } else if(m.task === 0.9) {
  396. if(m.err.code === 'ENOENT'){
  397. setLaunchDetails('Download error.. internet?')
  398. } else {
  399. setLaunchDetails('Download error.. try again.')
  400. }
  401. setTimeout(() => {
  402. toggleLaunchArea(false)
  403. }, 5000)
  404. } else if(m.task === 1){
  405. // Download will be at 100%, remove the loading from the OS progress bar.
  406. remote.getCurrentWindow().setProgressBar(-1)
  407. if(progressListener != null){
  408. clearInterval(progressListener)
  409. progressListener = null
  410. }
  411. setLaunchDetails('Preparing to launch..')
  412. aEx.send({task: 0, content: 'loadForgeData', argsArr: [serv.id]})
  413. } else {
  414. console.error('Unknown download data type.', m)
  415. }
  416. } else if(m.content === 'loadForgeData'){
  417. forgeData = m.result
  418. if(login) {
  419. //if(!(await AuthManager.validateSelected())){
  420. //
  421. //}
  422. const authUser = ConfigManager.getSelectedAccount()
  423. console.log('authu', authUser)
  424. let pb = new ProcessBuilder(ConfigManager.getGameDirectory(), serv, versionData, forgeData, authUser)
  425. setLaunchDetails('Launching game..')
  426. try {
  427. // Build Minecraft process.
  428. proc = pb.build()
  429. setLaunchDetails('Done. Enjoy the server!')
  430. // Attach a temporary listener to the client output.
  431. // Will wait for a certain bit of text meaning that
  432. // the client application has started, and we can hide
  433. // the progress bar stuff.
  434. const tempListener = function(data){
  435. if(data.indexOf('[Client thread/INFO]: -- System Details --') > -1){
  436. toggleLaunchArea(false)
  437. if(hasRPC){
  438. DiscordWrapper.updateDetails('Loading game..')
  439. }
  440. proc.stdout.removeListener('data', tempListener)
  441. }
  442. }
  443. // Listener for Discord RPC.
  444. const gameStateChange = function(data){
  445. if(servJoined.test(data)){
  446. DiscordWrapper.updateDetails('Exploring the Realm!')
  447. } else if(gameJoined.test(data)){
  448. DiscordWrapper.updateDetails('Idling on Main Menu')
  449. }
  450. }
  451. // Bind listeners to stdout.
  452. proc.stdout.on('data', tempListener)
  453. proc.stdout.on('data', gameStateChange)
  454. // Init Discord Hook
  455. const distro = AssetGuard.retrieveDistributionDataSync(ConfigManager.getLauncherDirectory())
  456. if(distro.discord != null && serv.discord != null){
  457. DiscordWrapper.initRPC(distro.discord, serv.discord)
  458. hasRPC = true
  459. proc.on('close', (code, signal) => {
  460. console.log('Shutting down Discord Rich Presence..')
  461. DiscordWrapper.shutdownRPC()
  462. hasRPC = false
  463. proc = null
  464. })
  465. }
  466. } catch(err) {
  467. // Show that there was an error then hide the
  468. // progress area. Maybe switch this to an error
  469. // alert in the future. TODO
  470. setLaunchDetails('Error: See log for details..')
  471. console.log(err)
  472. setTimeout(function(){
  473. toggleLaunchArea(false)
  474. }, 5000)
  475. }
  476. }
  477. // Disconnect from AssetExec
  478. aEx.disconnect()
  479. }
  480. })
  481. // Begin Validations
  482. // Validate Forge files.
  483. setLaunchDetails('Loading server information..')
  484. aEx.send({task: 0, content: 'validateDistribution', argsArr: [ConfigManager.getSelectedServer()]})
  485. }
  486. /**
  487. * News Loading Functions
  488. */
  489. // News slide caches.
  490. let newsActive = false
  491. let newsGlideCount = 0
  492. /**
  493. * Show the news UI via a slide animation.
  494. *
  495. * @param {boolean} up True to slide up, otherwise false.
  496. */
  497. function slide_(up){
  498. const lCUpper = document.querySelector('#landingContainer > #upper')
  499. const lCLLeft = document.querySelector('#landingContainer > #lower > #left')
  500. const lCLCenter = document.querySelector('#landingContainer > #lower > #center')
  501. const lCLRight = document.querySelector('#landingContainer > #lower > #right')
  502. const newsBtn = document.querySelector('#landingContainer > #lower > #center #content')
  503. const landingContainer = document.getElementById('landingContainer')
  504. const newsContainer = document.querySelector('#landingContainer > #newsContainer')
  505. newsGlideCount++
  506. if(up){
  507. lCUpper.style.top = '-200vh'
  508. lCLLeft.style.top = '-200vh'
  509. lCLCenter.style.top = '-200vh'
  510. lCLRight.style.top = '-200vh'
  511. newsBtn.style.top = '130vh'
  512. newsContainer.style.top = '0px'
  513. //date.toLocaleDateString('en-US', {month: 'short', day: 'numeric', year: 'numeric', hour: 'numeric', minute: 'numeric'})
  514. //landingContainer.style.background = 'rgba(29, 29, 29, 0.55)'
  515. landingContainer.style.background = 'rgba(0, 0, 0, 0.50)'
  516. setTimeout(() => {
  517. if(newsGlideCount === 1){
  518. lCLCenter.style.transition = 'none'
  519. newsBtn.style.transition = 'none'
  520. }
  521. newsGlideCount--
  522. }, 2000)
  523. } else {
  524. setTimeout(() => {
  525. newsGlideCount--
  526. }, 2000)
  527. landingContainer.style.background = null
  528. lCLCenter.style.transition = null
  529. newsBtn.style.transition = null
  530. newsContainer.style.top = '100%'
  531. lCUpper.style.top = '0px'
  532. lCLLeft.style.top = '0px'
  533. lCLCenter.style.top = '0px'
  534. lCLRight.style.top = '0px'
  535. newsBtn.style.top = '10px'
  536. }
  537. }
  538. // Bind news button.
  539. document.getElementById('newsButton').onclick = () => {
  540. slide_(!newsActive)
  541. newsActive = !newsActive
  542. }
  543. // Array to store article meta.
  544. let newsArr = null
  545. // News load animation listener.
  546. let newsLoadingListener = null
  547. /**
  548. * Set the news loading animation.
  549. *
  550. * @param {boolean} val True to set loading animation, otherwise false.
  551. */
  552. function setNewsLoading(val){
  553. if(val){
  554. const nLStr = 'Checking for News'
  555. let dotStr = '..'
  556. nELoadSpan.innerHTML = nLStr + dotStr
  557. newsLoadingListener = setInterval(() => {
  558. if(dotStr.length >= 3){
  559. dotStr = ''
  560. } else {
  561. dotStr += '.'
  562. }
  563. nELoadSpan.innerHTML = nLStr + dotStr
  564. }, 750)
  565. } else {
  566. if(newsLoadingListener != null){
  567. clearInterval(newsLoadingListener)
  568. newsLoadingListener = null
  569. }
  570. }
  571. }
  572. // Bind retry button.
  573. newsErrorRetry.onclick = () => {
  574. $('#newsErrorFailed').fadeOut(250, () => {
  575. initNews()
  576. $('#newsErrorLoading').fadeIn(250)
  577. })
  578. }
  579. /**
  580. * Reload the news without restarting.
  581. */
  582. async function reloadNews(){
  583. $('#newsContent').fadeOut(250, () => {
  584. $('#newsErrorLoading').fadeIn(250)
  585. })
  586. await initNews()
  587. }
  588. /**
  589. * Initialize News UI. This will load the news and prepare
  590. * the UI accordingly.
  591. */
  592. async function initNews(){
  593. setNewsLoading(true)
  594. let news = {}
  595. try {
  596. news = await loadNews()
  597. } catch (err) {
  598. // Empty
  599. }
  600. newsArr = news.articles || null
  601. if(newsArr == null){
  602. // News Loading Failed
  603. setNewsLoading(false)
  604. $('#newsErrorLoading').fadeOut(250, () => {
  605. $('#newsErrorFailed').fadeIn(250)
  606. })
  607. } else if(newsArr.length === 0) {
  608. // No News Articles
  609. setNewsLoading(false)
  610. $('#newsErrorLoading').fadeOut(250, () => {
  611. $('#newsErrorNone').fadeIn(250)
  612. })
  613. } else {
  614. // Success
  615. setNewsLoading(false)
  616. $('#newsErrorContainer').fadeOut(250, () => {
  617. displayArticle(newsArr[0], 1)
  618. $('#newsContent').fadeIn(250)
  619. })
  620. const switchHandler = (forward) => {
  621. let cArt = parseInt(newsContent.getAttribute('article'))
  622. let nxtArt = forward ? (cArt >= newsArr.length-1 ? 0 : cArt + 1) : (cArt <= 0 ? newsArr.length-1 : cArt - 1)
  623. displayArticle(newsArr[nxtArt], nxtArt+1)
  624. }
  625. document.getElementById('newsNavigateRight').onclick = () => { switchHandler(true) }
  626. document.getElementById('newsNavigateLeft').onclick = () => { switchHandler(false) }
  627. }
  628. }
  629. /**
  630. * Display a news article on the UI.
  631. *
  632. * @param {Object} articleObject The article meta object.
  633. * @param {number} index The article index.
  634. */
  635. function displayArticle(articleObject, index){
  636. newsArticleTitle.innerHTML = articleObject.title
  637. newsArticleTitle.href = articleObject.link
  638. newsArticleAuthor.innerHTML = 'by ' + articleObject.author
  639. newsArticleDate.innerHTML = articleObject.date
  640. newsArticleComments.innerHTML = articleObject.comments
  641. newsArticleComments.href = articleObject.commentsLink
  642. newsArticleContent.innerHTML = articleObject.content
  643. newsNavigationStatus.innerHTML = index + ' of ' + newsArr.length
  644. newsContent.setAttribute('article', index-1)
  645. }
  646. /**
  647. * Load news information from the RSS feed specified in the
  648. * distribution index.
  649. */
  650. function loadNews(){
  651. return new Promise((resolve, reject) => {
  652. AssetGuard.retrieveDistributionData(ConfigManager.getLauncherDirectory(), true).then((v) => {
  653. const newsFeed = v['news_feed']
  654. const newsHost = new URL(newsFeed).origin + '/'
  655. $.get(newsFeed, (data) => {
  656. const items = $(data).find('item')
  657. const articles = []
  658. for(let i=0; i<items.length; i++){
  659. // JQuery Element
  660. const el = $(items[i])
  661. // Resolve date.
  662. const date = new Date(el.find('pubDate').text()).toLocaleDateString('en-US', {month: 'short', day: 'numeric', year: 'numeric', hour: 'numeric', minute: 'numeric'})
  663. // Resolve comments.
  664. let comments = el.find('slash\\:comments').text() || '0'
  665. comments = comments + ' Comment' + (comments === '1' ? '' : 's')
  666. // Fix relative links in content.
  667. let content = el.find('content\\:encoded').text()
  668. let regex = /src="(?!http:\/\/|https:\/\/)(.+)"/g
  669. let matches
  670. while(matches = regex.exec(content)){
  671. content = content.replace(matches[1], newsHost + matches[1])
  672. }
  673. let link = el.find('link').text()
  674. let title = el.find('title').text()
  675. let author = el.find('dc\\:creator').text()
  676. // Generate article.
  677. articles.push(
  678. {
  679. link,
  680. title,
  681. date,
  682. author,
  683. content,
  684. comments,
  685. commentsLink: link + '#comments'
  686. }
  687. )
  688. }
  689. resolve({
  690. articles
  691. })
  692. }).catch(err => {
  693. reject(err)
  694. })
  695. })
  696. })
  697. }
  698. // Load News
  699. initNews()