landing.js 33 KB

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