actionbinder.js 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500
  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. //m.result = null
  186. if(m.result == null){
  187. // If the result is null, no valid Java installation was found.
  188. // Show this information to the user.
  189. setOverlayContent(
  190. 'No Compatible<br>Java Installation Found..',
  191. '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>.',
  192. 'Install Java'
  193. )
  194. setOverlayHandler(() => {
  195. setLaunchDetails('Preparing Java Download..')
  196. sysAEx.send({task: 0, content: '_enqueueOracleJRE', argsArr: [ConfigManager.getLauncherDirectory()]})
  197. toggleOverlay(false)
  198. })
  199. toggleOverlay(true)
  200. // TODO Add option to not install Java x64.
  201. } else {
  202. // Java installation found, use this to launch the game.
  203. ConfigManager.setJavaExecutable(m.result)
  204. ConfigManager.save()
  205. if(launchAfter){
  206. dlAsync()
  207. }
  208. sysAEx.disconnect()
  209. }
  210. } else if(m.content === '_enqueueOracleJRE'){
  211. if(m.result === true){
  212. // Oracle JRE enqueued successfully, begin download.
  213. setLaunchDetails('Downloading Java..')
  214. sysAEx.send({task: 0, content: 'processDlQueues', argsArr: [[{id:'java', limit:1}]]})
  215. } else {
  216. // Oracle JRE enqueue failed. Probably due to a change in their website format.
  217. // User will have to follow the guide to install Java.
  218. setOverlayContent(
  219. 'Yikes!<br>Java download failed.',
  220. 'Unfortunately we\'ve encountered an issue while attempting to install Java. You will need to install a copy yourself. Please check out <a href="http://westeroscraft.wikia.com/wiki/Troubleshooting_Guide">this guide</a> for more details and instructions.',
  221. 'Got it'
  222. )
  223. setOverlayHandler(null)
  224. toggleOverlay(true)
  225. sysAEx.disconnect()
  226. }
  227. } else if(m.content === 'dl'){
  228. if(m.task === 0){
  229. // Downloading..
  230. setDownloadPercentage(m.value, m.total, m.percent)
  231. } else if(m.task === 1){
  232. // Download will be at 100%, remove the loading from the OS progress bar.
  233. remote.getCurrentWindow().setProgressBar(-1)
  234. // Wait for extration to complete.
  235. setLaunchDetails('Extracting..')
  236. } else if(m.task === 2){
  237. // Extraction completed successfully.
  238. ConfigManager.setJavaExecutable(m.jPath)
  239. ConfigManager.save()
  240. setLaunchDetails('Java Installed!')
  241. if(launchAfter){
  242. dlAsync()
  243. }
  244. sysAEx.disconnect()
  245. } else {
  246. console.error('Unknown download data type.', m)
  247. }
  248. }
  249. })
  250. // Begin system Java scan.
  251. setLaunchDetails('Checking system info..')
  252. sysAEx.send({task: 0, content: 'validateJava', argsArr: [ConfigManager.getLauncherDirectory()]})
  253. }
  254. // Keep reference to Minecraft Process
  255. let proc
  256. // Is DiscordRPC enabled
  257. let hasRPC = false
  258. // Joined server regex
  259. 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
  260. const gameJoined = /\[[0-2][0-9]:[0-6][0-9]:[0-6][0-9]\] \[Client thread\/WARN\]: Skipping bad option: lastServer:/g
  261. const gameJoined2 = /\[[0-2][0-9]:[0-6][0-9]:[0-6][0-9]\] \[Client thread\/INFO\]: Created: \d+x\d+ textures-atlas/g
  262. let aEx
  263. let serv
  264. let versionData
  265. let forgeData
  266. function dlAsync(login = true){
  267. // Login parameter is temporary for debug purposes. Allows testing the validation/downloads without
  268. // launching the game.
  269. if(login) {
  270. if(ConfigManager.getSelectedAccount() == null){
  271. console.error('login first.')
  272. //in devtools AuthManager.addAccount(username, pass)
  273. return
  274. }
  275. }
  276. setLaunchDetails('Please wait..')
  277. toggleLaunchArea(true)
  278. setLaunchPercentage(0, 100)
  279. // Start AssetExec to run validations and downloads in a forked process.
  280. aEx = cp.fork(path.join(__dirname, 'assets', 'js', 'assetexec.js'), [
  281. ConfigManager.getGameDirectory(),
  282. ConfigManager.getJavaExecutable()
  283. ])
  284. // Establish communications between the AssetExec and current process.
  285. aEx.on('message', (m) => {
  286. if(m.content === 'validateDistribution'){
  287. setLaunchPercentage(20, 100)
  288. serv = m.result
  289. console.log('Forge Validation Complete.')
  290. // Begin version load.
  291. setLaunchDetails('Loading version information..')
  292. aEx.send({task: 0, content: 'loadVersionData', argsArr: [serv.mc_version]})
  293. } else if(m.content === 'loadVersionData'){
  294. setLaunchPercentage(40, 100)
  295. versionData = m.result
  296. console.log('Version data loaded.')
  297. // Begin asset validation.
  298. setLaunchDetails('Validating asset integrity..')
  299. aEx.send({task: 0, content: 'validateAssets', argsArr: [versionData]})
  300. } else if(m.content === 'validateAssets'){
  301. // Asset validation can *potentially* take longer, so let's track progress.
  302. if(m.task === 0){
  303. const perc = (m.value/m.total)*20
  304. setLaunchPercentage(40+perc, 100, parseInt(40+perc))
  305. } else {
  306. setLaunchPercentage(60, 100)
  307. console.log('Asset Validation Complete')
  308. // Begin library validation.
  309. setLaunchDetails('Validating library integrity..')
  310. aEx.send({task: 0, content: 'validateLibraries', argsArr: [versionData]})
  311. }
  312. } else if(m.content === 'validateLibraries'){
  313. setLaunchPercentage(80, 100)
  314. console.log('Library validation complete.')
  315. // Begin miscellaneous validation.
  316. setLaunchDetails('Validating miscellaneous file integrity..')
  317. aEx.send({task: 0, content: 'validateMiscellaneous', argsArr: [versionData]})
  318. } else if(m.content === 'validateMiscellaneous'){
  319. setLaunchPercentage(100, 100)
  320. console.log('File validation complete.')
  321. // Download queued files.
  322. setLaunchDetails('Downloading files..')
  323. aEx.send({task: 0, content: 'processDlQueues'})
  324. } else if(m.content === 'dl'){
  325. if(m.task === 0){
  326. setDownloadPercentage(m.value, m.total, m.percent)
  327. } else if(m.task === 1){
  328. // Download will be at 100%, remove the loading from the OS progress bar.
  329. remote.getCurrentWindow().setProgressBar(-1)
  330. setLaunchDetails('Preparing to launch..')
  331. aEx.send({task: 0, content: 'loadForgeData', argsArr: [serv.id]})
  332. } else {
  333. console.error('Unknown download data type.', m)
  334. }
  335. } else if(m.content === 'loadForgeData'){
  336. forgeData = m.result
  337. if(login) {
  338. //if(!(await AuthManager.validateSelected())){
  339. //
  340. //}
  341. const authUser = ConfigManager.getSelectedAccount();
  342. console.log('authu', authUser)
  343. let pb = new ProcessBuilder(ConfigManager.getGameDirectory(), serv, versionData, forgeData, authUser)
  344. setLaunchDetails('Launching game..')
  345. try {
  346. // Build Minecraft process.
  347. proc = pb.build()
  348. setLaunchDetails('Done. Enjoy the server!')
  349. // Attach a temporary listener to the client output.
  350. // Will wait for a certain bit of text meaning that
  351. // the client application has started, and we can hide
  352. // the progress bar stuff.
  353. const tempListener = function(data){
  354. if(data.indexOf('[Client thread/INFO]: -- System Details --') > -1){
  355. toggleLaunchArea(false)
  356. if(hasRPC){
  357. DiscordWrapper.updateDetails('Loading game..')
  358. }
  359. proc.stdout.removeListener('data', tempListener)
  360. }
  361. }
  362. // Listener for Discord RPC.
  363. const gameStateChange = function(data){
  364. if(servJoined.test(data)){
  365. DiscordWrapper.updateDetails('Exploring the Realm!')
  366. } else if(gameJoined.test(data)){
  367. DiscordWrapper.updateDetails('Idling on Main Menu')
  368. }
  369. }
  370. // Bind listeners to stdout.
  371. proc.stdout.on('data', tempListener)
  372. proc.stdout.on('data', gameStateChange)
  373. // Init Discord Hook
  374. const distro = AssetGuard.retrieveDistributionDataSync(ConfigManager.getGameDirectory)
  375. if(distro.discord != null && serv.discord != null){
  376. DiscordWrapper.initRPC(distro.discord, serv.discord)
  377. hasRPC = true
  378. proc.on('close', (code, signal) => {
  379. console.log('Shutting down Discord Rich Presence..')
  380. DiscordWrapper.shutdownRPC()
  381. hasRPC = false
  382. proc = null
  383. })
  384. }
  385. } catch(err) {
  386. // Show that there was an error then hide the
  387. // progress area. Maybe switch this to an error
  388. // alert in the future. TODO
  389. setLaunchDetails('Error: See log for details..')
  390. console.log(err)
  391. setTimeout(function(){
  392. toggleLaunchArea(false)
  393. }, 5000)
  394. }
  395. }
  396. // Disconnect from AssetExec
  397. aEx.disconnect()
  398. }
  399. })
  400. // Begin Validations
  401. // Validate Forge files.
  402. setLaunchDetails('Loading server information..')
  403. aEx.send({task: 0, content: 'validateDistribution', argsArr: [ConfigManager.getSelectedServer()]})
  404. }