landing.js 37 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070
  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 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 && authUser.username != null){
  111. username = authUser.displayName
  112. }
  113. user_text.innerHTML = username
  114. }
  115. updateSelectedAccount(ConfigManager.getSelectedAccount())
  116. // Bind selected server
  117. function updateSelectedServer(serverName){
  118. if(serverName == null){
  119. serverName = 'No Server Selected'
  120. }
  121. server_selection_button.innerHTML = '\u2022 ' + serverName
  122. }
  123. // Real text is set in uibinder.js on distributionIndexDone.
  124. updateSelectedServer('Loading..')
  125. server_selection_button.addEventListener('click', (e) => {
  126. e.target.blur()
  127. toggleServerSelection(true)
  128. })
  129. // Update Mojang Status Color
  130. const refreshMojangStatuses = async function(){
  131. console.log('Refreshing Mojang Statuses..')
  132. let status = 'grey'
  133. let tooltipEssentialHTML = ``
  134. let tooltipNonEssentialHTML = ``
  135. try {
  136. const statuses = await Mojang.status()
  137. greenCount = 0
  138. greyCount = 0
  139. for(let i=0; i<statuses.length; i++){
  140. const service = statuses[i]
  141. if(service.essential){
  142. tooltipEssentialHTML += `<div class="mojangStatusContainer">
  143. <span class="mojangStatusIcon" style="color: ${Mojang.statusToHex(service.status)};">&#8226;</span>
  144. <span class="mojangStatusName">${service.name}</span>
  145. </div>`
  146. } else {
  147. tooltipNonEssentialHTML += `<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. }
  152. if(service.status === 'yellow' && status !== 'red'){
  153. status = 'yellow'
  154. } else if(service.status === 'red'){
  155. status = 'red'
  156. } else {
  157. if(service.status === 'grey'){
  158. ++greyCount
  159. }
  160. ++greenCount
  161. }
  162. }
  163. if(greenCount === statuses.length){
  164. if(greyCount === statuses.length){
  165. status = 'grey'
  166. } else {
  167. status = 'green'
  168. }
  169. }
  170. } catch (err) {
  171. console.warn('Unable to refresh Mojang service status.')
  172. console.debug(err)
  173. }
  174. document.getElementById('mojangStatusEssentialContainer').innerHTML = tooltipEssentialHTML
  175. document.getElementById('mojangStatusNonEssentialContainer').innerHTML = tooltipNonEssentialHTML
  176. document.getElementById('mojang_status_icon').style.color = Mojang.statusToHex(status)
  177. }
  178. const refreshServerStatus = async function(fade = false){
  179. console.log('Refreshing Server Status')
  180. const serv = AssetGuard.getServerById(ConfigManager.getSelectedServer())
  181. let pLabel = 'SERVER'
  182. let pVal = 'OFFLINE'
  183. try {
  184. const serverURL = new URL('my://' + serv.server_ip)
  185. const servStat = await ServerStatus.getStatus(serverURL.hostname, serverURL.port)
  186. if(servStat.online){
  187. pLabel = 'PLAYERS'
  188. pVal = servStat.onlinePlayers + '/' + servStat.maxPlayers
  189. }
  190. } catch (err) {
  191. console.warn('Unable to refresh server status, assuming offline.')
  192. console.debug(err)
  193. }
  194. if(fade){
  195. $('#server_status_wrapper').fadeOut(250, () => {
  196. document.getElementById('landingPlayerLabel').innerHTML = pLabel
  197. document.getElementById('player_count').innerHTML = pVal
  198. $('#server_status_wrapper').fadeIn(500)
  199. })
  200. } else {
  201. document.getElementById('landingPlayerLabel').innerHTML = pLabel
  202. document.getElementById('player_count').innerHTML = pVal
  203. }
  204. }
  205. refreshMojangStatuses()
  206. // Server Status is refreshed in uibinder.js on distributionIndexDone.
  207. // Set refresh rate to once every 5 minutes.
  208. let mojangStatusListener = setInterval(() => refreshMojangStatuses(true), 300000)
  209. let serverStatusListener = setInterval(() => refreshServerStatus(true), 300000)
  210. /* System (Java) Scan */
  211. let sysAEx
  212. let scanAt
  213. let extractListener
  214. function asyncSystemScan(launchAfter = true){
  215. setLaunchDetails('Please wait..')
  216. toggleLaunchArea(true)
  217. setLaunchPercentage(0, 100)
  218. // Fork a process to run validations.
  219. sysAEx = cp.fork(path.join(__dirname, 'assets', 'js', 'assetexec.js'), [
  220. ConfigManager.getCommonDirectory(),
  221. ConfigManager.getLauncherDirectory(),
  222. ConfigManager.getJavaExecutable(),
  223. ConfigManager.getInstanceDirectory()
  224. ], {
  225. stdio: 'pipe'
  226. })
  227. // Stdout
  228. sysAEx.stdio[1].on('data', (data) => {
  229. console.log('%c[SysAEx]', 'color: #353232; font-weight: bold', data.toString('utf-8'))
  230. })
  231. // Stderr
  232. sysAEx.stdio[2].on('data', (data) => {
  233. console.log('%c[SysAEx]', 'color: #353232; font-weight: bold', data.toString('utf-8'))
  234. })
  235. sysAEx.on('message', (m) => {
  236. if(m.content === 'validateJava'){
  237. if(m.result == null){
  238. // If the result is null, no valid Java installation was found.
  239. // Show this information to the user.
  240. setOverlayContent(
  241. 'No Compatible<br>Java Installation Found',
  242. '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>.',
  243. 'Install Java',
  244. 'Install Manually'
  245. )
  246. setOverlayHandler(() => {
  247. setLaunchDetails('Preparing Java Download..')
  248. sysAEx.send({task: 0, content: '_enqueueOracleJRE', argsArr: [ConfigManager.getLauncherDirectory()]})
  249. toggleOverlay(false)
  250. })
  251. setDismissHandler(() => {
  252. $('#overlayContent').fadeOut(250, () => {
  253. //$('#overlayDismiss').toggle(false)
  254. setOverlayContent(
  255. 'Don\'t Forget!<br>Java is Required',
  256. '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.',
  257. 'I Understand',
  258. 'Go Back'
  259. )
  260. setOverlayHandler(() => {
  261. toggleLaunchArea(false)
  262. toggleOverlay(false)
  263. })
  264. setDismissHandler(() => {
  265. toggleOverlay(false, true)
  266. asyncSystemScan()
  267. })
  268. $('#overlayContent').fadeIn(250)
  269. })
  270. })
  271. toggleOverlay(true, true)
  272. } else {
  273. // Java installation found, use this to launch the game.
  274. ConfigManager.setJavaExecutable(m.result)
  275. ConfigManager.save()
  276. // We need to make sure that the updated value is on the settings UI.
  277. // Just incase the settings UI is already open.
  278. settingsJavaExecVal.value = m.result
  279. populateJavaExecDetails(settingsJavaExecVal.value)
  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. // 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. * Display a news article on the UI.
  832. *
  833. * @param {Object} articleObject The article meta object.
  834. * @param {number} index The article index.
  835. */
  836. function displayArticle(articleObject, index){
  837. newsArticleTitle.innerHTML = articleObject.title
  838. newsArticleTitle.href = articleObject.link
  839. newsArticleAuthor.innerHTML = 'by ' + articleObject.author
  840. newsArticleDate.innerHTML = articleObject.date
  841. newsArticleComments.innerHTML = articleObject.comments
  842. newsArticleComments.href = articleObject.commentsLink
  843. newsArticleContentScrollable.innerHTML = '<div id="newsArticleContentWrapper"><div class="newsArticleSpacerTop"></div>' + articleObject.content + '<div class="newsArticleSpacerBot"></div></div>'
  844. newsNavigationStatus.innerHTML = index + ' of ' + newsArr.length
  845. newsContent.setAttribute('article', index-1)
  846. }
  847. /**
  848. * Load news information from the RSS feed specified in the
  849. * distribution index.
  850. */
  851. function loadNews(){
  852. return new Promise((resolve, reject) => {
  853. const distroData = AssetGuard.getDistributionData()
  854. const newsFeed = distroData['news_feed']
  855. const newsHost = new URL(newsFeed).origin + '/'
  856. $.ajax(
  857. {
  858. url: newsFeed,
  859. success: (data) => {
  860. const items = $(data).find('item')
  861. const articles = []
  862. for(let i=0; i<items.length; i++){
  863. // JQuery Element
  864. const el = $(items[i])
  865. // Resolve date.
  866. const date = new Date(el.find('pubDate').text()).toLocaleDateString('en-US', {month: 'short', day: 'numeric', year: 'numeric', hour: 'numeric', minute: 'numeric'})
  867. // Resolve comments.
  868. let comments = el.find('slash\\:comments').text() || '0'
  869. comments = comments + ' Comment' + (comments === '1' ? '' : 's')
  870. // Fix relative links in content.
  871. let content = el.find('content\\:encoded').text()
  872. let regex = /src="(?!http:\/\/|https:\/\/)(.+)"/g
  873. let matches
  874. while(matches = regex.exec(content)){
  875. content = content.replace(matches[1], newsHost + matches[1])
  876. }
  877. let link = el.find('link').text()
  878. let title = el.find('title').text()
  879. let author = el.find('dc\\:creator').text()
  880. // Generate article.
  881. articles.push(
  882. {
  883. link,
  884. title,
  885. date,
  886. author,
  887. content,
  888. comments,
  889. commentsLink: link + '#comments'
  890. }
  891. )
  892. }
  893. resolve({
  894. articles
  895. })
  896. },
  897. timeout: 2500
  898. }).catch(err => {
  899. resolve({
  900. articles: null
  901. })
  902. })
  903. })
  904. }