MOBILE-3320 events: Refactor service to singleton

main
Noel De Martin 2020-10-22 12:48:23 +02:00
parent 3647bc628a
commit 10e7df2ce6
17 changed files with 65 additions and 77 deletions

View File

@ -16,7 +16,7 @@ import { createComponent, createMock, prepareComponentTest } from '@/tests/utils
import { AppComponent } from '@app/app.component'; import { AppComponent } from '@app/app.component';
import { CoreLangProvider } from '@services/lang'; import { CoreLangProvider } from '@services/lang';
import { CoreEvents, CoreEventsProvider } from '@services/events'; import { CoreEvents } from '@singletons/events';
describe('App component', () => { describe('App component', () => {
@ -25,7 +25,6 @@ describe('App component', () => {
beforeEach(() => { beforeEach(() => {
langProvider = createMock<CoreLangProvider>(['clearCustomStrings']); langProvider = createMock<CoreLangProvider>(['clearCustomStrings']);
CoreEvents.setInstance(new CoreEventsProvider());
prepareComponentTest(AppComponent, [ prepareComponentTest(AppComponent, [
{ provide: CoreLangProvider, useValue: langProvider }, { provide: CoreLangProvider, useValue: langProvider },
]); ]);
@ -42,7 +41,7 @@ describe('App component', () => {
const fixture = createComponent(AppComponent); const fixture = createComponent(AppComponent);
fixture.componentInstance.ngOnInit(); fixture.componentInstance.ngOnInit();
CoreEvents.instance.trigger(CoreEventsProvider.LOGOUT); CoreEvents.trigger(CoreEvents.LOGOUT);
expect(langProvider.clearCustomStrings).toHaveBeenCalled(); expect(langProvider.clearCustomStrings).toHaveBeenCalled();
}); });

View File

@ -14,7 +14,7 @@
import { Component, OnInit } from '@angular/core'; import { Component, OnInit } from '@angular/core';
import { CoreLangProvider } from '@services/lang'; import { CoreLangProvider } from '@services/lang';
import { CoreEvents, CoreEventsProvider } from '@services/events'; import { CoreEvents } from '@singletons/events';
@Component({ @Component({
selector: 'app-root', selector: 'app-root',
@ -32,7 +32,7 @@ export class AppComponent implements OnInit {
* Component being initialized. * Component being initialized.
*/ */
ngOnInit(): void { ngOnInit(): void {
CoreEvents.instance.on(CoreEventsProvider.LOGOUT, () => { CoreEvents.on(CoreEvents.LOGOUT, () => {
// Go to sites page when user is logged out. // Go to sites page when user is logged out.
// Due to DeepLinker, we need to use the ViewCtrl instead of name. // Due to DeepLinker, we need to use the ViewCtrl instead of name.
// Otherwise some pages are re-created when they shouldn't. // Otherwise some pages are re-created when they shouldn't.

View File

@ -28,7 +28,6 @@ import { CoreAppProvider } from '@services/app';
import { CoreConfigProvider } from '@services/config'; import { CoreConfigProvider } from '@services/config';
import { CoreCronDelegate } from '@services/cron'; import { CoreCronDelegate } from '@services/cron';
import { CoreDbProvider } from '@services/db'; import { CoreDbProvider } from '@services/db';
import { CoreEventsProvider } from '@services/events';
import { CoreFileHelperProvider } from '@services/file-helper'; import { CoreFileHelperProvider } from '@services/file-helper';
import { CoreFileSessionProvider } from '@services/file-session'; import { CoreFileSessionProvider } from '@services/file-session';
import { CoreFileProvider, CoreFile } from '@services/file'; import { CoreFileProvider, CoreFile } from '@services/file';
@ -90,7 +89,6 @@ export function createTranslateLoader(http: HttpClient): TranslateHttpLoader {
CoreConfigProvider, CoreConfigProvider,
CoreCronDelegate, CoreCronDelegate,
CoreDbProvider, CoreDbProvider,
CoreEventsProvider,
CoreFileHelperProvider, CoreFileHelperProvider,
CoreFileSessionProvider, CoreFileSessionProvider,
CoreFileProvider, CoreFileProvider,

View File

@ -13,7 +13,7 @@
// limitations under the License. // limitations under the License.
import { CoreSites } from '@services/sites'; import { CoreSites } from '@services/sites';
import { CoreEvents, CoreEventsProvider } from '@services/events'; import { CoreEvents } from '@singletons/events';
import { CoreSite } from '@classes/site'; import { CoreSite } from '@classes/site';
import { CoreLogger } from '@singletons/logger'; import { CoreLogger } from '@singletons/logger';
@ -95,9 +95,9 @@ export class CoreDelegate {
if (listenSiteEvents) { if (listenSiteEvents) {
// Update handlers on this cases. // Update handlers on this cases.
CoreEvents.instance.on(CoreEventsProvider.LOGIN, this.updateHandlers.bind(this)); CoreEvents.on(CoreEvents.LOGIN, this.updateHandlers.bind(this));
CoreEvents.instance.on(CoreEventsProvider.SITE_UPDATED, this.updateHandlers.bind(this)); CoreEvents.on(CoreEvents.SITE_UPDATED, this.updateHandlers.bind(this));
CoreEvents.instance.on(CoreEventsProvider.SITE_PLUGINS_LOADED, this.updateHandlers.bind(this)); CoreEvents.on(CoreEvents.SITE_PLUGINS_LOADED, this.updateHandlers.bind(this));
} }
} }

View File

@ -17,7 +17,7 @@ import { Md5 } from 'ts-md5/dist/md5';
import { CoreApp } from '@services/app'; import { CoreApp } from '@services/app';
import { CoreDB } from '@services/db'; import { CoreDB } from '@services/db';
import { CoreEvents, CoreEventsProvider } from '@services/events'; import { CoreEvents } from '@singletons/events';
import { CoreFile } from '@services/file'; import { CoreFile } from '@services/file';
import { CoreWS, CoreWSPreSets, CoreWSFileUploadOptions, CoreWSAjaxPreSets, CoreWSExternalWarning } from '@services/ws'; import { CoreWS, CoreWSPreSets, CoreWSFileUploadOptions, CoreWSAjaxPreSets, CoreWSExternalWarning } from '@services/ws';
import { CoreDomUtils } from '@services/utils/dom'; import { CoreDomUtils } from '@services/utils/dom';
@ -576,26 +576,26 @@ export class CoreSite {
} }
// Session expired, trigger event. // Session expired, trigger event.
CoreEvents.instance.trigger(CoreEventsProvider.SESSION_EXPIRED, {}, this.id); CoreEvents.trigger(CoreEvents.SESSION_EXPIRED, {}, this.id);
// Change error message. Try to get data from cache, the event will handle the error. // Change error message. Try to get data from cache, the event will handle the error.
error.message = Translate.instance.instant('core.lostconnection'); error.message = Translate.instance.instant('core.lostconnection');
} else if (error.errorcode === 'userdeleted') { } else if (error.errorcode === 'userdeleted') {
// User deleted, trigger event. // User deleted, trigger event.
CoreEvents.instance.trigger(CoreEventsProvider.USER_DELETED, { params: data }, this.id); CoreEvents.trigger(CoreEvents.USER_DELETED, { params: data }, this.id);
error.message = Translate.instance.instant('core.userdeleted'); error.message = Translate.instance.instant('core.userdeleted');
throw new CoreWSError(error); throw new CoreWSError(error);
} else if (error.errorcode === 'forcepasswordchangenotice') { } else if (error.errorcode === 'forcepasswordchangenotice') {
// Password Change Forced, trigger event. Try to get data from cache, the event will handle the error. // Password Change Forced, trigger event. Try to get data from cache, the event will handle the error.
CoreEvents.instance.trigger(CoreEventsProvider.PASSWORD_CHANGE_FORCED, {}, this.id); CoreEvents.trigger(CoreEvents.PASSWORD_CHANGE_FORCED, {}, this.id);
error.message = Translate.instance.instant('core.forcepasswordchangenotice'); error.message = Translate.instance.instant('core.forcepasswordchangenotice');
} else if (error.errorcode === 'usernotfullysetup') { } else if (error.errorcode === 'usernotfullysetup') {
// User not fully setup, trigger event. Try to get data from cache, the event will handle the error. // User not fully setup, trigger event. Try to get data from cache, the event will handle the error.
CoreEvents.instance.trigger(CoreEventsProvider.USER_NOT_FULLY_SETUP, {}, this.id); CoreEvents.trigger(CoreEvents.USER_NOT_FULLY_SETUP, {}, this.id);
error.message = Translate.instance.instant('core.usernotfullysetup'); error.message = Translate.instance.instant('core.usernotfullysetup');
} else if (error.errorcode === 'sitepolicynotagreed') { } else if (error.errorcode === 'sitepolicynotagreed') {
// Site policy not agreed, trigger event. // Site policy not agreed, trigger event.
CoreEvents.instance.trigger(CoreEventsProvider.SITE_POLICY_NOT_AGREED, {}, this.id); CoreEvents.trigger(CoreEvents.SITE_POLICY_NOT_AGREED, {}, this.id);
error.message = Translate.instance.instant('core.login.sitepolicynotagreederror'); error.message = Translate.instance.instant('core.login.sitepolicynotagreederror');
throw new CoreWSError(error); throw new CoreWSError(error);
@ -1100,7 +1100,7 @@ export class CoreSite {
try { try {
await this.db.updateRecords(CoreSite.WS_CACHE_TABLE, { expirationTime: 0 }); await this.db.updateRecords(CoreSite.WS_CACHE_TABLE, { expirationTime: 0 });
} finally { } finally {
CoreEvents.instance.trigger(CoreEventsProvider.WS_CACHE_INVALIDATED, {}, this.getId()); CoreEvents.trigger(CoreEvents.WS_CACHE_INVALIDATED, {}, this.getId());
} }
} }

View File

@ -14,7 +14,7 @@
import { Component, Input, OnInit, OnChanges, SimpleChange, ViewChild, ElementRef, AfterViewInit } from '@angular/core'; import { Component, Input, OnInit, OnChanges, SimpleChange, ViewChild, ElementRef, AfterViewInit } from '@angular/core';
import { CoreEventLoadingChangedData, CoreEvents, CoreEventsProvider } from '@services/events'; import { CoreEventLoadingChangedData, CoreEvents } from '@singletons/events';
import { CoreUtils } from '@services/utils/utils'; import { CoreUtils } from '@services/utils/utils';
import { Translate } from '@singletons/core.singletons'; import { Translate } from '@singletons/core.singletons';
@ -109,7 +109,7 @@ export class CoreLoadingComponent implements OnInit, OnChanges, AfterViewInit {
// Trigger the event after a timeout since the elements inside ngIf haven't been added to DOM yet. // Trigger the event after a timeout since the elements inside ngIf haven't been added to DOM yet.
setTimeout(() => { setTimeout(() => {
CoreEvents.instance.trigger(CoreEventsProvider.CORE_LOADING_CHANGED, <CoreEventLoadingChangedData> { CoreEvents.trigger(CoreEvents.CORE_LOADING_CHANGED, <CoreEventLoadingChangedData> {
loaded: !!this.hideUntil, loaded: !!this.hideUntil,
uniqueId: this.uniqueId, uniqueId: this.uniqueId,
}); });

View File

@ -25,7 +25,7 @@ import { CoreLoginHelper, CoreLoginHelperProvider } from '@core/login/services/h
import { CoreConstants } from '@/app/core/constants'; import { CoreConstants } from '@/app/core/constants';
import { Translate } from '@singletons/core.singletons'; import { Translate } from '@singletons/core.singletons';
import { CoreSiteIdentityProvider, CoreSitePublicConfigResponse } from '@/app/classes/site'; import { CoreSiteIdentityProvider, CoreSitePublicConfigResponse } from '@/app/classes/site';
import { CoreEvents, CoreEventsProvider } from '@/app/services/events'; import { CoreEvents } from '@singletons/events';
/** /**
* Page that displays a "splash screen" while the app is being initialized. * Page that displays a "splash screen" while the app is being initialized.
@ -172,7 +172,7 @@ export class CoreLoginCredentialsPage implements OnInit, OnDestroy {
if (!this.eventThrown && !this.viewLeft) { if (!this.eventThrown && !this.viewLeft) {
this.eventThrown = true; this.eventThrown = true;
CoreEvents.instance.trigger(CoreEventsProvider.LOGIN_SITE_CHECKED, { config: this.siteConfig }); CoreEvents.trigger(CoreEvents.LOGIN_SITE_CHECKED, { config: this.siteConfig });
} }
} else { } else {
this.authInstructions = undefined; this.authInstructions = undefined;
@ -330,7 +330,7 @@ export class CoreLoginCredentialsPage implements OnInit, OnDestroy {
*/ */
ngOnDestroy(): void { ngOnDestroy(): void {
this.viewLeft = true; this.viewLeft = true;
CoreEvents.instance.trigger(CoreEventsProvider.LOGIN_SITE_UNCHECKED, { config: this.siteConfig }, this.siteId); CoreEvents.trigger(CoreEvents.LOGIN_SITE_UNCHECKED, { config: this.siteConfig }, this.siteId);
} }
} }

View File

@ -20,7 +20,7 @@ import { Md5 } from 'ts-md5/dist/md5';
import { CoreApp, CoreStoreConfig } from '@services/app'; import { CoreApp, CoreStoreConfig } from '@services/app';
import { CoreConfig } from '@services/config'; import { CoreConfig } from '@services/config';
import { CoreEvents, CoreEventSessionExpiredData, CoreEventsProvider } from '@services/events'; import { CoreEvents, CoreEventSessionExpiredData } from '@singletons/events';
import { CoreSites, CoreLoginSiteInfo } from '@services/sites'; import { CoreSites, CoreLoginSiteInfo } from '@services/sites';
import { CoreWS, CoreWSExternalWarning } from '@services/ws'; import { CoreWS, CoreWSExternalWarning } from '@services/ws';
import { CoreDomUtils } from '@services/utils/dom'; import { CoreDomUtils } from '@services/utils/dom';
@ -59,7 +59,7 @@ export class CoreLoginHelperProvider {
) { ) {
this.logger = CoreLogger.getInstance('CoreLoginHelper'); this.logger = CoreLogger.getInstance('CoreLoginHelper');
CoreEvents.instance.on(CoreEventsProvider.MAIN_MENU_OPEN, () => { CoreEvents.on(CoreEvents.MAIN_MENU_OPEN, () => {
/* If there is any page pending to be opened, do it now. Don't open pages stored more than 5 seconds ago, probably /* If there is any page pending to be opened, do it now. Don't open pages stored more than 5 seconds ago, probably
the function to open the page was called when it shouldn't. */ the function to open the page was called when it shouldn't. */
if (this.pageToLoad && Date.now() - this.pageToLoad.time < 5000) { if (this.pageToLoad && Date.now() - this.pageToLoad.time < 5000) {
@ -561,7 +561,7 @@ export class CoreLoginHelperProvider {
} }
if (site.isLoggedOut()) { if (site.isLoggedOut()) {
CoreEvents.instance.trigger(CoreEventsProvider.SESSION_EXPIRED, { CoreEvents.trigger(CoreEvents.SESSION_EXPIRED, {
pageName, pageName,
params, params,
}, site.getId()); }, site.getId());
@ -657,7 +657,7 @@ export class CoreLoginHelperProvider {
if (page == CoreLoginHelperProvider.OPEN_COURSE) { if (page == CoreLoginHelperProvider.OPEN_COURSE) {
// @todo Use the openCourse function. // @todo Use the openCourse function.
} else { } else {
CoreEvents.instance.trigger(CoreEventsProvider.LOAD_PAGE_MAIN_MENU, { redirectPage: page, redirectParams: params }); CoreEvents.trigger(CoreEvents.LOAD_PAGE_MAIN_MENU, { redirectPage: page, redirectParams: params });
} }
} }

View File

@ -15,7 +15,7 @@
import { Directive, ElementRef, Input, Output, EventEmitter, OnChanges, SimpleChange, Optional } from '@angular/core'; import { Directive, ElementRef, Input, Output, EventEmitter, OnChanges, SimpleChange, Optional } from '@angular/core';
import { NavController, IonContent } from '@ionic/angular'; import { NavController, IonContent } from '@ionic/angular';
import { CoreEventLoadingChangedData, CoreEventObserver, CoreEvents, CoreEventsProvider } from '@services/events'; import { CoreEventLoadingChangedData, CoreEventObserver, CoreEvents } from '@singletons/events';
import { CoreSites } from '@services/sites'; import { CoreSites } from '@services/sites';
import { CoreDomUtils } from '@services/utils/dom'; import { CoreDomUtils } from '@services/utils/dom';
import { CoreIframeUtils, CoreIframeUtilsProvider } from '@services/utils/iframe'; import { CoreIframeUtils, CoreIframeUtilsProvider } from '@services/utils/iframe';
@ -355,7 +355,7 @@ export class CoreFormatTextDirective implements OnChanges {
if (!this.loadingChangedListener) { if (!this.loadingChangedListener) {
// Recalculate the height if a parent core-loading displays the content. // Recalculate the height if a parent core-loading displays the content.
this.loadingChangedListener = this.loadingChangedListener =
CoreEvents.instance.on(CoreEventsProvider.CORE_LOADING_CHANGED, (data: CoreEventLoadingChangedData) => { CoreEvents.on(CoreEvents.CORE_LOADING_CHANGED, (data: CoreEventLoadingChangedData) => {
if (data.loaded && CoreDomUtils.instance.closest(this.element.parentElement, '#' + data.uniqueId)) { if (data.loaded && CoreDomUtils.instance.closest(this.element.parentElement, '#' + data.uniqueId)) {
// The format-text is inside the loading, re-calculate the height. // The format-text is inside the loading, re-calculate the height.
this.calculateHeight(); this.calculateHeight();

View File

@ -17,7 +17,7 @@ import { Params } from '@angular/router';
import { Connection } from '@ionic-native/network/ngx'; import { Connection } from '@ionic-native/network/ngx';
import { CoreDB } from '@services/db'; import { CoreDB } from '@services/db';
import { CoreEvents, CoreEventsProvider } from '@services/events'; import { CoreEvents } from '@singletons/events';
import { CoreUtils, PromiseDefer } from '@services/utils/utils'; import { CoreUtils, PromiseDefer } from '@services/utils/utils';
import { SQLiteDB, SQLiteDBTableSchema } from '@classes/sqlitedb'; import { SQLiteDB, SQLiteDBTableSchema } from '@classes/sqlitedb';
import { CoreConstants } from '@core/constants'; import { CoreConstants } from '@core/constants';
@ -86,7 +86,7 @@ export class CoreAppProvider {
this.setKeyboardShown(true); this.setKeyboardShown(true);
// Error on iOS calculating size. // Error on iOS calculating size.
// More info: https://github.com/ionic-team/ionic-plugin-keyboard/issues/276 . // More info: https://github.com/ionic-team/ionic-plugin-keyboard/issues/276 .
CoreEvents.instance.trigger(CoreEventsProvider.KEYBOARD_CHANGE, data.keyboardHeight); CoreEvents.trigger(CoreEvents.KEYBOARD_CHANGE, data.keyboardHeight);
}); });
}); });
Keyboard.instance.onKeyboardHide().subscribe(() => { Keyboard.instance.onKeyboardHide().subscribe(() => {
@ -94,7 +94,7 @@ export class CoreAppProvider {
zone.run(() => { zone.run(() => {
document.body.classList.remove('keyboard-is-open'); document.body.classList.remove('keyboard-is-open');
this.setKeyboardShown(false); this.setKeyboardShown(false);
CoreEvents.instance.trigger(CoreEventsProvider.KEYBOARD_CHANGE, 0); CoreEvents.trigger(CoreEvents.KEYBOARD_CHANGE, 0);
}); });
}); });
Keyboard.instance.onKeyboardWillShow().subscribe(() => { Keyboard.instance.onKeyboardWillShow().subscribe(() => {
@ -481,7 +481,7 @@ export class CoreAppProvider {
setMainMenuOpen(id: number, open: boolean): void { setMainMenuOpen(id: number, open: boolean): void {
if (open) { if (open) {
this.mainMenuOpen = id; this.mainMenuOpen = id;
CoreEvents.instance.trigger(CoreEventsProvider.MAIN_MENU_OPEN); CoreEvents.trigger(CoreEvents.MAIN_MENU_OPEN);
} else if (this.mainMenuOpen == id) { } else if (this.mainMenuOpen == id) {
delete this.mainMenuOpen; delete this.mainMenuOpen;
} }

View File

@ -16,7 +16,7 @@ import { Injectable } from '@angular/core';
import { Md5 } from 'ts-md5/dist/md5'; import { Md5 } from 'ts-md5/dist/md5';
import { CoreApp, CoreAppSchema } from '@services/app'; import { CoreApp, CoreAppSchema } from '@services/app';
import { CoreEvents, CoreEventsProvider } from '@services/events'; import { CoreEvents } from '@singletons/events';
import { CoreFile } from '@services/file'; import { CoreFile } from '@services/file';
import { CoreInit } from '@services/init'; import { CoreInit } from '@services/init';
import { CorePluginFile } from '@services/plugin-file-delegate'; import { CorePluginFile } from '@services/plugin-file-delegate';
@ -2455,7 +2455,7 @@ export class CoreFilepoolProvider {
componentId: link.componentId, componentId: link.componentId,
}, eventData); }, eventData);
CoreEvents.instance.trigger(CoreEventsProvider.COMPONENT_FILE_ACTION, data, siteId); CoreEvents.trigger(CoreEvents.COMPONENT_FILE_ACTION, data, siteId);
}); });
} }
@ -2472,7 +2472,7 @@ export class CoreFilepoolProvider {
action: CoreFilepoolFileActions.DELETED, action: CoreFilepoolFileActions.DELETED,
}; };
CoreEvents.instance.trigger(this.getFileEventName(siteId, fileId), data); CoreEvents.trigger(this.getFileEventName(siteId, fileId), data);
this.notifyFileActionToComponents(siteId, data, links); this.notifyFileActionToComponents(siteId, data, links);
} }
@ -2490,7 +2490,7 @@ export class CoreFilepoolProvider {
success: true, success: true,
}; };
CoreEvents.instance.trigger(this.getFileEventName(siteId, fileId), data); CoreEvents.trigger(this.getFileEventName(siteId, fileId), data);
this.notifyFileActionToComponents(siteId, data, links); this.notifyFileActionToComponents(siteId, data, links);
} }
@ -2508,7 +2508,7 @@ export class CoreFilepoolProvider {
success: false, success: false,
}; };
CoreEvents.instance.trigger(this.getFileEventName(siteId, fileId), data); CoreEvents.trigger(this.getFileEventName(siteId, fileId), data);
this.notifyFileActionToComponents(siteId, data, links); this.notifyFileActionToComponents(siteId, data, links);
} }
@ -2525,7 +2525,7 @@ export class CoreFilepoolProvider {
action: CoreFilepoolFileActions.DOWNLOADING, action: CoreFilepoolFileActions.DOWNLOADING,
}; };
CoreEvents.instance.trigger(this.getFileEventName(siteId, fileId), data); CoreEvents.trigger(this.getFileEventName(siteId, fileId), data);
this.notifyFileActionToComponents(siteId, data, links); this.notifyFileActionToComponents(siteId, data, links);
} }
@ -2542,7 +2542,7 @@ export class CoreFilepoolProvider {
action: CoreFilepoolFileActions.OUTDATED, action: CoreFilepoolFileActions.OUTDATED,
}; };
CoreEvents.instance.trigger(this.getFileEventName(siteId, fileId), data); CoreEvents.trigger(this.getFileEventName(siteId, fileId), data);
this.notifyFileActionToComponents(siteId, data, links); this.notifyFileActionToComponents(siteId, data, links);
} }
@ -3121,7 +3121,7 @@ export class CoreFilepoolProvider {
status, status,
}; };
CoreEvents.instance.trigger(CoreEventsProvider.PACKAGE_STATUS_CHANGED, data, siteId); CoreEvents.trigger(CoreEvents.PACKAGE_STATUS_CHANGED, data, siteId);
} }
/** /**

View File

@ -18,7 +18,7 @@ import { ILocalNotification } from '@ionic-native/local-notifications';
import { CoreApp, CoreAppSchema } from '@services/app'; import { CoreApp, CoreAppSchema } from '@services/app';
import { CoreConfig } from '@services/config'; import { CoreConfig } from '@services/config';
import { CoreEventObserver, CoreEvents, CoreEventsProvider } from '@services/events'; import { CoreEventObserver, CoreEvents } from '@singletons/events';
import { CoreTextUtils } from '@services/utils/text'; import { CoreTextUtils } from '@services/utils/text';
import { CoreUtils, PromiseDefer } from '@services/utils/utils'; import { CoreUtils, PromiseDefer } from '@services/utils/utils';
import { SQLiteDB } from '@classes/sqlitedb'; import { SQLiteDB } from '@classes/sqlitedb';
@ -159,7 +159,7 @@ export class CoreLocalNotificationsProvider {
this.createDefaultChannel(); this.createDefaultChannel();
}); });
CoreEvents.instance.on(CoreEventsProvider.SITE_DELETED, (site: CoreSite) => { CoreEvents.on(CoreEvents.SITE_DELETED, (site: CoreSite) => {
if (site) { if (site) {
this.cancelSiteNotifications(site.id!); this.cancelSiteNotifications(site.id!);
} }

View File

@ -17,7 +17,7 @@ import { Md5 } from 'ts-md5/dist/md5';
import { timeout } from 'rxjs/operators'; import { timeout } from 'rxjs/operators';
import { CoreApp, CoreAppSchema, CoreStoreConfig } from '@services/app'; import { CoreApp, CoreAppSchema, CoreStoreConfig } from '@services/app';
import { CoreEvents, CoreEventsProvider } from '@services/events'; import { CoreEvents } from '@singletons/events';
import { CoreWS } from '@services/ws'; import { CoreWS } from '@services/ws';
import { CoreDomUtils } from '@services/utils/dom'; import { CoreDomUtils } from '@services/utils/dom';
import { CoreTextUtils } from '@services/utils/text'; import { CoreTextUtils } from '@services/utils/text';
@ -660,7 +660,7 @@ export class CoreSitesProvider {
this.login(siteId); this.login(siteId);
} }
CoreEvents.instance.trigger(CoreEventsProvider.SITE_ADDED, info, siteId); CoreEvents.trigger(CoreEvents.SITE_ADDED, info, siteId);
return siteId; return siteId;
} catch (error) { } catch (error) {
@ -966,7 +966,7 @@ export class CoreSitesProvider {
if (site.isLoggedOut()) { if (site.isLoggedOut()) {
// Logged out, trigger session expired event and stop. // Logged out, trigger session expired event and stop.
CoreEvents.instance.trigger(CoreEventsProvider.SESSION_EXPIRED, { CoreEvents.trigger(CoreEvents.SESSION_EXPIRED, {
pageName, pageName,
params, params,
}, site.getId()); }, site.getId());
@ -979,7 +979,7 @@ export class CoreSitesProvider {
await site.checkIfLocalMobileInstalledAndNotUsed(); await site.checkIfLocalMobileInstalledAndNotUsed();
// Local mobile was added. Throw invalid session to force reconnect and create a new token. // Local mobile was added. Throw invalid session to force reconnect and create a new token.
CoreEvents.instance.trigger(CoreEventsProvider.SESSION_EXPIRED, { CoreEvents.trigger(CoreEvents.SESSION_EXPIRED, {
pageName, pageName,
params, params,
}, siteId); }, siteId);
@ -1093,7 +1093,7 @@ export class CoreSitesProvider {
// Site deleted from sites list, now delete the folder. // Site deleted from sites list, now delete the folder.
await site.deleteFolder(); await site.deleteFolder();
CoreEvents.instance.trigger(CoreEventsProvider.SITE_DELETED, site, siteId); CoreEvents.trigger(CoreEvents.SITE_DELETED, site, siteId);
} }
/** /**
@ -1301,7 +1301,7 @@ export class CoreSitesProvider {
await this.appDB.insertRecord(CURRENT_SITE_TABLE, entry); await this.appDB.insertRecord(CURRENT_SITE_TABLE, entry);
CoreEvents.instance.trigger(CoreEventsProvider.LOGIN, {}, siteId); CoreEvents.trigger(CoreEvents.LOGIN, {}, siteId);
} }
/** /**
@ -1331,7 +1331,7 @@ export class CoreSitesProvider {
try { try {
await Promise.all(promises); await Promise.all(promises);
} finally { } finally {
CoreEvents.instance.trigger(CoreEventsProvider.LOGOUT, {}, siteId); CoreEvents.trigger(CoreEvents.LOGOUT, {}, siteId);
} }
} }
@ -1473,7 +1473,7 @@ export class CoreSitesProvider {
try { try {
await this.appDB.updateRecords(SITES_TABLE, newValues, { id: siteId }); await this.appDB.updateRecords(SITES_TABLE, newValues, { id: siteId });
} finally { } finally {
CoreEvents.instance.trigger(CoreEventsProvider.SITE_UPDATED, info, siteId); CoreEvents.trigger(CoreEvents.SITE_UPDATED, info, siteId);
} }
} catch (error) { } catch (error) {
// Ignore that we cannot fetch site info. Probably the auth token is invalid. // Ignore that we cannot fetch site info. Probably the auth token is invalid.

View File

@ -13,7 +13,7 @@
// limitations under the License. // limitations under the License.
import { Injectable } from '@angular/core'; import { Injectable } from '@angular/core';
import { CoreEvents, CoreEventsProvider } from '@services/events'; import { CoreEvents } from '@singletons/events';
import { CoreSites, CoreSiteSchema } from '@services/sites'; import { CoreSites, CoreSiteSchema } from '@services/sites';
import { makeSingleton } from '@singletons/core.singletons'; import { makeSingleton } from '@singletons/core.singletons';
@ -64,7 +64,7 @@ export class CoreSyncProvider {
CoreSites.instance.registerSiteSchema(this.siteSchema); CoreSites.instance.registerSiteSchema(this.siteSchema);
// Unblock all blocks on logout. // Unblock all blocks on logout.
CoreEvents.instance.on(CoreEventsProvider.LOGOUT, (data: {siteId: string}) => { CoreEvents.on(CoreEvents.LOGOUT, (data: {siteId: string}) => {
this.clearAllBlocks(data.siteId); this.clearAllBlocks(data.siteId);
}); });
} }

View File

@ -20,7 +20,7 @@ import { Md5 } from 'ts-md5';
import { CoreApp } from '@services/app'; import { CoreApp } from '@services/app';
import { CoreConfig } from '@services/config'; import { CoreConfig } from '@services/config';
import { CoreEvents, CoreEventsProvider } from '@services/events'; import { CoreEvents } from '@singletons/events';
import { CoreFile } from '@services/file'; import { CoreFile } from '@services/file';
import { CoreWSExternalWarning } from '@services/ws'; import { CoreWSExternalWarning } from '@services/ws';
import { CoreTextUtils, CoreTextErrorObject } from '@services/utils/text'; import { CoreTextUtils, CoreTextErrorObject } from '@services/utils/text';
@ -1723,7 +1723,7 @@ export class CoreDomUtilsProvider {
return; return;
} }
CoreEvents.instance.trigger(CoreEventsProvider.FORM_ACTION, { CoreEvents.trigger(CoreEvents.FORM_ACTION, {
action: 'cancel', action: 'cancel',
form: formRef.nativeElement, form: formRef.nativeElement,
}, siteId); }, siteId);
@ -1741,7 +1741,7 @@ export class CoreDomUtilsProvider {
return; return;
} }
CoreEvents.instance.trigger(CoreEventsProvider.FORM_ACTION, { CoreEvents.trigger(CoreEvents.FORM_ACTION, {
action: 'submit', action: 'submit',
form: formRef.nativeElement, form: formRef.nativeElement,
online: !!online, online: !!online,

View File

@ -18,7 +18,7 @@ import { FileEntry } from '@ionic-native/file';
import { Subscription } from 'rxjs'; import { Subscription } from 'rxjs';
import { CoreApp } from '@services/app'; import { CoreApp } from '@services/app';
import { CoreEvents, CoreEventsProvider } from '@services/events'; import { CoreEvents } from '@singletons/events';
import { CoreFile } from '@services/file'; import { CoreFile } from '@services/file';
import { CoreLang } from '@services/lang'; import { CoreLang } from '@services/lang';
import { CoreWS, CoreWSExternalFile } from '@services/ws'; import { CoreWS, CoreWSExternalFile } from '@services/ws';
@ -973,7 +973,7 @@ export class CoreUtilsProvider {
loadStartUrls.shift(); loadStartUrls.shift();
} }
CoreEvents.instance.trigger(CoreEventsProvider.IAB_LOAD_START, event); CoreEvents.trigger(CoreEvents.IAB_LOAD_START, event);
}); });
}); });
@ -984,7 +984,7 @@ export class CoreUtilsProvider {
this.zone.run(() => { this.zone.run(() => {
if (loadStartUrls.indexOf(event.url) == -1) { if (loadStartUrls.indexOf(event.url) == -1) {
// The URL was stopped but not started, probably a custom URL scheme. // The URL was stopped but not started, probably a custom URL scheme.
CoreEvents.instance.trigger(CoreEventsProvider.IAB_LOAD_START, event); CoreEvents.trigger(CoreEvents.IAB_LOAD_START, event);
} }
}); });
}); });
@ -996,7 +996,7 @@ export class CoreUtilsProvider {
loadStartSubscription.unsubscribe(); loadStartSubscription.unsubscribe();
loadStopSubscription && loadStopSubscription.unsubscribe(); loadStopSubscription && loadStopSubscription.unsubscribe();
exitSubscription.unsubscribe(); exitSubscription.unsubscribe();
CoreEvents.instance.trigger(CoreEventsProvider.IAB_EXIT, event); CoreEvents.trigger(CoreEvents.IAB_EXIT, event);
}); });
}); });
} }

View File

@ -12,12 +12,10 @@
// See the License for the specific language governing permissions and // See the License for the specific language governing permissions and
// limitations under the License. // limitations under the License.
import { Injectable } from '@angular/core';
import { Params } from '@angular/router'; import { Params } from '@angular/router';
import { Subject } from 'rxjs'; import { Subject } from 'rxjs';
import { CoreLogger } from '@singletons/logger'; import { CoreLogger } from '@singletons/logger';
import { makeSingleton } from '@singletons/core.singletons';
/** /**
* Observer instance to stop listening to an event. * Observer instance to stop listening to an event.
@ -32,8 +30,7 @@ export interface CoreEventObserver {
/* /*
* Service to send and listen to events. * Service to send and listen to events.
*/ */
@Injectable() export class CoreEvents {
export class CoreEventsProvider {
static readonly SESSION_EXPIRED = 'session_expired'; static readonly SESSION_EXPIRED = 'session_expired';
static readonly PASSWORD_CHANGE_FORCED = 'password_change_forced'; static readonly PASSWORD_CHANGE_FORCED = 'password_change_forced';
@ -72,13 +69,9 @@ export class CoreEventsProvider {
static readonly FORM_ACTION = 'form_action'; static readonly FORM_ACTION = 'form_action';
static readonly ACTIVITY_DATA_SENT = 'activity_data_sent'; static readonly ACTIVITY_DATA_SENT = 'activity_data_sent';
protected logger: CoreLogger; protected static logger = CoreLogger.getInstance('CoreEvents');
protected observables: { [eventName: string]: Subject<unknown> } = {}; protected static observables: { [eventName: string]: Subject<unknown> } = {};
protected uniqueEvents: { [eventName: string]: {data: unknown} } = {}; protected static uniqueEvents: { [eventName: string]: {data: unknown} } = {};
constructor() {
this.logger = CoreLogger.getInstance('CoreEventsProvider');
}
/** /**
* Listen for a certain event. To stop listening to the event: * Listen for a certain event. To stop listening to the event:
@ -91,7 +84,7 @@ export class CoreEventsProvider {
* @param siteId Site where to trigger the event. Undefined won't check the site. * @param siteId Site where to trigger the event. Undefined won't check the site.
* @return Observer to stop listening. * @return Observer to stop listening.
*/ */
on(eventName: string, callBack: (value: unknown) => void, siteId?: string): CoreEventObserver { static on(eventName: string, callBack: (value: unknown) => void, siteId?: string): CoreEventObserver {
// If it's a unique event and has been triggered already, call the callBack. // If it's a unique event and has been triggered already, call the callBack.
// We don't need to create an observer because the event won't be triggered again. // We don't need to create an observer because the event won't be triggered again.
if (this.uniqueEvents[eventName]) { if (this.uniqueEvents[eventName]) {
@ -138,7 +131,7 @@ export class CoreEventsProvider {
* @param siteId Site where to trigger the event. Undefined won't check the site. * @param siteId Site where to trigger the event. Undefined won't check the site.
* @return Observer to stop listening. * @return Observer to stop listening.
*/ */
onMultiple(eventNames: string[], callBack: (value: unknown) => void, siteId?: string): CoreEventObserver { static onMultiple(eventNames: string[], callBack: (value: unknown) => void, siteId?: string): CoreEventObserver {
const observers = eventNames.map((name) => this.on(name, callBack, siteId)); const observers = eventNames.map((name) => this.on(name, callBack, siteId));
// Create and return a CoreEventObserver. // Create and return a CoreEventObserver.
@ -158,7 +151,7 @@ export class CoreEventsProvider {
* @param data Data to pass to the observers. * @param data Data to pass to the observers.
* @param siteId Site where to trigger the event. Undefined means no Site. * @param siteId Site where to trigger the event. Undefined means no Site.
*/ */
trigger(eventName: string, data?: unknown, siteId?: string): void { static trigger(eventName: string, data?: unknown, siteId?: string): void {
this.logger.debug(`Event '${eventName}' triggered.`); this.logger.debug(`Event '${eventName}' triggered.`);
if (this.observables[eventName]) { if (this.observables[eventName]) {
if (siteId) { if (siteId) {
@ -175,7 +168,7 @@ export class CoreEventsProvider {
* @param data Data to pass to the observers. * @param data Data to pass to the observers.
* @param siteId Site where to trigger the event. Undefined means no Site. * @param siteId Site where to trigger the event. Undefined means no Site.
*/ */
triggerUnique(eventName: string, data: unknown, siteId?: string): void { static triggerUnique(eventName: string, data: unknown, siteId?: string): void {
if (this.uniqueEvents[eventName]) { if (this.uniqueEvents[eventName]) {
this.logger.debug(`Unique event '${eventName}' ignored because it was already triggered.`); this.logger.debug(`Unique event '${eventName}' ignored because it was already triggered.`);
} else { } else {
@ -199,8 +192,6 @@ export class CoreEventsProvider {
} }
export class CoreEvents extends makeSingleton(CoreEventsProvider) {}
/** /**
* Data passed to SESSION_EXPIRED event. * Data passed to SESSION_EXPIRED event.
*/ */