landing.js 38 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099
  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. // Download will be at 100%, remove the loading from the OS progress bar.
  316. remote.getCurrentWindow().setProgressBar(-1)
  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. // Extraction completed successfully.
  331. ConfigManager.setJavaExecutable(m.jPath)
  332. ConfigManager.save()
  333. if(extractListener != null){
  334. clearInterval(extractListener)
  335. extractListener = null
  336. }
  337. setLaunchDetails('Java Installed!')
  338. if(launchAfter){
  339. dlAsync()
  340. }
  341. sysAEx.disconnect()
  342. } else {
  343. console.error('Unknown download data type.', m)
  344. }
  345. }
  346. })
  347. // Begin system Java scan.
  348. setLaunchDetails('Checking system info..')
  349. sysAEx.send({task: 0, content: 'validateJava', argsArr: [ConfigManager.getLauncherDirectory()]})
  350. }
  351. // Keep reference to Minecraft Process
  352. let proc
  353. // Is DiscordRPC enabled
  354. let hasRPC = false
  355. // Joined server regex
  356. 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
  357. const gameJoined = /\[[0-2][0-9]:[0-6][0-9]:[0-6][0-9]\] \[Client thread\/WARN\]: Skipping bad option: lastServer:/g
  358. const gameJoined2 = /\[[0-2][0-9]:[0-6][0-9]:[0-6][0-9]\] \[Client thread\/INFO\]: Created: \d+x\d+ textures-atlas/g
  359. let aEx
  360. let serv
  361. let versionData
  362. let forgeData
  363. let progressListener
  364. function dlAsync(login = true){
  365. // Login parameter is temporary for debug purposes. Allows testing the validation/downloads without
  366. // launching the game.
  367. if(login) {
  368. if(ConfigManager.getSelectedAccount() == null){
  369. console.error('login first.')
  370. //in devtools AuthManager.addAccount(username, pass)
  371. return
  372. }
  373. }
  374. setLaunchDetails('Please wait..')
  375. toggleLaunchArea(true)
  376. setLaunchPercentage(0, 100)
  377. // Start AssetExec to run validations and downloads in a forked process.
  378. aEx = cp.fork(path.join(__dirname, 'assets', 'js', 'assetexec.js'), [
  379. ConfigManager.getCommonDirectory(),
  380. ConfigManager.getLauncherDirectory(),
  381. ConfigManager.getJavaExecutable(),
  382. ConfigManager.getInstanceDirectory()
  383. ], {
  384. stdio: 'pipe'
  385. })
  386. // Stdout
  387. aEx.stdio[1].on('data', (data) => {
  388. console.log('%c[AEx]', 'color: #353232; font-weight: bold', data.toString('utf-8'))
  389. })
  390. // Stderr
  391. aEx.stdio[2].on('data', (data) => {
  392. console.log('%c[AEx]', 'color: #353232; font-weight: bold', data.toString('utf-8'))
  393. })
  394. // Establish communications between the AssetExec and current process.
  395. aEx.on('message', (m) => {
  396. if(m.content === 'validateDistribution'){
  397. setLaunchPercentage(20, 100)
  398. serv = m.result
  399. console.log('Validated distibution index.')
  400. // Begin version load.
  401. setLaunchDetails('Loading version information..')
  402. aEx.send({task: 0, content: 'loadVersionData', argsArr: [serv.mc_version]})
  403. } else if(m.content === 'loadVersionData'){
  404. setLaunchPercentage(40, 100)
  405. versionData = m.result
  406. console.log('Version data loaded.')
  407. // Begin asset validation.
  408. setLaunchDetails('Validating asset integrity..')
  409. aEx.send({task: 0, content: 'validateAssets', argsArr: [versionData]})
  410. } else if(m.content === 'validateAssets'){
  411. // Asset validation can *potentially* take longer, so let's track progress.
  412. if(m.task === 0){
  413. const perc = (m.value/m.total)*20
  414. setLaunchPercentage(40+perc, 100, parseInt(40+perc))
  415. } else {
  416. setLaunchPercentage(60, 100)
  417. console.log('Asset Validation Complete')
  418. // Begin library validation.
  419. setLaunchDetails('Validating library integrity..')
  420. aEx.send({task: 0, content: 'validateLibraries', argsArr: [versionData]})
  421. }
  422. } else if(m.content === 'validateLibraries'){
  423. setLaunchPercentage(80, 100)
  424. console.log('Library validation complete.')
  425. // Begin miscellaneous validation.
  426. setLaunchDetails('Validating miscellaneous file integrity..')
  427. aEx.send({task: 0, content: 'validateMiscellaneous', argsArr: [versionData]})
  428. } else if(m.content === 'validateMiscellaneous'){
  429. setLaunchPercentage(100, 100)
  430. console.log('File validation complete.')
  431. // Download queued files.
  432. setLaunchDetails('Downloading files..')
  433. aEx.send({task: 0, content: 'processDlQueues'})
  434. } else if(m.content === 'dl'){
  435. if(m.task === 0){
  436. setDownloadPercentage(m.value, m.total, m.percent)
  437. } else if(m.task === 0.7){
  438. // Download done, extracting.
  439. const eLStr = 'Extracting libraries'
  440. let dotStr = ''
  441. setLaunchDetails(eLStr)
  442. progressListener = setInterval(() => {
  443. if(dotStr.length >= 3){
  444. dotStr = ''
  445. } else {
  446. dotStr += '.'
  447. }
  448. setLaunchDetails(eLStr + dotStr)
  449. }, 750)
  450. } else if(m.task === 0.9) {
  451. console.error(m.err)
  452. if(m.err.code === 'ENOENT'){
  453. setOverlayContent(
  454. 'Download Error',
  455. 'Could not connect to the file server. Ensure that you are connected to the internet and try again.',
  456. 'Okay'
  457. )
  458. setOverlayHandler(null)
  459. } else {
  460. setOverlayContent(
  461. 'Download Error',
  462. 'Check the console for more details. Please try again.',
  463. 'Okay'
  464. )
  465. setOverlayHandler(null)
  466. }
  467. toggleOverlay(true)
  468. toggleLaunchArea(false)
  469. // Disconnect from AssetExec
  470. aEx.disconnect()
  471. } else if(m.task === 1){
  472. // Download will be at 100%, remove the loading from the OS progress bar.
  473. remote.getCurrentWindow().setProgressBar(-1)
  474. if(progressListener != null){
  475. clearInterval(progressListener)
  476. progressListener = null
  477. }
  478. setLaunchDetails('Preparing to launch..')
  479. aEx.send({task: 0, content: 'loadForgeData', argsArr: [serv.id]})
  480. } else {
  481. console.error('Unknown download data type.', m)
  482. }
  483. } else if(m.content === 'loadForgeData'){
  484. forgeData = m.result
  485. if(login) {
  486. //if(!(await AuthManager.validateSelected())){
  487. //
  488. //}
  489. const authUser = ConfigManager.getSelectedAccount()
  490. console.log('authu', authUser)
  491. let pb = new ProcessBuilder(serv, versionData, forgeData, authUser)
  492. setLaunchDetails('Launching game..')
  493. try {
  494. // Build Minecraft process.
  495. proc = pb.build()
  496. setLaunchDetails('Done. Enjoy the server!')
  497. // Attach a temporary listener to the client output.
  498. // Will wait for a certain bit of text meaning that
  499. // the client application has started, and we can hide
  500. // the progress bar stuff.
  501. const tempListener = function(data){
  502. if(data.indexOf('[Client thread/INFO]: -- System Details --') > -1){
  503. toggleLaunchArea(false)
  504. if(hasRPC){
  505. DiscordWrapper.updateDetails('Loading game..')
  506. }
  507. proc.stdout.removeListener('data', tempListener)
  508. }
  509. }
  510. // Listener for Discord RPC.
  511. const gameStateChange = function(data){
  512. if(servJoined.test(data)){
  513. DiscordWrapper.updateDetails('Exploring the Realm!')
  514. } else if(gameJoined.test(data)){
  515. DiscordWrapper.updateDetails('Idling on Main Menu')
  516. }
  517. }
  518. // Bind listeners to stdout.
  519. proc.stdout.on('data', tempListener)
  520. proc.stdout.on('data', gameStateChange)
  521. // Init Discord Hook
  522. const distro = AssetGuard.getDistributionData()
  523. if(distro.discord != null && serv.discord != null){
  524. DiscordWrapper.initRPC(distro.discord, serv.discord)
  525. hasRPC = true
  526. proc.on('close', (code, signal) => {
  527. console.log('Shutting down Discord Rich Presence..')
  528. DiscordWrapper.shutdownRPC()
  529. hasRPC = false
  530. proc = null
  531. })
  532. }
  533. } catch(err) {
  534. console.error('Error during launch', err)
  535. setOverlayContent(
  536. 'Error During Launch',
  537. 'Please check the console for more details.',
  538. 'Okay'
  539. )
  540. setOverlayHandler(null)
  541. toggleOverlay(true)
  542. toggleLaunchArea(false)
  543. }
  544. }
  545. // Disconnect from AssetExec
  546. aEx.disconnect()
  547. }
  548. })
  549. // Begin Validations
  550. // Validate Forge files.
  551. setLaunchDetails('Loading server information..')
  552. if(AssetGuard.isLocalLaunch()){
  553. refreshDistributionIndex(false, (data) => {
  554. onDistroRefresh(data)
  555. aEx.send({task: 0, content: 'validateDistribution', argsArr: [ConfigManager.getSelectedServer()]})
  556. }, (err) => {
  557. console.error('Unable to refresh distribution index.', err)
  558. if(AssetGuard.getDistributionData() == null){
  559. setOverlayContent(
  560. 'Fatal Error',
  561. 'Could not load a copy of the distribution index. See the console for more details.',
  562. 'Okay'
  563. )
  564. setOverlayHandler(null)
  565. toggleOverlay(true)
  566. toggleLaunchArea(false)
  567. // Disconnect from AssetExec
  568. aEx.disconnect()
  569. } else {
  570. aEx.send({task: 0, content: 'validateDistribution', argsArr: [ConfigManager.getSelectedServer()]})
  571. }
  572. })
  573. } else {
  574. refreshDistributionIndex(true, (data) => {
  575. onDistroRefresh(data)
  576. aEx.send({task: 0, content: 'validateDistribution', argsArr: [ConfigManager.getSelectedServer()]})
  577. }, (err) => {
  578. refreshDistributionIndex(false, (data) => {
  579. onDistroRefresh(data)
  580. }, (err) => {
  581. console.error('Unable to refresh distribution index.', err)
  582. if(AssetGuard.getDistributionData() == null){
  583. setOverlayContent(
  584. 'Fatal Error',
  585. 'Could not load a copy of the distribution index. See the console for more details.',
  586. 'Okay'
  587. )
  588. setOverlayHandler(null)
  589. toggleOverlay(true)
  590. toggleLaunchArea(false)
  591. // Disconnect from AssetExec
  592. aEx.disconnect()
  593. } else {
  594. aEx.send({task: 0, content: 'validateDistribution', argsArr: [ConfigManager.getSelectedServer()]})
  595. }
  596. })
  597. })
  598. }
  599. }
  600. /**
  601. * News Loading Functions
  602. */
  603. // DOM Cache
  604. const newsContent = document.getElementById('newsContent')
  605. const newsArticleTitle = document.getElementById('newsArticleTitle')
  606. const newsArticleDate = document.getElementById('newsArticleDate')
  607. const newsArticleAuthor = document.getElementById('newsArticleAuthor')
  608. const newsArticleComments = document.getElementById('newsArticleComments')
  609. const newsNavigationStatus = document.getElementById('newsNavigationStatus')
  610. const newsArticleContentScrollable = document.getElementById('newsArticleContentScrollable')
  611. const nELoadSpan = document.getElementById('nELoadSpan')
  612. // News slide caches.
  613. let newsActive = false
  614. let newsGlideCount = 0
  615. /**
  616. * Show the news UI via a slide animation.
  617. *
  618. * @param {boolean} up True to slide up, otherwise false.
  619. */
  620. function slide_(up){
  621. const lCUpper = document.querySelector('#landingContainer > #upper')
  622. const lCLLeft = document.querySelector('#landingContainer > #lower > #left')
  623. const lCLCenter = document.querySelector('#landingContainer > #lower > #center')
  624. const lCLRight = document.querySelector('#landingContainer > #lower > #right')
  625. const newsBtn = document.querySelector('#landingContainer > #lower > #center #content')
  626. const landingContainer = document.getElementById('landingContainer')
  627. const newsContainer = document.querySelector('#landingContainer > #newsContainer')
  628. newsGlideCount++
  629. if(up){
  630. lCUpper.style.top = '-200vh'
  631. lCLLeft.style.top = '-200vh'
  632. lCLCenter.style.top = '-200vh'
  633. lCLRight.style.top = '-200vh'
  634. newsBtn.style.top = '130vh'
  635. newsContainer.style.top = '0px'
  636. //date.toLocaleDateString('en-US', {month: 'short', day: 'numeric', year: 'numeric', hour: 'numeric', minute: 'numeric'})
  637. //landingContainer.style.background = 'rgba(29, 29, 29, 0.55)'
  638. landingContainer.style.background = 'rgba(0, 0, 0, 0.50)'
  639. setTimeout(() => {
  640. if(newsGlideCount === 1){
  641. lCLCenter.style.transition = 'none'
  642. newsBtn.style.transition = 'none'
  643. }
  644. newsGlideCount--
  645. }, 2000)
  646. } else {
  647. setTimeout(() => {
  648. newsGlideCount--
  649. }, 2000)
  650. landingContainer.style.background = null
  651. lCLCenter.style.transition = null
  652. newsBtn.style.transition = null
  653. newsContainer.style.top = '100%'
  654. lCUpper.style.top = '0px'
  655. lCLLeft.style.top = '0px'
  656. lCLCenter.style.top = '0px'
  657. lCLRight.style.top = '0px'
  658. newsBtn.style.top = '10px'
  659. }
  660. }
  661. // Bind news button.
  662. document.getElementById('newsButton').onclick = () => {
  663. // Toggle tabbing.
  664. if(newsActive){
  665. $('#landingContainer *').removeAttr('tabindex')
  666. $('#newsContainer *').attr('tabindex', '-1')
  667. } else {
  668. $('#landingContainer *').attr('tabindex', '-1')
  669. $('#newsContainer, #newsContainer *, #lower, #lower #center *').removeAttr('tabindex')
  670. if(newsAlertShown){
  671. $('#newsButtonAlert').fadeOut(2000)
  672. newsAlertShown = false
  673. ConfigManager.setNewsCacheDismissed(true)
  674. ConfigManager.save()
  675. }
  676. }
  677. slide_(!newsActive)
  678. newsActive = !newsActive
  679. }
  680. // Array to store article meta.
  681. let newsArr = null
  682. // News load animation listener.
  683. let newsLoadingListener = null
  684. /**
  685. * Set the news loading animation.
  686. *
  687. * @param {boolean} val True to set loading animation, otherwise false.
  688. */
  689. function setNewsLoading(val){
  690. if(val){
  691. const nLStr = 'Checking for News'
  692. let dotStr = '..'
  693. nELoadSpan.innerHTML = nLStr + dotStr
  694. newsLoadingListener = setInterval(() => {
  695. if(dotStr.length >= 3){
  696. dotStr = ''
  697. } else {
  698. dotStr += '.'
  699. }
  700. nELoadSpan.innerHTML = nLStr + dotStr
  701. }, 750)
  702. } else {
  703. if(newsLoadingListener != null){
  704. clearInterval(newsLoadingListener)
  705. newsLoadingListener = null
  706. }
  707. }
  708. }
  709. // Bind retry button.
  710. newsErrorRetry.onclick = () => {
  711. $('#newsErrorFailed').fadeOut(250, () => {
  712. initNews()
  713. $('#newsErrorLoading').fadeIn(250)
  714. })
  715. }
  716. newsArticleContentScrollable.onscroll = (e) => {
  717. if(e.target.scrollTop > Number.parseFloat($('.newsArticleSpacerTop').css('height'))){
  718. newsContent.setAttribute('scrolled', '')
  719. } else {
  720. newsContent.removeAttribute('scrolled')
  721. }
  722. }
  723. /**
  724. * Reload the news without restarting.
  725. *
  726. * @returns {Promise.<void>} A promise which resolves when the news
  727. * content has finished loading and transitioning.
  728. */
  729. function reloadNews(){
  730. return new Promise((resolve, reject) => {
  731. $('#newsContent').fadeOut(250, () => {
  732. $('#newsErrorLoading').fadeIn(250)
  733. initNews().then(() => {
  734. resolve()
  735. })
  736. })
  737. })
  738. }
  739. let newsAlertShown = false
  740. /**
  741. * Show the news alert indicating there is new news.
  742. */
  743. function showNewsAlert(){
  744. newsAlertShown = true
  745. $(newsButtonAlert).fadeIn(250)
  746. }
  747. /**
  748. * Initialize News UI. This will load the news and prepare
  749. * the UI accordingly.
  750. *
  751. * @returns {Promise.<void>} A promise which resolves when the news
  752. * content has finished loading and transitioning.
  753. */
  754. function initNews(){
  755. return new Promise((resolve, reject) => {
  756. setNewsLoading(true)
  757. let news = {}
  758. loadNews().then(news => {
  759. newsArr = news.articles || null
  760. if(newsArr == null){
  761. // News Loading Failed
  762. setNewsLoading(false)
  763. $('#newsErrorLoading').fadeOut(250, () => {
  764. $('#newsErrorFailed').fadeIn(250, () => {
  765. resolve()
  766. })
  767. })
  768. } else if(newsArr.length === 0) {
  769. // No News Articles
  770. setNewsLoading(false)
  771. ConfigManager.setNewsCache({
  772. date: null,
  773. content: null,
  774. dismissed: false
  775. })
  776. ConfigManager.save()
  777. $('#newsErrorLoading').fadeOut(250, () => {
  778. $('#newsErrorNone').fadeIn(250, () => {
  779. resolve()
  780. })
  781. })
  782. } else {
  783. // Success
  784. setNewsLoading(false)
  785. const lN = newsArr[0]
  786. const cached = ConfigManager.getNewsCache()
  787. let newHash = crypto.createHash('sha1').update(lN.content).digest('hex')
  788. let newDate = new Date(lN.date)
  789. let isNew = false
  790. if(cached.date != null && cached.content != null){
  791. if(new Date(cached.date) >= newDate){
  792. // Compare Content
  793. if(cached.content !== newHash){
  794. isNew = true
  795. showNewsAlert()
  796. } else {
  797. if(!cached.dismissed){
  798. isNew = true
  799. showNewsAlert()
  800. }
  801. }
  802. } else {
  803. isNew = true
  804. showNewsAlert()
  805. }
  806. } else {
  807. isNew = true
  808. showNewsAlert()
  809. }
  810. if(isNew){
  811. ConfigManager.setNewsCache({
  812. date: newDate.getTime(),
  813. content: newHash,
  814. dismissed: false
  815. })
  816. ConfigManager.save()
  817. }
  818. const switchHandler = (forward) => {
  819. let cArt = parseInt(newsContent.getAttribute('article'))
  820. let nxtArt = forward ? (cArt >= newsArr.length-1 ? 0 : cArt + 1) : (cArt <= 0 ? newsArr.length-1 : cArt - 1)
  821. displayArticle(newsArr[nxtArt], nxtArt+1)
  822. }
  823. document.getElementById('newsNavigateRight').onclick = () => { switchHandler(true) }
  824. document.getElementById('newsNavigateLeft').onclick = () => { switchHandler(false) }
  825. $('#newsErrorContainer').fadeOut(250, () => {
  826. displayArticle(newsArr[0], 1)
  827. $('#newsContent').fadeIn(250, () => {
  828. resolve()
  829. })
  830. })
  831. }
  832. })
  833. })
  834. }
  835. /**
  836. * Add keyboard controls to the news UI. Left and right arrows toggle
  837. * between articles. If you are on the landing page, the up arrow will
  838. * open the news UI.
  839. */
  840. document.addEventListener('keydown', (e) => {
  841. if(newsActive){
  842. if(e.key === 'ArrowRight' || e.key === 'ArrowLeft'){
  843. document.getElementById(e.key === 'ArrowRight' ? 'newsNavigateRight' : 'newsNavigateLeft').click()
  844. }
  845. // Interferes with scrolling an article using the down arrow.
  846. // Not sure of a straight forward solution at this point.
  847. // if(e.key === 'ArrowDown'){
  848. // document.getElementById('newsButton').click()
  849. // }
  850. } else {
  851. if(getCurrentView() === VIEWS.landing){
  852. if(e.key === 'ArrowUp'){
  853. document.getElementById('newsButton').click()
  854. }
  855. }
  856. }
  857. })
  858. /**
  859. * Display a news article on the UI.
  860. *
  861. * @param {Object} articleObject The article meta object.
  862. * @param {number} index The article index.
  863. */
  864. function displayArticle(articleObject, index){
  865. newsArticleTitle.innerHTML = articleObject.title
  866. newsArticleTitle.href = articleObject.link
  867. newsArticleAuthor.innerHTML = 'by ' + articleObject.author
  868. newsArticleDate.innerHTML = articleObject.date
  869. newsArticleComments.innerHTML = articleObject.comments
  870. newsArticleComments.href = articleObject.commentsLink
  871. newsArticleContentScrollable.innerHTML = '<div id="newsArticleContentWrapper"><div class="newsArticleSpacerTop"></div>' + articleObject.content + '<div class="newsArticleSpacerBot"></div></div>'
  872. newsNavigationStatus.innerHTML = index + ' of ' + newsArr.length
  873. newsContent.setAttribute('article', index-1)
  874. }
  875. /**
  876. * Load news information from the RSS feed specified in the
  877. * distribution index.
  878. */
  879. function loadNews(){
  880. return new Promise((resolve, reject) => {
  881. const distroData = AssetGuard.getDistributionData()
  882. const newsFeed = distroData['news_feed']
  883. const newsHost = new URL(newsFeed).origin + '/'
  884. $.ajax(
  885. {
  886. url: newsFeed,
  887. success: (data) => {
  888. const items = $(data).find('item')
  889. const articles = []
  890. for(let i=0; i<items.length; i++){
  891. // JQuery Element
  892. const el = $(items[i])
  893. // Resolve date.
  894. const date = new Date(el.find('pubDate').text()).toLocaleDateString('en-US', {month: 'short', day: 'numeric', year: 'numeric', hour: 'numeric', minute: 'numeric'})
  895. // Resolve comments.
  896. let comments = el.find('slash\\:comments').text() || '0'
  897. comments = comments + ' Comment' + (comments === '1' ? '' : 's')
  898. // Fix relative links in content.
  899. let content = el.find('content\\:encoded').text()
  900. let regex = /src="(?!http:\/\/|https:\/\/)(.+)"/g
  901. let matches
  902. while(matches = regex.exec(content)){
  903. content = content.replace(matches[1], newsHost + matches[1])
  904. }
  905. let link = el.find('link').text()
  906. let title = el.find('title').text()
  907. let author = el.find('dc\\:creator').text()
  908. // Generate article.
  909. articles.push(
  910. {
  911. link,
  912. title,
  913. date,
  914. author,
  915. content,
  916. comments,
  917. commentsLink: link + '#comments'
  918. }
  919. )
  920. }
  921. resolve({
  922. articles
  923. })
  924. },
  925. timeout: 2500
  926. }).catch(err => {
  927. resolve({
  928. articles: null
  929. })
  930. })
  931. })
  932. }