uibinder.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383
  1. /**
  2. * Initialize UI functions which depend on internal modules.
  3. * Loaded after core UI functions are initialized in uicore.js.
  4. */
  5. // Requirements
  6. const path = require('path')
  7. const AuthManager = require('./assets/js/authmanager')
  8. const ConfigManager = require('./assets/js/configmanager')
  9. const DistroManager = require('./assets/js/distromanager')
  10. let rscShouldLoad = false
  11. let fatalStartupError = false
  12. // Mapping of each view to their container IDs.
  13. const VIEWS = {
  14. landing: '#landingContainer',
  15. login: '#loginContainer',
  16. settings: '#settingsContainer',
  17. welcome: '#welcomeContainer'
  18. }
  19. // The currently shown view container.
  20. let currentView
  21. /**
  22. * Switch launcher views.
  23. *
  24. * @param {string} current The ID of the current view container.
  25. * @param {*} next The ID of the next view container.
  26. * @param {*} currentFadeTime Optional. The fade out time for the current view.
  27. * @param {*} nextFadeTime Optional. The fade in time for the next view.
  28. * @param {*} onCurrentFade Optional. Callback function to execute when the current
  29. * view fades out.
  30. * @param {*} onNextFade Optional. Callback function to execute when the next view
  31. * fades in.
  32. */
  33. function switchView(current, next, currentFadeTime = 500, nextFadeTime = 500, onCurrentFade = () => {}, onNextFade = () => {}){
  34. currentView = next
  35. $(`${current}`).fadeOut(currentFadeTime, () => {
  36. onCurrentFade()
  37. $(`${next}`).fadeIn(nextFadeTime, () => {
  38. onNextFade()
  39. })
  40. })
  41. }
  42. /**
  43. * Get the currently shown view container.
  44. *
  45. * @returns {string} The currently shown view container.
  46. */
  47. function getCurrentView(){
  48. return currentView
  49. }
  50. function showMainUI(data){
  51. if(!isDev){
  52. console.log('%c[AutoUpdater]', 'color: #a02d2a; font-weight: bold', 'Initializing..')
  53. ipcRenderer.send('autoUpdateAction', 'initAutoUpdater', ConfigManager.getAllowPrerelease())
  54. }
  55. updateSelectedServer(data.getServer(ConfigManager.getSelectedServer()).getName())
  56. refreshServerStatus()
  57. setTimeout(() => {
  58. document.getElementById('frameBar').style.backgroundColor = 'rgba(0, 0, 0, 0.5)'
  59. document.body.style.backgroundImage = `url('assets/images/backgrounds/${document.body.getAttribute('bkid')}.jpg')`
  60. $('#main').show()
  61. const isLoggedIn = Object.keys(ConfigManager.getAuthAccounts()).length > 0
  62. // If this is enabled in a development environment we'll get ratelimited.
  63. // The relaunch frequency is usually far too high.
  64. if(!isDev && isLoggedIn){
  65. validateSelectedAccount().then((v) => {
  66. if(v){
  67. console.log('%c[AuthManager]', 'color: #209b07; font-weight: bold', 'Account access token validated.')
  68. } else {
  69. console.log('%c[AuthManager]', 'color: #a02d2a; font-weight: bold', 'Account access token is invalid.')
  70. }
  71. })
  72. }
  73. if(ConfigManager.isFirstLaunch()){
  74. currentView = VIEWS.welcome
  75. $(VIEWS.welcome).fadeIn(1000)
  76. } else {
  77. if(isLoggedIn){
  78. currentView = VIEWS.landing
  79. $(VIEWS.landing).fadeIn(1000)
  80. } else {
  81. currentView = VIEWS.login
  82. $(VIEWS.login).fadeIn(1000)
  83. }
  84. }
  85. setTimeout(() => {
  86. $('#loadingContainer').fadeOut(500, () => {
  87. $('#loadSpinnerImage').removeClass('rotating')
  88. })
  89. }, 250)
  90. }, 750)
  91. // Disable tabbing to the news container.
  92. initNews().then(() => {
  93. $("#newsContainer *").attr('tabindex', '-1')
  94. })
  95. }
  96. function showFatalStartupError(){
  97. setTimeout(() => {
  98. $('#loadingContainer').fadeOut(250, () => {
  99. document.getElementById('overlayContainer').style.background = 'none'
  100. setOverlayContent(
  101. 'Fatal Error: Unable to Load Distribution Index',
  102. 'A connection could not be established to our servers to download the distribution index. No local copies were available to load. <br><br>The distribution index is an essential file which provides the latest server information. The launcher is unable to start without it. Ensure you are connected to the internet and relaunch the application.',
  103. 'Close'
  104. )
  105. setOverlayHandler(() => {
  106. const window = remote.getCurrentWindow()
  107. window.close()
  108. })
  109. toggleOverlay(true)
  110. })
  111. }, 750)
  112. }
  113. /**
  114. * Common functions to perform after refreshing the distro index.
  115. *
  116. * @param {Object} data The distro index object.
  117. */
  118. function onDistroRefresh(data){
  119. updateSelectedServer(data.getServer(ConfigManager.getSelectedServer()).getName())
  120. refreshServerStatus()
  121. initNews()
  122. syncModConfigurations(data)
  123. }
  124. /**
  125. * Sync the mod configurations with the distro index.
  126. *
  127. * @param {Object} data The distro index object.
  128. */
  129. function syncModConfigurations(data){
  130. const syncedCfgs = []
  131. for(let serv of data.getServers()){
  132. const id = serv.getID()
  133. const mdls = serv.getModules()
  134. const cfg = ConfigManager.getModConfiguration(id)
  135. if(cfg != null){
  136. const modsOld = cfg.mods
  137. const mods = {}
  138. for(let mdl of mdls){
  139. const type = mdl.getType()
  140. if(type === DistroManager.Types.ForgeMod || type === DistroManager.Types.LiteMod || type === DistroManager.Types.LiteLoader){
  141. if(!mdl.getRequired().isRequired()){
  142. const mdlID = mdl.getVersionlessID()
  143. if(modsOld[mdlID] == null){
  144. mods[mdlID] = scanOptionalSubModules(mdl.getSubModules(), mdl)
  145. } else {
  146. mods[mdlID] = mergeModConfiguration(modsOld[mdlID], scanOptionalSubModules(mdl.getSubModules(), mdl))
  147. }
  148. }
  149. }
  150. }
  151. syncedCfgs.push({
  152. id,
  153. mods
  154. })
  155. } else {
  156. const mods = {}
  157. for(let mdl of mdls){
  158. const type = mdl.getType()
  159. if(type === DistroManager.Types.ForgeMod || type === DistroManager.Types.LiteMod || type === DistroManager.Types.LiteLoader){
  160. if(!mdl.getRequired().isRequired()){
  161. mods[mdl.getVersionlessID()] = scanOptionalSubModules(mdl.getSubModules(), mdl)
  162. }
  163. }
  164. }
  165. syncedCfgs.push({
  166. id,
  167. mods
  168. })
  169. }
  170. }
  171. ConfigManager.setModConfigurations(syncedCfgs)
  172. ConfigManager.save()
  173. }
  174. /**
  175. * Recursively scan for optional sub modules. If none are found,
  176. * this function returns a boolean. If optional sub modules do exist,
  177. * a recursive configuration object is returned.
  178. *
  179. * @returns {boolean | Object} The resolved mod configuration.
  180. */
  181. function scanOptionalSubModules(mdls, origin){
  182. if(mdls != null){
  183. const mods = {}
  184. for(let mdl of mdls){
  185. const type = mdl.getType()
  186. // Optional types.
  187. if(type === DistroManager.Types.ForgeMod || type === DistroManager.Types.LiteMod || type === DistroManager.Types.LiteLoader){
  188. // It is optional.
  189. if(!mdl.getRequired().isRequired()){
  190. mods[mdl.getVersionlessID()] = scanOptionalSubModules(mdl.getSubModules(), mdl)
  191. }
  192. }
  193. }
  194. if(Object.keys(mods).length > 0){
  195. return {
  196. value: origin.getRequired().isDefault(),
  197. mods
  198. }
  199. }
  200. }
  201. return origin.getRequired().isDefault()
  202. }
  203. /**
  204. * Recursively merge an old configuration into a new configuration.
  205. *
  206. * @param {boolean | Object} o The old configuration value.
  207. * @param {boolean | Object} n The new configuration value.
  208. *
  209. * @returns {boolean | Object} The merged configuration.
  210. */
  211. function mergeModConfiguration(o, n){
  212. if(typeof o === 'boolean'){
  213. if(typeof n === 'boolean') return o
  214. else if(typeof n === 'object'){
  215. n.value = o
  216. return n
  217. }
  218. } else if(typeof o === 'object'){
  219. if(typeof n === 'boolean') return o.value
  220. else if(typeof n === 'object'){
  221. n.value = o.value
  222. const newMods = Object.keys(n.mods)
  223. for(let i=0; i<newMods.length; i++){
  224. const mod = newMods[i]
  225. if(o.mods[mod] != null){
  226. n.mods[mod] = mergeModConfiguration(o.mods[mod], n.mods[mod])
  227. }
  228. }
  229. return n
  230. }
  231. }
  232. // If for some reason we haven't been able to merge,
  233. // wipe the old value and use the new one. Just to be safe
  234. return n
  235. }
  236. function refreshDistributionIndex(remote, onSuccess, onError){
  237. if(remote){
  238. DistroManager.pullRemote()
  239. .then(onSuccess)
  240. .catch(onError)
  241. } else {
  242. DistroManager.pullLocal()
  243. .then(onSuccess)
  244. .catch(onError)
  245. }
  246. }
  247. async function validateSelectedAccount(){
  248. const selectedAcc = ConfigManager.getSelectedAccount()
  249. if(selectedAcc != null){
  250. const val = await AuthManager.validateSelected()
  251. if(!val){
  252. ConfigManager.removeAuthAccount(selectedAcc.uuid)
  253. ConfigManager.save()
  254. const accLen = Object.keys(ConfigManager.getAuthAccounts()).length
  255. setOverlayContent(
  256. 'Failed to Refresh Login',
  257. `We were unable to refresh the login for <strong>${selectedAcc.displayName}</strong>. Please ${accLen > 0 ? 'select another account or ' : ''} login again.`,
  258. 'Login',
  259. 'Select Another Account'
  260. )
  261. setOverlayHandler(() => {
  262. document.getElementById('loginUsername').value = selectedAcc.username
  263. validateEmail(selectedAcc.username)
  264. loginViewOnSuccess = getCurrentView()
  265. switchView(getCurrentView(), VIEWS.login)
  266. toggleOverlay(false)
  267. })
  268. setDismissHandler(() => {
  269. if(accLen > 1){
  270. prepareAccountSelectionList()
  271. $('#overlayContent').fadeOut(250, () => {
  272. $('#accountSelectContent').fadeIn(250)
  273. })
  274. } else {
  275. const accountsObj = ConfigManager.getAuthAccounts()
  276. const accounts = Array.from(Object.keys(accountsObj), v => accountsObj[v]);
  277. // This function validates the account switch.
  278. setSelectedAccount(accounts[0].uuid)
  279. toggleOverlay(false)
  280. }
  281. })
  282. toggleOverlay(true, accLen > 0)
  283. } else {
  284. return true
  285. }
  286. } else {
  287. return true
  288. }
  289. }
  290. /**
  291. * Temporary function to update the selected account along
  292. * with the relevent UI elements.
  293. *
  294. * @param {string} uuid The UUID of the account.
  295. */
  296. function setSelectedAccount(uuid){
  297. const authAcc = ConfigManager.setSelectedAccount(uuid)
  298. ConfigManager.save()
  299. updateSelectedAccount(authAcc)
  300. validateSelectedAccount()
  301. }
  302. // Synchronous Listener
  303. document.addEventListener('readystatechange', function(){
  304. if (document.readyState === 'complete'){
  305. if(rscShouldLoad){
  306. if(!fatalStartupError){
  307. const data = DistroManager.getDistribution()
  308. showMainUI(data)
  309. } else {
  310. showFatalStartupError()
  311. }
  312. }
  313. } else if(document.readyState === 'interactive'){
  314. //toggleOverlay(true, 'loadingContent')
  315. }
  316. /*if (document.readyState === 'interactive'){
  317. }*/
  318. }, false)
  319. // Actions that must be performed after the distribution index is downloaded.
  320. ipcRenderer.on('distributionIndexDone', (event, res) => {
  321. if(res) {
  322. const data = DistroManager.getDistribution()
  323. syncModConfigurations(data)
  324. if(document.readyState === 'complete'){
  325. showMainUI(data)
  326. } else {
  327. rscShouldLoad = true
  328. }
  329. } else {
  330. fatalStartupError = true
  331. if(document.readyState === 'complete'){
  332. showFatalStartupError()
  333. } else {
  334. rscShouldLoad = true
  335. }
  336. }
  337. })