actionbinder.js 18 KB

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