landing.js 37 KB

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