landing.js 29 KB

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