landing.js 18 KB

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