landing.js 18 KB

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