landing.js 38 KB

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