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. let status = 'grey'
  54. try {
  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. } catch (err) {
  71. console.warn('Unable to refresh Mojang service status.')
  72. console.debug(err)
  73. }
  74. document.getElementById('mojang_status_icon').style.color = Mojang.statusToHex(status)
  75. }
  76. refreshMojangStatuses()
  77. // Set refresh rate to once every 5 minutes.
  78. mojangStatusListener = setInterval(refreshMojangStatuses, 300000)
  79. }
  80. }, false)
  81. /* Overlay Wrapper Functions */
  82. /**
  83. * Toggle the visibility of the overlay.
  84. *
  85. * @param {boolean} toggleState True to display, false to hide.
  86. */
  87. function toggleOverlay(toggleState){
  88. if(toggleState == null){
  89. toggleState = !document.getElementById('main').hasAttribute('overlay')
  90. }
  91. if(toggleState){
  92. document.getElementById('main').setAttribute('overlay', true)
  93. $('#overlayContainer').fadeToggle(250)
  94. } else {
  95. document.getElementById('main').removeAttribute('overlay')
  96. $('#overlayContainer').fadeToggle(250)
  97. }
  98. }
  99. /**
  100. * Set the content of the overlay.
  101. *
  102. * @param {string} title Overlay title text.
  103. * @param {string} description Overlay description text.
  104. * @param {string} acknowledge Acknowledge button text.
  105. */
  106. function setOverlayContent(title, description, acknowledge){
  107. document.getElementById('overlayTitle').innerHTML = title
  108. document.getElementById('overlayDesc').innerHTML = description
  109. document.getElementById('overlayAcknowledge').innerHTML = acknowledge
  110. }
  111. /**
  112. * Set the onclick handler of the overlay acknowledge button.
  113. * If the handler is null, a default handler will be added.
  114. *
  115. * @param {function} handler
  116. */
  117. function setOverlayHandler(handler){
  118. if(handler == null){
  119. document.getElementById('overlayAcknowledge').onclick = () => {
  120. toggleOverlay(false)
  121. }
  122. } else {
  123. document.getElementById('overlayAcknowledge').onclick = handler
  124. }
  125. }
  126. /* Launch Progress Wrapper Functions */
  127. /**
  128. * Show/hide the loading area.
  129. *
  130. * @param {boolean} loading True if the loading area should be shown, otherwise false.
  131. */
  132. function toggleLaunchArea(loading){
  133. if(loading){
  134. launch_details.style.display = 'flex'
  135. launch_content.style.display = 'none'
  136. } else {
  137. launch_details.style.display = 'none'
  138. launch_content.style.display = 'inline-flex'
  139. }
  140. }
  141. /**
  142. * Set the details text of the loading area.
  143. *
  144. * @param {string} details The new text for the loading details.
  145. */
  146. function setLaunchDetails(details){
  147. launch_details_text.innerHTML = details
  148. }
  149. /**
  150. * Set the value of the loading progress bar and display that value.
  151. *
  152. * @param {number} value The progress value.
  153. * @param {number} max The total size.
  154. * @param {number|string} percent Optional. The percentage to display on the progress label.
  155. */
  156. function setLaunchPercentage(value, max, percent = ((value/max)*100)){
  157. launch_progress.setAttribute('max', max)
  158. launch_progress.setAttribute('value', value)
  159. launch_progress_label.innerHTML = percent + '%'
  160. }
  161. /**
  162. * Set the value of the OS progress bar and display that on the UI.
  163. *
  164. * @param {number} value The progress value.
  165. * @param {number} max The total download size.
  166. * @param {number|string} percent Optional. The percentage to display on the progress label.
  167. */
  168. function setDownloadPercentage(value, max, percent = ((value/max)*100)){
  169. remote.getCurrentWindow().setProgressBar(value/max)
  170. setLaunchPercentage(value, max, percent)
  171. }
  172. /* System (Java) Scan */
  173. let sysAEx
  174. let scanAt
  175. function asyncSystemScan(launchAfter = true){
  176. setLaunchDetails('Please wait..')
  177. toggleLaunchArea(true)
  178. setLaunchPercentage(0, 100)
  179. // Fork a process to run validations.
  180. sysAEx = cp.fork(path.join(__dirname, 'assets', 'js', 'assetexec.js'), [
  181. ConfigManager.getGameDirectory(),
  182. ConfigManager.getJavaExecutable()
  183. ])
  184. sysAEx.on('message', (m) => {
  185. if(m.content === 'validateJava'){
  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. 'Unexpected Issue:<br>Java Download Failed',
  220. '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.',
  221. 'I Understand'
  222. )
  223. setOverlayHandler(() => {
  224. toggleOverlay(false)
  225. toggleLaunchArea(false)
  226. })
  227. toggleOverlay(true)
  228. sysAEx.disconnect()
  229. }
  230. } else if(m.content === 'dl'){
  231. if(m.task === 0){
  232. // Downloading..
  233. setDownloadPercentage(m.value, m.total, m.percent)
  234. } else if(m.task === 1){
  235. // Download will be at 100%, remove the loading from the OS progress bar.
  236. remote.getCurrentWindow().setProgressBar(-1)
  237. // Wait for extration to complete.
  238. setLaunchDetails('Extracting..')
  239. } else if(m.task === 2){
  240. // Extraction completed successfully.
  241. ConfigManager.setJavaExecutable(m.jPath)
  242. ConfigManager.save()
  243. setLaunchDetails('Java Installed!')
  244. if(launchAfter){
  245. dlAsync()
  246. }
  247. sysAEx.disconnect()
  248. } else {
  249. console.error('Unknown download data type.', m)
  250. }
  251. }
  252. })
  253. // Begin system Java scan.
  254. setLaunchDetails('Checking system info..')
  255. sysAEx.send({task: 0, content: 'validateJava', argsArr: [ConfigManager.getLauncherDirectory()]})
  256. }
  257. // Keep reference to Minecraft Process
  258. let proc
  259. // Is DiscordRPC enabled
  260. let hasRPC = false
  261. // Joined server regex
  262. 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
  263. const gameJoined = /\[[0-2][0-9]:[0-6][0-9]:[0-6][0-9]\] \[Client thread\/WARN\]: Skipping bad option: lastServer:/g
  264. const gameJoined2 = /\[[0-2][0-9]:[0-6][0-9]:[0-6][0-9]\] \[Client thread\/INFO\]: Created: \d+x\d+ textures-atlas/g
  265. let aEx
  266. let serv
  267. let versionData
  268. let forgeData
  269. function dlAsync(login = true){
  270. // Login parameter is temporary for debug purposes. Allows testing the validation/downloads without
  271. // launching the game.
  272. if(login) {
  273. if(ConfigManager.getSelectedAccount() == null){
  274. console.error('login first.')
  275. //in devtools AuthManager.addAccount(username, pass)
  276. return
  277. }
  278. }
  279. setLaunchDetails('Please wait..')
  280. toggleLaunchArea(true)
  281. setLaunchPercentage(0, 100)
  282. // Start AssetExec to run validations and downloads in a forked process.
  283. aEx = cp.fork(path.join(__dirname, 'assets', 'js', 'assetexec.js'), [
  284. ConfigManager.getGameDirectory(),
  285. ConfigManager.getJavaExecutable()
  286. ])
  287. // Establish communications between the AssetExec and current process.
  288. aEx.on('message', (m) => {
  289. if(m.content === 'validateDistribution'){
  290. setLaunchPercentage(20, 100)
  291. serv = m.result
  292. console.log('Forge Validation Complete.')
  293. // Begin version load.
  294. setLaunchDetails('Loading version information..')
  295. aEx.send({task: 0, content: 'loadVersionData', argsArr: [serv.mc_version]})
  296. } else if(m.content === 'loadVersionData'){
  297. setLaunchPercentage(40, 100)
  298. versionData = m.result
  299. console.log('Version data loaded.')
  300. // Begin asset validation.
  301. setLaunchDetails('Validating asset integrity..')
  302. aEx.send({task: 0, content: 'validateAssets', argsArr: [versionData]})
  303. } else if(m.content === 'validateAssets'){
  304. // Asset validation can *potentially* take longer, so let's track progress.
  305. if(m.task === 0){
  306. const perc = (m.value/m.total)*20
  307. setLaunchPercentage(40+perc, 100, parseInt(40+perc))
  308. } else {
  309. setLaunchPercentage(60, 100)
  310. console.log('Asset Validation Complete')
  311. // Begin library validation.
  312. setLaunchDetails('Validating library integrity..')
  313. aEx.send({task: 0, content: 'validateLibraries', argsArr: [versionData]})
  314. }
  315. } else if(m.content === 'validateLibraries'){
  316. setLaunchPercentage(80, 100)
  317. console.log('Library validation complete.')
  318. // Begin miscellaneous validation.
  319. setLaunchDetails('Validating miscellaneous file integrity..')
  320. aEx.send({task: 0, content: 'validateMiscellaneous', argsArr: [versionData]})
  321. } else if(m.content === 'validateMiscellaneous'){
  322. setLaunchPercentage(100, 100)
  323. console.log('File validation complete.')
  324. // Download queued files.
  325. setLaunchDetails('Downloading files..')
  326. aEx.send({task: 0, content: 'processDlQueues'})
  327. } else if(m.content === 'dl'){
  328. if(m.task === 0){
  329. setDownloadPercentage(m.value, m.total, m.percent)
  330. } else if(m.task === 1){
  331. // Download will be at 100%, remove the loading from the OS progress bar.
  332. remote.getCurrentWindow().setProgressBar(-1)
  333. setLaunchDetails('Preparing to launch..')
  334. aEx.send({task: 0, content: 'loadForgeData', argsArr: [serv.id]})
  335. } else {
  336. console.error('Unknown download data type.', m)
  337. }
  338. } else if(m.content === 'loadForgeData'){
  339. forgeData = m.result
  340. if(login) {
  341. //if(!(await AuthManager.validateSelected())){
  342. //
  343. //}
  344. const authUser = ConfigManager.getSelectedAccount();
  345. console.log('authu', authUser)
  346. let pb = new ProcessBuilder(ConfigManager.getGameDirectory(), serv, versionData, forgeData, authUser)
  347. setLaunchDetails('Launching game..')
  348. try {
  349. // Build Minecraft process.
  350. proc = pb.build()
  351. setLaunchDetails('Done. Enjoy the server!')
  352. // Attach a temporary listener to the client output.
  353. // Will wait for a certain bit of text meaning that
  354. // the client application has started, and we can hide
  355. // the progress bar stuff.
  356. const tempListener = function(data){
  357. if(data.indexOf('[Client thread/INFO]: -- System Details --') > -1){
  358. toggleLaunchArea(false)
  359. if(hasRPC){
  360. DiscordWrapper.updateDetails('Loading game..')
  361. }
  362. proc.stdout.removeListener('data', tempListener)
  363. }
  364. }
  365. // Listener for Discord RPC.
  366. const gameStateChange = function(data){
  367. if(servJoined.test(data)){
  368. DiscordWrapper.updateDetails('Exploring the Realm!')
  369. } else if(gameJoined.test(data)){
  370. DiscordWrapper.updateDetails('Idling on Main Menu')
  371. }
  372. }
  373. // Bind listeners to stdout.
  374. proc.stdout.on('data', tempListener)
  375. proc.stdout.on('data', gameStateChange)
  376. // Init Discord Hook
  377. const distro = AssetGuard.retrieveDistributionDataSync(ConfigManager.getGameDirectory)
  378. if(distro.discord != null && serv.discord != null){
  379. DiscordWrapper.initRPC(distro.discord, serv.discord)
  380. hasRPC = true
  381. proc.on('close', (code, signal) => {
  382. console.log('Shutting down Discord Rich Presence..')
  383. DiscordWrapper.shutdownRPC()
  384. hasRPC = false
  385. proc = null
  386. })
  387. }
  388. } catch(err) {
  389. // Show that there was an error then hide the
  390. // progress area. Maybe switch this to an error
  391. // alert in the future. TODO
  392. setLaunchDetails('Error: See log for details..')
  393. console.log(err)
  394. setTimeout(function(){
  395. toggleLaunchArea(false)
  396. }, 5000)
  397. }
  398. }
  399. // Disconnect from AssetExec
  400. aEx.disconnect()
  401. }
  402. })
  403. // Begin Validations
  404. // Validate Forge files.
  405. setLaunchDetails('Loading server information..')
  406. aEx.send({task: 0, content: 'validateDistribution', argsArr: [ConfigManager.getSelectedServer()]})
  407. }