landing.js 36 KB

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