landing.js 38 KB

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