landing.js 16 KB

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