landing.js 34 KB

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