landing.js 38 KB

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