landing.js 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509
  1. /**
  2. * Script for landing.ejs
  3. */
  4. // Requirements
  5. const cp = require('child_process')
  6. const {URL} = require('url')
  7. // Internal Requirements
  8. const {AssetGuard} = require(path.join(__dirname, 'assets', 'js', 'assetguard.js'))
  9. const AuthManager = require(path.join(__dirname, 'assets', 'js', 'authmanager.js'))
  10. const DiscordWrapper = require(path.join(__dirname, 'assets', 'js', 'discordwrapper.js'))
  11. const Mojang = require(path.join(__dirname, 'assets', 'js', 'mojang.js'))
  12. const ProcessBuilder = require(path.join(__dirname, 'assets', 'js', 'processbuilder.js'))
  13. const ServerStatus = require(path.join(__dirname, 'assets', 'js', 'serverstatus.js'))
  14. // Launch Elements
  15. const launch_content = document.getElementById('launch_content')
  16. const launch_details = document.getElementById('launch_details')
  17. const launch_progress = document.getElementById('launch_progress')
  18. const launch_progress_label = document.getElementById('launch_progress_label')
  19. const launch_details_text = document.getElementById('launch_details_text')
  20. const server_selection_button = document.getElementById('server_selection_button')
  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. // Bind launch button
  68. document.getElementById('launch_button').addEventListener('click', function(e){
  69. console.log('Launching game..')
  70. const jExe = ConfigManager.getJavaExecutable()
  71. if(jExe == null){
  72. asyncSystemScan()
  73. } else {
  74. setLaunchDetails('Please wait..')
  75. toggleLaunchArea(true)
  76. setLaunchPercentage(0, 100)
  77. AssetGuard._validateJavaBinary(jExe).then((v) => {
  78. if(v){
  79. dlAsync()
  80. } else {
  81. asyncSystemScan()
  82. }
  83. })
  84. }
  85. })
  86. // Bind selected server
  87. server_selection_button.innerHTML = '\u2022 ' + AssetGuard.getServerById(ConfigManager.getGameDirectory(), ConfigManager.getSelectedServer()).name
  88. server_selection_button.addEventListener('click', (e) => {
  89. e.target.blur()
  90. toggleOverlay(true, 'serverSelectContent')
  91. })
  92. // Test menu transform.
  93. function slide_(up){
  94. const lCUpper = document.querySelector('#landingContainer > #upper')
  95. const lCLLeft = document.querySelector('#landingContainer > #lower > #left')
  96. const lCLCenter = document.querySelector('#landingContainer > #lower > #center')
  97. const lCLRight = document.querySelector('#landingContainer > #lower > #right')
  98. const menuBtn = document.querySelector('#landingContainer > #lower > #center #content')
  99. if(up){
  100. lCUpper.style.top = '-200vh'
  101. lCLLeft.style.top = '-200vh'
  102. lCLCenter.style.top = '-200vh'
  103. lCLRight.style.top = '-200vh'
  104. menuBtn.style.top = '130vh'
  105. } else {
  106. lCUpper.style.top = '0px'
  107. lCLLeft.style.top = '0px'
  108. lCLCenter.style.top = '0px'
  109. lCLRight.style.top = '0px'
  110. menuBtn.style.top = '10px'
  111. }
  112. }
  113. // Update Mojang Status Color
  114. const refreshMojangStatuses = async function(){
  115. console.log('Refreshing Mojang Statuses..')
  116. let status = 'grey'
  117. try {
  118. const statuses = await Mojang.status()
  119. greenCount = 0
  120. for(let i=0; i<statuses.length; i++){
  121. if(statuses[i].status === 'yellow' && status !== 'red'){
  122. status = 'yellow'
  123. continue
  124. } else if(statuses[i].status === 'red'){
  125. status = 'red'
  126. break
  127. }
  128. ++greenCount
  129. }
  130. if(greenCount == statuses.length){
  131. status = 'green'
  132. }
  133. } catch (err) {
  134. console.warn('Unable to refresh Mojang service status.')
  135. console.debug(err)
  136. }
  137. document.getElementById('mojang_status_icon').style.color = Mojang.statusToHex(status)
  138. }
  139. const refreshServerStatus = async function(){
  140. console.log('Refreshing Server Status')
  141. const serv = AssetGuard.resolveSelectedServer(ConfigManager.getGameDirectory())
  142. let pLabel = 'SERVER'
  143. let pVal = 'OFFLINE'
  144. try {
  145. const serverURL = new URL('my://' + serv.server_ip)
  146. const servStat = await ServerStatus.getStatus(serverURL.hostname, serverURL.port)
  147. if(servStat.online){
  148. pLabel = 'PLAYERS'
  149. pVal = servStat.onlinePlayers + '/' + servStat.maxPlayers
  150. }
  151. } catch (err) {
  152. console.warn('Unable to refresh server status, assuming offline.')
  153. console.debug(err)
  154. }
  155. document.getElementById('landingPlayerLabel').innerHTML = pLabel
  156. document.getElementById('player_count').innerHTML = pVal
  157. }
  158. refreshMojangStatuses()
  159. refreshServerStatus()
  160. // Set refresh rate to once every 5 minutes.
  161. let mojangStatusListener = setInterval(refreshMojangStatuses, 300000)
  162. let serverStatusListener = setInterval(refreshServerStatus, 300000)
  163. /* System (Java) Scan */
  164. let sysAEx
  165. let scanAt
  166. function asyncSystemScan(launchAfter = true){
  167. setLaunchDetails('Please wait..')
  168. toggleLaunchArea(true)
  169. setLaunchPercentage(0, 100)
  170. // Fork a process to run validations.
  171. sysAEx = cp.fork(path.join(__dirname, 'assets', 'js', 'assetexec.js'), [
  172. ConfigManager.getGameDirectory(),
  173. ConfigManager.getJavaExecutable()
  174. ])
  175. sysAEx.on('message', (m) => {
  176. if(m.content === 'validateJava'){
  177. if(m.result == null){
  178. // If the result is null, no valid Java installation was found.
  179. // Show this information to the user.
  180. setOverlayContent(
  181. 'No Compatible<br>Java Installation Found',
  182. '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>.',
  183. 'Install Java',
  184. 'Install Manually'
  185. )
  186. setOverlayHandler(() => {
  187. setLaunchDetails('Preparing Java Download..')
  188. sysAEx.send({task: 0, content: '_enqueueOracleJRE', argsArr: [ConfigManager.getLauncherDirectory()]})
  189. toggleOverlay(false)
  190. })
  191. setDismissHandler(() => {
  192. $('#overlayContent').fadeOut(250, () => {
  193. //$('#overlayDismiss').toggle(false)
  194. setOverlayContent(
  195. 'Don\'t Forget!<br>Java is Required',
  196. '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.',
  197. 'I Understand',
  198. 'Go Back'
  199. )
  200. setOverlayHandler(() => {
  201. toggleLaunchArea(false)
  202. toggleOverlay(false)
  203. })
  204. setDismissHandler(() => {
  205. toggleOverlay(false, true)
  206. asyncSystemScan()
  207. })
  208. $('#overlayContent').fadeIn(250)
  209. })
  210. })
  211. toggleOverlay(true, true)
  212. // TODO Add option to not install Java x64.
  213. } else {
  214. // Java installation found, use this to launch the game.
  215. ConfigManager.setJavaExecutable(m.result)
  216. ConfigManager.save()
  217. if(launchAfter){
  218. dlAsync()
  219. }
  220. sysAEx.disconnect()
  221. }
  222. } else if(m.content === '_enqueueOracleJRE'){
  223. if(m.result === true){
  224. // Oracle JRE enqueued successfully, begin download.
  225. setLaunchDetails('Downloading Java..')
  226. sysAEx.send({task: 0, content: 'processDlQueues', argsArr: [[{id:'java', limit:1}]]})
  227. } else {
  228. // Oracle JRE enqueue failed. Probably due to a change in their website format.
  229. // User will have to follow the guide to install Java.
  230. setOverlayContent(
  231. 'Unexpected Issue:<br>Java Download Failed',
  232. '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.',
  233. 'I Understand'
  234. )
  235. setOverlayHandler(() => {
  236. toggleOverlay(false)
  237. toggleLaunchArea(false)
  238. })
  239. toggleOverlay(true)
  240. sysAEx.disconnect()
  241. }
  242. } else if(m.content === 'dl'){
  243. if(m.task === 0){
  244. // Downloading..
  245. setDownloadPercentage(m.value, m.total, m.percent)
  246. } else if(m.task === 1){
  247. // Download will be at 100%, remove the loading from the OS progress bar.
  248. remote.getCurrentWindow().setProgressBar(-1)
  249. // Wait for extration to complete.
  250. setLaunchDetails('Extracting..')
  251. } else if(m.task === 2){
  252. // Extraction completed successfully.
  253. ConfigManager.setJavaExecutable(m.jPath)
  254. ConfigManager.save()
  255. setLaunchDetails('Java Installed!')
  256. if(launchAfter){
  257. dlAsync()
  258. }
  259. sysAEx.disconnect()
  260. } else {
  261. console.error('Unknown download data type.', m)
  262. }
  263. }
  264. })
  265. // Begin system Java scan.
  266. setLaunchDetails('Checking system info..')
  267. sysAEx.send({task: 0, content: 'validateJava', argsArr: [ConfigManager.getLauncherDirectory()]})
  268. }
  269. // Keep reference to Minecraft Process
  270. let proc
  271. // Is DiscordRPC enabled
  272. let hasRPC = false
  273. // Joined server regex
  274. 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
  275. const gameJoined = /\[[0-2][0-9]:[0-6][0-9]:[0-6][0-9]\] \[Client thread\/WARN\]: Skipping bad option: lastServer:/g
  276. const gameJoined2 = /\[[0-2][0-9]:[0-6][0-9]:[0-6][0-9]\] \[Client thread\/INFO\]: Created: \d+x\d+ textures-atlas/g
  277. let aEx
  278. let serv
  279. let versionData
  280. let forgeData
  281. function dlAsync(login = true){
  282. // Login parameter is temporary for debug purposes. Allows testing the validation/downloads without
  283. // launching the game.
  284. if(login) {
  285. if(ConfigManager.getSelectedAccount() == null){
  286. console.error('login first.')
  287. //in devtools AuthManager.addAccount(username, pass)
  288. return
  289. }
  290. }
  291. setLaunchDetails('Please wait..')
  292. toggleLaunchArea(true)
  293. setLaunchPercentage(0, 100)
  294. // Start AssetExec to run validations and downloads in a forked process.
  295. aEx = cp.fork(path.join(__dirname, 'assets', 'js', 'assetexec.js'), [
  296. ConfigManager.getGameDirectory(),
  297. ConfigManager.getJavaExecutable()
  298. ])
  299. // Establish communications between the AssetExec and current process.
  300. aEx.on('message', (m) => {
  301. if(m.content === 'validateDistribution'){
  302. setLaunchPercentage(20, 100)
  303. serv = m.result
  304. console.log('Forge Validation Complete.')
  305. // Begin version load.
  306. setLaunchDetails('Loading version information..')
  307. aEx.send({task: 0, content: 'loadVersionData', argsArr: [serv.mc_version]})
  308. } else if(m.content === 'loadVersionData'){
  309. setLaunchPercentage(40, 100)
  310. versionData = m.result
  311. console.log('Version data loaded.')
  312. // Begin asset validation.
  313. setLaunchDetails('Validating asset integrity..')
  314. aEx.send({task: 0, content: 'validateAssets', argsArr: [versionData]})
  315. } else if(m.content === 'validateAssets'){
  316. // Asset validation can *potentially* take longer, so let's track progress.
  317. if(m.task === 0){
  318. const perc = (m.value/m.total)*20
  319. setLaunchPercentage(40+perc, 100, parseInt(40+perc))
  320. } else {
  321. setLaunchPercentage(60, 100)
  322. console.log('Asset Validation Complete')
  323. // Begin library validation.
  324. setLaunchDetails('Validating library integrity..')
  325. aEx.send({task: 0, content: 'validateLibraries', argsArr: [versionData]})
  326. }
  327. } else if(m.content === 'validateLibraries'){
  328. setLaunchPercentage(80, 100)
  329. console.log('Library validation complete.')
  330. // Begin miscellaneous validation.
  331. setLaunchDetails('Validating miscellaneous file integrity..')
  332. aEx.send({task: 0, content: 'validateMiscellaneous', argsArr: [versionData]})
  333. } else if(m.content === 'validateMiscellaneous'){
  334. setLaunchPercentage(100, 100)
  335. console.log('File validation complete.')
  336. // Download queued files.
  337. setLaunchDetails('Downloading files..')
  338. aEx.send({task: 0, content: 'processDlQueues'})
  339. } else if(m.content === 'dl'){
  340. if(m.task === 0){
  341. setDownloadPercentage(m.value, m.total, m.percent)
  342. } else if(m.task === 1){
  343. // Download will be at 100%, remove the loading from the OS progress bar.
  344. remote.getCurrentWindow().setProgressBar(-1)
  345. setLaunchDetails('Preparing to launch..')
  346. aEx.send({task: 0, content: 'loadForgeData', argsArr: [serv.id]})
  347. } else {
  348. console.error('Unknown download data type.', m)
  349. }
  350. } else if(m.content === 'loadForgeData'){
  351. forgeData = m.result
  352. if(login) {
  353. //if(!(await AuthManager.validateSelected())){
  354. //
  355. //}
  356. const authUser = ConfigManager.getSelectedAccount()
  357. console.log('authu', authUser)
  358. let pb = new ProcessBuilder(ConfigManager.getGameDirectory(), serv, versionData, forgeData, authUser)
  359. setLaunchDetails('Launching game..')
  360. try {
  361. // Build Minecraft process.
  362. proc = pb.build()
  363. setLaunchDetails('Done. Enjoy the server!')
  364. // Attach a temporary listener to the client output.
  365. // Will wait for a certain bit of text meaning that
  366. // the client application has started, and we can hide
  367. // the progress bar stuff.
  368. const tempListener = function(data){
  369. if(data.indexOf('[Client thread/INFO]: -- System Details --') > -1){
  370. toggleLaunchArea(false)
  371. if(hasRPC){
  372. DiscordWrapper.updateDetails('Loading game..')
  373. }
  374. proc.stdout.removeListener('data', tempListener)
  375. }
  376. }
  377. // Listener for Discord RPC.
  378. const gameStateChange = function(data){
  379. if(servJoined.test(data)){
  380. DiscordWrapper.updateDetails('Exploring the Realm!')
  381. } else if(gameJoined.test(data)){
  382. DiscordWrapper.updateDetails('Idling on Main Menu')
  383. }
  384. }
  385. // Bind listeners to stdout.
  386. proc.stdout.on('data', tempListener)
  387. proc.stdout.on('data', gameStateChange)
  388. // Init Discord Hook
  389. const distro = AssetGuard.retrieveDistributionDataSync(ConfigManager.getGameDirectory)
  390. if(distro.discord != null && serv.discord != null){
  391. DiscordWrapper.initRPC(distro.discord, serv.discord)
  392. hasRPC = true
  393. proc.on('close', (code, signal) => {
  394. console.log('Shutting down Discord Rich Presence..')
  395. DiscordWrapper.shutdownRPC()
  396. hasRPC = false
  397. proc = null
  398. })
  399. }
  400. } catch(err) {
  401. // Show that there was an error then hide the
  402. // progress area. Maybe switch this to an error
  403. // alert in the future. TODO
  404. setLaunchDetails('Error: See log for details..')
  405. console.log(err)
  406. setTimeout(function(){
  407. toggleLaunchArea(false)
  408. }, 5000)
  409. }
  410. }
  411. // Disconnect from AssetExec
  412. aEx.disconnect()
  413. }
  414. })
  415. // Begin Validations
  416. // Validate Forge files.
  417. setLaunchDetails('Loading server information..')
  418. aEx.send({task: 0, content: 'validateDistribution', argsArr: [ConfigManager.getSelectedServer()]})
  419. }